source: sans/Dev/trunk/NCNR_User_Procedures/Reduction/USANS/U_CALC.ipf @ 1004

Last change on this file since 1004 was 939, checked in by srkline, 9 years ago

correcting typos in U_CALC and SumSANSModels

File size: 58.9 KB
Line 
1#pragma rtGlobals=1             // Use modern global access method.
2#pragma IgorVersion=6.1
3
4
5// USANS version of SASCALC
6
7// to simulate the intensity from a USANS experiment for planning
8// see John's instrument paper:
9//
10// J. Appl. Cryst. (2005) 38 1004-1011.
11//
12// SRK JUL 2009
13
14
15// ideas:
16//
17// - more presets
18//
19// - NEED -
20// - printable output that makes sense to an instrument scientist at least
21//   for instrument setup
22//
23// - make sure that the # points <-> increment relation meshes with ICP
24
25//
26// X plot as countrate, not absolute scale
27// X 3e-5 cutoff
28// X ? don't plot lowest angle range (but needs to be in the count time)
29// - need empty beam and empty cell count rate vs. aperture (Cd vs. Gd?)
30//
31
32
33// need to add in empty and background corrections to see "reduced" data
34// or at least compare to what the empty cell would give in the same count time
35//
36// -? model the direct beam?? currently the "red" region from -1 to 0.6 is almost entirely
37// the primary beam, so it's a bit artificial (qmin is really ~ 3e-5)
38//
39
40//
41// Need T_wide, T_rock, I peak for proper absolute scaling, but I don't know if it's really important
42// to be able to simlulate to this extent
43//
44
45
46//#include "MultScatter_MonteCarlo_2D"
47
48
49
50// Bring the UCALC panel to the front
51// ALWAYS initializes the folders and variables
52// then draws the panel if necessary
53Proc Show_UCALC()
54
55        DoWindow/F UCALC
56        if(V_Flag==0)
57                Init_UCALC()
58                UCALC_Panel()
59                CalcTotalCountTime()
60                ControlUpdate/W=UCALC U_popup0          //force a pop of the function list
61        Endif
62       
63End
64
65
66//set up the global values for the angles, # points, and count time
67Proc Init_UCALC()
68       
69        //
70        NewDataFolder/O root:Simulation                         // required to calculate the RandomDeviate
71        NewDataFolder/O root:Packages:NIST:SAS                          // required to calculate the RandomDeviate
72
73//
74        NewDataFolder/O root:Packages:NIST:USANS:SIM            //for the fake raw data
75        NewDataFolder/O/S root:Packages:NIST:USANS:Globals:U_Sim                //for constants, panel, etc
76
77        Variable/G gAngLow1 = -1
78        Variable/G gAngHigh1 = 0.6
79        Variable/G gNumPts1 = 33
80        Variable/G gCtTime1 = 20
81        Variable/G gIncr1 = 0.05       
82       
83        Variable/G gAngLow2 = 0.7
84        Variable/G gAngHigh2 = 1.9
85        Variable/G gNumPts2 = 13
86        Variable/G gCtTime2 = 50
87        Variable/G gIncr2 = 0.1
88       
89        Variable/G gAngLow3 = 2
90        Variable/G gAngHigh3 = 4.8
91        Variable/G gNumPts3 = 15
92        Variable/G gCtTime3 = 100
93        Variable/G gIncr3 = 0.2
94       
95        Variable/G gAngLow4 = 5
96        Variable/G gAngHigh4 = 9.5
97        Variable/G gNumPts4 = 10
98        Variable/G gCtTime4 = 200
99        Variable/G gIncr4 = 0.5
100       
101        Variable/G gAngLow5 = 10
102        Variable/G gAngHigh5 = 19
103        Variable/G gNumPts5 = 10
104        Variable/G gCtTime5 = 500
105        Variable/G gIncr5 = 1
106       
107        Variable/G gAngLow6 = 20
108        Variable/G gAngHigh6 = 48
109        Variable/G gNumPts6 = 15
110        Variable/G gCtTime6 = 1000
111        Variable/G gIncr6 = 2   
112       
113        Variable/G gAngLow7 = 50
114        Variable/G gAngHigh7 = 95
115        Variable/G gNumPts7 = 10
116        Variable/G gCtTime7 = 0
117        Variable/G gIncr7 = 5   
118       
119        // results, setup values
120        String/G gFuncStr=""
121        String/G gTotTimeStr=""
122        Variable/G gAnalyzerOmega = 7.1e-7              //solid angle of the analyzer, in steradians
123//      Variable/G gBeamCurrent=25000           // (?? not used) beam current Ed*I      (n/s) for 5/8" diam = 25000 n/s
124        Variable/G gThick=0.1           //sample thickness (cm)
125        Variable/G gSamTrans=0.8
126        Variable/G g_1D_DoABS = 0               //=1 for abs scale, 0 for just counts
127        Variable/G g_1D_PlotCR = 1              //=1 to plot countrate
128        Variable/G g_1D_AddNoise = 1            // add in appropriate noise to simulation
129       
130// a box for the results
131        // ??   maybe not useful to report
132        Variable/G g_1DEstDetCR  = 0            // estimated detector count rate
133        Variable/G g_1DTotCts = 0               
134        Variable/G g_1DFracScatt= 0     // ??
135        Variable/G g_1DEstTrans = 0     // ? can I calculate this?
136        Variable/G g_MultScattFraction = 0
137
138
139// not on panel yet
140        Variable/G g_Empirical_EMP = 0          // use an emperical model for empty cell subtraction
141        Variable/G g_EmptyLevel = 0.7
142        Variable/G g_BkgLevel = 0.6
143
144        SetDataFolder root:
145       
146End
147
148//// make the display panel a graph with a control bar just as in SASCALC
149//// so that the subwindow syntax doesn't break all of the other functionality
150////
151//Window UCALC_Panel() : Graph
152//      PauseUpdate; Silent 1           // building window...
153//      Display /W=(55,44,670,850) /K=1
154//      ModifyGraph cbRGB=(36929,50412,31845)
155//      DoWindow/C UCALC
156//      DoWindow/T UCALC,"USANS Simulation"
157//      ControlBar 320
158//     
159//      GroupBox group0,pos={5,0},size={577,159},title="Instrument Setup"
160//      GroupBox group1,pos={5,165},size={240,147},title="Sample Setup"
161//      GroupBox group2,pos={327,165},size={259,147},title="Results"
162//     
163//      PopupMenu popup0,pos={17,18},size={165,20},title="Sample Aperture Diam (in)"
164//      PopupMenu popup0,mode=3,popvalue="0.625",value="0.25;0.50;0.625;0.75;1.0;1.75;2.0;"
165//      PopupMenu popup2,pos={220,18},size={165,20},title="Presets"
166//      PopupMenu popup2,mode=3,popvalue="Long Count",value="Short Count;Medium Count;Long Count;"
167//      PopupMenu popup2,proc=UCALC_PresetPopup
168//
169//      SetDataFolder root:Packages:NIST:USANS:Globals:U_Sim
170//     
171//      Variable top=44,pt=0,inc=18
172//      SetVariable setvar1a,pos={12,top},size={100,15},title="theta min",value= gAngLow1
173//      SetVariable setvar1b,pos={119,top},size={100,15},title="theta max",value= gAngHigh1
174//      SetVariable setvar1c,pos={227,top},size={100,15},title="increm",value= gIncr1
175//      SetVariable setvar1d,pos={335,top},size={100,15},title="# points",value= gNumPts1
176//      SetVariable setvar1e,pos={443,top},size={100,15},title="count (s)",value= gCtTime1
177//      SetVariable setvar1a,labelBack=(65535,32768,32768)
178//     
179//      pt += inc
180//      SetVariable setvar2a,pos={12,top+pt},size={100,15},title="theta min",value= gAngLow2
181//      SetVariable setvar2b,pos={119,top+pt},size={100,15},title="theta max",value= gAngHigh2
182//      SetVariable setvar2c,pos={227,top+pt},size={100,15},title="increm",value= gIncr2
183//      SetVariable setvar2d,pos={335,top+pt},size={100,15},title="# points",value= gNumPts2
184//      SetVariable setvar2e,pos={443,top+pt},size={100,15},title="count (s)",value= gCtTime2
185//      SetVariable setvar2a labelBack=(65535,65533,32768)
186//     
187//      pt += inc
188//      SetVariable setvar3a,pos={12,top+pt},size={100,15},title="theta min",value= gAngLow3
189//      SetVariable setvar3b,pos={119,top+pt},size={100,15},title="theta max",value= gAngHigh3
190//      SetVariable setvar3c,pos={227,top+pt},size={100,15},title="increm",value= gIncr3
191//      SetVariable setvar3d,pos={335,top+pt},size={100,15},title="# points",value= gNumPts3
192//      SetVariable setvar3e,pos={443,top+pt},size={100,15},title="count (s)",value= gCtTime3
193//      SetVariable setvar3a labelBack=(32769,65535,32768)
194//     
195//      pt += inc
196//      SetVariable setvar4a,pos={12,top+pt},size={100,15},title="theta min",value= gAngLow4
197//      SetVariable setvar4b,pos={119,top+pt},size={100,15},title="theta max",value= gAngHigh4
198//      SetVariable setvar4c,pos={227,top+pt},size={100,15},title="increm",value= gIncr4
199//      SetVariable setvar4d,pos={335,top+pt},size={100,15},title="# points",value= gNumPts4
200//      SetVariable setvar4e,pos={443,top+pt},size={100,15},title="count (s)",value= gCtTime4
201//      SetVariable setvar4a labelBack=(32768,65535,65535)
202//     
203//      pt += inc
204//      SetVariable setvar5a,pos={12,top+pt},size={100,15},title="theta min",value= gAngLow5
205//      SetVariable setvar5b,pos={119,top+pt},size={100,15},title="theta max",value= gAngHigh5
206//      SetVariable setvar5c,pos={227,top+pt},size={100,15},title="increm",value= gIncr5
207//      SetVariable setvar5d,pos={335,top+pt},size={100,15},title="# points",value= gNumPts5
208//      SetVariable setvar5e,pos={443,top+pt},size={100,15},title="count (s)",value= gCtTime5
209//      SetVariable setvar5a labelBack=(32768,54615,65535)
210//     
211//      pt += inc
212//      SetVariable setvar6a,pos={12,top+pt},size={100,15},title="theta min",value= gAngLow6
213//      SetVariable setvar6b,pos={119,top+pt},size={100,15},title="theta max",value= gAngHigh6
214//      SetVariable setvar6c,pos={227,top+pt},size={100,15},title="increm",value= gIncr6
215//      SetVariable setvar6d,pos={335,top+pt},size={100,15},title="# points",value= gNumPts6
216//      SetVariable setvar6e,pos={443,top+pt},size={100,15},title="count (s)",value= gCtTime6
217//      SetVariable setvar6a labelBack=(44253,29492,58982)
218//
219//// the action procedures and limits/increments
220//      SetVariable setvar1a proc=ThetaMinSetVarProc            //,limits={-2,0,0.1}
221//      SetVariable setvar2a proc=ThetaMinSetVarProc
222//      SetVariable setvar3a proc=ThetaMinSetVarProc
223//      SetVariable setvar4a proc=ThetaMinSetVarProc
224//      SetVariable setvar5a proc=ThetaMinSetVarProc
225//      SetVariable setvar6a proc=ThetaMinSetVarProc
226//
227////
228//      SetVariable setvar1b proc=ThetaMaxSetVarProc            //,limits={0.4,1,0.1}
229//      SetVariable setvar2b proc=ThetaMaxSetVarProc
230//      SetVariable setvar3b proc=ThetaMaxSetVarProc
231//      SetVariable setvar4b proc=ThetaMaxSetVarProc
232//      SetVariable setvar5b proc=ThetaMaxSetVarProc
233//      SetVariable setvar6b proc=ThetaMaxSetVarProc
234////
235//      SetVariable setvar1c proc=IncrSetVarProc,limits={0.01,0.1,0.01}
236//      SetVariable setvar2c proc=IncrSetVarProc,limits={0.02,0.2,0.02}
237//      SetVariable setvar3c proc=IncrSetVarProc,limits={0.05,0.4,0.05}
238//      SetVariable setvar4c proc=IncrSetVarProc,limits={0.1,1,0.1}
239//      SetVariable setvar5c proc=IncrSetVarProc,limits={0.5,5,1}
240//      SetVariable setvar6c proc=IncrSetVarProc,limits={1,10,2}
241////
242//      SetVariable setvar1d proc=NumPtsSetVarProc,limits={2,50,1}
243//      SetVariable setvar2d proc=NumPtsSetVarProc,limits={2,50,1}
244//      SetVariable setvar3d proc=NumPtsSetVarProc,limits={2,50,1}
245//      SetVariable setvar4d proc=NumPtsSetVarProc,limits={2,50,1}
246//      SetVariable setvar5d proc=NumPtsSetVarProc,limits={2,50,1}
247//      SetVariable setvar6d proc=NumPtsSetVarProc,limits={2,50,1}
248////
249//      SetVariable setvar1e proc=CtTimeSetVarProc,limits={-1,50000,1}
250//      SetVariable setvar2e proc=CtTimeSetVarProc,limits={-1,50000,10}
251//      SetVariable setvar3e proc=CtTimeSetVarProc,limits={-1,50000,10}
252//      SetVariable setvar4e proc=CtTimeSetVarProc,limits={-1,50000,30}
253//      SetVariable setvar5e proc=CtTimeSetVarProc,limits={-1,50000,100}
254//      SetVariable setvar6e proc=CtTimeSetVarProc,limits={-1,50000,100}
255//     
256//      Button button0,pos={255,180},size={60,20},fColor=(65535,65535,0),proc=U_SimPlotButtonProc,title="Plot"
257//      Button button1,pos={260,286},size={50,20},proc=U_SaveButtonProc,title="Save"
258//
259////checkbox for "easy" mode
260//      CheckBox check0 title="Simple mode?",pos={400,19},proc=EnterModeCheckProc,value=1
261//      ThetaEditMode(2)                //checked on startup
262//     
263////    instrument setup
264//      SetVariable U_setvar0_1,pos={20,211},size={160,15},title="Thickness (cm)"
265//      SetVariable U_setvar0_1,limits={0,inf,0.1},value= root:Packages:NIST:USANS:Globals:U_Sim:gThick
266//      SetVariable U_setvar0_3,pos={20,235},size={160,15},title="Sample Transmission"
267//      SetVariable U_setvar0_3,limits={0,1,0.01},value= root:Packages:NIST:USANS:Globals:U_Sim:gSamTrans
268//      PopupMenu U_popup0,pos={20,185},size={165,20},proc=Sim_USANS_ModelPopMenuProc,title="Model"
269//      PopupMenu U_popup0,mode=1,value= #"U_FunctionPopupList()"
270//      SetVariable setvar0,pos={20,259},size={120,15},title="Empty Level"
271//      SetVariable setvar0,limits={0,10,0.01},value= root:Packages:NIST:USANS:Globals:U_Sim:g_EmptyLevel
272//      SetVariable setvar0_1,pos={20,284},size={120,15},title="Bkg Level"
273//      SetVariable setvar0_1,limits={0,10,0.01},value= root:Packages:NIST:USANS:Globals:U_Sim:g_BkgLevel
274//     
275//      CheckBox check0_4 title="Show EMP?",pos={160,260},proc=ShowEMPCheckProc,value=0
276//     
277//      CheckBox check0_2,pos={253,239},size={60,14},title="CountRate?",variable= root:Packages:NIST:USANS:Globals:U_Sim:g_1D_PlotCR
278//      CheckBox check0_3,pos={262,264},size={60,14},title="Noise?",variable= root:Packages:NIST:USANS:Globals:U_Sim:g_1D_AddNoise
279//     
280//// a box for the results
281//      SetVariable totalTime,pos={338,185},size={150,15},title="Count time (h:m)",value= gTotTimeStr
282////    ValDisplay valdisp0,pos={338,210},size={220,13},title="Total detector counts"
283////    ValDisplay valdisp0,limits={0,0,0},barmisc={0,1000},value= root:Packages:NIST:USANS:Globals:U_Sim:g_1DTotCts
284//      ValDisplay valdisp0_2,pos={338,234},size={220,13},title="Fraction of beam scattered"
285//      ValDisplay valdisp0_2,limits={0,0,0},barmisc={0,1000},value= root:Packages:NIST:USANS:Globals:U_Sim:g_1DFracScatt
286//      ValDisplay valdisp0_3,pos={338,259},size={220,13},title="Estimated transmission"
287//      ValDisplay valdisp0_3,limits={0,0,0},barmisc={0,1000},value=root:Packages:NIST:USANS:Globals:U_Sim:g_1DEstTrans
288//
289//     
290//      SetDataFolder root:
291//
292//EndMacro
293
294// ??make the USANS simulation results into a graph and a separate panel.
295// the control bar at the top makes the whole thing too large, and control bars are limited
296// to 500 pix wide, which is really tight
297// left of 1055 is good for Mac, 955 is better for Win
298//
299Window UCALC_Panel()
300        PauseUpdate; Silent 1           // building window...
301        String platform=UpperStr(IgorInfo(2))
302        Variable pos=strsearch(platform,"WINDOWS",0)
303        if(pos >= 0)            //windows
304                Display /W=(55,44,855,450) /K=1
305        else            //mac
306                Display /W=(55,44,1055,544) /K=1
307        endif
308       
309        ModifyGraph cbRGB=(36929,50412,31845)
310        DoWindow/C UCALC
311        DoWindow/T UCALC,"USANS Simulation"
312        ControlBar/L 500
313       
314        GroupBox group0,pos={5,1},size={493,177},title="Instrument Setup"
315        GroupBox group1,pos={5,183},size={240,110},title="Sample Setup"
316        GroupBox group2,pos={5,310},size={240,170},title="Results"
317       
318        PopupMenu popup0,pos={17,19},size={165,20},title="Sample Aperture Diam (in)"
319        PopupMenu popup0,mode=3,popvalue="0.625",value="0.25;0.50;0.625;0.75;1.0;1.75;2.0;"
320        PopupMenu popup0,proc=UCALC_SampleAperturePopup
321        PopupMenu popup2,pos={220,19},size={165,20},title="Presets"
322        PopupMenu popup2,mode=2,popvalue="Medium Count",value="Short Count;Medium Count;Long Count;"
323        PopupMenu popup2,proc=UCALC_PresetPopup
324
325        SetDataFolder root:Packages:NIST:USANS:Globals:U_Sim
326       
327        Variable top=46,pt=0,inc=18,left=0//left=533
328        SetVariable setvar1a,pos={left+17,top},size={90,15},title="theta min",value= gAngLow1
329        SetVariable setvar1b,pos={left+113,top},size={89,15},title="theta max",value= gAngHigh1
330        SetVariable setvar1c,pos={left+209,top},size={89,15},title="increm",value= gIncr1
331        SetVariable setvar1d,pos={left+299,top},size={100,15},title="# points",value= gNumPts1
332        SetVariable setvar1e,pos={left+399,top},size={93,15},title="count (s)",value= gCtTime1
333//      SetVariable setvar1a,labelBack=(65535,32768,32768)              //old rainbow
334        SetVariable setvar1a,labelBack=(49858,65535,65535)
335       
336        pt += inc
337        SetVariable setvar2a,pos={left+17,top+pt},size={90,15},title="theta min",value= gAngLow2
338        SetVariable setvar2b,pos={left+113,top+pt},size={89,15},title="theta max",value= gAngHigh2
339        SetVariable setvar2c,pos={left+209,top+pt},size={89,15},title="increm",value= gIncr2
340        SetVariable setvar2d,pos={left+299,top+pt},size={100,15},title="# points",value= gNumPts2
341        SetVariable setvar2e,pos={left+399,top+pt},size={93,15},title="count (s)",value= gCtTime2
342//      SetVariable setvar2a labelBack=(65535,65533,32768)              //old rainbow
343        SetVariable setvar2a labelBack=(21074,8995,21074)
344       
345        pt += inc
346        SetVariable setvar3a,pos={left+17,top+pt},size={90,15},title="theta min",value= gAngLow3
347        SetVariable setvar3b,pos={left+113,top+pt},size={89,15},title="theta max",value= gAngHigh3
348        SetVariable setvar3c,pos={left+209,top+pt},size={89,15},title="increm",value= gIncr3
349        SetVariable setvar3d,pos={left+299,top+pt},size={100,15},title="# points",value= gNumPts3
350        SetVariable setvar3e,pos={left+399,top+pt},size={93,15},title="count (s)",value= gCtTime3
351//      SetVariable setvar3a labelBack=(32769,65535,32768)              //old rainbow
352        SetVariable setvar3a labelBack=(0,60652,60652)
353       
354        pt += inc
355        SetVariable setvar4a,pos={left+17,top+pt},size={90,15},title="theta min",value= gAngLow4
356        SetVariable setvar4b,pos={left+113,top+pt},size={89,15},title="theta max",value= gAngHigh4
357        SetVariable setvar4c,pos={left+209,top+pt},size={89,15},title="increm",value= gIncr4
358        SetVariable setvar4d,pos={left+299,top+pt},size={100,15},title="# points",value= gNumPts4
359        SetVariable setvar4e,pos={left+399,top+pt},size={93,15},title="count (s)",value= gCtTime4
360//      SetVariable setvar4a labelBack=(32768,65535,65535)              //old rainbow
361        SetVariable setvar4a labelBack=(0,51400,0)
362       
363        pt += inc
364        SetVariable setvar5a,pos={left+17,top+pt},size={90,15},title="theta min",value= gAngLow5
365        SetVariable setvar5b,pos={left+113,top+pt},size={89,15},title="theta max",value= gAngHigh5
366        SetVariable setvar5c,pos={left+209,top+pt},size={89,15},title="increm",value= gIncr5
367        SetVariable setvar5d,pos={left+299,top+pt},size={100,15},title="# points",value= gNumPts5
368        SetVariable setvar5e,pos={left+399,top+pt},size={93,15},title="count (s)",value= gCtTime5
369//      SetVariable setvar5a labelBack=(32768,54615,65535)              //old rainbow
370        SetVariable setvar5a labelBack=(59367,49344,0)
371       
372        pt += inc
373        SetVariable setvar6a,pos={left+17,top+pt},size={90,15},title="theta min",value= gAngLow6
374        SetVariable setvar6b,pos={left+113,top+pt},size={89,15},title="theta max",value= gAngHigh6
375        SetVariable setvar6c,pos={left+209,top+pt},size={89,15},title="increm",value= gIncr6
376        SetVariable setvar6d,pos={left+299,top+pt},size={100,15},title="# points",value= gNumPts6
377        SetVariable setvar6e,pos={left+399,top+pt},size={93,15},title="count (s)",value= gCtTime6
378//      SetVariable setvar6a labelBack=(44253,29492,58982)              //old rainbow
379        SetVariable setvar6a labelBack=(54998,0,0)
380
381        pt += inc
382        SetVariable setvar7a,pos={left+17,top+pt},size={90,15},title="theta min",value= gAngLow7
383        SetVariable setvar7b,pos={left+113,top+pt},size={89,15},title="theta max",value= gAngHigh7
384        SetVariable setvar7c,pos={left+209,top+pt},size={89,15},title="increm",value= gIncr7
385        SetVariable setvar7d,pos={left+299,top+pt},size={100,15},title="# points",value= gNumPts7
386        SetVariable setvar7e,pos={left+399,top+pt},size={93,15},title="count (s)",value= gCtTime7
387//      SetVariable setvar7a labelBack=(44253,29492,58982)              //old rainbow
388        SetVariable setvar7a labelBack=(39321,21845,51657)
389
390// the action procedures and limits/increments
391        SetVariable setvar1a proc=ThetaMinSetVarProc            //,limits={-2,0,0.1}
392        SetVariable setvar2a proc=ThetaMinSetVarProc
393        SetVariable setvar3a proc=ThetaMinSetVarProc
394        SetVariable setvar4a proc=ThetaMinSetVarProc
395        SetVariable setvar5a proc=ThetaMinSetVarProc
396        SetVariable setvar6a proc=ThetaMinSetVarProc
397        SetVariable setvar7a proc=ThetaMinSetVarProc
398
399//
400        SetVariable setvar1b proc=ThetaMaxSetVarProc            //,limits={0.4,1,0.1}
401        SetVariable setvar2b proc=ThetaMaxSetVarProc
402        SetVariable setvar3b proc=ThetaMaxSetVarProc
403        SetVariable setvar4b proc=ThetaMaxSetVarProc
404        SetVariable setvar5b proc=ThetaMaxSetVarProc
405        SetVariable setvar6b proc=ThetaMaxSetVarProc
406        SetVariable setvar7b proc=ThetaMaxSetVarProc
407//
408        SetVariable setvar1c proc=IncrSetVarProc,limits={0.01,0.1,0.01}
409        SetVariable setvar2c proc=IncrSetVarProc,limits={0.02,0.2,0.02}
410        SetVariable setvar3c proc=IncrSetVarProc,limits={0.05,0.4,0.05}
411        SetVariable setvar4c proc=IncrSetVarProc,limits={0.1,1,0.1}
412        SetVariable setvar5c proc=IncrSetVarProc,limits={0.5,5,1}
413        SetVariable setvar6c proc=IncrSetVarProc,limits={1,10,2}
414        SetVariable setvar7c proc=IncrSetVarProc,limits={1,20,2}
415//
416        SetVariable setvar1d proc=NumPtsSetVarProc,limits={2,50,1}
417        SetVariable setvar2d proc=NumPtsSetVarProc,limits={2,50,1}
418        SetVariable setvar3d proc=NumPtsSetVarProc,limits={2,50,1}
419        SetVariable setvar4d proc=NumPtsSetVarProc,limits={2,50,1}
420        SetVariable setvar5d proc=NumPtsSetVarProc,limits={2,50,1}
421        SetVariable setvar6d proc=NumPtsSetVarProc,limits={2,50,1}
422        SetVariable setvar7d proc=NumPtsSetVarProc,limits={2,50,1}
423//
424        SetVariable setvar1e proc=CtTimeSetVarProc,limits={-1,50000,1}
425        SetVariable setvar2e proc=CtTimeSetVarProc,limits={-1,50000,10}
426        SetVariable setvar3e proc=CtTimeSetVarProc,limits={-1,50000,10}
427        SetVariable setvar4e proc=CtTimeSetVarProc,limits={-1,50000,30}
428        SetVariable setvar5e proc=CtTimeSetVarProc,limits={-1,50000,100}
429        SetVariable setvar6e proc=CtTimeSetVarProc,limits={-1,50000,100}
430        SetVariable setvar7e proc=CtTimeSetVarProc,limits={-1,50000,100}
431       
432        Button button0,pos={left+280,200},size={130,20},fColor=(65535,65535,0),proc=U_SimPlotButtonProc,title="Simulate USANS"
433        CheckBox check0_2,pos={left+280,250},size={60,14},title="CountRate?",variable= root:Packages:NIST:USANS:Globals:U_Sim:g_1D_PlotCR
434        CheckBox check0_3,pos={left+280,270},size={60,14},title="Noise?",variable= root:Packages:NIST:USANS:Globals:U_Sim:g_1D_AddNoise
435        CheckBox check0_4 title="Show EMP?",pos={left+280,290},proc=ShowEMPCheckProc,value=0
436
437
438//checkbox for "easy" mode
439        CheckBox check0 title="Simple mode?",pos={left+400,19},proc=EnterModeCheckProc,value=1
440        ThetaEditMode(2)                //checked on startup
441       
442//      sample setup
443        SetVariable U_setvar0_1,pos={left+20,231},size={160,15},title="Thickness (cm)"
444        SetVariable U_setvar0_1,limits={0,inf,0.1},value= root:Packages:NIST:USANS:Globals:U_Sim:gThick
445        SetVariable U_setvar0_3,pos={left+20,255},size={160,15},title="Sample Transmission"
446        SetVariable U_setvar0_3,limits={0,1,0.01},value= root:Packages:NIST:USANS:Globals:U_Sim:gSamTrans
447        PopupMenu U_popup0,pos={left+20,205},size={165,20},proc=Sim_USANS_ModelPopMenuProc,title="Model"
448        PopupMenu U_popup0,mode=1,value= #"U_FunctionPopupList()"
449       
450        //unused as of yet, not sure I'll ever need these
451//      SetVariable setvar0,pos={left+20,279},size={120,15},title="Empty Level",disable=2
452//      SetVariable setvar0,limits={0,10,0.01},value= root:Packages:NIST:USANS:Globals:U_Sim:g_EmptyLevel
453//      SetVariable setvar0_1,pos={left+20,304},size={120,15},title="Bkg Level",disable=2
454//      SetVariable setvar0_1,limits={0,10,0.01},value= root:Packages:NIST:USANS:Globals:U_Sim:g_BkgLevel
455       
456       
457       
458// a box for the results
459        SetVariable totalTime,pos={left+20,335},size={150,15},title="Count time (h:m)",value= gTotTimeStr
460        SetVariable totalTime,limits={-inf,inf,0},noedit=1
461        SetVariable valdisp0_2,pos={left+20,365},size={200,15},title="Multiple Coherent Scattering"
462        SetVariable valdisp0_2,limits={-inf,inf,0},format="%8f",noedit=1,value=g_MultScattFraction
463//      ValDisplay valdisp0_3,pos={left+20,420},size={220,13},title="Estimated transmission"
464//      ValDisplay valdisp0_3,limits={0,0,0},barmisc={0,1000},value=root:Packages:NIST:USANS:Globals:U_Sim:g_1DEstTrans
465//      ValDisplay valdisp0_3,disable=1
466        Button button1,pos={left+20,390},size={150,20},proc=U_SavePanelProc,title="Save PNG"
467        Button button2,pos={left+20,420},size={150,20},proc=U_ConfigTextProc,title="Config Text"
468        Button button3,pos={left+20,450},size={150,20},proc=U_SaveButtonProc,title="Save Simulated Data"
469
470// help, done buttons
471        Button U_helpButton,pos={300,440},size={25,20},proc=showUCALCHelp,title="?"
472        Button U_helpButton,help={"Show help file for simulation of USANS Data"}
473        Button U_DoneButton,pos={350,440},size={50,20},proc=UCALCDoneButton,title="Done"
474        Button U_DoneButton,help={"This button will close the panel"}
475               
476        SetDataFolder root:
477
478EndMacro
479
480Proc UCALCDoneButton(ctrlName): ButtonControl
481        String ctrlName
482        DoWindow/K UCALC
483end
484
485Proc showUCALCHelp(ctrlName): ButtonControl
486        String ctrlName
487        DisplayHelpTopic/K=1/Z "UCALC"
488        if(V_flag !=0)
489                DoAlert 0,"The USANS Simulation Help file could not be found"
490        endif
491end
492
493// changing theta min - hold incr and #, result is new theta max
494Function ThetaMinSetVarProc(sva) : SetVariableControl
495        STRUCT WMSetVariableAction &sva
496
497        switch( sva.eventCode )
498                case 1: // mouse up
499                case 2: // Enter key
500                case 3: // Live update
501                        Variable ThetaMin = sva.dval
502                        String ns=CtrlNumber(sva.ctrlName)              //control number as a string
503                        NVAR incr = $("root:Packages:NIST:USANS:Globals:U_Sim:"+"gIncr"+ns)
504                        NVAR NumPts = $("root:Packages:NIST:USANS:Globals:U_Sim:"+"gNumPts"+ns)
505                        NVAR thetaMax = $("root:Packages:NIST:USANS:Globals:U_Sim:"+"gAngHigh"+ns)
506                       
507                        thetaMax = ThetaMin + incr*NumPts
508                       
509                        break
510        endswitch
511
512        return 0
513End
514
515
516// changing theta max - hold min and incr, result is new # of points
517// then need to recalculate the total counting time
518Function ThetaMaxSetVarProc(sva) : SetVariableControl
519        STRUCT WMSetVariableAction &sva
520
521        switch( sva.eventCode )
522                case 1: // mouse up
523                case 2: // Enter key
524                case 3: // Live update
525                        Variable ThetaMax = sva.dval
526                        String ns=CtrlNumber(sva.ctrlName)              //control number as a string
527                        NVAR thetaMin = $("root:Packages:NIST:USANS:Globals:U_Sim:"+"gAngLow"+ns)
528                        NVAR NumPts = $("root:Packages:NIST:USANS:Globals:U_Sim:"+"gNumPts"+ns)
529                        NVAR Incr = $("root:Packages:NIST:USANS:Globals:U_Sim:"+"gIncr"+ns)
530                       
531                        NumPts = trunc( (thetaMax - ThetaMin) / incr ) + 1                      //+1 to count both ends of the interval
532               
533                        CalcTotalCountTime()
534                       
535                        break
536        endswitch
537
538        return 0
539End
540
541// changing increment - hold min and #, result is new max
542Function IncrSetVarProc(sva) : SetVariableControl
543        STRUCT WMSetVariableAction &sva
544
545        switch( sva.eventCode )
546                case 1: // mouse up
547                case 2: // Enter key
548                case 3: // Live update
549                        Variable incr = sva.dval
550                        String ns=CtrlNumber(sva.ctrlName)              //control number as a string
551                        NVAR thetaMin = $("root:Packages:NIST:USANS:Globals:U_Sim:"+"gAngLow"+ns)
552                        NVAR NumPts = $("root:Packages:NIST:USANS:Globals:U_Sim:"+"gNumPts"+ns)
553                        NVAR thetaMax = $("root:Packages:NIST:USANS:Globals:U_Sim:"+"gAngHigh"+ns)
554                       
555                        thetaMax = ThetaMin + incr*NumPts
556               
557                        break
558        endswitch
559
560        return 0
561End
562
563// changing #pts - hold min and incr, result is new max
564// then recalculate the total count time
565Function NumPtsSetVarProc(sva) : SetVariableControl
566        STRUCT WMSetVariableAction &sva
567
568        switch( sva.eventCode )
569                case 1: // mouse up
570                case 2: // Enter key
571                case 3: // Live update
572                        Variable NumPts = sva.dval
573                        String ns=CtrlNumber(sva.ctrlName)              //control number as a string
574                        NVAR thetaMin = $("root:Packages:NIST:USANS:Globals:U_Sim:"+"gAngLow"+ns)
575                        NVAR incr = $("root:Packages:NIST:USANS:Globals:U_Sim:"+"gIncr"+ns)
576                        NVAR thetaMax = $("root:Packages:NIST:USANS:Globals:U_Sim:"+"gAngHigh"+ns)
577
578// old way, like ICP                   
579//                      thetaMax = ThetaMin + incr*NumPts
580
581// new way - to spread the points out over the specified angle range
582                        incr = (thetaMax - thetaMin) /( numpts -1 )                     //-1 since end points are both counted
583                       
584                        CalcTotalCountTime()
585                       
586                        break
587        endswitch
588
589        return 0
590End
591
592// changing count time -
593// then recalculate the total count time
594Function CtTimeSetVarProc(sva) : SetVariableControl
595        STRUCT WMSetVariableAction &sva
596
597        switch( sva.eventCode )
598                case 1: // mouse up
599                case 2: // Enter key
600                case 3: // Live update
601                        CalcTotalCountTime()
602                        break
603        endswitch
604
605        return 0
606End
607
608// hard-wired for 7 controls
609// return value is in seconds
610// global display string is set with hrs:min
611Function CalcTotalCountTime()
612
613        Variable ii,num,totTime=0
614        String pathStr="root:Packages:NIST:USANS:Globals:U_Sim:"
615        num=7
616       
617        for(ii=1;ii<=num;ii+=1)
618                NVAR ctTime = $(pathStr+"gCtTime"+num2str(ii))
619                NVAR numPts = $(pathStr+"gNumPts"+num2str(ii))
620                if(ctTime>0)
621                        totTime += ctTime*numPts
622                endif
623        endfor
624        Variable hrs,mins
625        hrs = trunc(totTime/3600)
626        mins = trunc(mod(totTime,3600)/60)
627//      Printf "Counting time (hr:min) = %d:%d\r",hrs,mins
628       
629        SVAR str = $(pathStr+"gTotTimeStr")
630        sprintf str,"%d:%d",hrs,mins
631       
632        return(totTime)
633End
634
635//returns the control number from the name string
636// all are setvarNa
637Function/S CtrlNumber(str)
638        String str
639       
640        return(str[6])
641End
642
643// changes edit mode of the theta min/max boxes and increment for simplified setup
644// val = 2 = disable
645// val = 0 = edit enabled
646Function ThetaEditMode(val)
647        Variable val
648       
649        SetVariable setvar1a,win=UCALC,disable=val
650        SetVariable setvar1b,win=UCALC,disable=val
651        SetVariable setvar1c,win=UCALC,disable=val
652       
653        SetVariable setvar2a,win=UCALC,disable=val
654        SetVariable setvar2b,win=UCALC,disable=val
655        SetVariable setvar2c,win=UCALC,disable=val
656       
657        SetVariable setvar3a,win=UCALC,disable=val
658        SetVariable setvar3b,win=UCALC,disable=val
659        SetVariable setvar3c,win=UCALC,disable=val
660       
661        SetVariable setvar4a,win=UCALC,disable=val
662        SetVariable setvar4b,win=UCALC,disable=val
663        SetVariable setvar4c,win=UCALC,disable=val
664       
665        SetVariable setvar5a,win=UCALC,disable=val
666        SetVariable setvar5b,win=UCALC,disable=val
667        SetVariable setvar5c,win=UCALC,disable=val
668       
669        SetVariable setvar6a,win=UCALC,disable=val
670        SetVariable setvar6b,win=UCALC,disable=val
671        SetVariable setvar6c,win=UCALC,disable=val
672       
673        SetVariable setvar7a,win=UCALC,disable=val
674        SetVariable setvar7b,win=UCALC,disable=val
675        SetVariable setvar7c,win=UCALC,disable=val
676        return(0)
677End
678
679
680
681Function EnterModeCheckProc(cba) : CheckBoxControl
682        STRUCT WMCheckboxAction &cba
683
684        switch( cba.eventCode )
685                case 2: // mouse up
686                        Variable checked = cba.checked
687                       
688                        if(checked)
689                                ThetaEditMode(2)
690                        else
691                                ThetaEditMode(0)
692                        endif
693                       
694                        break
695        endswitch
696
697        return 0
698End
699
700
701Function ShowEMPCheckProc(cba) : CheckBoxControl
702        STRUCT WMCheckboxAction &cba
703
704        switch( cba.eventCode )
705                case 2: // mouse up
706                        Variable checked = cba.checked
707
708                        String list,item,popStr,qval,CR
709                        Variable OK=1
710
711                        if(exists("root:Packages:NIST:USANS:Globals:Q_2p0")==0)                 //
712                                MakeUSANSEmptyWaves()
713                        endif
714                       
715                       
716                        if(checked)
717                                // put it on the graph
718                                SetDataFolder root:Packages:NIST:USANS:Globals
719                                ControlInfo/W=UCALC popup0
720                                popStr = S_Value
721                                strswitch(popStr)       // string switch
722                                        case "0.25":            // execute if case matches expression
723                                                qval = "Q_0p25"
724                                                CR = "CR_0p25"
725                                                break           
726                                        case "0.50":   
727                                                qval = "Q_0p50"
728                                                CR = "CR_0p50"
729                                                break   
730                                        case "0.625":           
731                                                qval = "Q_0p625"
732                                                CR = "CR_0p625"
733                                                break   
734                                        case "1.75":           
735                                                qval = "Q_1p75"
736                                                CR = "CR_1p75"
737                                                break   
738                                        case "2.0":             
739                                                qval = "Q_2p0"
740                                                CR = "CR_2p0"
741                                                break   
742                                        default:                                                        // optional default expression executed
743                                                OK=0
744                                endswitch
745                               
746                                if(OK)
747                                        AppendToGraph/W=UCALC $CR vs $qval
748                                        ModifyGraph marker=19,mode($CR)=4,msize($CR)=3,rgb($CR)=(0,0,0)
749                                endif
750                               
751                        else
752                                //take it off of the graph
753                                SetDataFolder root:Packages:NIST:USANS:Globals
754                                list=WaveList("CR*", ";", "WIN:UCALC")
755                                item=StringFromList(0, list ,";")               //should be one item
756                                if(strlen(item) != 0)
757                                        RemoveFromGraph/W=UCALC $item
758                                endif
759                        endif
760                       
761                        break
762        endswitch
763
764        SetDataFolder root:
765        return 0
766End
767
768
769
770// based on the angle ranges above (with non-zero count times)
771// plot where the data points would be
772//
773Function U_SimPlotButtonProc(ba) : ButtonControl
774        STRUCT WMButtonAction &ba
775
776       
777        switch( ba.eventCode )
778                case 2: // mouse up
779                        // click code here
780                       
781                        CalcUSANS()
782                       
783                        break
784        endswitch
785
786        return 0
787End
788
789
790
791// Fills a fake USANS folder with the concatenated ranges, and converts to Q
792// root:Packages:NIST:USANS:SIM
793//
794// does the work of calculating and smearing the simluated USANS data set
795Function CalcUSANS()   
796
797        Variable num,ii,firstSet=0
798        String pathStr="root:Packages:NIST:USANS:Globals:U_Sim:gCtTime"
799        String fromType="SWAP",toType="SIM"
800        SVAR USANSFolder = root:Packages:NIST:USANS:Globals:gUSANSFolder
801       
802        num = 7                 //# of angular ranges
803       
804        // only try to plot ranges with non-zero count times
805        firstSet=0
806        for(ii=1;ii<=num;ii+=1)
807                NVAR dum = $(pathStr+num2str(ii))
808                if(dum>0)                                               
809//                      print "CtTime = ",dum
810                        firstSet += 1
811                        LoadSimulatedAngleRange(ii,"SWAP")      //overwrite what's in the SWAP folder
812                       
813                        // did not do this step
814                        //Convert2Countrate("SWAP",1)
815                        //
816                       
817                        if(firstSet==1) //first time, overwrite
818                                NewDataWaves("SWAP","SIM")
819                                //plus my two waves
820                                Duplicate/O $(USANSFolder+":"+fromType+":countingTime"),$(USANSFolder+":"+toType+":countingTime")
821                                Duplicate/O $(USANSFolder+":"+fromType+":SetNumber"),$(USANSFolder+":"+toType+":SetNumber")
822
823                        else            //append to waves in "SIM"
824                                AppendDataWaves("SWAP","SIM")
825                                // and my two waves
826                                ConcatenateData( (USANSFolder+":"+toType+":countingTime"),(USANSFolder+":"+fromType+":countingTime") )
827                                ConcatenateData( (USANSFolder+":"+toType+":SetNumber"),(USANSFolder+":"+fromType+":SetNumber") )
828
829                        endif
830                       
831                endif
832        endfor
833
834
835        //sort after all loaded - not by angle, but by Q
836// Get rid of the negative angles - the smearing integration does not like these!
837// (may add them back in later, but probably not)
838        UDoAngleSort("SIM")
839       
840        ConvertAngle2Qvals("SIM",0)
841       
842       
843       
844        //fill the data with something
845        WAVE qvals = root:Packages:NIST:USANS:SIM:qvals
846        WAVE DetCts = root:Packages:NIST:USANS:SIM:DetCts
847       
848
849        //find the Trans Cts for T_Wide
850//      FindTWideCts("EMP")
851
852//generate a "fake" 1d data folder/set named "Sim_USANS" that can be used for smearing
853// DOES NOT calculate a matrix, but instead fills 4-5-6 columns with -dQv
854// so that the trapezoid rule is used
855//     
856
857        FakeUSANSDataFolder(qvals,DetCts,0.117,"Sim_USANS")
858
859        // now calculate the smearing... instead of the counts
860        SVAR funcStr = root:Packages:NIST:USANS:Globals:U_Sim:gFuncStr          //set by the popup     
861       
862        Wave inten = root:Sim_USANS:Sim_USANS_i
863        Wave sigave = root:Sim_USANS:Sim_USANS_s
864        Wave countingTime = root:Sim_USANS:countingTime         //counting time per point in the set
865
866        Duplicate/O inten root:Sim_USANS:Smeared_inten          // a place for the smeared result for probabilities
867        Wave Smeared_inten = root:Sim_USANS:Smeared_inten
868
869        String coefStr=""
870        Variable sig_sas=0,wavelength = 2.4
871        Variable Imon
872       
873
874        NVAR omega = root:Packages:NIST:USANS:Globals:U_Sim:gAnalyzerOmega
875       
876        if(exists(funcStr) != 0)
877                FUNCREF SANSModelAAO_proto func=$("fSmeared"+funcStr)                   //a wrapper for the structure version
878                FUNCREF SANSModelAAO_proto funcUnsmeared=$(funcStr)             //unsmeared
879                coefStr = MC_getFunctionCoef(funcStr)
880               
881                if(!MC_CheckFunctionAndCoef(funcStr,coefStr))
882                        Abort "Function and coefficients do not match. You must plot the unsmeared function before simulation."
883                endif
884               
885                // do the smearing calculation
886                func($coefStr,Smeared_inten,qvals)
887
888
889                NVAR thick = root:Packages:NIST:USANS:Globals:U_Sim:gThick
890                NVAR trans = root:Packages:NIST:USANS:Globals:U_Sim:gSamTrans
891                NVAR SimDetCts = root:Packages:NIST:USANS:Globals:U_Sim:g_1DTotCts                      //summed counts (simulated)
892                NVAR estDetCR = root:Packages:NIST:USANS:Globals:U_Sim:g_1DEstDetCR                     // estimated detector count rate
893                NVAR fracScat = root:Packages:NIST:USANS:Globals:U_Sim:g_1DFracScatt            // fraction of beam captured on detector
894                NVAR estTrans = root:Packages:NIST:USANS:Globals:U_Sim:g_1DEstTrans             // estimated transmission of sample
895//              NVAR SimCountTime = root:Packages:NIST:USANS:Globals:U_Sim:gCntTime             //counting time used for simulation
896               
897                Imon = GetUSANSBeamIntensity()                          //based on the aperture size, select the beam intensity
898                Print "imon=",imon
899               
900                // calculate the scattering cross section simply to be able to estimate the transmission
901                // unfortunately, this calculation is useless in the USANS range. So although it's calculated, the
902                // results are never reported.
903                // -- the main issue is that the integration range is optimized for SANS, and is not useful for USANS
904                // -there are only a few points in the USANS range, and extending it lower caused issues before.
905                CalculateRandomDeviate(funcUnsmeared,$coefStr,wavelength,"root:Packages:NIST:SAS:ran_dev",sig_sas)
906
907                if(sig_sas > 100)
908                        DoAlert 0,"SAS cross section > 100. Estimates of multiple scattering are unreliable. Choosing a model with a well-defined Rg may help"
909                endif                   
910//              if(sig_sas > 100)
911//                      sprintf abortStr,"sig_sas = %g. Please check that the model coefficients have a zero background, or the low q is well-behaved.",sig_sas
912//              endif
913                // calculate the multiple scattering fraction for display (10/2009)
914                NVAR mScat = root:Packages:NIST:USANS:Globals:U_Sim:g_MultScattFraction
915                Variable nMax=10,tau
916                mScat=0
917                tau = thick*sig_sas
918                // this sums the normalized scattering P', so the result is the fraction of multiply coherently scattered
919                // neutrons out of those that were scattered
920                for(ii=2;ii<nMax;ii+=1)
921                        mScat += tau^(ii)/factorial(ii)
922        //              print tau^(ii)/factorial(ii)
923                endfor
924                estTrans = exp(-1*thick*sig_sas)                //thickness and sigma both in units of cm
925                mscat *= (estTrans)/(1-estTrans)
926               
927                if(mScat > 0.1)
928                        SetVariable valdisp0_2 win=UCALC,labelBack=(65535,32768,32768)
929                else
930                        SetVariable valdisp0_2 win=UCALC,labelBack=0
931                endif
932
933
934                Print "Sig_sas = ",sig_sas
935                Print "Estimated Transmission = ",estTrans
936               
937                Duplicate/O qvals prob_i
938                                       
939                prob_i = trans*thick*omega*Smeared_inten                        //probability of a neutron in q-bin(i)
940               
941//              Variable P_on = sum(prob_i,-inf,inf)
942//              Print "P_on = ",P_on
943                fracScat = 1-estTrans
944               
945                inten = (Imon*countingTime)*prob_i
946               
947                // do I round to an integer?
948                inten = round(inten)
949
950//              SimDetCts = sum(inten,-inf,inf)
951//              estDetCR = SimDetCts/SimCountTime
952               
953               
954                NVAR doABS = root:Packages:NIST:USANS:Globals:U_Sim:g_1D_DoABS
955                NVAR plotCR = root:Packages:NIST:USANS:Globals:U_Sim:g_1D_PlotCR
956                NVAR addNoise = root:Packages:NIST:USANS:Globals:U_Sim:g_1D_AddNoise
957                                       
958                sigave = sqrt(inten)            // assuming that N is large
959               
960                // add in random error in aveint based on the sigave
961                if(addNoise)
962                        inten += gnoise(sigave)
963                       
964                        //round to an integer again
965                        inten = round(inten)           
966                endif
967
968                // convert to absolute scale? Maybe not needed
969                // does nothing yet - need Ipeak, Twide
970//              if(doABS)
971//                      Variable kappa = thick*omega*trans*iMon*ctTime
972//                      inten /= kappa
973//                      inten /= kappa
974//              endif
975
976                // plot as countrate - maybe easier to visualize, and all of the data overlaps
977                if(plotCR)
978                        inten /= countingTime
979                        sigave /= countingTime
980                endif
981               
982                GraphSIM()
983
984        else
985                //no function plotted, no simulation can be done
986                DoAlert 0,"No function is selected or plotted, so no simulation is done. The default power law function is used."
987
988                inten = U_Power_Law_Model(1e-6,3,0,qvals)
989//              inten = U_SphereForm(1,9000,6e-6,0,qvals)               
990       
991                GraphSIM()
992
993        endif
994       
995
996end
997
998
999//sort the data in the "type"folder, based on angle
1000//carry along all associated waves
1001//
1002// ---a duplicate of DoAngleSort(), by modified to
1003// include counting time and setNumber
1004//
1005// also trims the beginning of each data set so that it does not include any negative or zero angles
1006//
1007Function UDoAngleSort(type)
1008        String type
1009       
1010        SVAR USANSFolder = root:Packages:NIST:USANS:Globals:gUSANSFolder
1011       
1012        Wave angle = $(USANSFolder+":"+Type+":Angle")
1013        Wave detCts = $(USANSFolder+":"+Type+":DetCts")
1014        Wave ErrdetCts = $(USANSFolder+":"+Type+":ErrDetCts")
1015        Wave MonCts = $(USANSFolder+":"+Type+":MonCts")
1016        Wave TransCts = $(USANSFolder+":"+Type+":TransCts")
1017        Wave countingTime = $(USANSFolder+":"+Type+":countingTime")
1018        Wave SetNumber = $(USANSFolder+":"+Type+":SetNumber")
1019       
1020        Sort Angle DetCts,ErrDetCts,MonCts,TransCts,Angle,countingTime,SetNumber
1021       
1022        Variable ii,num,numBad,ang,val
1023        num=numpnts(angle)
1024        ii=0
1025        numBad=0
1026        val = 0         //cutoff value
1027        do
1028                ang = angle[ii]
1029                if(ang <= val)
1030                        numBad += 1
1031                else            //keep the points
1032                        Angle[ii-numBad] = ang
1033                        DetCts[ii-numBad] = DetCts[ii]
1034                        ErrDetCts[ii-numBad] = ErrDetCts[ii]
1035                        MonCts[ii-numBad] = MonCts[ii]
1036                        TransCts[ii-numBad] = TransCts[ii]
1037                        countingTime[ii-numBad] = countingTime[ii]
1038                        SetNumber[ii-numBad] = SetNumber[ii]
1039                endif
1040                ii += 1
1041        while(ii<num)
1042        //trim the end of the waves
1043        DeletePoints num-numBad, numBad, DetCts,ErrDetCts,MonCts,TransCts,Angle,countingTime,SetNumber
1044       
1045       
1046        return(0)
1047End
1048
1049// a simple default function
1050//
1051Function U_SphereForm(scale,radius,delrho,bkg,x)                               
1052        Variable scale,radius,delrho,bkg
1053        Variable x
1054       
1055        // variables are:                                                       
1056        //[0] scale
1057        //[1] radius (A)
1058        //[2] delrho (A-2)
1059        //[3] background (cm-1)
1060
1061       
1062        // calculates scale * f^2/Vol where f=Vol*3*delrho*((sin(qr)-qrcos(qr))/qr^3
1063        // and is rescaled to give [=] cm^-1
1064       
1065        Variable bes,f,vol,f2
1066        //
1067        //handle q==0 separately
1068        If(x==0)
1069                f = 4/3*pi*radius^3*delrho*delrho*scale*1e8 + bkg
1070                return(f)
1071        Endif
1072       
1073        bes = 3*(sin(x*radius)-x*radius*cos(x*radius))/x^3/radius^3
1074        vol = 4*pi/3*radius^3
1075        f = vol*bes*delrho              // [=] A
1076        // normalize to single particle volume, convert to 1/cm
1077        f2 = f * f / vol * 1.0e8                // [=] 1/cm
1078       
1079        return (scale*f2+bkg)   // Scale, then add in the background
1080       
1081End
1082
1083// better default function
1084Function U_Power_Law_Model(A,m,bgd,x) : FitFunc
1085        Variable A, m,bgd,x
1086//       Input (fitting) variables are:
1087        //[0] Coefficient
1088        //[1] (-) Power
1089        //[2] incoherent background
1090       
1091//      local variables
1092        Variable inten, qval
1093//      x is the q-value for the calculation
1094        qval = x
1095//      do the calculation and return the function value
1096       
1097        inten = A*qval^-m + bgd
1098        Return (inten)
1099End
1100
1101
1102// mimics LoadBT5File
1103// creates two other waves to identify the set and the counting time for that set
1104//
1105Function LoadSimulatedAngleRange(set,type)
1106        Variable set
1107        String type
1108
1109        SVAR USANSFolder = root:Packages:NIST:USANS:Globals:gUSANSFolder
1110       
1111        String s=num2str(set)
1112        NVAR angLow = $("root:Packages:NIST:USANS:Globals:U_Sim:gAngLow"+s)
1113        NVAR angHigh = $("root:Packages:NIST:USANS:Globals:U_Sim:gAngHigh"+s)
1114        NVAR numPts = $("root:Packages:NIST:USANS:Globals:U_Sim:gNumPts"+s)
1115        NVAR ctTime = $("root:Packages:NIST:USANS:Globals:U_Sim:gCtTime"+s)
1116        NVAR incr = $("root:Packages:NIST:USANS:Globals:U_Sim:gIncr"+s)
1117       
1118        Variable ii, err=0
1119       
1120        // generate q-points based on angular range from panel
1121       
1122        Make/O/D/N=(numPts) $(USANSFolder+":"+type+":Angle")
1123        Make/O/D/N=(numPts) $(USANSFolder+":"+type+":DetCts")
1124        Make/O/D/N=(numPts) $(USANSFolder+":"+type+":ErrDetCts")
1125        Make/O/D/N=(numPts) $(USANSFolder+":"+type+":MonCts")
1126        Make/O/D/N=(numPts) $(USANSFolder+":"+type+":TransCts")
1127        //
1128        Make/O/D/N=(numPts) $(USANSFolder+":"+type+":CountingTime")
1129        Make/O/D/N=(numPts) $(USANSFolder+":"+type+":SetNumber")
1130       
1131        Wave Angle = $(USANSFolder+":"+type+":Angle")
1132        Wave DetCts = $(USANSFolder+":"+type+":DetCts")
1133        Wave ErrDetCts = $(USANSFolder+":"+type+":ErrDetCts")
1134        Wave MonCts = $(USANSFolder+":"+type+":MonCts")
1135        Wave TransCts = $(USANSFolder+":"+type+":TransCts")
1136        Wave countingTime = $(USANSFolder+":"+type+":countingTime")
1137        Wave SetNumber = $(USANSFolder+":"+type+":SetNumber")
1138       
1139        countingTime = ctTime
1140        SetNumber = set
1141       
1142        for(ii=0;ii<numPts;ii+=1)
1143                Angle[ii] = angLow + ii*incr
1144                DetCts[ii] = set
1145        endfor
1146       
1147        //set the wave note for the DetCts
1148        String str=""
1149        str = "FILE:Sim "+s+";"
1150        str += "TIMEPT:"+num2str(ctTime)+";"
1151        str += "PEAKANG:0;"             //no value yet
1152        str += "STATUS:;"               //no value yet
1153        str += "LABEL:SimSet "+s+";"
1154        str += "PEAKVAL:;"              //no value yet
1155        str += "TWIDE:0;"               //no value yet
1156        Note DetCts,str
1157       
1158        return err                      // Zero signifies no error.     
1159End
1160
1161// add SIM data to the graph if it exists and is not already on the graph
1162//
1163//
1164// ** currently, I have changed the graph to not display the angle at the top. I have not yet
1165// found a way to keep the scaling of the two axes in-sync when the empty cell data is added to the
1166// graph (versus Q)
1167//
1168Function GraphSIM()
1169
1170//      SVAR USANSFolder = root:Packages:NIST:USANS:Globals:gUSANSFolder
1171//      SetDataFolder $(USANSFolder+":SIM")
1172
1173        SetDataFolder root:Sim_USANS
1174        //is it already on the graph?
1175        String list=""
1176        list = Wavelist("Sim_USANS*",";","WIN:UCALC")
1177       
1178        if(strlen(list)!=0)
1179//              Print "SIM already on graph"
1180                SetDataFolder root:
1181                return(0)
1182        Endif
1183       
1184        //append the data if it exists
1185        If(waveExists($"Sim_USANS_i")==1)
1186                DoWindow/F UCALC
1187
1188// lines for the no-noise result vs angle
1189//              AppendToGraph/T Smeared_inten vs angle
1190                AppendToGraph Smeared_inten vs Sim_USANS_q
1191                ModifyGraph rgb(Smeared_inten)=(1,12815,52428)
1192                ModifyGraph mode(Smeared_inten)=4,marker(Smeared_inten)=19,msize(Smeared_inten)=2
1193                ModifyGraph tickUnit=1
1194
1195// colored points for the simulation with noise on top
1196                AppendToGraph Sim_USANS_i vs Sim_USANS_q
1197                ModifyGraph mode(Sim_USANS_i)=3,marker(Sim_USANS_i)=19,msize(Sim_USANS_i)=4
1198                //don't reverse the dbZ21 or the highest angle will have "invisible" light blue error bars
1199                ModifyGraph zColor(Sim_USANS_i)={setNumber,1,7,dBZ21,0}                         //better for 7 colors
1200//              ModifyGraph zColor(Sim_USANS_i)={setNumber,1,7,Rainbow,0}                       //force the colors from 1->7
1201                ModifyGraph useMrkStrokeRGB(Sim_USANS_i)=1
1202                ErrorBars/T=0 Sim_USANS_i Y,wave=(Sim_USANS_s,Sim_USANS_s)
1203               
1204                ModifyGraph log=1
1205                ModifyGraph mirror(left)=1
1206                // if no top axis, then
1207//              ModifyGraph mirror(bottom)=1
1208                ModifyGraph grid=2
1209                ModifyGraph standoff=0
1210               
1211                // to make sure that the scales are the same (but fails on zoom)
1212                NewFreeAxis/O/T top_angle
1213                ModifyFreeAxis/Z top_angle,master= bottom,hook= TransformAngleAxisHook
1214                ModifyGraph lblPos(top_angle)=50,freePos(top_angle)=0
1215                ModifyGraph log(top_angle)=1
1216               
1217                SetDrawEnv linefgc= (39321,1,1),dash= 3,linethick= 3
1218                SetDrawEnv xcoord= bottom
1219                DrawLine 3e-05,0.01,3e-05,0.99
1220               
1221                Label top_angle "Angle"
1222                Label bottom "Q (1/A)"
1223                Label left "Counts or Count Rate"
1224               
1225                Legend
1226        endif
1227       
1228        SetDataFolder root:
1229End
1230
1231Function TransformAngleAxisHook(s)
1232        STRUCT WMAxisHookStruct &s
1233
1234        s.max= s.max/5.55e-5
1235        s.min= s.min/5.55e-5
1236       
1237        return 0
1238End
1239
1240//fakes a folder with loaded 1-d usans data, no calculation of the matrix
1241Function        FakeUSANSDataFolder(qval,aveint,dqv,dataFolder)
1242        WAVE qval,aveint
1243        Variable dqv
1244        String dataFolder
1245       
1246
1247        String baseStr=dataFolder
1248        if(DataFolderExists("root:"+baseStr))
1249                SetDataFolder $("root:"+baseStr)
1250        else
1251                NewDataFolder/S $("root:"+baseStr)
1252        endif
1253
1254        ////overwrite the existing data, if it exists
1255        Duplicate/O qval, $(baseStr+"_q")
1256        Duplicate/O aveint, $(baseStr+"_i")
1257       
1258        Duplicate/O qval, $(baseStr+"_s")
1259        Wave sigave = $(baseStr+"_s")
1260
1261        sigave = sqrt(aveint)
1262
1263        // make a resolution matrix for SANS data
1264        Variable np=numpnts(qval)
1265        Make/D/O/N=(np,4) $(baseStr+"_res")
1266        Wave res=$(baseStr+"_res")
1267       
1268        res[][0] = -dQv         //sigQ
1269        res[][1] = -dQv         //qBar
1270        res[][2] = -dQv         //fShad
1271        res[][3] = qval[p]              //Qvalues
1272       
1273        // extra waves of set number and counting time for the simulation
1274        WAVE ctW = root:Packages:NIST:USANS:SIM:countingTime
1275        WAVE setW = root:Packages:NIST:USANS:SIM:setNumber
1276        WAVE ang = root:Packages:NIST:USANS:SIM:Angle
1277        Duplicate/O ctW countingTime
1278        Duplicate/O setW setNumber
1279        Duplicate/O ang Angle
1280
1281
1282        //clean up             
1283        SetDataFolder root:
1284       
1285End
1286
1287
1288Function/S U_FunctionPopupList()
1289        String list,tmp
1290        list = User_FunctionPopupList()
1291       
1292        //simplify the display, forcing smeared calculations behind the scenes
1293        tmp = FunctionList("Smear*",";","NPARAMS:1")    //smeared dependency calculations
1294        list = RemoveFromList(tmp, list ,";")
1295
1296
1297        if(strlen(list)==0)
1298                list = "No functions plotted"
1299        endif
1300       
1301        list = SortList(list)
1302       
1303        return(list)
1304End     
1305
1306Function Sim_USANS_ModelPopMenuProc(pa) : PopupMenuControl
1307        STRUCT WMPopupAction &pa
1308
1309        switch( pa.eventCode )
1310                case 2: // mouse up
1311                        Variable popNum = pa.popNum
1312                        String popStr = pa.popStr
1313                        SVAR gStr = root:Packages:NIST:USANS:Globals:U_Sim:gFuncStr
1314                        gStr = popStr
1315                       
1316                        break
1317        endswitch
1318
1319        return 0
1320End         
1321
1322// if the sample aperture is changed, AND the empty data is displayed, change to the proper data
1323Function UCALC_SampleAperturePopup(pa) : PopupMenuControl
1324        STRUCT WMPopupAction &pa
1325
1326        switch( pa.eventCode )
1327                case 2: // mouse up
1328                        Variable popNum = pa.popNum
1329                        String popStr = pa.popStr
1330
1331                        ControlInfo/W=UCALC check0_4
1332                        if(V_Value==1)          //currently checked, need to update
1333                               
1334                                STRUCT WMCheckboxAction cba
1335                                cba.checked=0           //"un-check"
1336                                cba.eventCode=2
1337                                ShowEMPCheckProc(cba)
1338                               
1339                                cba.checked=1           //"re-check"
1340                                ShowEMPCheckProc(cba)
1341                       
1342                        endif
1343                        break
1344                       
1345        endswitch
1346       
1347        return 0
1348End 
1349
1350
1351Function UCALC_PresetPopup(pa) : PopupMenuControl
1352        STRUCT WMPopupAction &pa
1353
1354        switch( pa.eventCode )
1355                case 2: // mouse up
1356                        Variable popNum = pa.popNum
1357                        String popStr = pa.popStr
1358
1359                        SetDataFolder root:Packages:NIST:USANS:Globals:U_Sim
1360                       
1361                        NVAR gAngLow1 = gAngLow1
1362                        NVAR gAngHigh1 = gAngHigh1
1363                        NVAR gNumPts1 = gNumPts1
1364                        NVAR gCtTime1 = gCtTime1
1365                        NVAR gIncr1 = gIncr1
1366                       
1367                        NVAR gAngLow2 = gAngLow2
1368                        NVAR gAngHigh2 = gAngHigh2
1369                        NVAR gNumPts2 = gNumPts2
1370                        NVAR gCtTime2 = gCtTime2
1371                        NVAR gIncr2 = gIncr2
1372                       
1373                        NVAR gAngLow3 = gAngLow3
1374                        NVAR gAngHigh3 = gAngHigh3
1375                        NVAR gNumPts3 = gNumPts3
1376                        NVAR gCtTime3 = gCtTime3
1377                        NVAR gIncr3 = gIncr3
1378                       
1379                        NVAR gAngLow4 = gAngLow4
1380                        NVAR gAngHigh4 = gAngHigh4
1381                        NVAR gNumPts4 = gNumPts4
1382                        NVAR gCtTime4 = gCtTime4
1383                        NVAR gIncr4 = gIncr4
1384                       
1385                        NVAR gAngLow5 = gAngLow5
1386                        NVAR gAngHigh5 = gAngHigh5
1387                        NVAR gNumPts5 = gNumPts5
1388                        NVAR gCtTime5 = gCtTime5
1389                        NVAR gIncr5 = gIncr5
1390                       
1391                        NVAR gAngLow6 = gAngLow6
1392                        NVAR gAngHigh6 = gAngHigh6
1393                        NVAR gNumPts6 = gNumPts6
1394                        NVAR gCtTime6 = gCtTime6
1395                        NVAR gIncr6 = gIncr6
1396                       
1397                        NVAR gAngLow7 = gAngLow7
1398                        NVAR gAngHigh7 = gAngHigh7
1399                        NVAR gNumPts7 = gNumPts7
1400                        NVAR gCtTime7 = gCtTime7
1401                        NVAR gIncr7 = gIncr7
1402                       
1403                        strswitch(popStr)       // string switch
1404                                case "Short Count":             // execute if case matches expression
1405                                       
1406                                        gAngLow1 = -1
1407                                        gAngHigh1 = 0.6
1408                                        gNumPts1 = 33
1409                                        gCtTime1 = 10
1410                                        gIncr1 = 0.05   
1411                                       
1412                                        gAngLow2 = 0.7
1413                                        gAngHigh2 = 1.9
1414                                        gNumPts2 = 6
1415                                        gCtTime2 = 60
1416                                        gIncr2 = 0.2   
1417                                       
1418                                        gAngLow3 = 2
1419                                        gAngHigh3 = 4.8
1420                                        gNumPts3 = 7
1421                                        gCtTime3 = 120
1422                                        gIncr3 = 0.4   
1423                                       
1424                                        gAngLow4 = 5
1425                                        gAngHigh4 = 9.5
1426                                        gNumPts4 = 5
1427                                        gCtTime4 = 180
1428                                        gIncr4 = 0.9   
1429                                       
1430                                        gAngLow5 = 10
1431                                        gAngHigh5 = 19
1432                                        gNumPts5 = 5
1433                                        gCtTime5 = 240
1434                                        gIncr5 = 1.8
1435                                       
1436                                        gAngLow6 = 20
1437                                        gAngHigh6 = 48
1438                                        gNumPts6 = 15
1439                                        gCtTime6 = 0
1440                                        gIncr6 = 2
1441                                       
1442                                        gAngLow7 = 50
1443                                        gAngHigh7 = 95
1444                                        gNumPts7 = 10
1445                                        gCtTime7 = 0
1446                                        gIncr7 = 5
1447                                       
1448                                        break                                           
1449                                case "Medium Count":   
1450                       
1451                                        gAngLow1 = -1
1452                                        gAngHigh1 = 0.6
1453                                        gNumPts1 = 33
1454                                        gCtTime1 = 20
1455                                        gIncr1 = 0.05   
1456                                       
1457                                        gAngLow2 = 0.7
1458                                        gAngHigh2 = 1.9
1459                                        gNumPts2 = 13
1460                                        gCtTime2 = 50
1461                                        gIncr2 = 0.1   
1462                                       
1463                                        gAngLow3 = 2
1464                                        gAngHigh3 = 4.8
1465                                        gNumPts3 = 15
1466                                        gCtTime3 = 100
1467                                        gIncr3 = 0.2   
1468                                       
1469                                        gAngLow4 = 5
1470                                        gAngHigh4 = 9.5
1471                                        gNumPts4 = 10
1472                                        gCtTime4 = 200
1473                                        gIncr4 = 0.5   
1474                                       
1475                                        gAngLow5 = 10
1476                                        gAngHigh5 = 19
1477                                        gNumPts5 = 10
1478                                        gCtTime5 = 500
1479                                        gIncr5 = 1
1480                                       
1481                                        gAngLow6 = 20
1482                                        gAngHigh6 = 48
1483                                        gNumPts6 = 15
1484                                        gCtTime6 = 1000
1485                                        gIncr6 = 2     
1486                                       
1487                                        gAngLow7 = 50
1488                                        gAngHigh7 = 95
1489                                        gNumPts7 = 10
1490                                        gCtTime7 = 0
1491                                        gIncr7 = 5
1492                                                               
1493                                        break
1494                                case "Long Count":     
1495                                       
1496                                        gAngLow1 = -1
1497                                        gAngHigh1 = 0.6
1498                                        gNumPts1 = 33
1499                                        gCtTime1 = 25
1500                                        gIncr1 = 0.05   
1501                                       
1502                                        gAngLow2 = 0.7
1503                                        gAngHigh2 = 1.9
1504                                        gNumPts2 = 13
1505                                        gCtTime2 = 100
1506                                        gIncr2 = 0.1   
1507                                       
1508                                        gAngLow3 = 2
1509                                        gAngHigh3 = 4.8
1510                                        gNumPts3 = 15
1511                                        gCtTime3 = 300
1512                                        gIncr3 = 0.2   
1513                                       
1514                                        gAngLow4 = 5
1515                                        gAngHigh4 = 9.5
1516                                        gNumPts4 = 10
1517                                        gCtTime4 = 600
1518                                        gIncr4 = 0.5   
1519                                       
1520                                        gAngLow5 = 10
1521                                        gAngHigh5 = 19
1522                                        gNumPts5 = 10
1523                                        gCtTime5 = 1200
1524                                        gIncr5 = 1
1525                                       
1526                                        gAngLow6 = 20
1527                                        gAngHigh6 = 48
1528                                        gNumPts6 = 15
1529                                        gCtTime6 = 2000
1530                                        gIncr6 = 2
1531                                       
1532                                        gAngLow7 = 50
1533                                        gAngHigh7 = 95
1534                                        gNumPts7 = 10
1535                                        gCtTime7 = 3000
1536                                        gIncr7 = 5
1537                                       
1538                                        break
1539                                default:                       
1540                        endswitch
1541                       
1542                        break
1543        endswitch
1544
1545        //update the count time
1546        CalcTotalCountTime()
1547
1548        SetDataFolder root:
1549       
1550        return 0
1551End     
1552
1553
1554// return the beam intensity based on the sample aperture diameter
1555//
1556// based on the equation in John's instrument paper
1557//
1558Function GetUSANSBeamIntensity()       
1559
1560        String popStr
1561        Variable flux,diam,rad
1562       
1563        ControlInfo/W=UCALC popup0
1564        popStr = S_Value
1565        diam=str2num(popStr)            //in inches
1566        rad = diam/2*25.4                       //radius in mm
1567       
1568        flux = 662*rad*rad-39.9*rad*rad*rad+0.70*rad*rad*rad*rad
1569       
1570        return(flux)
1571End
1572
1573// based on the angle ranges above (with non-zero count times)
1574// save fake data points into a fake BT5 data file
1575//
1576Function U_SaveButtonProc(ba) : ButtonControl
1577        STRUCT WMButtonAction &ba
1578
1579       
1580        switch( ba.eventCode )
1581                case 2: // mouse up
1582                        // click code here
1583                       
1584                        Variable num,ii,baseNumber=101,firstSet=0
1585                        String pathStr="root:Packages:NIST:USANS:Globals:U_Sim:gCtTime"
1586                        SVAR USANSFolder = root:Packages:NIST:USANS:Globals:gUSANSFolder
1587                        String baseName="SIMUL"
1588                       
1589                        num = 7                 //# of angular ranges
1590                       
1591                        // only try to plot ranges with non-zero count times
1592                        firstSet=0
1593                        for(ii=1;ii<=num;ii+=1)
1594                                NVAR dum = $(pathStr+num2str(ii))
1595                                if(dum>0)                                               
1596                                        firstSet += 1
1597                                        if(firstSet==1) //first time, ask for base name
1598                                                Prompt baseName,"Enter a base name for the files"
1599                                                Prompt baseNumber,"Enter the starting index"
1600                                                DoPrompt "Enter Information for Save",baseName,baseNumber
1601                                               
1602                                                if(V_Flag==1)           //user canceled
1603                                                        return(1)
1604                                                endif
1605                                        endif
1606                                               
1607                                        SaveFakeUSANS(baseName,baseNumber-1,ii)
1608                                       
1609                                endif
1610                        endfor
1611                       
1612                        // no save the fake "COR" file that is the combination and rescaling of the data sets
1613                        // - the combination is in root:Sim_USANS:
1614                        NVAR g_1D_PlotCR = root:Packages:NIST:USANS:Globals:U_Sim:g_1D_PlotCR
1615
1616                        if(g_1D_PlotCR) // right now, save COR only if the CR is plotted
1617                                SaveFakeCOR(baseName)                   
1618                        endif
1619                       
1620                        break
1621        endswitch
1622
1623        return 0
1624End
1625
1626
1627Function SaveFakeCOR(nameStr)
1628        String nameStr
1629       
1630        NVAR gThick = root:Packages:NIST:USANS:Globals:U_Sim:gThick
1631        NVAR gSamTrans = root:Packages:NIST:USANS:Globals:U_Sim:gSamTrans
1632        NVAR gAnalyzerOmega = root:Packages:NIST:USANS:Globals:U_Sim:gAnalyzerOmega
1633        NVAR g_MultScattFraction = root:Packages:NIST:USANS:Globals:U_Sim:g_MultScattFraction
1634        SVAR funcStr = root:Packages:NIST:USANS:Globals:U_Sim:gFuncStr
1635       
1636        String folder = "root:Sim_USANS:",fileStr=""
1637        String termStr="\r\n"           //VAX uses only <CR> as terminator, but only CRLF seems to FTP correctly to VAX
1638        String destStr="",formatStr = "%15.6g %15.6g %15.6g %15.6g %15.6g %15.6g"+termStr
1639
1640        Variable refNum,integer,realval
1641        //*****these waves MUST EXIST, or IGOR Pro will crash, with a type 2 error****
1642        WAVE qvals =$(folder + "Sim_USANS_q")
1643        WAVE inten=$(folder + "Sim_USANS_i")
1644        WAVE sig=$(folder + "Sim_USANS_s")
1645       
1646        //check each wave
1647        If(!(WaveExists(qvals)))
1648                Abort "qvals DNExist in SaveFakeCOR()"
1649        Endif
1650        If(!(WaveExists(inten)))
1651                Abort "inten DNExist in SaveFakeCOR()"
1652        Endif
1653        If(!(WaveExists(sig)))
1654                Abort "sig DNExist in SaveFakeCOR()"
1655        Endif
1656       
1657        //dummy wave for the resolution
1658        Duplicate/O qvals,dumWave
1659        SVAR USANSFolder = root:Packages:NIST:USANS:Globals:gUSANSFolder
1660        NVAR DQv=$(USANSFolder+":Globals:MainPanel:gDQv")
1661        dumWave = - DQv
1662       
1663        //temp waves for the rescaling
1664        Duplicate/O qvals,tq,ti,te
1665        ti=inten
1666        te=sig
1667        tq=qvals
1668
1669        //rescale
1670        ti *= 1.0e6 / GetUSANSBeamIntensity()           //converts to "SAM" scaled data
1671        ti *= 1/(gSamTrans*gThick*gAnalyzerOmega*1.0e6)         //converts to "COR" scaling (approx, since I don't know Twide)
1672        //rescale error appropriately too
1673        te *= 1.0e6 / GetUSANSBeamIntensity()           //converts to "SAM" scaled data
1674        te *= 1/(gSamTrans*gThick*gAnalyzerOmega*1.0e6)         //converts to "COR" scaling (approx, since I don't know Twide)
1675
1676        // add fake error to every few data points to mark it as simulated data
1677        te[2,numpnts(te)-1;7] *= 10
1678       
1679        // now trim off the q-values less than 3e-5
1680        if(tq[0] < 3e-5)
1681                do
1682                        DeletePoints 0, 1, ti,tq,te,dumWave
1683                while(tq[0] < 3e-5)
1684        endif
1685       
1686        String samStr="",empStr="",dateStr="",samLabelStr="",paramStr="",empLevStr="",bkgLevStr="",pkStr=""
1687        samStr = "SIM FILES: "+StringByKey("FILE",note(inten),":",";")
1688        empStr = "EMP FILES: "+"none"
1689        empLevStr = "EMP LEVEL: " + "none"
1690        bkgLevStr = "BKG LEVEL: " + "not used"
1691        paramStr = "Ds = "+num2str(gthick)+" cm ; "
1692        paramStr += "Twide = "+"unknown"+" ; "
1693        paramStr += "Trock = "+num2str(gSamTrans)       
1694        pkStr += "Multiple coherent scattering fraction: "+num2str(g_MultScattFraction)
1695       
1696        //these strings are always the same
1697        samLabelStr ="LABEL: "+"Simulated USANS Data from: "+funcStr
1698        dateStr = date()+" at  "+time()// + " "+Secs2Time(DateTime,2)
1699       
1700       
1701        fileStr=nameStr+".cor"
1702        //actually open the file
1703        PathInfo savePathName
1704        if(V_flag==1)
1705                Open/P=savePathName refNum as fileStr
1706        else
1707                Open refNum as fileStr
1708        endif
1709       
1710        fprintf refnum,"%s"+termStr,samStr
1711        fprintf refnum,"%s"+termStr,dateStr
1712        fprintf refnum,"%s"+termStr,samLabelStr
1713        fprintf refnum,"%s"+termStr,empStr
1714        fprintf refnum,"%s"+termStr,paramStr
1715        fprintf refnum,"%s"+termStr,pkStr
1716        fprintf refnum,"%s"+termStr,empLevStr + " ; "+bkglevStr
1717       
1718        //
1719        wfprintf refnum, formatStr, tq,ti,te,dumWave,dumWave,dumWave
1720       
1721        Close refnum
1722       
1723        Killwaves/Z dumWave,ti,te,tq
1724       
1725       
1726       
1727        return(0)
1728End
1729
1730
1731//
1732// duplicates the BT5 file format
1733//
1734Function SaveFakeUSANS(nameStr,num,set)
1735        String nameStr
1736        Variable num,set
1737               
1738        String folder = "root:Packages:NIST:USANS:SIM:"
1739        String pathStr="root:Packages:NIST:USANS:Globals:U_Sim:"
1740        String termStr="\r\n"           //VAX uses only <CR> as terminator, but only CRLF seems to FTP correctly to VAX
1741       
1742//      WAVE DetCts = $(folder+"DetCts")                //these are only dummy values
1743        WAVE DetCts = root:Sim_USANS:Sim_USANS_i
1744        WAVE angle = $(folder+"Angle")
1745        WAVE SetNumber = $(folder+"SetNumber")
1746        WAVE countingTime = $(folder+"countingTime")
1747       
1748        NVAR ang1 = $(pathStr+"gAngLow"+num2str(set))
1749        NVAR ang2 = $(pathStr+"gAngHigh"+num2str(set))
1750        NVAR incr = $(pathStr+"gIncr"+num2str(set))
1751        SVAR ext = root:Packages:NIST:USANS:Globals:MainPanel:gUExt
1752
1753       
1754        Variable refNum,ii,wavePts,numPts,first,last,ctTime,monCt,transDet
1755        String str,fileStr,dateStr
1756       
1757        wavePts = numpnts(angle)
1758        for(ii=0;ii<wavePts;ii+=1)
1759                if(setNumber[ii] == set)
1760                        first = ii
1761                        break
1762                endif
1763        endfor
1764               
1765        for(ii=wavePts-1;ii>=0;ii-=1)
1766                if(setNumber[ii] == set)
1767                        last = ii
1768                        break
1769                endif
1770        endfor
1771       
1772//      Print "First, last = ",first,last
1773       
1774        // set up some of the strings needed
1775        fileStr=nameStr+num2str(num+set)+ext
1776        dateStr = date()
1777        ctTime = countingTime[first]
1778        numPts = last-first+1
1779       
1780        MonCt = ctTime*GetUSANSBeamIntensity()
1781       
1782        transDet = 999          //bogus and constant value
1783               
1784        //actually open the file
1785        PathInfo savePathName
1786        if(V_flag==1)
1787                Open/P=savePathName refNum as fileStr
1788        else
1789                Open refNum as fileStr
1790        endif
1791       
1792        sprintf str,"'%s' '%s' 'I'        %d    1  'TIME'   %d  'RAW'",fileStr,dateStr,ctTime,numpts
1793        fprintf refnum,"%s"+termStr,str
1794        fprintf refnum,"%s"+termStr,"  Filename         Date            Scan       Mon    Prf  Base   #pts  Type"
1795       
1796        fprintf refnum,"Simulated USANS data"+termStr
1797
1798        fprintf refnum,"%s"+termStr,"   0    0    0    0   0  0  0     0.0000     0.00000 0.00000   0.00000    2"
1799        fprintf refnum,"%s"+termStr," Collimation      Mosaic    Wavelength   T-Start   Incr.   H-field #Det    "
1800        fprintf refnum,"%s"+termStr,"  1       0.00000    0.00000    0.00000"
1801        fprintf refnum,"  2       %9.5f    %9.5f    %9.5f"+termStr,ang1,incr,ang2
1802        fprintf refnum,"%s"+termStr,"  3      10.00000    0.00000   10.00000"
1803        fprintf refnum,"%s"+termStr,"  4      10.00000    0.00000   10.00000"
1804        fprintf refnum,"%s"+termStr,"  5       0.00000    0.00000    0.00000"
1805        fprintf refnum,"%s"+termStr,"  6       0.00000    0.00000    0.00000"
1806        fprintf refnum,"%s"+termStr," Mot:    Start       Step      End"
1807        fprintf refnum,"%s"+termStr,"     A2       MIN      MONITOR      COUNTS      EXTRA  "
1808
1809        //loop over the waves, picking out the desired set
1810        //write 2 lines each time
1811        for(ii=first;ii<=last;ii+=1)
1812                sprintf str,"      %6.3f    %6.2f    %d     %d     %d",angle[ii],ctTime/60,MonCt,DetCts[ii]*ctTime,transDet
1813                fprintf refnum,"%s"+termStr,str
1814
1815                sprintf str,"%d,%d,0,%d,0,0,0,0",MonCt,DetCts[ii]*ctTime,transDet
1816                fprintf refnum,"%s"+termStr,str
1817        endfor
1818       
1819        Close refnum
1820
1821        return(0)
1822end
1823
1824
1825// print out the USANS configuration in some reasonable format
1826Function/S USANSConfigurationText()
1827
1828        String str="",temp
1829
1830        SetDataFolder root:Packages:NIST:USANS:Globals:U_Sim
1831       
1832        // results, setup values
1833        SVAR gTotTimeStr=gTotTimeStr
1834       
1835        Variable ii,num
1836        String pathStr="root:Packages:NIST:USANS:Globals:U_Sim:"
1837        num=7
1838       
1839        str += "USANS Instrument Configuration:\r\r"
1840        str += "Theta Min  Theta Max   Increment   # Points   Count Time\r"
1841       
1842       
1843        for(ii=1;ii<=num;ii+=1)
1844                NVAR ctTime = $(pathStr+"gCtTime"+num2str(ii))
1845                if(ctTime>0)
1846                        NVAR angLow = $(pathStr+"gAngLow"+num2str(ii))
1847                        NVAR angHigh = $(pathStr+"gAngHigh"+num2str(ii))
1848                        NVAR incr = $(pathStr+"gIncr"+num2str(ii))
1849                        NVAR numPts = $(pathStr+"gNumPts"+num2str(ii))
1850                       
1851                        sprintf temp,"%9.3f  %9.3f  %9.3f  %9d  %9d\r",angLow,angHigh,incr,numPts,ctTime
1852                        str += temp
1853                endif
1854        endfor
1855       
1856       
1857        sprintf temp,"\r\rTotal Counting Time (HR:MIN) = %s\r",gTotTimeStr
1858        str += temp
1859
1860       
1861   setDataFolder root:
1862   return str                   
1863End
1864
1865Function DisplayUCALCText()
1866
1867        if(WinType("USANS_Configuration")==0)
1868                NewNotebook/F=0/K=1/N=USANS_Configuration /W=(480,44,880,369)
1869        endif
1870        //replace the text
1871        Notebook USANS_Configuration selection={startOfFile, endOfFile}
1872        Notebook USANS_Configuration font="Monaco",fSize=10,text=USANSConfigurationText()
1873        return(0)
1874end
1875
1876
1877//
1878Function U_ConfigTextProc(ba) : ButtonControl
1879        STRUCT WMButtonAction &ba
1880
1881       
1882        switch( ba.eventCode )
1883                case 2: // mouse up
1884                        // click code here
1885                       
1886                                DisplayUCALCText()                                     
1887                        break
1888        endswitch
1889
1890        return 0
1891End
1892
1893// this will save a graphic of the whole panel that then needs to be opened and printed
1894// must be a PNG @ screen resolution
1895//
1896Function U_SavePanelProc(ba) : ButtonControl
1897        STRUCT WMButtonAction &ba
1898
1899       
1900        switch( ba.eventCode )
1901                case 2: // mouse up
1902                        // click code here
1903                       
1904                        SavePICT/P=home/E=-5/B=72/SNAP=1       
1905                       
1906                        // can I reload and print?
1907                        // how will the users know where this went and what to do with it?
1908                        //                     
1909                        break
1910        endswitch
1911
1912        return 0
1913End
Note: See TracBrowser for help on using the repository browser.