source: sans/Dev/trunk/NCNR_User_Procedures/Reduction/SANS/MC_SimulationScripting.ipf @ 921

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

fixed an issue in Invariant where the file loader would fail if it tried to load in a name that was too long and needed to be truncated. Issue was resolved and updated to behave like the main file loader. Another good reason to consolidate the file loaders rather than have them scattered around...

File size: 29.2 KB
Line 
1#pragma rtGlobals=1             // Use modern global access method.
2
3
4
5
6//************
7// un-comment the Macros menu declaration to provide easier access to the functions
8//************
9
10
11
12// this is a file with all of the functions that can be used to
13// script the MC simulation of data
14//
15// there are a lot of utility functions to "move" the parts of an instrument that
16// are "moveable" into different configurations. The aim is to have this appear as
17// much like running an experiment as possible.
18//
19//
20//  The basic cycle:
21//
22// 1) plot the model function, and set the coefficients to what you want
23//
24// 2) set (and save) as many configurations as you like -picking ones that are most appropriate for the sample scattering
25//
26//              Sim_SaveConfiguration(waveStr)
27//
28// 3) simulate the sample scattering at your configurations for specified times. The 1D count rate
29//               should match fairly well to the 2D count rate. (Check this for low/high incoherent levels)
30//-or-
31// 4) run everything for a short time (say 1s to 10s) to get the count rates
32//  - this will actually save the files - just like a real experiment. This is like step 6, but with short count times.
33//
34// 5) with the sample count rates, find the optimal count times
35//
36//              OptimalCount(samCR,empCR)
37//
38// 6) Write a function to "run" the samples at configurations and count times. Don't forget to simulate
39//               the transmissions. (See the examples below). Copy the function to a new procedure window, rename it,
40//              and edit it there as you wish.
41//
42//              ListSASCALCConfigs() will print out the list of configurations
43//
44// 7) Then with the optimal count times, do a dry run to see how long the whole simulation would take.
45//
46//              Sim_DryRun(funcStr)
47//
48// 8) Then if that's OK, run the full simulation
49//
50//              Your function here()
51//
52// 9) If it's 1D data, use NSORT to combine. If it's 2D data, reduce as usual. Be sure to skip the detector
53//              efficiency correction, and set the dead time to a tiny value so that it won't have any
54//    effect (since the detector CR is fictionally high, and the detector is perfect):
55//
56//              Sim_SetDeadTimeTiny()
57//
58// When you have a lot of 1D waves to combine, and they are not numbered like in a real reduction
59// experiment, see:
60//
61//  MakeCombineTable_byName()
62//  DoCombineFiles_byName(lowQfile,medQfile,hiQfile,saveName) (in NSORT.ipf)
63//
64// this works with 1, 2, or 3 data files
65//
66
67
68// In general, when setting up a simulation, it's easier to set up sample conditions for a particular
69// sample, and loop through the configurations. If you want your 2D data to "look" like a typical
70// experiment, then you'll need to simulate each different sample at one configuration, then "move"
71// to a different configuration and loop through the samples again. Somewhat more cumbersome, all to
72// get the file catalog to be "grouped" like a real SANS experiment.
73
74
75//
76// Important - in the reduction process, set the  dead time correction to something
77// really small, say 10^-15
78//
79// see Sim_SetDeadTimeTiny()
80
81//
82// TODO:
83// x- need to update the 1D writer to allow a name to be passed in, rather than
84// always using the dialog
85// x- fill in the "RunSample" functions
86//
87//  -- I need a little panel to control all of this, and get the information, just
88//     like setting up a real experiment. Or maybe not. Maybe better to keep some of this
89//     hidden.
90//  -- It would be nice to be able to automatically do the sum_model to add the 2D empty cell contribution
91//     For some experiments it's quite useful to see the level of this contribution, rather than
92//     the completely clean simulation.
93//  -- in this file, clearly separate the examples from the utility functions
94//  -- get a function list of everything, and document what each does (if not obvious)
95//  -- step by step comments of one of the examples (1D and 2D) are probably the most useful
96//  -- "dry run" function to estimate the total simulation time for 2D. (? set all monitor counts to 1000
97//      or whatever I use to get other estimates, and then run through everything to get estimated times)
98//
99// set the global:
100//      NVAR g_estimateOnly = root:Packages:NIST:SAS:g_estimateOnly             // == 1 for just a time estimate, == 0 (default) to do the simulation
101// and then do the dry run
102//
103//
104// ----- transmission really doesn't work in the simulation...
105// -- add function to simulate transmission in 2D by saving a "Trans" configuration
106//     and automatically using that. Currently the trans is already written to the file
107// x- would also need a function to simulate an empty beam measurement to rescale the
108//     transmissions. (use the model given, set scale (w[0] to something really small)
109//  -- or better, use the empty cell function that is guaranteed to have coefficients that are
110//     well behaved - and I can set/reset them to get a proper "empty beam"
111//
112//
113// -- scattering from an empty cell is NOT provided in 2D
114
115xMenu "Macros"
116        Submenu "Simulation Scripting - Beta"
117                "Save Configuration",Sim_saveConfProc()
118                "Move to Configuration",Sim_moveConfProc()
119                "List Configurations",ListSASCALCConfigs()
120                "Setup Sim Example",Setup_Sim_Example()
121                "1D Count Rates",DryRunProc_1D()
122                "2D Dry Run",DryRunProc_2D()
123                "Optimal Count Times",OptimalCountProc()
124                "Make Table to Combine By Name",MakeCombineTable_byName()
125                "Combine by Name",DoCombineFiles_byName(lowQfile,medQfile,hiQfile,saveName)
126                "Turn Off Dead Time Correction",Sim_SetDeadTimeTiny()
127        End
128End
129
130// run this before the examples to make sure that the proper named configurations exist.
131// this function will overwrite any same-named waves
132Function Setup_Sim_Example()
133
134        SetDataFolder root:Packages:NIST:SAS:
135       
136        Make/O/T/N=20 Config_1m,Config_4m,Config_13m
137        Config_1m = {"checkNG7","8","5.08 cm","6","0.115","checkChamber","1/2\"","0","100","25","","","","","","","","","",""}
138        Config_4m = {"checkNG7","5","5.08 cm","6","0.115","checkChamber","1/2\"","0","400","0","","","","","","","","","",""}
139        Config_13m = {"checkNG7","1","5.08 cm","6","0.115","checkChamber","1/2\"","0","1300","0","","","","","","","","","",""}
140 
141        SetDataFolder root:
142
143End
144
145Function Example_1DSim()
146
147        String confList,ctTimeList,saveNameList,funcStr,titleStr
148       
149
150        Sim_SetSimulationType(0)                //kill the simulation panel
151        Sim_SetSimulationType(1)                //open the 1D simulation panel
152       
153//(1)   enter the (unsmeared) function name
154        funcStr = "SchulzSpheres_SC"
155        Wave cw = $("root:"+getFunctionCoef(funcStr))
156        Sim_SetModelFunction(funcStr)                                           // model function name
157               
158//(2) model coefficients here, if needed. Wave name is "cw"
159//   then set the sample thickness. Be sure to use an appropriate incoherent background in the model
160        Sim_Set1D_Transmission(0.75)                                            // For 1D, I need to supply the transmission
161        Sim_SetThickness(0.2)                                                           // thickness
162        Sim_Set1D_ABS(1)                                                                                // absolute scaling (1== yes)
163        Sim_Set1D_Noise(1)                                                                      // noise (1== yes, add statistical noise)
164
165        cw[0] = 0.1
166        // as needed - look at the parameter list for the model
167       
168       
169//(3) set the configuration list, times, and saved names
170// -- the mumber of listed configurations must match the number of discrete count times and save names
171// titleStr is the label and is the same for each run of the same sample
172        confList = "Config_1m;Config_4m;Config_13m;"
173        ctTimeList = "100;300;900;"
174        saveNameList = "sim_1m.abs;sim_4m.abs;sim_13m.abs;"
175        titleStr = "MySample 1"
176
177        // then this runs the samples as listed
178        Sim_RunSample_1D(confList,ctTimeList,titleStr,saveNameList)
179
180        // no transmissions or empty beam measurements to make for 1D simulation
181
182        return(0)       
183End
184
185//
186Function Example_2DSim()
187
188        String confList,ctTimeList,titleStr,transConfList,transCtTimeList
189        Variable runIndex,val,totalTime
190        String funcStr
191
192tic()
193
194        Sim_SetSimulationType(0)                //kill the simulation panel
195        Sim_SetSimulationType(2)                //open the 2D simulation panel
196        Sim_SetSimTimeWarning(36000)                    //sets the threshold for the warning dialog to 10 hours
197        totalTime = 0
198
199
200//(1)   enter the (unsmeared) function name
201        funcStr = "SchulzSpheres_SC"
202        Wave cw = $("root:"+getFunctionCoef(funcStr))
203        Sim_SetModelFunction(funcStr)                                           // model function name
204
205//(2) set the standard sample cell size (1" diam banjo cell)
206// and set the conditions for beam stop in, and raw counts
207        Sim_SetSampleRadius(1.27)                                                       // sam radius (cm)
208        Sim_SetRawCountsCheck(1)                                                        // raw cts? 1== yes
209        Sim_SetBeamStopInOut(1)                                                         // BS in? 1==yes
210
211//(3) model coefficients here, if needed. Wave name is "cw"
212//   then set the sample thickness and incoherent cross section
213
214        cw[0] = 0.1
215        // as needed - look at the parameter list for the model
216
217        Sim_SetThickness(0.2)                                                           // thickness (cm)
218        Sim_SetIncohXS(1.3)                                                                     // incoh XS
219       
220//(4) starting run index for the saved raw data files. this will automatically increment
221//    as the sample is "Run"
222        runIndex = 400
223       
224//(5) set the configuration list, times, a single sample label, and the starting run index
225// -- the mumber of listed configurations must match the number of discrete count times
226        confList = "Config_1m;Config_4m;Config_13m;"
227        ctTimeList = "100;300;900;"
228        transConfList = "Config_13m;"           // trans only @ 13m
229        transCtTimeList = "1;"                          // trans count time = 1s
230        titleStr = "MySample 1"
231
232        // runIndex is PBR and updates as the number of files are written
233       
234        // this runs the sample
235        totalTime += Sim_RunSample_2D(confList,ctTimeList,titleStr,runIndex)
236        // this runs the transmissions
237        totalTime += Sim_RunTrans_2D(transConfList,transCtTimeList,titleStr,runIndex)
238       
239        // run the empty beam at all configurations
240        // This will automatically change the function to "EC_Empirical" and "empty beam" conditions
241        transConfList = "Config_1m;Config_4m;Config_13m;"
242        transCtTimeList = "1;1;1;"     
243        titleStr = "Empty Beam"
244        totalTime += Sim_RunEmptyBeamTrans_2D(transConfList,transCtTimeList,titleStr,runIndex)
245       
246        Print "runIndex = ",runIndex
247
248        Sim_SetSimTimeWarning(10)
249
250toc()
251       
252        return(totalTime)
253End
254
255// this example was really used, run repeatedly with different count times to get
256// replicate data sets to test the overlap
257Function Example_Loop_1DSim()
258
259        String confList,ctTimeList,saveNameList,funcStr,titleStr
260       
261
262        Sim_SetSimulationType(0)                //kill the simulation panel
263        Sim_SetSimulationType(1)                //open the 1D simulation panel
264       
265//(1)   enter the (unsmeared) function name
266        funcStr = "DAB_model"
267        Wave cw = $("root:"+getFunctionCoef(funcStr))
268        Sim_SetModelFunction(funcStr)                                           // model function name
269               
270//(2) model coefficients here, if needed. Wave name is "cw"
271//   then set the sample thickness. Be sure to use an appropriate incoherent background in the model
272        Sim_Set1D_Transmission(0.8)                                             // For 1D, I need to supply the transmission
273        Sim_SetThickness(0.1)                                                           // thickness
274        Sim_Set1D_ABS(1)                                                                                // absolute scaling (1== yes)
275        Sim_Set1D_Noise(1)                                                                      // noise (1== yes, add statistical noise)
276
277
278        cw = {1e-05,200,0}
279       
280       
281//(3) set the configuration list, times, and saved names
282// -- the mumber of listed configurations must match the number of discrete count times and save names
283// titleStr is the label and is the same for each run of the same sample
284        confList = "Config_4m;"
285        ctTimeList = ""         //filled in the loop
286        saveNameList = ""
287        titleStr = "DAB versus count time t = "
288
289        Make/O/D ctTime = {5,11,16,21,27,32,37,43,48,53,107,160,214,267,321,374,428,481,535,1604,5348,21390,53476}
290
291        Variable ii=0,nTrials=10,jj
292       
293        for(jj=0;jj<numpnts(ctTime);jj+=1)     
294                for(ii=0;ii<nTrials;ii+=1)
295                        titleStr = "DAB versus count time t = "+num2str(ctTime[jj])
296                        saveNameList = "DAB_4m_t"+num2str(ctTime[jj])+"_"+num2str(ii)+".abs;"
297                        ctTimeList = num2str(ctTime[jj])+";"
298                        // then this runs the samples as listed
299                        Sim_RunSample_1D(confList,ctTimeList,titleStr,saveNameList)
300                endfor
301        endfor
302
303        // no transmissions or empty beam measurements to make for 1D simulation
304
305        return(0)       
306End
307
308
309
310
311
312// pass in a semicolon delimited list of configurations + corresponding count times + saved names
313Function Sim_RunSample_1D(confList,ctTimeList,titleStr,saveNameList)
314        String confList,ctTimeList,titleStr,saveNameList
315       
316        Variable ii,num,ct,cr,numPt
317        String twStr,fname,type
318        NVAR g_estimateOnly = root:Packages:NIST:SAS:g_estimateOnly             // == 1 for just count rate, == 0 (default) to do the simulation and save
319        WAVE/Z crWave = root:CR_1D
320        WAVE/Z/T fileWave = root:Files_1D
321
322        type = "SAS"            // since this is a simulation
323        num=ItemsInList(confList)
324       
325        for(ii=0;ii<num;ii+=1)
326                twStr = StringFromList(ii, confList,";")
327                Wave/T tw=$("root:Packages:NIST:SAS:"+twStr)
328                ct = str2num(StringFromList(ii, ctTimeList,";"))
329                fname = StringFromList(ii, saveNameList,";")
330               
331                Sim_MoveToConfiguration(tw)
332                Sim_SetCountTime(ct)
333                cr = Sim_Do1DSimulation()
334               
335                // either save it out, or return a table of the count rates
336                if(g_estimateOnly)
337                        numPt = numpnts(crWave)
338                        InsertPoints numPt, 1, crWave,fileWave
339                        crWave[numPt] = cr
340                        fileWave[numPt] = fname
341                else
342                        Sim_Save1D_wName(type,titleStr,fname)           //this function will increment the runIndex
343                endif
344       
345        endfor
346
347        return(0)
348End
349
350// fakes an empty beam transmission by setting the conditions of the
351// empty cell temporarily to something that doesn't scatter
352Function Sim_RunEmptyBeamTrans_2D(confList,ctTimeList,titleStr,runIndex)
353        String confList,ctTimeList,titleStr
354        Variable &runIndex
355       
356        Wave cw = root:Packages:NIST:SAS:coef_ECEmp             //EC coefs are in the SAS folder, not root:
357        Variable totalTime
358       
359        // change the function and coefficients
360        Sim_SetModelFunction("EC_Empirical")
361        cw = {1e-18,3.346,0,9,0}
362        Sim_SetIncohXS(0)                                                                       // incoh XS = 0 for empty beam
363        Sim_SetThickness(0.1)                                                   // thickness (cm) to give proper level of scattering
364
365               
366        totalTime = Sim_RunTrans_2D(confList,ctTimeList,titleStr,runIndex)
367               
368        // change them back
369        cw = {2.2e-08,3.346,0.0065,9,0.016}
370       
371        return(totalTime)
372End
373
374 
375// should be called with each list having only one item
376// and a count time of 1 s
377//
378// -- for an empty beam, before calling, set the incoh XS = 0 and set the scale
379// of the model to something tiny so that there is no coherent scattering
380//
381Function Sim_RunTrans_2D(confList,ctTimeList,titleStr,runIndex)
382        String confList,ctTimeList,titleStr
383        Variable &runIndex
384       
385        Variable ii,num,ct,index,totalTime
386        String twStr,type
387
388        NVAR g_estimateOnly = root:Packages:NIST:SAS:g_estimateOnly             // == 1 for just a time estimate, == 0 (default) to do the simulation
389        NVAR g_estimatedMCTime = root:Packages:NIST:SAS:g_estimatedMCTime               // estimated MC sim time
390        totalTime = 0
391               
392        type = "SAS"            // since this is a simulation
393        num=ItemsInList(confList)
394       
395        for(ii=0;ii<num;ii+=1)
396                twStr = StringFromList(ii, confList,";")
397                Wave/T tw=$("root:Packages:NIST:SAS:"+twStr)
398                ct = str2num(StringFromList(ii, ctTimeList,";"))
399               
400                Sim_MoveToConfiguration(tw)
401                Sim_SetBeamStopInOut(0)                                                         // BS out for Trans
402                Sim_SetCountTime(ct)
403                Sim_DoMCSimulation()
404               
405                if(g_estimateOnly)
406                        totalTime += g_estimatedMCTime          //      don't save, don't increment. time passed back as global after each MC simulation
407                else
408                        SaveAsVAXButtonProc("",runIndex=runIndex,simLabel=(titleStr+" at "+twStr))
409                        runIndex += 1
410                endif
411
412        endfor
413       
414        Sim_SetBeamStopInOut(1)                                                         // put the BS back in
415
416        return(totalTime)
417End
418
419
420
421// if just an estimate, I can also get the count rate too
422// WAVE results = root:Packages:NIST:SAS:results
423//      Print "Sample Simulation (2D) CR = ",results[9]/ctTime
424// -- for estimates, iMon is set to 1000, so time=1000/(root:Packages:NIST:SAS:gImon)
425Function Sim_RunSample_2D(confList,ctTimeList,titleStr,runIndex)
426        String confList,ctTimeList,titleStr
427        Variable &runIndex
428
429        Variable ii,num,ct,index,totalTime
430        String twStr,type
431
432        NVAR g_estimateOnly = root:Packages:NIST:SAS:g_estimateOnly             // == 1 for just a time estimate, == 0 (default) to do the simulation
433        NVAR g_estimatedMCTime = root:Packages:NIST:SAS:g_estimatedMCTime               // estimated MC sim time
434        totalTime = 0
435       
436        type = "SAS"            // since this is a simulation
437        num=ItemsInList(confList)
438       
439       
440        for(ii=0;ii<num;ii+=1)
441                twStr = StringFromList(ii, confList,";")
442                Wave/T tw=$("root:Packages:NIST:SAS:"+twStr)
443                ct = str2num(StringFromList(ii, ctTimeList,";"))
444               
445                Sim_MoveToConfiguration(tw)
446                Sim_SetBeamStopInOut(1)                                                         // BS in?
447                Sim_SetCountTime(ct)
448                Sim_DoMCSimulation()
449               
450                if(g_estimateOnly)
451                        totalTime += g_estimatedMCTime          //      don't save, don't increment. time passed back as global after each MC simulation
452                else
453                        SaveAsVAXButtonProc("",runIndex=runIndex,simLabel=(titleStr+" at "+twStr))
454                        runIndex += 1
455                endif
456               
457        endfor
458
459        return(totalTime)
460End
461
462// a prototype function with no parameters
463// for a real experiment - it must return the total time, if you want a proper estimate
464Function Sim_Expt_Proto()
465        Print "In the Sim_Expt_Proto -- error"
466        return(0)
467End
468
469Proc DryRunProc_2D(funcStr)
470        String funcStr
471        Sim_2DDryRun(funcStr)
472end
473
474// pass the function string, no parameters
475Function Sim_2DDryRun(funcStr)
476        String funcStr
477       
478        FUNCREF Sim_Expt_Proto func=$funcStr
479       
480        NVAR g_estimateOnly = root:Packages:NIST:SAS:g_estimateOnly
481        g_estimateOnly = 1
482       
483        Variable totalTime
484//      totalTime = Sim_CountTime_2D()  // your "exeriment" here, returning the totalTime
485       
486        totalTime = func()
487        g_estimateOnly = 0
488       
489        Printf "Total Estimated Time = %g s or %g h\r",totalTime,totalTime/3600
490end
491
492Proc DryRunProc_1D(funcStr)
493        String funcStr
494        Sim_1DDryRun(funcStr)
495end
496
497// pass the function string, no parameters
498// makes a (new) table of the files and CR
499Function Sim_1DDryRun(funcStr)
500        String funcStr
501       
502        FUNCREF Sim_Expt_Proto func=$funcStr
503       
504        NVAR g_estimateOnly = root:Packages:NIST:SAS:g_estimateOnly
505        g_estimateOnly = 1
506       
507        Variable totalTime
508       
509        Make/O/D/N=0 root:CR_1D
510        Make/O/T/N=0 root:Files_1D
511       
512        totalTime = func()
513        g_estimateOnly = 0
514       
515        Edit Files_1D,CR_1D
516       
517//      Printf "Total Estimated Time = %g s or %g h\r",totalTime,totalTime/3600
518        return(0)
519end
520
521
522
523
524
525Proc OptimalCountProc(samCountRate,emptyCountRate)
526        Variable samCountRate,emptyCountRate
527        OptimalCount(samCountRate,emptyCountRate)
528End
529
530Function OptimalCount(samCR,empCR)
531        Variable samCR,empCR
532       
533        String str
534        Variable ratio,target
535        ratio = sqrt(samCR/empCR)
536       
537        str = "For %g Sample counts, t sam = %g s and t emp = %g s\r"
538       
539        target = 1e6
540        printf str,target,round(target/samCR),round((target/samCR)/ratio)
541       
542        target = 1e5
543        printf str,target,round(target/samCR),round((target/samCR)/ratio)       
544
545        target = 1e4
546        printf str,target,round(target/samCR),round((target/samCR)/ratio)       
547        return(0)
548end
549
550
551//
552// Important - in the reduction process, set the dead time correction to something
553// really small, say 10^-15 so that  it won't have any effect (since the detector CR is fictionally high)
554//
555Function Sim_SetDeadTimeTiny()
556
557//      NVAR DeadtimeNG3_ILL = root:myGlobals:DeadtimeNG3_ILL           //pixel resolution in cm
558//      NVAR DeadtimeNG5_ILL = root:myGlobals:DeadtimeNG5_ILL
559//      NVAR DeadtimeNG7_ILL = root:myGlobals:DeadtimeNG7_ILL
560//      NVAR DeadtimeNGB_ILL = root:myGlobals:DeadtimeNGB_ILL
561        NVAR DeadtimeNG3_ORNL_VAX = root:myGlobals:DeadtimeNG3_ORNL_VAX
562//      NVAR DeadtimeNG3_ORNL_ICE = root:myGlobals:DeadtimeNG3_ORNL_ICE
563//      NVAR DeadtimeNG5_ORNL = root:myGlobals:DeadtimeNG5_ORNL
564        NVAR DeadtimeNG7_ORNL_VAX = root:myGlobals:DeadtimeNG7_ORNL_VAX
565//      NVAR DeadtimeNG7_ORNL_ICE = root:myGlobals:DeadtimeNG7_ORNL_ICE
566        NVAR DeadtimeNGB_ORNL_ICE = root:myGlobals:DeadtimeNGB_ORNL_ICE
567        NVAR DeadtimeDefault = root:myGlobals:DeadtimeDefault
568
569        DeadtimeNG3_ORNL_VAX = 1e-15
570        DeadtimeNG7_ORNL_VAX = 1e-15
571        DeadtimeNGB_ORNL_ICE = 1e-15
572        DeadtimeDefault = 1e-15
573       
574        return(0)
575End
576
577
578
579/////////////////////////////////////////////////////////////////////
580///////////// All of the utility functions to make things "move"
581
582
583
584// set the wavelength
585Function Sim_SetLambda(val)
586        Variable val
587
588        NVAR lam = root:Packages:NIST:SAS:gLambda
589        lam=val
590        LambdaSetVarProc("",val,num2str(val),"")
591        return(0)
592end
593
594// set the wavelength spread
595// ?? what are the allowable choices
596// there are 3 choices for each instrument
597//
598// TO DO ?? do this in a better way
599// currently there is no error checking...
600//
601Function Sim_SetDeltaLambda(strVal)
602        String strVal
603       
604       
605        DeltaLambdaPopMenuProc("",1,strVal)             // recalculates intensity if 2nd param==1, skip if == 0
606        PopupMenu popup0_2 win=SASCALC,popmatch=strVal
607//      ControlUpdate/W=SASCALC popup0_2
608       
609        return(0)
610End
611
612// if state == 0, lenses out (box un-checked, no parameters change)
613// if state == 1, lenses in, changes guides, aperture, SDD and wavelength appropriately
614// if prisms desired, follow this call with a set wavelength=17.2
615Function Sim_SetLenses(state)
616        Variable state
617       
618        LensCheckProc("",state)
619        CheckBox checkLens,win=SASCALC,value=state
620       
621        return(0)
622End
623
624// instrName = "checkNG3" or "checkNG7" or "checkNGB"
625// these are the only allowable choices
626Function Sim_SetInstrument(instrName)
627        String instrName
628       
629        SelectInstrumentCheckProc(instrName,0)
630        return(0)
631End
632
633
634//two steps to change the number of guides
635// - first the number of guides, then the source aperture (if 0g, 7g where there are choices)
636//
637// strVal is "5 cm" or "1.43 cm" (MUST be identical to the popup string, MUST have the units)
638///
639Function Sim_SetNumGuides_SrcAp(ng,strVal)
640        Variable ng
641        String strVal
642
643        NVAR gNg=root:Packages:NIST:SAS:gNg
644        gNg = ng
645       
646        Slider SC_Slider,win=SASCALC,variable=root:Packages:NIST:SAS:gNg                                //guides
647
648        // with the new number of guides, update the allowable source aperture popups
649        DoWindow/F SASCALC
650        UpdateControls()
651       
652        // TO DO -- this needs some logic added, or an additional parameter to properly set the
653        // source aperture
654       
655        popupmenu popup0 win=SASCALC,popmatch=strVal
656        Variable dum=sourceApertureDiam()               //sets the proper value in the header wave
657        return(0)
658End
659
660// strVal is "1/2\"" or similar. note the extra backslash so that " is part of the string
661//
662Function Sim_SetSampleApertureDiam(strVal)
663        String strVal
664       
665        popupmenu popup0_1 win=SASCALC,popmatch=strVal
666        Variable dum=sampleApertureDiam()               //sets the proper value in the header wave
667        return(0)
668End     
669
670Function Sim_SetOffset(offset)
671        Variable offset
672       
673        NVAR detOffset = root:Packages:NIST:SAS:gOffset
674        detOffset = offset      //in cm
675        detectorOffset()                //changes header and estimates (x,y) beamcenter
676        return(0)
677end
678
679Function Sim_SetSDD(sdd)
680        Variable sdd
681       
682        NVAR detDist = root:Packages:NIST:SAS:gDetDist
683
684        detDist = sdd
685        sampleToDetectorDist()          //changes the SDD and wave (DetDist is the global)
686        return(0)
687end
688
689
690// change the huber/sample chamber position
691// if str="checkHuber", the pos is set to huber
692// otherwise, it's set to the sample chamber position
693//
694Function Sim_SetTablePos(strVal)
695        String strVal
696       
697        TableCheckProc(strVal,0)
698        return(0)
699end
700
701
702//
703// ------------ specifc for the simulation
704//
705//
706// type = 0 = none, kills panel
707// type = 1 = 1D
708// type = 2 = 2D
709//
710// -- DON'T leave the do2D global set to 1 - be sure to set back to 0 before exiting
711//
712Function Sim_SetSimulationType(type)
713        Variable type
714
715        STRUCT WMCheckboxAction CB_Struct
716        Variable checkState
717        if(type == 1 || type == 2)
718                CB_Struct.checked = 1
719                checkState = 1
720        else
721                CB_Struct.checked = 0
722                checkState = 0
723        endif
724
725        NVAR do2D = root:Packages:NIST:SAS:gDoMonteCarlo
726
727        if(type == 1)
728                do2D = 0
729        else
730                do2D = 1
731        endif
732       
733        SimCheckProc(CB_Struct)
734
735        // Very important
736        do2D = 0
737       
738        CheckBox checkSim win=SASCALC,value=checkState
739        return(0)
740End
741
742Function Sim_DoMCSimulation()
743
744        STRUCT WMButtonAction ba
745        ba.eventCode = 2                        //fake mouse click on button
746
747        MC_DoItButtonProc(ba)
748        return(0)
749End
750
751Function Sim_Do1DSimulation()
752
753        ReCalculateInten(1)
754        NVAR estCR = root:Packages:NIST:SAS:g_1DEstDetCR
755        return(estCR)
756End
757
758// counting time (set this last - after all of the instrument moves are done AND the
759// intensity has been updated)
760//
761// ctTime is in seconds
762// sets the global variable, and fakes an "entry" in that field
763Function Sim_SetCountTime(ctTime)
764        Variable ctTime
765       
766        STRUCT WMSetVariableAction sva
767        NVAR ct = root:Packages:NIST:SAS:gCntTime
768        ct=ctTime
769        sva.dval = ctTime                       //seconds
770        sva.eventCode = 3               //live update code
771        CountTimeSetVarProc(sva)
772        return(0)
773End
774
775
776Function Sim_SetIncohXS(val)
777        Variable val
778       
779        NVAR xs = root:Packages:NIST:SAS:gSig_incoh
780        xs = val
781        return(0)
782End
783
784Function Sim_SetThickness(val)
785        Variable val
786       
787        NVAR th = root:Packages:NIST:SAS:gThick
788        th = val
789        return(0)
790End
791
792Function Sim_SetSampleRadius(val)
793        Variable val
794       
795        NVAR r2 = root:Packages:NIST:SAS:gR2
796        r2 = val
797       
798        return(0)
799End
800
801Function Sim_SetNumberOfNeutrons(val)
802        Variable val
803       
804        NVAR num = root:Packages:NIST:SAS:gImon
805        num = val
806       
807        return(0)
808End
809
810// 1 == beam stop in
811// 0 == beam stop out == transmission
812//
813Function Sim_SetBeamStopInOut(val)
814        Variable val
815       
816        NVAR BS = root:Packages:NIST:SAS:gBeamStopIn                    //set to zero for beamstop out (transmission)
817        WAVE rw=root:Packages:NIST:SAS:realsRead
818       
819        BS = val                        //set the global
820       
821        // fake the header
822        if(BS == 1)
823                rw[37] = 0                              // make sure BS X = 0 if BS is in
824        else
825                rw[37] = -10                    // fake BS out as X = -10 cm
826        endif
827       
828        return(0)
829End
830
831Function Sim_SetRawCountsCheck(val)
832        Variable val
833       
834        NVAR rawCt = root:Packages:NIST:SAS:gRawCounts
835        rawCt = val
836        return(0)
837End
838
839Function Sim_Set1D_ABS(val)
840        Variable val
841       
842        NVAR gAbs = root:Packages:NIST:SAS:g_1D_DoABS
843        gAbs = val
844       
845        return(0)
846End
847
848Function Sim_Set1D_Noise(val)
849        Variable val
850       
851        NVAR doNoise = root:Packages:NIST:SAS:g_1D_AddNoise
852        doNoise = val
853        return(0)
854End
855
856Function Sim_Set1D_Transmission(val)
857        Variable val
858       
859        NVAR trans = root:Packages:NIST:SAS:gSamTrans
860        trans = val
861        return(0)
862End
863
864Function Sim_SetModelFunction(strVal)
865        String strVal
866       
867        DoWindow MC_SASCALC
868        if(V_flag==1)
869                //then 2D
870                PopupMenu MC_popup0 win=MC_SASCALC,popmatch=strVal
871        endif
872       
873        DoWindow        Sim_1D_Panel
874        if(V_flag==1)
875                //then 1D
876                PopupMenu MC_popup0 win=Sim_1D_Panel,popmatch=strVal
877        endif
878       
879        SVAR gStr = root:Packages:NIST:SAS:gFuncStr
880        gStr = strVal
881
882        return(0)
883End
884
885
886// ------------
887
888//
889// set the threshold for the time warning dialog to some really large value (say 36000 s)
890// while doing the simulation to keep the dialog from popping up and stopping the simulation.
891// then be sure to set it back to 10 s for "normal" simulations that are atttended
892//
893// input val is in seconds
894Function Sim_SetSimTimeWarning(val)
895        Variable val
896
897        NVAR SimTimeWarn = root:Packages:NIST:SAS:g_SimTimeWarn
898        SimTimeWarn = val                       //sets the threshold for the warning dialog     
899
900        return(0)
901end
902
903// if you need to eliminate the high count data to save the rest of the set
904Function Sim_TrimOverflowCounts()
905        Wave w = root:Packages:NIST:SAS:linear_data
906        w = (w > 2767000) ? 0 : w
907        return(0)
908End
909
910// if home path exists, save there, otherwise present a dialog
911// (no sense to use catPathName, since this is simulation, not real data
912//
913Function Sim_Save1D_wName(type,titleStr,fname)
914        String type,titleStr,fname
915       
916        String fullPath
917        NVAR autoSaveIndex = root:Packages:NIST:SAS:gAutoSaveIndex
918
919        //now save the data     
920        PathInfo home
921        fullPath = S_path + fname
922       
923        Save_1DSimData("",runIndex=autoSaveIndex,simLabel=titleStr,saveName=fullPath)
924       
925        autoSaveIndex += 1
926        return(0)
927End
928
929Proc Sim_saveConfProc(waveStr)
930        String waveStr
931       
932        Sim_SaveConfiguration(waveStr)
933End
934//
935// just make a wave and fill it
936// I'll keep track of what's in each element
937// -- not very user friendly, but nobody needs to see this
938//
939// poll the panel to fill it in
940//
941// 0 = instrument
942// 1 = number of guides
943// 2 = source aperture
944// 3 = lambda
945// 4 = delta lambda
946// 5 = huber/chamber
947// 6 = sample aperture
948// 7 = lenses/prism/none
949// 8 = SDD
950// 9 = offset
951//
952Function Sim_SaveConfiguration(waveStr)
953        String waveStr
954       
955        String str=""
956       
957        SetDataFolder root:Packages:NIST:SAS
958       
959        Make/O/T/N=20 $("Config_"+waveStr)
960        Wave/T tw=$("Config_"+waveStr)
961        tw = ""
962       
963        // 0 = instrument
964        SVAR instStr = root:Packages:NIST:SAS:gInstStr
965        tw[0] = "check"+instStr
966       
967        // 1 = number of guides
968        NVAR ng = root:Packages:NIST:SAS:gNg
969        tw[1] = num2str(ng)
970       
971        // 2 = source aperture
972        ControlInfo/W=SASCALC popup0
973        tw[2] = S_Value
974       
975        // 3 = lambda
976        NVAR lam = root:Packages:NIST:SAS:gLambda
977        tw[3] = num2str(lam)
978       
979        // 4 = delta lambda
980//      NVAR dlam = root:Packages:NIST:SAS:gDeltaLambda
981//      tw[4] = num2str(dlam)
982       
983        //or
984        ControlInfo/W=SASCALC popup0_2
985        tw[4] = S_Value
986       
987       
988        // 5 = huber/chamber
989        NVAR sampleTable = root:Packages:NIST:SAS:gTable                //2=chamber, 1=table
990        if(sampleTable==1)
991                str = "checkHuber"
992        else
993                str = "checkChamber"
994        endif
995        tw[5] = str
996       
997        // 6 = sample aperture
998        ControlInfo/W=SASCALC popup0_1
999        tw[6] = S_Value
1000       
1001        // 7 = lenses/prism/none
1002        NVAR lens = root:Packages:NIST:SAS:gUsingLenses         //==0 for no lenses, 1 for lenses(or prisms)
1003        tw[7] = num2str(lens)
1004       
1005        // 8 = SDD
1006        NVAR sdd = root:Packages:NIST:SAS:gDetDist
1007        tw[8] = num2str(sdd)
1008       
1009        // 9 = offset
1010        NVAR offset = root:Packages:NIST:SAS:gOffset
1011        tw[9] = num2str(offset)
1012       
1013        //
1014       
1015        SetDataFolder root:
1016        return(0)
1017End
1018
1019Proc Sim_moveConfProc(waveStr)
1020        String waveStr
1021        Prompt waveStr,"Select Configuration",popup,ListSASCALCConfigs()
1022       
1023        Sim_MoveToConfiguration($("root:Packages:NIST:SAS:"+waveStr))
1024End
1025// restore the configuration given a wave of information
1026//
1027// be sure to recalculate the intensity after all is set
1028// -- some changes recalculate, some do not...
1029//
1030Function Sim_MoveToConfiguration(tw)
1031        WAVE/T tw
1032
1033
1034// 0 = instrument
1035        Sim_SetInstrument(tw[0])
1036         
1037// 1 = number of guides
1038// 2 = source aperture
1039        Sim_SetNumGuides_SrcAp(str2num(tw[1]),tw[2])
1040       
1041// 3 = lambda
1042        Sim_SetLambda(str2num(tw[3]))
1043       
1044// 4 = delta lambda
1045        Sim_SetDeltaLambda(tw[4])
1046
1047// 5 = huber/chamber
1048        Sim_SetTablePos(tw[5])
1049
1050// 6 = sample aperture
1051        Sim_SetSampleApertureDiam(tw[6])
1052
1053// 7 = lenses/prism/none
1054        Sim_SetLenses(str2num(tw[7]))
1055       
1056// 8 = SDD
1057        Sim_SetSDD(str2num(tw[8]))
1058
1059// 9 = offset
1060        Sim_SetOffset(str2num(tw[9]))
1061
1062
1063        ReCalculateInten(1)
1064        return(0)
1065end
1066
1067
1068///////////// a panel to (maybe) write to speed the setup of the runs
1069//
1070Function/S ListSASCALCConfigs()
1071        String str
1072        SetDataFolder root:Packages:NIST:SAS
1073        str = WaveList("Conf*",";","")
1074        SetDataFolder root:
1075        print str
1076        return(str)
1077End
1078
1079//Proc Sim_SetupRunPanel() : Panel
1080//      PauseUpdate; Silent 1           // building window...
1081//      NewPanel /W=(399,44,764,386)
1082//      ModifyPanel cbRGB=(56639,28443,117)
1083//      ShowTools/A
1084//EndMacro
Note: See TracBrowser for help on using the repository browser.