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

Last change on this file since 795 was 704, checked in by srkline, 13 years ago

Added flag /MAT on GenCurveFit? to actially generate the W_sigma error estimates and passed the values of the "V_" variables back to the wrapper for display and reports.

Changed how the USANS simulator calculates the number of points from the range and increment to match what is actually done on USANS.

File size: 58.7 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 = 25
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 = 100
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 = 300
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 = 600
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 = 1200
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 = 2000
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 = 3000
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=3,popvalue="Long 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//                      sprintf abortStr,"sig_sas = %g. Please check that the model coefficients have a zero background, or the low q is well-behaved.",sig_sas
909//              endif
910                // calculate the multiple scattering fraction for display (10/2009)
911                NVAR mScat = root:Packages:NIST:USANS:Globals:U_Sim:g_MultScattFraction
912                Variable nMax=10,tau
913                mScat=0
914                tau = thick*sig_sas
915                // this sums the normalized scattering P', so the result is the fraction of multiply coherently scattered
916                // neutrons out of those that were scattered
917                for(ii=2;ii<nMax;ii+=1)
918                        mScat += tau^(ii)/factorial(ii)
919        //              print tau^(ii)/factorial(ii)
920                endfor
921                estTrans = exp(-1*thick*sig_sas)                //thickness and sigma both in units of cm
922                mscat *= (estTrans)/(1-estTrans)
923               
924                if(mScat > 0.1)
925                        SetVariable valdisp0_2 win=UCALC,labelBack=(65535,32768,32768)
926                else
927                        SetVariable valdisp0_2 win=UCALC,labelBack=0
928                endif
929
930
931                Print "Sig_sas = ",sig_sas
932               
933               
934                Duplicate/O qvals prob_i
935                                       
936                prob_i = trans*thick*omega*Smeared_inten                        //probability of a neutron in q-bin(i)
937               
938//              Variable P_on = sum(prob_i,-inf,inf)
939//              Print "P_on = ",P_on
940                fracScat = 1-estTrans
941               
942                inten = (Imon*countingTime)*prob_i
943               
944                // do I round to an integer?
945                inten = round(inten)
946
947//              SimDetCts = sum(inten,-inf,inf)
948//              estDetCR = SimDetCts/SimCountTime
949               
950               
951                NVAR doABS = root:Packages:NIST:USANS:Globals:U_Sim:g_1D_DoABS
952                NVAR plotCR = root:Packages:NIST:USANS:Globals:U_Sim:g_1D_PlotCR
953                NVAR addNoise = root:Packages:NIST:USANS:Globals:U_Sim:g_1D_AddNoise
954                                       
955                sigave = sqrt(inten)            // assuming that N is large
956               
957                // add in random error in aveint based on the sigave
958                if(addNoise)
959                        inten += gnoise(sigave)
960                       
961                        //round to an integer again
962                        inten = round(inten)           
963                endif
964
965                // convert to absolute scale? Maybe not needed
966                // does nothing yet - need Ipeak, Twide
967//              if(doABS)
968//                      Variable kappa = thick*omega*trans*iMon*ctTime
969//                      inten /= kappa
970//                      inten /= kappa
971//              endif
972
973                // plot as countrate - maybe easier to visualize, and all of the data overlaps
974                if(plotCR)
975                        inten /= countingTime
976                        sigave /= countingTime
977                endif
978               
979                GraphSIM()
980
981        else
982                //no function plotted, no simulation can be done
983                DoAlert 0,"No function is selected or plotted, so no simulation is done. The default power law function is used."
984
985                inten = U_Power_Law_Model(1e-6,3,0,qvals)
986//              inten = U_SphereForm(1,9000,6e-6,0,qvals)               
987       
988                GraphSIM()
989
990        endif
991       
992
993end
994
995
996//sort the data in the "type"folder, based on angle
997//carry along all associated waves
998//
999// ---a duplicate of DoAngleSort(), by modified to
1000// include counting time and setNumber
1001//
1002// also trims the beginning of each data set so that it does not include any negative or zero angles
1003//
1004Function UDoAngleSort(type)
1005        String type
1006       
1007        SVAR USANSFolder = root:Packages:NIST:USANS:Globals:gUSANSFolder
1008       
1009        Wave angle = $(USANSFolder+":"+Type+":Angle")
1010        Wave detCts = $(USANSFolder+":"+Type+":DetCts")
1011        Wave ErrdetCts = $(USANSFolder+":"+Type+":ErrDetCts")
1012        Wave MonCts = $(USANSFolder+":"+Type+":MonCts")
1013        Wave TransCts = $(USANSFolder+":"+Type+":TransCts")
1014        Wave countingTime = $(USANSFolder+":"+Type+":countingTime")
1015        Wave SetNumber = $(USANSFolder+":"+Type+":SetNumber")
1016       
1017        Sort Angle DetCts,ErrDetCts,MonCts,TransCts,Angle,countingTime,SetNumber
1018       
1019        Variable ii,num,numBad,ang,val
1020        num=numpnts(angle)
1021        ii=0
1022        numBad=0
1023        val = 0         //cutoff value
1024        do
1025                ang = angle[ii]
1026                if(ang <= val)
1027                        numBad += 1
1028                else            //keep the points
1029                        Angle[ii-numBad] = ang
1030                        DetCts[ii-numBad] = DetCts[ii]
1031                        ErrDetCts[ii-numBad] = ErrDetCts[ii]
1032                        MonCts[ii-numBad] = MonCts[ii]
1033                        TransCts[ii-numBad] = TransCts[ii]
1034                        countingTime[ii-numBad] = countingTime[ii]
1035                        SetNumber[ii-numBad] = SetNumber[ii]
1036                endif
1037                ii += 1
1038        while(ii<num)
1039        //trim the end of the waves
1040        DeletePoints num-numBad, numBad, DetCts,ErrDetCts,MonCts,TransCts,Angle,countingTime,SetNumber
1041       
1042       
1043        return(0)
1044End
1045
1046// a simple default function
1047//
1048Function U_SphereForm(scale,radius,delrho,bkg,x)                               
1049        Variable scale,radius,delrho,bkg
1050        Variable x
1051       
1052        // variables are:                                                       
1053        //[0] scale
1054        //[1] radius (A)
1055        //[2] delrho (A-2)
1056        //[3] background (cm-1)
1057
1058       
1059        // calculates scale * f^2/Vol where f=Vol*3*delrho*((sin(qr)-qrcos(qr))/qr^3
1060        // and is rescaled to give [=] cm^-1
1061       
1062        Variable bes,f,vol,f2
1063        //
1064        //handle q==0 separately
1065        If(x==0)
1066                f = 4/3*pi*radius^3*delrho*delrho*scale*1e8 + bkg
1067                return(f)
1068        Endif
1069       
1070        bes = 3*(sin(x*radius)-x*radius*cos(x*radius))/x^3/radius^3
1071        vol = 4*pi/3*radius^3
1072        f = vol*bes*delrho              // [=] A
1073        // normalize to single particle volume, convert to 1/cm
1074        f2 = f * f / vol * 1.0e8                // [=] 1/cm
1075       
1076        return (scale*f2+bkg)   // Scale, then add in the background
1077       
1078End
1079
1080// better default function
1081Function U_Power_Law_Model(A,m,bgd,x) : FitFunc
1082        Variable A, m,bgd,x
1083//       Input (fitting) variables are:
1084        //[0] Coefficient
1085        //[1] (-) Power
1086        //[2] incoherent background
1087       
1088//      local variables
1089        Variable inten, qval
1090//      x is the q-value for the calculation
1091        qval = x
1092//      do the calculation and return the function value
1093       
1094        inten = A*qval^-m + bgd
1095        Return (inten)
1096End
1097
1098
1099// mimics LoadBT5File
1100// creates two other waves to identify the set and the counting time for that set
1101//
1102Function LoadSimulatedAngleRange(set,type)
1103        Variable set
1104        String type
1105
1106        SVAR USANSFolder = root:Packages:NIST:USANS:Globals:gUSANSFolder
1107       
1108        String s=num2str(set)
1109        NVAR angLow = $("root:Packages:NIST:USANS:Globals:U_Sim:gAngLow"+s)
1110        NVAR angHigh = $("root:Packages:NIST:USANS:Globals:U_Sim:gAngHigh"+s)
1111        NVAR numPts = $("root:Packages:NIST:USANS:Globals:U_Sim:gNumPts"+s)
1112        NVAR ctTime = $("root:Packages:NIST:USANS:Globals:U_Sim:gCtTime"+s)
1113        NVAR incr = $("root:Packages:NIST:USANS:Globals:U_Sim:gIncr"+s)
1114       
1115        Variable ii, err=0
1116       
1117        // generate q-points based on angular range from panel
1118       
1119        Make/O/D/N=(numPts) $(USANSFolder+":"+type+":Angle")
1120        Make/O/D/N=(numPts) $(USANSFolder+":"+type+":DetCts")
1121        Make/O/D/N=(numPts) $(USANSFolder+":"+type+":ErrDetCts")
1122        Make/O/D/N=(numPts) $(USANSFolder+":"+type+":MonCts")
1123        Make/O/D/N=(numPts) $(USANSFolder+":"+type+":TransCts")
1124        //
1125        Make/O/D/N=(numPts) $(USANSFolder+":"+type+":CountingTime")
1126        Make/O/D/N=(numPts) $(USANSFolder+":"+type+":SetNumber")
1127       
1128        Wave Angle = $(USANSFolder+":"+type+":Angle")
1129        Wave DetCts = $(USANSFolder+":"+type+":DetCts")
1130        Wave ErrDetCts = $(USANSFolder+":"+type+":ErrDetCts")
1131        Wave MonCts = $(USANSFolder+":"+type+":MonCts")
1132        Wave TransCts = $(USANSFolder+":"+type+":TransCts")
1133        Wave countingTime = $(USANSFolder+":"+type+":countingTime")
1134        Wave SetNumber = $(USANSFolder+":"+type+":SetNumber")
1135       
1136        countingTime = ctTime
1137        SetNumber = set
1138       
1139        for(ii=0;ii<numPts;ii+=1)
1140                Angle[ii] = angLow + ii*incr
1141                DetCts[ii] = set
1142        endfor
1143       
1144        //set the wave note for the DetCts
1145        String str=""
1146        str = "FILE:Sim "+s+";"
1147        str += "TIMEPT:"+num2str(ctTime)+";"
1148        str += "PEAKANG:0;"             //no value yet
1149        str += "STATUS:;"               //no value yet
1150        str += "LABEL:SimSet "+s+";"
1151        str += "PEAKVAL:;"              //no value yet
1152        str += "TWIDE:0;"               //no value yet
1153        Note DetCts,str
1154       
1155        return err                      // Zero signifies no error.     
1156End
1157
1158// add SIM data to the graph if it exists and is not already on the graph
1159//
1160//
1161// ** currently, I have changed the graph to not display the angle at the top. I have not yet
1162// found a way to keep the scaling of the two axes in-sync when the empty cell data is added to the
1163// graph (versus Q)
1164//
1165Function GraphSIM()
1166
1167//      SVAR USANSFolder = root:Packages:NIST:USANS:Globals:gUSANSFolder
1168//      SetDataFolder $(USANSFolder+":SIM")
1169
1170        SetDataFolder root:Sim_USANS
1171        //is it already on the graph?
1172        String list=""
1173        list = Wavelist("Sim_USANS*",";","WIN:UCALC")
1174       
1175        if(strlen(list)!=0)
1176//              Print "SIM already on graph"
1177                SetDataFolder root:
1178                return(0)
1179        Endif
1180       
1181        //append the data if it exists
1182        If(waveExists($"Sim_USANS_i")==1)
1183                DoWindow/F UCALC
1184
1185// lines for the no-noise result vs angle
1186//              AppendToGraph/T Smeared_inten vs angle
1187                AppendToGraph Smeared_inten vs Sim_USANS_q
1188                ModifyGraph rgb(Smeared_inten)=(1,12815,52428)
1189                ModifyGraph mode(Smeared_inten)=4,marker(Smeared_inten)=19,msize(Smeared_inten)=2
1190                ModifyGraph tickUnit=1
1191
1192// colored points for the simulation with noise on top
1193                AppendToGraph Sim_USANS_i vs Sim_USANS_q
1194                ModifyGraph mode(Sim_USANS_i)=3,marker(Sim_USANS_i)=19,msize(Sim_USANS_i)=4
1195                //don't reverse the dbZ21 or the highest angle will have "invisible" light blue error bars
1196                ModifyGraph zColor(Sim_USANS_i)={setNumber,1,7,dBZ21,0}                         //better for 7 colors
1197//              ModifyGraph zColor(Sim_USANS_i)={setNumber,1,7,Rainbow,0}                       //force the colors from 1->7
1198                ModifyGraph useMrkStrokeRGB(Sim_USANS_i)=1
1199                ErrorBars/T=0 Sim_USANS_i Y,wave=(Sim_USANS_s,Sim_USANS_s)
1200               
1201                ModifyGraph log=1
1202                ModifyGraph mirror(left)=1
1203                // if no top axis, then
1204//              ModifyGraph mirror(bottom)=1
1205                ModifyGraph grid=2
1206                ModifyGraph standoff=0
1207               
1208                // to make sure that the scales are the same (but fails on zoom)
1209                NewFreeAxis/O/T top_angle
1210                ModifyFreeAxis/Z top_angle,master= bottom,hook= TransformAngleAxisHook
1211                ModifyGraph lblPos(top_angle)=50,freePos(top_angle)=0
1212                ModifyGraph log(top_angle)=1
1213               
1214                SetDrawEnv linefgc= (39321,1,1),dash= 3,linethick= 3
1215                SetDrawEnv xcoord= bottom
1216                DrawLine 3e-05,0.01,3e-05,0.99
1217               
1218                Label top_angle "Angle"
1219                Label bottom "Q (1/A)"
1220                Label left "Counts or Count Rate"
1221               
1222                Legend
1223        endif
1224       
1225        SetDataFolder root:
1226End
1227
1228Function TransformAngleAxisHook(s)
1229        STRUCT WMAxisHookStruct &s
1230
1231        s.max= s.max/5.55e-5
1232        s.min= s.min/5.55e-5
1233       
1234        return 0
1235End
1236
1237//fakes a folder with loaded 1-d usans data, no calculation of the matrix
1238Function        FakeUSANSDataFolder(qval,aveint,dqv,dataFolder)
1239        WAVE qval,aveint
1240        Variable dqv
1241        String dataFolder
1242       
1243
1244        String baseStr=dataFolder
1245        if(DataFolderExists("root:"+baseStr))
1246                SetDataFolder $("root:"+baseStr)
1247        else
1248                NewDataFolder/S $("root:"+baseStr)
1249        endif
1250
1251        ////overwrite the existing data, if it exists
1252        Duplicate/O qval, $(baseStr+"_q")
1253        Duplicate/O aveint, $(baseStr+"_i")
1254       
1255        Duplicate/O qval, $(baseStr+"_s")
1256        Wave sigave = $(baseStr+"_s")
1257
1258        sigave = sqrt(aveint)
1259
1260        // make a resolution matrix for SANS data
1261        Variable np=numpnts(qval)
1262        Make/D/O/N=(np,4) $(baseStr+"_res")
1263        Wave res=$(baseStr+"_res")
1264       
1265        res[][0] = -dQv         //sigQ
1266        res[][1] = -dQv         //qBar
1267        res[][2] = -dQv         //fShad
1268        res[][3] = qval[p]              //Qvalues
1269       
1270        // extra waves of set number and counting time for the simulation
1271        WAVE ctW = root:Packages:NIST:USANS:SIM:countingTime
1272        WAVE setW = root:Packages:NIST:USANS:SIM:setNumber
1273        WAVE ang = root:Packages:NIST:USANS:SIM:Angle
1274        Duplicate/O ctW countingTime
1275        Duplicate/O setW setNumber
1276        Duplicate/O ang Angle
1277
1278
1279        //clean up             
1280        SetDataFolder root:
1281       
1282End
1283
1284
1285Function/S U_FunctionPopupList()
1286        String list,tmp
1287        list = User_FunctionPopupList()
1288       
1289        //simplify the display, forcing smeared calculations behind the scenes
1290        tmp = FunctionList("Smear*",";","NPARAMS:1")    //smeared dependency calculations
1291        list = RemoveFromList(tmp, list ,";")
1292
1293
1294        if(strlen(list)==0)
1295                list = "No functions plotted"
1296        endif
1297       
1298        list = SortList(list)
1299       
1300        return(list)
1301End     
1302
1303Function Sim_USANS_ModelPopMenuProc(pa) : PopupMenuControl
1304        STRUCT WMPopupAction &pa
1305
1306        switch( pa.eventCode )
1307                case 2: // mouse up
1308                        Variable popNum = pa.popNum
1309                        String popStr = pa.popStr
1310                        SVAR gStr = root:Packages:NIST:USANS:Globals:U_Sim:gFuncStr
1311                        gStr = popStr
1312                       
1313                        break
1314        endswitch
1315
1316        return 0
1317End         
1318
1319// if the sample aperture is changed, AND the empty data is displayed, change to the proper data
1320Function UCALC_SampleAperturePopup(pa) : PopupMenuControl
1321        STRUCT WMPopupAction &pa
1322
1323        switch( pa.eventCode )
1324                case 2: // mouse up
1325                        Variable popNum = pa.popNum
1326                        String popStr = pa.popStr
1327
1328                        ControlInfo/W=UCALC check0_4
1329                        if(V_Value==1)          //currently checked, need to update
1330                               
1331                                STRUCT WMCheckboxAction cba
1332                                cba.checked=0           //"un-check"
1333                                cba.eventCode=2
1334                                ShowEMPCheckProc(cba)
1335                               
1336                                cba.checked=1           //"re-check"
1337                                ShowEMPCheckProc(cba)
1338                       
1339                        endif
1340                        break
1341                       
1342        endswitch
1343       
1344        return 0
1345End 
1346
1347
1348Function UCALC_PresetPopup(pa) : PopupMenuControl
1349        STRUCT WMPopupAction &pa
1350
1351        switch( pa.eventCode )
1352                case 2: // mouse up
1353                        Variable popNum = pa.popNum
1354                        String popStr = pa.popStr
1355
1356                        SetDataFolder root:Packages:NIST:USANS:Globals:U_Sim
1357                       
1358                        NVAR gAngLow1 = gAngLow1
1359                        NVAR gAngHigh1 = gAngHigh1
1360                        NVAR gNumPts1 = gNumPts1
1361                        NVAR gCtTime1 = gCtTime1
1362                        NVAR gIncr1 = gIncr1
1363                       
1364                        NVAR gAngLow2 = gAngLow2
1365                        NVAR gAngHigh2 = gAngHigh2
1366                        NVAR gNumPts2 = gNumPts2
1367                        NVAR gCtTime2 = gCtTime2
1368                        NVAR gIncr2 = gIncr2
1369                       
1370                        NVAR gAngLow3 = gAngLow3
1371                        NVAR gAngHigh3 = gAngHigh3
1372                        NVAR gNumPts3 = gNumPts3
1373                        NVAR gCtTime3 = gCtTime3
1374                        NVAR gIncr3 = gIncr3
1375                       
1376                        NVAR gAngLow4 = gAngLow4
1377                        NVAR gAngHigh4 = gAngHigh4
1378                        NVAR gNumPts4 = gNumPts4
1379                        NVAR gCtTime4 = gCtTime4
1380                        NVAR gIncr4 = gIncr4
1381                       
1382                        NVAR gAngLow5 = gAngLow5
1383                        NVAR gAngHigh5 = gAngHigh5
1384                        NVAR gNumPts5 = gNumPts5
1385                        NVAR gCtTime5 = gCtTime5
1386                        NVAR gIncr5 = gIncr5
1387                       
1388                        NVAR gAngLow6 = gAngLow6
1389                        NVAR gAngHigh6 = gAngHigh6
1390                        NVAR gNumPts6 = gNumPts6
1391                        NVAR gCtTime6 = gCtTime6
1392                        NVAR gIncr6 = gIncr6
1393                       
1394                        NVAR gAngLow7 = gAngLow7
1395                        NVAR gAngHigh7 = gAngHigh7
1396                        NVAR gNumPts7 = gNumPts7
1397                        NVAR gCtTime7 = gCtTime7
1398                        NVAR gIncr7 = gIncr7
1399                       
1400                        strswitch(popStr)       // string switch
1401                                case "Short Count":             // execute if case matches expression
1402                                       
1403                                        gAngLow1 = -1
1404                                        gAngHigh1 = 0.6
1405                                        gNumPts1 = 33
1406                                        gCtTime1 = 10
1407                                        gIncr1 = 0.05   
1408                                       
1409                                        gAngLow2 = 0.7
1410                                        gAngHigh2 = 1.9
1411                                        gNumPts2 = 6
1412                                        gCtTime2 = 60
1413                                        gIncr2 = 0.2   
1414                                       
1415                                        gAngLow3 = 2
1416                                        gAngHigh3 = 4.8
1417                                        gNumPts3 = 7
1418                                        gCtTime3 = 120
1419                                        gIncr3 = 0.4   
1420                                       
1421                                        gAngLow4 = 5
1422                                        gAngHigh4 = 9.5
1423                                        gNumPts4 = 5
1424                                        gCtTime4 = 180
1425                                        gIncr4 = 0.9   
1426                                       
1427                                        gAngLow5 = 10
1428                                        gAngHigh5 = 19
1429                                        gNumPts5 = 5
1430                                        gCtTime5 = 240
1431                                        gIncr5 = 1.8
1432                                       
1433                                        gAngLow6 = 20
1434                                        gAngHigh6 = 48
1435                                        gNumPts6 = 15
1436                                        gCtTime6 = 0
1437                                        gIncr6 = 2
1438                                       
1439                                        gAngLow7 = 50
1440                                        gAngHigh7 = 95
1441                                        gNumPts7 = 10
1442                                        gCtTime7 = 0
1443                                        gIncr7 = 5
1444                                       
1445                                        break                                           
1446                                case "Medium Count":   
1447                       
1448                                        gAngLow1 = -1
1449                                        gAngHigh1 = 0.6
1450                                        gNumPts1 = 33
1451                                        gCtTime1 = 10
1452                                        gIncr1 = 0.05   
1453                                       
1454                                        gAngLow2 = 0.7
1455                                        gAngHigh2 = 1.9
1456                                        gNumPts2 = 13
1457                                        gCtTime2 = 60
1458                                        gIncr2 = 0.1   
1459                                       
1460                                        gAngLow3 = 2
1461                                        gAngHigh3 = 4.8
1462                                        gNumPts3 = 15
1463                                        gCtTime3 = 120
1464                                        gIncr3 = 0.2   
1465                                       
1466                                        gAngLow4 = 5
1467                                        gAngHigh4 = 9.5
1468                                        gNumPts4 = 10
1469                                        gCtTime4 = 300
1470                                        gIncr4 = 0.5   
1471                                       
1472                                        gAngLow5 = 10
1473                                        gAngHigh5 = 19
1474                                        gNumPts5 = 10
1475                                        gCtTime5 = 600
1476                                        gIncr5 = 1
1477                                       
1478                                        gAngLow6 = 20
1479                                        gAngHigh6 = 48
1480                                        gNumPts6 = 15
1481                                        gCtTime6 = 1200
1482                                        gIncr6 = 2     
1483                                       
1484                                        gAngLow7 = 50
1485                                        gAngHigh7 = 95
1486                                        gNumPts7 = 10
1487                                        gCtTime7 = 0
1488                                        gIncr7 = 5
1489                                                               
1490                                        break
1491                                case "Long Count":     
1492                                       
1493                                        gAngLow1 = -1
1494                                        gAngHigh1 = 0.6
1495                                        gNumPts1 = 33
1496                                        gCtTime1 = 25
1497                                        gIncr1 = 0.05   
1498                                       
1499                                        gAngLow2 = 0.7
1500                                        gAngHigh2 = 1.9
1501                                        gNumPts2 = 13
1502                                        gCtTime2 = 100
1503                                        gIncr2 = 0.1   
1504                                       
1505                                        gAngLow3 = 2
1506                                        gAngHigh3 = 4.8
1507                                        gNumPts3 = 15
1508                                        gCtTime3 = 300
1509                                        gIncr3 = 0.2   
1510                                       
1511                                        gAngLow4 = 5
1512                                        gAngHigh4 = 9.5
1513                                        gNumPts4 = 10
1514                                        gCtTime4 = 600
1515                                        gIncr4 = 0.5   
1516                                       
1517                                        gAngLow5 = 10
1518                                        gAngHigh5 = 19
1519                                        gNumPts5 = 10
1520                                        gCtTime5 = 1200
1521                                        gIncr5 = 1
1522                                       
1523                                        gAngLow6 = 20
1524                                        gAngHigh6 = 48
1525                                        gNumPts6 = 15
1526                                        gCtTime6 = 2000
1527                                        gIncr6 = 2
1528                                       
1529                                        gAngLow7 = 50
1530                                        gAngHigh7 = 95
1531                                        gNumPts7 = 10
1532                                        gCtTime7 = 3000
1533                                        gIncr7 = 5
1534                                       
1535                                        break
1536                                default:                       
1537                        endswitch
1538                       
1539                        break
1540        endswitch
1541
1542        //update the count time
1543        CalcTotalCountTime()
1544
1545        SetDataFolder root:
1546       
1547        return 0
1548End     
1549
1550
1551// return the beam intensity based on the sample aperture diameter
1552//
1553// based on the equation in John's instrument paper
1554//
1555Function GetUSANSBeamIntensity()       
1556
1557        String popStr
1558        Variable flux,diam,rad
1559       
1560        ControlInfo/W=UCALC popup0
1561        popStr = S_Value
1562        diam=str2num(popStr)            //in inches
1563        rad = diam/2*25.4                       //radius in mm
1564       
1565        flux = 662*rad*rad-39.9*rad*rad*rad+0.70*rad*rad*rad*rad
1566       
1567        return(flux)
1568End
1569
1570// based on the angle ranges above (with non-zero count times)
1571// save fake data points into a fake BT5 data file
1572//
1573Function U_SaveButtonProc(ba) : ButtonControl
1574        STRUCT WMButtonAction &ba
1575
1576       
1577        switch( ba.eventCode )
1578                case 2: // mouse up
1579                        // click code here
1580                       
1581                        Variable num,ii,baseNumber=101,firstSet=0
1582                        String pathStr="root:Packages:NIST:USANS:Globals:U_Sim:gCtTime"
1583                        SVAR USANSFolder = root:Packages:NIST:USANS:Globals:gUSANSFolder
1584                        String baseName="SIMUL"
1585                       
1586                        num = 7                 //# of angular ranges
1587                       
1588                        // only try to plot ranges with non-zero count times
1589                        firstSet=0
1590                        for(ii=1;ii<=num;ii+=1)
1591                                NVAR dum = $(pathStr+num2str(ii))
1592                                if(dum>0)                                               
1593                                        firstSet += 1
1594                                        if(firstSet==1) //first time, ask for base name
1595                                                Prompt baseName,"Enter a base name for the files"
1596                                                Prompt baseNumber,"Enter the starting index"
1597                                                DoPrompt "Enter Information for Save",baseName,baseNumber
1598                                               
1599                                                if(V_Flag==1)           //user canceled
1600                                                        return(1)
1601                                                endif
1602                                        endif
1603                                               
1604                                        SaveFakeUSANS(baseName,baseNumber-1,ii)
1605                                       
1606                                endif
1607                        endfor
1608                       
1609                        // no save the fake "COR" file that is the combination and rescaling of the data sets
1610                        // - the combination is in root:Sim_USANS:
1611                        NVAR g_1D_PlotCR = root:Packages:NIST:USANS:Globals:U_Sim:g_1D_PlotCR
1612
1613                        if(g_1D_PlotCR) // right now, save COR only if the CR is plotted
1614                                SaveFakeCOR(baseName)                   
1615                        endif
1616                       
1617                        break
1618        endswitch
1619
1620        return 0
1621End
1622
1623
1624Function SaveFakeCOR(nameStr)
1625        String nameStr
1626       
1627        NVAR gThick = root:Packages:NIST:USANS:Globals:U_Sim:gThick
1628        NVAR gSamTrans = root:Packages:NIST:USANS:Globals:U_Sim:gSamTrans
1629        NVAR gAnalyzerOmega = root:Packages:NIST:USANS:Globals:U_Sim:gAnalyzerOmega
1630        NVAR g_MultScattFraction = root:Packages:NIST:USANS:Globals:U_Sim:g_MultScattFraction
1631        SVAR funcStr = root:Packages:NIST:USANS:Globals:U_Sim:gFuncStr
1632       
1633        String folder = "root:Sim_USANS:",fileStr=""
1634        String termStr="\r\n"           //VAX uses only <CR> as terminator, but only CRLF seems to FTP correctly to VAX
1635        String destStr="",formatStr = "%15.6g %15.6g %15.6g %15.6g %15.6g %15.6g"+termStr
1636
1637        Variable refNum,integer,realval
1638        //*****these waves MUST EXIST, or IGOR Pro will crash, with a type 2 error****
1639        WAVE qvals =$(folder + "Sim_USANS_q")
1640        WAVE inten=$(folder + "Sim_USANS_i")
1641        WAVE sig=$(folder + "Sim_USANS_s")
1642       
1643        //check each wave
1644        If(!(WaveExists(qvals)))
1645                Abort "qvals DNExist in SaveFakeCOR()"
1646        Endif
1647        If(!(WaveExists(inten)))
1648                Abort "inten DNExist in SaveFakeCOR()"
1649        Endif
1650        If(!(WaveExists(sig)))
1651                Abort "sig DNExist in SaveFakeCOR()"
1652        Endif
1653       
1654        //dummy wave for the resolution
1655        Duplicate/O qvals,dumWave
1656        SVAR USANSFolder = root:Packages:NIST:USANS:Globals:gUSANSFolder
1657        NVAR DQv=$(USANSFolder+":Globals:MainPanel:gDQv")
1658        dumWave = - DQv
1659       
1660        //temp waves for the rescaling
1661        Duplicate/O qvals,tq,ti,te
1662        ti=inten
1663        te=sig
1664        tq=qvals
1665
1666        //rescale
1667        ti *= 1.0e6 / GetUSANSBeamIntensity()           //converts to "SAM" scaled data
1668        ti *= 1/(gSamTrans*gThick*gAnalyzerOmega*1.0e6)         //converts to "COR" scaling (approx, since I don't know Twide)
1669        //rescale error appropriately too
1670        te *= 1.0e6 / GetUSANSBeamIntensity()           //converts to "SAM" scaled data
1671        te *= 1/(gSamTrans*gThick*gAnalyzerOmega*1.0e6)         //converts to "COR" scaling (approx, since I don't know Twide)
1672
1673        // add fake error to every few data points to mark it as simulated data
1674        te[2,numpnts(te)-1;7] *= 10
1675       
1676        // now trim off the q-values less than 3e-5
1677        if(tq[0] < 3e-5)
1678                do
1679                        DeletePoints 0, 1, ti,tq,te,dumWave
1680                while(tq[0] < 3e-5)
1681        endif
1682       
1683        String samStr="",empStr="",dateStr="",samLabelStr="",paramStr="",empLevStr="",bkgLevStr="",pkStr=""
1684        samStr = "SIM FILES: "+StringByKey("FILE",note(inten),":",";")
1685        empStr = "EMP FILES: "+"none"
1686        empLevStr = "EMP LEVEL: " + "none"
1687        bkgLevStr = "BKG LEVEL: " + "not used"
1688        paramStr = "Ds = "+num2str(gthick)+" cm ; "
1689        paramStr += "Twide = "+"unknown"+" ; "
1690        paramStr += "Trock = "+num2str(gSamTrans)       
1691        pkStr += "Multiple coherent scattering fraction: "+num2str(g_MultScattFraction)
1692       
1693        //these strings are always the same
1694        samLabelStr ="LABEL: "+"Simulated USANS Data from: "+funcStr
1695        dateStr = date()+" at  "+time()// + " "+Secs2Time(DateTime,2)
1696       
1697       
1698        fileStr=nameStr+".cor"
1699        //actually open the file
1700        PathInfo savePathName
1701        if(V_flag==1)
1702                Open/P=savePathName refNum as fileStr
1703        else
1704                Open refNum as fileStr
1705        endif
1706       
1707        fprintf refnum,"%s"+termStr,samStr
1708        fprintf refnum,"%s"+termStr,dateStr
1709        fprintf refnum,"%s"+termStr,samLabelStr
1710        fprintf refnum,"%s"+termStr,empStr
1711        fprintf refnum,"%s"+termStr,paramStr
1712        fprintf refnum,"%s"+termStr,pkStr
1713        fprintf refnum,"%s"+termStr,empLevStr + " ; "+bkglevStr
1714       
1715        //
1716        wfprintf refnum, formatStr, tq,ti,te,dumWave,dumWave,dumWave
1717       
1718        Close refnum
1719       
1720        Killwaves/Z dumWave,ti,te,tq
1721       
1722       
1723       
1724        return(0)
1725End
1726
1727
1728//
1729// duplicates the BT5 file format
1730//
1731Function SaveFakeUSANS(nameStr,num,set)
1732        String nameStr
1733        Variable num,set
1734               
1735        String folder = "root:Packages:NIST:USANS:SIM:"
1736        String pathStr="root:Packages:NIST:USANS:Globals:U_Sim:"
1737        String termStr="\r\n"           //VAX uses only <CR> as terminator, but only CRLF seems to FTP correctly to VAX
1738       
1739//      WAVE DetCts = $(folder+"DetCts")                //these are only dummy values
1740        WAVE DetCts = root:Sim_USANS:Sim_USANS_i
1741        WAVE angle = $(folder+"Angle")
1742        WAVE SetNumber = $(folder+"SetNumber")
1743        WAVE countingTime = $(folder+"countingTime")
1744       
1745        NVAR ang1 = $(pathStr+"gAngLow"+num2str(set))
1746        NVAR ang2 = $(pathStr+"gAngHigh"+num2str(set))
1747        NVAR incr = $(pathStr+"gIncr"+num2str(set))
1748       
1749        Variable refNum,ii,wavePts,numPts,first,last,ctTime,monCt,transDet
1750        String str,fileStr,dateStr
1751       
1752        wavePts = numpnts(angle)
1753        for(ii=0;ii<wavePts;ii+=1)
1754                if(setNumber[ii] == set)
1755                        first = ii
1756                        break
1757                endif
1758        endfor
1759               
1760        for(ii=wavePts-1;ii>=0;ii-=1)
1761                if(setNumber[ii] == set)
1762                        last = ii
1763                        break
1764                endif
1765        endfor
1766       
1767//      Print "First, last = ",first,last
1768       
1769        // set up some of the strings needed
1770        fileStr=nameStr+num2str(num+set)+".bt5"
1771        dateStr = date()
1772        ctTime = countingTime[first]
1773        numPts = last-first+1
1774       
1775        MonCt = ctTime*GetUSANSBeamIntensity()
1776       
1777        transDet = 999          //bogus and constant value
1778               
1779        //actually open the file
1780        PathInfo savePathName
1781        if(V_flag==1)
1782                Open/P=savePathName refNum as fileStr
1783        else
1784                Open refNum as fileStr
1785        endif
1786       
1787        sprintf str,"'%s' '%s' 'I'        %d    1  'TIME'   %d  'RAW'",fileStr,dateStr,ctTime,numpts
1788        fprintf refnum,"%s"+termStr,str
1789        fprintf refnum,"%s"+termStr,"  Filename         Date            Scan       Mon    Prf  Base   #pts  Type"
1790       
1791        fprintf refnum,"Simulated USANS data"+termStr
1792
1793        fprintf refnum,"%s"+termStr,"   0    0    0    0   0  0  0     0.0000     0.00000 0.00000   0.00000    2"
1794        fprintf refnum,"%s"+termStr," Collimation      Mosaic    Wavelength   T-Start   Incr.   H-field #Det    "
1795        fprintf refnum,"%s"+termStr,"  1       0.00000    0.00000    0.00000"
1796        fprintf refnum,"  2       %9.5f    %9.5f    %9.5f"+termStr,ang1,incr,ang2
1797        fprintf refnum,"%s"+termStr,"  3      10.00000    0.00000   10.00000"
1798        fprintf refnum,"%s"+termStr,"  4      10.00000    0.00000   10.00000"
1799        fprintf refnum,"%s"+termStr,"  5       0.00000    0.00000    0.00000"
1800        fprintf refnum,"%s"+termStr,"  6       0.00000    0.00000    0.00000"
1801        fprintf refnum,"%s"+termStr," Mot:    Start       Step      End"
1802        fprintf refnum,"%s"+termStr,"     A2       MIN      MONITOR      COUNTS      EXTRA  "
1803
1804        //loop over the waves, picking out the desired set
1805        //write 2 lines each time
1806        for(ii=first;ii<=last;ii+=1)
1807                sprintf str,"      %6.3f    %6.2f    %d     %d     %d",angle[ii],ctTime/60,MonCt,DetCts[ii]*ctTime,transDet
1808                fprintf refnum,"%s"+termStr,str
1809
1810                sprintf str,"%d,%d,0,%d,0,0,0,0",MonCt,DetCts[ii]*ctTime,transDet
1811                fprintf refnum,"%s"+termStr,str
1812        endfor
1813       
1814        Close refnum
1815
1816        return(0)
1817end
1818
1819
1820// print out the USANS configuration in some reasonable format
1821Function/S USANSConfigurationText()
1822
1823        String str="",temp
1824
1825        SetDataFolder root:Packages:NIST:USANS:Globals:U_Sim
1826       
1827        // results, setup values
1828        SVAR gTotTimeStr=gTotTimeStr
1829       
1830        Variable ii,num
1831        String pathStr="root:Packages:NIST:USANS:Globals:U_Sim:"
1832        num=7
1833       
1834        str += "USANS Instrument Configuration:\r\r"
1835        str += "Theta Min  Theta Max   Increment   # Points   Count Time\r"
1836       
1837       
1838        for(ii=1;ii<=num;ii+=1)
1839                NVAR ctTime = $(pathStr+"gCtTime"+num2str(ii))
1840                if(ctTime>0)
1841                        NVAR angLow = $(pathStr+"gAngLow"+num2str(ii))
1842                        NVAR angHigh = $(pathStr+"gAngHigh"+num2str(ii))
1843                        NVAR incr = $(pathStr+"gIncr"+num2str(ii))
1844                        NVAR numPts = $(pathStr+"gNumPts"+num2str(ii))
1845                       
1846                        sprintf temp,"%9.3f  %9.3f  %9.3f  %9d  %9d\r",angLow,angHigh,incr,numPts,ctTime
1847                        str += temp
1848                endif
1849        endfor
1850       
1851       
1852        sprintf temp,"\r\rTotal Counting Time (HR:MIN) = %s\r",gTotTimeStr
1853        str += temp
1854
1855       
1856   setDataFolder root:
1857   return str                   
1858End
1859
1860Function DisplayUCALCText()
1861
1862        if(WinType("USANS_Configuration")==0)
1863                NewNotebook/F=0/K=1/N=USANS_Configuration /W=(480,44,880,369)
1864        endif
1865        //replace the text
1866        Notebook USANS_Configuration selection={startOfFile, endOfFile}
1867        Notebook USANS_Configuration font="Monaco",fSize=10,text=USANSConfigurationText()
1868        return(0)
1869end
1870
1871
1872//
1873Function U_ConfigTextProc(ba) : ButtonControl
1874        STRUCT WMButtonAction &ba
1875
1876       
1877        switch( ba.eventCode )
1878                case 2: // mouse up
1879                        // click code here
1880                       
1881                                DisplayUCALCText()                                     
1882                        break
1883        endswitch
1884
1885        return 0
1886End
1887
1888// this will save a graphic of the whole panel that then needs to be opened and printed
1889// must be a PNG @ screen resolution
1890//
1891Function U_SavePanelProc(ba) : ButtonControl
1892        STRUCT WMButtonAction &ba
1893
1894       
1895        switch( ba.eventCode )
1896                case 2: // mouse up
1897                        // click code here
1898                       
1899                        SavePICT/P=home/E=-5/B=72/SNAP=1       
1900                       
1901                        // can I reload and print?
1902                        // how will the users know where this went and what to do with it?
1903                        //                     
1904                        break
1905        endswitch
1906
1907        return 0
1908End
Note: See TracBrowser for help on using the repository browser.