source: sans/Dev/trunk/NCNR_User_Procedures/Reduction/VSANS/V_Protocol_Reduction.ipf @ 1051

Last change on this file since 1051 was 1051, checked in by srkline, 5 years ago

a lot of little changes:

changed the name of the Raw Data display procedure file (removed test)

lots of bug fixes, moving items from the macros menu to proper locations, getting the file status to display properly, some error checking, and cleaning up a few TODO items.

File size: 93.2 KB
Line 
1#pragma rtGlobals=1             // Use modern global access method.
2#pragma version=5.0
3#pragma IgorVersion=6.1
4
5//************************
6
7//
8//*************************
9//////////////////////////////////
10//
11//              KEYWORD=<value> lists used in protocol definitions
12//
13//              KEYWORDS are ALWAYS capitalized, and yes, it does matter
14//
15//              for ABSOLUTE parameters
16//              (4) possible keywords, all with numerical values
17//              TSTAND=value            transmission of the standard
18//              DSTAND=value            thickness of the standard, in centimeters
19//              IZERO=value             I(q=0) value for the standard, in normalized neutron counts
20//              XSECT=value             calibrated cross-section of the standard sample
21//
22//              For calibration with a transmission file, set TSTAND, DSTAND, and XSECT to 1.0
23//              and set IZERO to KAPPA (defined in Tania's handout, or in documentation of MRED_KAP on VAX)
24//
25//
26//              For AVERAGE and for DRAWING
27//                      DRAWING routines only use a subset of the total list, since saving, naming, etc. don't apply
28//              (10) possible keywords, some numerical, some string values
29//              AVTYPE=string           string from set {Circular,Annular,Rectangular,Sector,2D_ASCII,QxQy_ASCII,PNG_Graphic;Sector_PlusMinus;}
30//              PHI=value                       azimuthal angle (-90,90)
31//              DPHI=value                      +/- angular range around phi for average
32//              WIDTH=value             total width of rectangular section, in pixels
33//              SIDE=string             string from set {left,right,both} **note NOT capitalized
34//              QCENTER=value           q-value (1/A) of center of annulus for annular average
35//              QDELTA=value            total width of annulus centered at QCENTER
36//              PLOT=string             string from set {Yes,No} = truth of generating plot of averaged data
37//              SAVE=string             string from set {Yes,No} = truth of saving averaged data to disk, now with "Concatenate"  or "Individual"
38//              NAME=string             string from set {Auto,Manual} = Automatic name generation or Manual(dialog)
39//
40//
41//    BINTYPE=string (VSANS binning type) "One;Two;Four;Slit Mode;", as defined by ksBinTypeStr
42//
43//
44//              For work.DRK usage:
45//              **the list is COMMA delimited, separator is =
46//              DRK=none,DRKMODE=0,
47//              DRK=name                        is the name of the file, must be a full name, expected to be raw data
48//              DRKMODE=value           is a numeric value (0 or 10 to add to the Correct(mode) switch (unused?)
49//
50//////////////////////////////////
51
52Constant kNumProtocolSteps = 12
53
54//main entry procedure for initialzing and displaying the protocol panel
55// initilaizes folders and globals as needed
56//
57Proc V_ReductionProtocolPanel()
58        DoWindow/F V_ProtocolPanel
59        if(V_flag==0)
60                V_InitProtocolPanel()
61                V_ProtocolPanel()
62        Endif
63End
64
65//initialization procedure for the protocol panel
66//note that :gAbsStr is also shared (common global) to that used in
67//the questionnare form of the protcol (see protocol.ipf)
68//
69//0901, uses 8 points in protocol wave
70Proc V_InitProtocolPanel()
71
72        if(exists("     root:Packages:NIST:VSANS:CatVSHeaderInfo:Filenames") == 0)
73                Abort "You must generate a file catalog before building protocols"
74        endif
75       
76        //set up the global variables needed for the protocol panel
77        //global strings to put in a temporary protocol textwave
78        Variable ii=0
79        String waveStr="tempProtocol"
80        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
81        Make/O/T/N=(kNumProtocolSteps) $"root:Packages:NIST:VSANS:Globals:Protocols:tempProtocol" = ""
82
83        String/G root:Packages:NIST:VSANS:Globals:Protocols:gSAM="ask"
84        String/G root:Packages:NIST:VSANS:Globals:Protocols:gBGD="ask"
85        String/G root:Packages:NIST:VSANS:Globals:Protocols:gEMP="ask"
86        String/G root:Packages:NIST:VSANS:Globals:Protocols:gDIV="ask"
87        String/G root:Packages:NIST:VSANS:Globals:Protocols:gMASK="ask"
88        String/G root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr="ask"
89        String/G root:Packages:NIST:VSANS:Globals:Protocols:gAVE="AVTYPE=Circular;SAVE=Yes - Concatenate;NAME=Auto;PLOT=No;BINTYPE=One;"
90        String/G root:Packages:NIST:VSANS:Globals:Protocols:gDRK="DRK=none,DRKMODE=0,"
91       
92        // global strings for trimming data are initialized in the main VSANS initilization
93        //  in case the trimming is done before the protocol panel is opened
94       
95        SetDataFolder root:
96       
97End
98
99
100//button procedure to reset the panel seletctions/checks...etc...
101//to reflect the choices in a previously saved protocol
102// - parses through the protocol and resets the appropriate global strings and
103//updates the panel display
104//
105Function V_RecallProtocolButton(ctrlName) : ButtonControl
106        String ctrlName
107
108        //will reset panel values based on a previously saved protocol
109        //pick a protocol wave from the Protocols folder
110        //MUST move to Protocols folder to get wavelist
111        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
112        Execute "V_PickAProtocol()"
113       
114        //get the selected protocol wave choice through a global string variable
115        SVAR protocolName = root:Packages:NIST:VSANS:Globals:Protocols:gProtoStr
116
117        //If "CreateNew" was selected, ask user to try again
118        if(cmpstr("CreateNew",protocolName) == 0)
119                Abort "CreateNew is for making a new Protocol. Select a previously saved Protocol"
120        Endif
121       
122        //reset the panel based on the protocol textwave (currently a string)
123        V_ResetToSavedProtocol(protocolName)
124       
125        SetDataFolder root:
126        return(0)
127End
128
129//deletes the selected protocol from the list and from memory
130//
131Function V_DeleteProtocolButton(ctrlName) : ButtonControl
132        String ctrlName
133
134        //put up a list of protocols and pick one
135        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
136//      Execute "DeleteAProtocol()"
137        String Protocol=""
138        Prompt Protocol "Delete A Protocol",popup, V_DeletableProtocols()
139        DoPrompt "Select protocol to delete",protocol
140        If(V_flag==1)
141                return(0)
142        endif
143
144        //If "CreateNew, Base, DoAll, or tempProtocol" was selected, do nothing
145        strswitch(protocol)
146                case "CreateNew":
147                        break
148                case "DoAll":
149                        break
150                case "Base":
151                        break
152                case "tempProtocol":
153                        break
154                default:
155                        //delete the protocol
156                        KillWaves/Z $protocol
157        endswitch
158       
159        SetDataFolder root:
160        return(0)
161End
162
163//
164//function that actually parses the protocol specified by nameStr
165//which is just the name of the wave, without a datafolder path
166//
167// TODO
168//  -- update this for 12 steps
169//
170Function V_ResetToSavedProtocol(nameStr)
171        String nameStr
172       
173        //allow special cases of Base and DoAll Protocols to be recalled to panel - since they "ask"
174        //and don't need paths
175       
176        String catPathStr
177        PathInfo catPathName
178        catPathStr=S_path
179       
180        //SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols              //on windows, data folder seems to get reset (erratically) to root:
181        Wave/T w=$("root:Packages:NIST:VSANS:Globals:Protocols:" + nameStr)
182       
183        String fullPath="",comma=",",list="",nameList="",PathStr="",item=""
184        Variable ii=0,numItems,checked,specialProtocol
185       
186        if((cmpstr(nameStr,"Base")==0) || (cmpstr(nameStr,"DoAll")==0))
187                specialProtocol = 1
188        else
189                specialProtocol = 0
190        Endif
191       
192        //background
193        checked = 1
194        nameList = w[0]
195        If(cmpstr(nameList,"none") ==0)
196                checked = 0
197        Endif
198
199        //set the global string to display and checkbox
200        String/G root:Packages:NIST:VSANS:Globals:Protocols:gBGD = nameList
201        CheckBox prot_check win=V_ProtocolPanel,value=checked
202       
203        //empty
204        checked = 1
205        nameList = w[1]
206        If(cmpstr(nameList,"none") ==0)
207                checked = 0
208        Endif
209
210        //set the global string to display and checkbox
211        String/G root:Packages:NIST:VSANS:Globals:Protocols:gEMP = nameList
212        CheckBox prot_check_1 win=V_ProtocolPanel,value=checked
213       
214        //DIV file
215        checked = 1
216        nameList = w[2]
217        If(cmpstr(nameList,"none") ==0)
218                checked = 0
219        Endif
220
221        //set the global string to display and checkbox
222        String/G root:Packages:NIST:VSANS:Globals:Protocols:gDIV = nameList
223        CheckBox prot_check_2 win=V_ProtocolPanel,value=checked
224       
225        //Mask file
226        checked = 1
227        nameList = w[3]
228        If(cmpstr(nameList,"none") ==0)
229                checked = 0
230        Endif
231
232        //set the global string to display and checkbox
233        String/G root:Packages:NIST:VSANS:Globals:Protocols:gMASK = nameList
234        CheckBox prot_check_3 win=V_ProtocolPanel,value=checked
235       
236        //4 = abs parameters
237        list = w[4]
238        numItems = ItemsInList(list,";")
239        checked = 1
240        if(numitems == 4 || numitems == 5)              //allow for protocols with no SDEV list item
241                //correct number of parameters, assume ok
242                String/G root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr = list
243                CheckBox prot_check_9 win=V_ProtocolPanel,value=checked
244        else
245                item = StringFromList(0,list,";")
246                if(cmpstr(item,"none")==0)
247                        checked = 0
248                        list = "none"
249                        String/G root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr = list
250                        CheckBox prot_check_9 win=V_ProtocolPanel,value=checked
251                else
252                        //force to "ask"
253                        checked = 1
254                        String/G root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr = "ask"
255                        CheckBox prot_check_9 win=V_ProtocolPanel,value=checked
256                Endif
257        Endif
258       
259        //5 = averaging choices
260        list = w[5]
261        item = StringByKey("AVTYPE",list,"=",";")
262        if(cmpstr(item,"none") == 0)
263                checked = 0
264                String/G root:Packages:NIST:VSANS:Globals:Protocols:gAVE = "none"
265                CheckBox prot_check_5 win=V_ProtocolPanel,value=checked
266        else
267                checked = 1
268                String/G root:Packages:NIST:VSANS:Globals:Protocols:gAVE = list
269                CheckBox prot_check_5 win=V_ProtocolPanel,value=checked
270        Endif
271       
272//      //6 = DRK choice
273//      list = w[6]
274//      item = StringByKey("DRK",list,"=",",")
275//      //print list,item
276//      if(cmpstr(item,"none") == 0)
277//              checked = 0
278//              String/G root:Packages:NIST:VSANS:Globals:Protocols:gDRK = list
279//              CheckBox prot_check_6 win=V_ProtocolPanel,value=checked
280//      else
281//              checked = 1
282//              String/G root:Packages:NIST:VSANS:Globals:Protocols:gDRK = list
283//              CheckBox prot_check_6 win=V_ProtocolPanel,value=checked
284//      Endif
285       
286        //7 = beginning trim points
287        SVAR gBegPtsStr=root:Packages:NIST:VSANS:Globals:Protocols:gBegPtsStr
288        gBegPtsStr = w[7]
289        //8 = end trim points
290        SVAR gEndPtsStr=root:Packages:NIST:VSANS:Globals:Protocols:gEndPtsStr
291        gEndPtsStr = w[8]
292       
293        //9 = unused
294        //10 = unused
295        //11 = unused
296
297
298        //all has been reset, get out
299        Return (0)
300End
301
302//button action procedure that simply closes the panel
303//
304Function V_DoneProtocolButton(ctrlName) : ButtonControl
305        String ctrlName
306
307        //will gracefully close and exit the protocol panel
308       
309        DoWindow/K V_ProtocolPanel
310End
311
312//button action procedure that saves the current choices on the panel
313//as a named protocol, for later recall
314//asks for a valid name, then creates a protocol from the panel choices
315//creates a wave, and sets the current protocol name to this new protocol
316//
317//now allows the user the choice to overwrite a protocol
318//
319Function V_SaveProtocolButton(ctrlName) : ButtonControl
320        String ctrlName
321
322        Variable notDone=1, newProto=1
323        //will prompt for protocol name, and save the protocol as a text wave
324        //prompt for name of new protocol wave to save
325        do
326                Execute "V_AskForName()"
327                SVAR newProtocol = root:Packages:NIST:VSANS:Globals:Protocols:gNewStr
328               
329                //make sure it's a valid IGOR name
330                newProtocol = CleanupName(newProtocol,0)        //strict naming convention
331                String/G root:Packages:NIST:VSANS:Globals:Protocols:gNewStr=newProtocol         //reassign, if changed
332                Print "newProtocol = ",newProtocol
333               
334                SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
335                if(WaveExists( $("root:Packages:NIST:VSANS:Globals:Protocols:" + newProtocol) ) == 1)
336                        //wave already exists
337                        DoAlert 1,"That name is already in use. Do you wish to overwrite the existing protocol?"
338                        if(V_Flag==1)
339                                notDone = 0
340                                newProto = 0
341                        else
342                                notDone = 1
343                        endif
344                else
345                        //name is good
346                        notDone = 0
347                Endif
348        while(notDone)
349       
350        //current data folder is  root:Packages:NIST:VSANS:Globals:Protocols
351        if(newProto)
352                Make/O/T/N=(kNumProtocolSteps) $("root:Packages:NIST:VSANS:Globals:Protocols:" + newProtocol)
353        Endif
354       
355        V_MakeProtocolFromPanel( $("root:Packages:NIST:VSANS:Globals:Protocols:" + newProtocol) )
356        String/G  root:Packages:NIST:VSANS:Globals:Protocols:gProtoStr = newProtocol
357       
358        //the data folder WAS changed above, this must be reset to root:
359        SetDatafolder root:
360End
361
362//function that does the guts of reading the panel controls and globals
363//to create the necessary text fields for a protocol
364//Wave/T w (input) is an empty text wave of 8 elements for the protocol
365//on output, w[] is filled with the protocol strings as needed from the panel
366//
367// TODO
368// -- update for 12 points
369//
370Function V_MakeProtocolFromPanel(w)
371        Wave/T w
372       
373        //construct the protocol text wave form the panel
374        //it is to be parsed by ExecuteProtocol() for the actual data reduction
375        PathInfo catPathName                    //this is where the files came from
376        String pathstr=S_path,tempStr,curList
377        Variable checked,ii,numItems
378       
379        //look for checkbox, then take each item in list and prepend the path
380        //w[0] = background
381        ControlInfo/W=V_ProtocolPanel prot_check
382        checked = V_value
383        if(checked)
384                //build the list
385                //just read the global
386                SVAR str=root:Packages:NIST:VSANS:Globals:Protocols:gBGD
387                if(cmpstr(str,"ask")==0)
388                        w[0] = str              //just ask
389                else
390                        tempstr = V_ParseRunNumberList(str)
391                        if(strlen(tempStr)==0)
392                                return(1)                               //error parsing list
393                        else
394                                w[0] = tempstr
395                                str = tempstr           //set the protocol and the global
396                        endif
397                endif
398        else
399                //none used - set textwave (and global?)
400                w[0] = "none"
401                String/G root:Packages:NIST:VSANS:Globals:Protocols:gBGD = "none"
402        endif
403       
404        //w[1] = empty
405        ControlInfo/W=V_ProtocolPanel prot_check_1
406        checked = V_value
407        if(checked)
408                //build the list
409                //just read the global
410                SVAR str=root:Packages:NIST:VSANS:Globals:Protocols:gEMP
411                if(cmpstr(str,"ask")==0)
412                        w[1] = str
413                else
414                        tempstr = V_ParseRunNumberList(str)
415                        if(strlen(tempStr)==0)
416                                return(1)
417                        else
418                                w[1] = tempstr
419                                str=tempStr
420                        endif
421                endif
422        else
423                //none used - set textwave (and global?)
424                w[1] = "none"
425                String/G root:Packages:NIST:VSANS:Globals:Protocols:gEMP = "none"
426        endif
427       
428        //w[2] = div file
429        ControlInfo/W=V_ProtocolPanel prot_check_2
430        checked = V_value
431        if(checked)
432                //build the list
433                //just read the global
434                SVAR str=root:Packages:NIST:VSANS:Globals:Protocols:gDIV
435                if(cmpstr(str,"ask")==0)
436                        w[2] = str
437                else
438                        tempStr = V_ParseRunNumberList(str)
439                        if(strlen(tempStr)==0)
440                                return(1)
441                        else
442                                w[2] = tempstr
443                                str=tempstr
444                        endif
445                endif
446        else
447                //none used - set textwave (and global?)
448                w[2] = "none"
449                String/G root:Packages:NIST:VSANS:Globals:Protocols:gDIV = "none"
450        endif
451       
452        //w[3] = mask file
453        ControlInfo/W=V_ProtocolPanel prot_check_3
454        checked = V_value
455        if(checked)
456                //build the list
457                //just read the global
458                SVAR str=root:Packages:NIST:VSANS:Globals:Protocols:gMASK
459                if(cmpstr(str,"ask")==0)
460                        w[3] = str
461                else
462                        tempstr = V_ParseRunNumberList(str)
463                        if(strlen(tempstr)==0)
464                                return(1)
465                        else
466                                w[3] = tempstr
467                                str = tempstr
468                        endif
469                endif
470        else
471                //none used - set textwave (and global?)
472                w[3] = "none"
473                String/G root:Packages:NIST:VSANS:Globals:Protocols:gMASK = "none"
474        endif
475       
476        //w[4] = abs parameters
477        ControlInfo/W=V_ProtocolPanel prot_check_9
478        checked = V_value
479        if(checked)
480                //build the list
481                //just read the global
482                SVAR str=root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr
483                w[4] = str
484        else
485                //none used - set textwave (and global?)
486                w[4] = "none"
487                String/G root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr = "none"
488        endif
489       
490        //w[5] = averaging choices
491        ControlInfo/W=V_ProtocolPanel prot_check_5                      //do the average?
492        checked = V_value
493        if(checked)
494                //just read the global
495                SVAR avestr=root:Packages:NIST:VSANS:Globals:Protocols:gAVE
496                w[5] = avestr
497        else
498                //none used - set textwave
499                w[5] = "AVTYPE=none;"
500        endif
501       
502        //w[6]
503        //work.DRK information
504        SVAR drkStr=root:Packages:NIST:VSANS:Globals:Protocols:gDRK
505        w[6] = drkStr
506       
507        //w[7]
508        // beginning trim points
509        SVAR gBegPtsStr=root:Packages:NIST:VSANS:Globals:Protocols:gBegPtsStr
510        w[7] = gBegPtsStr
511       
512        //w[8]
513        // End trim points
514        SVAR gEndPtsStr=root:Packages:NIST:VSANS:Globals:Protocols:gEndPtsStr   
515        w[8] = gEndPtsStr
516       
517        //w[9]
518        //currently unused
519        w[9] = ""
520        //w[10]
521        //currently unused
522        w[10] = ""
523        //w[11]
524        //currently unused
525        w[11] = ""
526               
527        return(0)
528End
529
530
531//
532Function V_PickSAMButton(ctrlName) : ButtonControl
533        String ctrlName
534
535
536End
537
538
539
540
541//
542// TODO
543// -- identifying "intent" using V_get can be very slow, since it reads in each and every data file.
544//   grep is a lot faster, but there can be a lot of false "hits" unless I do it correctly.
545//
546//
547//      //grep through what text I can find in the VAX binary
548//      // Grep Note: the \\b sequences limit matches to a word boundary before and after
549//      // "boondoggle", so "boondoggles" and "aboondoggle" won't match.
550//      if(gRadioVal == 2)
551//              for(ii=0;ii<num;ii+=1)
552//                      item=StringFromList(ii, newList , ";")
553////                    Grep/P=catPathName/Q/E=("(?i)\\b"+match+"\\b") item
554//                      Grep/P=catPathName/Q/E=("(?i)"+match) item
555//                      if( V_value )   // at least one instance was found
556////                            Print "found ", item,ii
557//                              list += item + ";"
558//                      endif
559//              endfor
560//
561//              newList = list
562//      endif
563
564// match is the string to look for in the search
565// 0 is a flag to tell it to look in the file catalog (the fastest method)
566// Other options are to grep, or to read the intent field in every file
567Function/S V_GetSAMList()
568
569        String match="SAMPLE"
570        String list = V_getFileIntentList(match,0)
571
572//      Printf "SAM files = %s\r",list 
573        return(list)
574end
575
576
577Function/S V_GetBGDList()
578
579        String match="BLOCKED BEAM"
580        String list = V_getFileIntentList(match,0)
581
582//      Printf "BGD files = %s\r",list 
583        return(list)
584end
585
586
587Function/S V_GetEMPList()
588
589        String match="EMPTY CELL"
590        String list = V_getFileIntentList(match,0)
591
592//      Printf "EMP files = %s\r",list 
593        return(list)
594end
595
596
597// testStr is the "intent" string, or grep string
598// method is the method to use to find the file
599// 0 = (default) is to use the file catalog (= fastest)
600// 1 = Grep (not terribly slow)
601// 2 = read every file (bad choice)
602//
603Function/S V_getFileIntentList(testStr,method)
604        String testStr
605        Variable method
606       
607        Variable ii,num
608        String list="",item="",fname,newList,intent
609
610        // read every file...
611        if(method == 2)
612                PathInfo catPathName
613                String path = S_path
614                newList = V_GetRawDataFileList()
615                num=ItemsInList(newList)
616               
617                for(ii=0;ii<num;ii+=1)
618                        item=StringFromList(ii, newList , ";")
619                        fname = path + item
620                        intent = V_getReduction_intent(fname)
621                        if(cmpstr(intent,testStr) == 0)
622                                list += item + ";"
623                        endif
624                endfor 
625        endif
626       
627        // use Grep
628        if(method == 1)
629                newList = V_GetRawDataFileList()
630                num=ItemsInList(newList)
631                for(ii=0;ii<num;ii+=1)
632                        item=StringFromList(ii, newList , ";")
633                        Grep/P=catPathName/Q/E=("(?i)"+testStr) item
634                        if( V_value )   // at least one instance was found
635        //                              Print "found ", item,ii
636                                list += item + ";"
637                        endif
638                endfor 
639       
640        else
641        // get the list from the file catalog
642       
643                WAVE/T fileNameW = root:Packages:NIST:VSANS:CatVSHeaderInfo:Filenames
644                WAVE/T intentW = root:Packages:NIST:VSANS:CatVSHeaderInfo:Intent
645               
646                Variable np = numpnts(intentW)          //fileNameW is LONGER - so don't use numpnts(fileWave)
647                for(ii=0;ii<np;ii+=1)
648                        if(cmpstr(intentW[ii],testStr)==0)              //this is case-INSENSITIVE (necessary, since the case is unknown)
649                                list += fileNameW[ii] + ";"
650                        endif           
651                endfor
652               
653                List = SortList(List,";",0)
654        endif
655       
656        return(list)
657end
658
659//
660// TODO
661// -- decide on the way to locate the blocked beam files. Is the enumerated text of the intent
662//    sufficiently unique to locate the file?
663// -- can I use the Data Catalog waves to locate the files  - faster?
664//    (fails if the catalog has not been read in recently enough)
665//
666//
667Function/S V_PickBGDButton(ctrlName) : ButtonControl
668        String ctrlName
669
670        String list="",item="",fname,newList,intent
671        Variable ii,num
672       
673        PathInfo catPathName
674        String path = S_path
675
676        String match="BLOCKED BEAM"
677
678//s_tic()
679// get the list from the file catalog (=0.0007s)
680//     
681        WAVE/T fileNameW = root:Packages:NIST:VSANS:CatVSHeaderInfo:Filenames
682        WAVE/T intentW = root:Packages:NIST:VSANS:CatVSHeaderInfo:Intent
683       
684        Variable np = numpnts(intentW)
685        for(ii=0;ii<np;ii+=1)
686                if(cmpstr(intentW[ii],match)==0)
687                        list += fileNameW[ii] + ";"
688                endif           
689        endfor
690       
691        List = SortList(List,";",0)
692        Printf "BGD files = %s\r",list 
693//S_toc()       
694       
695       
696////S_tic()                     // from grep = 3.3s
697//      newList = V_GetRawDataFileList()
698//      num=ItemsInList(newList)
699//     
700////    for(ii=0;ii<num;ii+=1)
701////            item=StringFromList(ii, newList , ";")
702////            fname = path + item
703////            intent = V_getReduction_intent(fname)
704////            if(cmpstr(intent,"BLOCKED BEAM") == 0)
705////                    list += item + ";"
706////            endif
707////
708////    endfor
709//      list = ""       
710//      for(ii=0;ii<num;ii+=1)
711//              item=StringFromList(ii, newList , ";")
712//              Grep/P=catPathName/Q/E=("(?i)"+match) item
713//              if( V_value )   // at least one instance was found
714////                            Print "found ", item,ii
715//                      list += item + ";"
716//              endif
717//      endfor
718//             
719//             
720//      List = SortList(List,";",0)
721//      Printf "BGD files = %s\r",list
722////S_toc()
723       
724        return(list)
725End
726
727
728//
729Function/S V_PickEMPButton(ctrlName) : ButtonControl
730        String ctrlName
731        String list="",item="",fname,newList,intent
732        Variable ii,num
733       
734        PathInfo catPathName
735        String path = S_path
736
737        String match="EMPTY CELL"
738
739// get the list from the file catalog (=0.0007s)
740//     
741        WAVE/T fileNameW = root:Packages:NIST:VSANS:CatVSHeaderInfo:Filenames
742        WAVE/T intentW = root:Packages:NIST:VSANS:CatVSHeaderInfo:Intent
743       
744        Variable np = numpnts(intentW)
745        for(ii=0;ii<np;ii+=1)
746                if(cmpstr(intentW[ii],match)==0)
747                        list += fileNameW[ii] + ";"
748                endif           
749        endfor
750       
751        List = SortList(List,";",0)
752        Printf "EMP files = %s\r",list 
753
754
755//     
756//      newList = V_GetRawDataFileList()
757//      num=ItemsInList(newList)
758//     
759////    for(ii=0;ii<num;ii+=1)
760////            item=StringFromList(ii, newList , ";")
761////            fname = path + item
762////            intent = V_getReduction_intent(fname)
763////            if(cmpstr(intent,"EMPTY CELL") == 0)
764////                    list += item + ";"
765////            endif
766////
767////    endfor
768//
769//      for(ii=0;ii<num;ii+=1)
770//              item=StringFromList(ii, newList , ";")
771//              Grep/P=catPathName/Q/E=("(?i)"+match) item
772//              if( V_value )   // at least one instance was found
773////                            Print "found ", item,ii
774//                      list += item + ";"
775//              endif
776//
777//      endfor
778//             
779//      List = SortList(List,";",0)
780//      Printf "EMP files = %s\r",list
781       
782        return(list)
783End
784
785
786//
787Function/S V_PickEMPBeamButton(ctrlName) : ButtonControl
788        String ctrlName
789        String list="",item="",fname,newList,intent
790        Variable ii,num
791       
792        PathInfo catPathName
793        String path = S_path
794
795        String match="EMPTY BEAM"
796
797// get the list from the file catalog (=0.0007s)
798//     
799        WAVE/T fileNameW = root:Packages:NIST:VSANS:CatVSHeaderInfo:Filenames
800        WAVE/T intentW = root:Packages:NIST:VSANS:CatVSHeaderInfo:Intent
801       
802        Variable np = numpnts(intentW)
803        for(ii=0;ii<np;ii+=1)
804                if(cmpstr(intentW[ii],match)==0)
805                        list += fileNameW[ii] + ";"
806                endif           
807        endfor
808       
809        List = SortList(List,";",0)
810        Printf "EMP Beam files = %s\r",list     
811
812
813
814       
815        return(list)
816End
817
818Function/S V_GetDIVList()
819
820        String list="",item="",fname,newList,intent
821        Variable ii,num
822       
823        PathInfo catPathName
824        String path = S_path
825       
826        newList = V_Get_NotRawDataFileList()
827        num=ItemsInList(newList)
828       
829//      for(ii=0;ii<num;ii+=1)
830//              item=StringFromList(ii, newList , ";")
831//              fname = path + item
832//              intent = V_getReduction_intent(fname)
833//              if(cmpstr(intent,"SENSITIVITY") == 0)
834//                      list += item + ";"
835//              endif
836//
837//      endfor
838
839        String match="DIV"
840        for(ii=0;ii<num;ii+=1)
841                item=StringFromList(ii, newList , ";")
842                Grep/P=catPathName/Q/E=("(?i)\\b"+match+"\\b") item
843//              Grep/P=catPathName/Q/E=("(?i)"+match) item
844                if( V_value )   // at least one instance was found
845//                              Print "found ", item,ii
846                        if(strsearch(item,"pxp",0,2) == -1)             //does NOT contain .pxp (the current experiment will be a match)
847                                list += item + ";"
848                        endif
849                endif
850        endfor
851               
852        List = SortList(List,";",0)
853
854        return(list)
855end
856
857// TODO
858// -- find proper way to search for these files
859// -- they *may* be written to the file header(reduction block)
860// -- or grep for VSANS_DIV (in the title)
861Function/S V_PickDIVButton(ctrlName) : ButtonControl
862        String ctrlName
863        String list="",item="",fname,newList,intent
864        Variable ii,num
865       
866        PathInfo catPathName
867        String path = S_path
868       
869        newList = V_Get_NotRawDataFileList()
870        num=ItemsInList(newList)
871       
872//      for(ii=0;ii<num;ii+=1)
873//              item=StringFromList(ii, newList , ";")
874//              fname = path + item
875//              intent = V_getReduction_intent(fname)
876//              if(cmpstr(intent,"SENSITIVITY") == 0)
877//                      list += item + ";"
878//              endif
879//
880//      endfor
881
882        String match="VSANS_DIV"                //this is part of the title of a VSANS DIV file
883        for(ii=0;ii<num;ii+=1)
884                item=StringFromList(ii, newList , ";")
885                Grep/P=catPathName/Q/E=("(?i)\\b"+match+"\\b") item
886//              Grep/P=catPathName/Q/E=("(?i)"+match) item
887                if( V_value )   // at least one instance was found
888//                              Print "found ", item,ii
889                                list += item + ";"
890                endif
891
892        endfor
893               
894        List = SortList(List,";",0)
895        Printf "DIV files = %s\r",list
896       
897        return(list)
898
899End
900
901Function/S V_GetMSKList()
902
903        String list="",item="",fname,newList,intent
904        Variable ii,num
905       
906        PathInfo catPathName
907        String path = S_path
908       
909        newList = V_Get_NotRawDataFileList()
910        num=ItemsInList(newList)
911       
912//      for(ii=0;ii<num;ii+=1)
913//              item=StringFromList(ii, newList , ";")
914//              fname = path + item
915//              intent = V_getReduction_intent(fname)
916//              if(cmpstr(intent,"SENSITIVITY") == 0)
917//                      list += item + ";"
918//              endif
919//
920//      endfor
921
922//      String match="MASK"             // this is part of the title of a VSANS MASK file
923        String match="VSANS_MASK"               // this is part of the title of a VSANS MASK file
924        for(ii=0;ii<num;ii+=1)
925                item=StringFromList(ii, newList , ";")
926                Grep/P=catPathName/Q/E=("(?i)\\b"+match+"\\b") item
927//              Grep/P=catPathName/Q/E=("(?i)"+match) item
928                if( V_value )   // at least one instance was found
929//                              Print "found ", item,ii
930                        if(strsearch(item,"pxp",0,2) == -1)             //does NOT contain .pxp (the current experiment will be a match)
931                                list += item + ";"
932                        endif
933                endif
934
935        endfor
936               
937        List = SortList(List,";",0)
938
939        return(list)
940end
941
942
943//
944// TODO
945// -- find proper way to search for these files
946// -- they *may* be written to the file header(reduction block)
947// -- or grep for VSANS_MASK (in the title)
948Function/S V_PickMASKButton(ctrlName) : ButtonControl
949        String ctrlName
950        String list="",item="",fname,newList,intent
951        Variable ii,num
952       
953        PathInfo catPathName
954        String path = S_path
955       
956        newList = V_Get_NotRawDataFileList()
957        num=ItemsInList(newList)
958       
959//      for(ii=0;ii<num;ii+=1)
960//              item=StringFromList(ii, newList , ";")
961//              fname = path + item
962//              intent = V_getReduction_intent(fname)
963//              if(cmpstr(intent,"MASK") == 0)
964//                      list += item + ";"
965//              endif
966//
967//      endfor
968
969        String match="MASK"
970        for(ii=0;ii<num;ii+=1)
971                item=StringFromList(ii, newList , ";")
972                Grep/P=catPathName/Q/E=("(?i)\\b"+match+"\\b") item
973//              Grep/P=catPathName/Q/E=("(?i)"+match) item
974                if( V_value )   // at least one instance was found
975//                              Print "found ", item,ii
976                        list += item + ";"
977                endif
978
979        endfor
980               
981        List = SortList(List,";",0)
982        Printf "MASK files = %s\r",list
983       
984        return(list)   
985
986       
987End
988
989//button action function to reduce one file with the information specified on
990//the panel
991//a temporary protocol is created, even if the fields correspond to a named protocol
992//(only the protocol wave values are written to the data header, but the name is written to the
993//schematic - this could cause some unwanted confusion)
994//
995//if a sample file(s) is selected, only that file(s) will be reduced
996//if no file is selected, the user will be prompted with a standard open
997//dialog to select sample data file(s)
998//
999Function V_ReduceOneButton(ctrlName) : ButtonControl
1000        String ctrlName
1001
1002        //parse the information on the panel and assign to tempProtocol wave (in protocol folder)
1003        //and execute
1004        String temp="root:Packages:NIST:VSANS:Globals:Protocols:tempProtocol"
1005        Wave/T w=$temp
1006        Variable ii=0,num=12
1007        do
1008                w[ii] = ""
1009                ii+=1
1010        while(ii<num)
1011       
1012        V_MakeProtocolFromPanel(w)
1013
1014        //the "current" protocol is the "tempProtocol" that was parsed from the panel input
1015        //set the global, so that the data writing routine can find the protocol wave (fatal otherwise)
1016        String/G root:Packages:NIST:VSANS:Globals:Protocols:gProtoStr="tempProtocol"
1017       
1018        PathInfo catPathName                    //this is where the files came from
1019        String pathstr=S_path,samStr
1020       
1021        //take the string from the panel
1022        SVAR tempStr = root:Packages:NIST:VSANS:Globals:Protocols:gSAM
1023       
1024        if( (strlen(tempStr) == 0) || (cmpstr(tempStr,"ask")==0) )
1025                //let user select the files
1026                tempStr="ask"
1027                V_ExecuteProtocol(temp,tempStr)
1028                return(0)
1029        Else
1030                //parse the list of numbers
1031                //send only the filenames, without paths
1032                samStr = V_ParseRunNumberList(tempStr)
1033                If(strlen(samStr)==0)
1034                        DoAlert 0,"The SAM file number cound not be interpreted. Please enter a valid run number or filename"
1035                        return(1)
1036                endif
1037                tempStr=samStr          //reset the global
1038                V_ExecuteProtocol(temp,samStr)
1039                return(0)
1040        endif
1041End
1042
1043
1044//button action function will prompt user for absolute scaling parameters
1045//either from an empty beam file or by manually entering the 4 required values
1046//uses the same function and shared global string as the questionnare form of reduction
1047//in "protocol.ipf" - the string is root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr
1048//
1049Function V_SetABSParamsButton(ctrlName) : ButtonControl
1050        String ctrlName
1051
1052        //will prompt for a list of ABS parameters (4) through a global string variable
1053       
1054        Execute "V_AskForAbsoluteParams_Quest()"
1055       
1056End
1057
1058
1059
1060//the panel recreation macro
1061//
1062Window V_ProtocolPanel()
1063        PauseUpdate; Silent 1           // building window...
1064        NewPanel /W=(1280,332,1630,932) /K=1 as "VSANS Reduction Protocol"
1065        ModifyPanel cbRGB=(56589,50441,50159), fixedSize=1
1066        SetDrawLayer UserBack
1067        DrawLine 3,65,301,65
1068        DrawLine 3,157,301,157
1069        DrawLine 3,208,301,208
1070        DrawLine 3,257,301,257
1071        DrawLine 3,305,301,305
1072        DrawLine 3,350,301,350
1073        DrawLine 3,445,301,445
1074        DrawLine 3,513,301,513
1075        DrawLine 3,396,301,396
1076
1077//
1078        Button button_help,pos={300,2},size={25,20},proc=V_ShowProtoHelp,title="?"
1079        Button button_help,help={"Show the help file for setting up a reduction protocol"}
1080        Button button_quest,pos={20,2},size={150,20},proc=V_ProtocolQuestionnaire,title="Questions"
1081        Button button_quest,help={"Run through the questionnaire for setting up a reduction protocol"}
1082        Button button_quest,disable=2
1083
1084
1085        PopupMenu popup_sam,pos={85,68},size={51,23},proc=SAMFilePopMenuProc
1086        PopupMenu popup_sam,mode=1,value= #"V_getSAMList()"     
1087        PopupMenu popup_bkg,pos={85,164},size={51,23},proc=BKGFilePopMenuProc
1088        PopupMenu popup_bkg,mode=1,value= #"V_getBGDList()"
1089        PopupMenu popup_emp,pos={85,213},size={51,23},proc=EMPFilePopMenuProc
1090        PopupMenu popup_emp,mode=1,value= #"V_getEMPList()"
1091        PopupMenu popup_div,pos={85,263},size={51,23},proc=DIVFilePopMenuProc
1092        PopupMenu popup_div,mode=1,value= #"V_getDIVList()"
1093        PopupMenu popup_msk,pos={85,356},size={51,23},proc=MSKFilePopMenuProc
1094        PopupMenu popup_msk,mode=1,value= #"V_getMSKList()"     
1095               
1096               
1097        CheckBox prot_check,pos={6,163},size={74,14},title="Background"
1098        CheckBox prot_check,help={"If checked, the specified background file will be included in the data reduction. If the file name is \"ask\", then the user will be prompted for the file"}
1099        CheckBox prot_check,value= 1
1100        CheckBox prot_check_1,pos={6,215},size={71,14},title="Empty Cell"
1101        CheckBox prot_check_1,help={"If checked, the specified empty cell file will be included in the data reduction. If the file name is \"ask\", then the user will be prompted for the file"}
1102        CheckBox prot_check_1,value= 1
1103        CheckBox prot_check_2,pos={6,263},size={72,14},title="Sensitivity"
1104        CheckBox prot_check_2,help={"If checked, the specified detector sensitivity file will be included in the data reduction. If the file name is \"ask\", then the user will be prompted for the file"}
1105        CheckBox prot_check_2,value= 1
1106        CheckBox prot_check_3,pos={6,356},size={43,14},title="Mask"
1107        CheckBox prot_check_3,help={"If checked, the specified mask file will be included in the data reduction. If the file name is \"ask\", then the user will be prompted for the file"}
1108        CheckBox prot_check_3,value= 1
1109        CheckBox prot_check_4,pos={6,70},size={53,14},title="Sample"
1110        CheckBox prot_check_4,help={"If checked, the specified sample file will be included in the data reduction. If the file name is \"ask\", then the user will be prompted for the file"}
1111        CheckBox prot_check_4,value= 1
1112        CheckBox prot_check_5,pos={6,399},size={56,14},title="Average"
1113        CheckBox prot_check_5,help={"If checked, the specified averaging will be performed at the end of the data reduction."}
1114        CheckBox prot_check_5,value= 1 
1115        CheckBox prot_check_9,pos={6,310},size={59,14},title="Absolute"
1116        CheckBox prot_check_9,help={"If checked, absolute calibration will be included in the data reduction. If the parameter list is \"ask\", then the user will be prompted for absolue parameters"}
1117        CheckBox prot_check_9,value= 1
1118       
1119
1120//      Button pick_sam,pos={214,28},size={70,20},proc=V_PickSAMButton,title="set SAM"
1121//      Button pick_sam,help={"This button will set the file selected in the File Catalog table to be the sample file"}
1122//      Button pick_bgd,pos={214,75},size={70,20},proc=V_PickBGDButton,title="set BGD"
1123//      Button pick_bgd,help={"This button will set the file selected in the File Catalog table to be the background file."}
1124//      Button pick_emp,pos={214,125},size={70,20},proc=V_PickEMPButton,title="set EMP"
1125//      Button pick_emp,help={"This button will set the file selected in the File Catalog table to be the empty cell file."}
1126//      Button pick_DIV,pos={214,173},size={70,20},proc=V_PickDIVButton,title="set DIV"
1127//      Button pick_DIV,help={"This button will set the file selected in the File Catalog table to be the sensitivity file."}
1128        Button pick_ABS,pos={264,308},size={70,20},proc=V_SetABSParamsButton,title="set ABS"
1129        Button pick_ABS,help={"This button will prompt the user for absolute scaling parameters"}       
1130//      Button pick_MASK,pos={214,266},size={70,20},proc=V_PickMASKButton,title="set MASK"
1131//      Button pick_MASK,help={"This button will set the file selected in the File Catalog table to be the mask file."}
1132
1133
1134        Button pick_AVE,pos={188,401},size={150,20},proc=V_SetAverageParamsButtonProc,title="set AVERAGE params"
1135        Button pick_AVE,help={"Prompts the user for the type of 1-D averaging to perform, as well as saving options"}
1136
1137       
1138        Button pick_trim,pos={264,454},size={70,20},proc=V_TrimDataProtoButton,title="Trim"
1139        Button pick_trim,help={"This button will prompt the user for trimming parameters"}     
1140       
1141       
1142        SetVariable samStr,pos={6,90},size={250,15},title="file:"
1143        SetVariable samStr,help={"Filename of the sample file(s) to be used in the data reduction"}
1144        SetVariable samStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gSAM           
1145        SetVariable bgdStr,pos={7,186},size={250,15},title="file:"
1146        SetVariable bgdStr,help={"Filename of the background file(s) to be used in the data reduction"}
1147        SetVariable bgdStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gBGD
1148        SetVariable empStr,pos={8,236},size={250,15},title="file:"
1149        SetVariable empStr,help={"Filename of the empty cell file(s) to be used in the data reduction"}
1150        SetVariable empStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gEMP
1151        SetVariable divStr,pos={9,285},size={250,15},title="file:"
1152        SetVariable divStr,help={"Filename of the detector sensitivity file to be used in the data reduction"}
1153        SetVariable divStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gDIV
1154        SetVariable maskStr,pos={9,377},size={250,15},title="file:"
1155        SetVariable maskStr,help={"Filename of the mask file to be used in the data reduction"}
1156        SetVariable maskStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gMASK
1157        SetVariable absStr,pos={7,331},size={250,15},title="parameters:"
1158        SetVariable absStr,help={"Keyword-string of values necessary for absolute scaling of data. Remaining parameters are taken from the sample file."}
1159        SetVariable absStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr
1160        SetVariable aveStr,pos={9,424},size={250,15},title="parameters:"
1161        SetVariable aveStr,help={"Keyword-string of choices used for averaging and saving the 1-D data files"}
1162        SetVariable aveStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gAVE
1163
1164        SetVariable begStr,pos={9,464},size={250,15},title="Beg Trim:"
1165        SetVariable begStr,help={"Keyword-string of choices used for averaging and saving the 1-D data files"}
1166        SetVariable begStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gBegPtsStr
1167        SetVariable endStr,pos={9,484},size={250,15},title="End Trim:"
1168        SetVariable endStr,help={"Keyword-string of choices used for averaging and saving the 1-D data files"}
1169        SetVariable endStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gEndPtsStr
1170
1171
1172       
1173        //only show DRK if user wants to see it
1174        //if global = 1,then show => set disable = 0
1175//      CheckBox prot_check_6,pos={6,363},size={113,14},proc=DrkCheckProc,title="Use DRK correction"
1176//      CheckBox prot_check_6,help={"If checked, the selected file will be used for DRK correction. Typically this is NOT checked"}
1177//      CheckBox prot_check_6,value= 0,disable = (!root:Packages:NIST:gAllowDRK)
1178//      SetVariable drkStr,pos={120,363},size={150,15},title="."
1179//      SetVariable drkStr,help={"DRK detector count file"},disable = (!root:Packages:NIST:gAllowDRK)
1180//      SetVariable drkStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gDRK
1181
1182
1183        Button export_button, size={120,20},pos={125,540},title="Export to Data",proc=V_ExportFileProtocol
1184        Button export_button, help={"Exports the protocol to data file on disk for Importing into another experiment"}
1185        Button import_button, size={120,20},pos={125,562},title="Import from Data",proc=V_ImportFileProtocol
1186        Button import_button,help={"Imports a protocol from a data file on disk for use in this experiment"}
1187        Button recallProt,pos={7,540},size={107,20},proc=V_RecallProtocolButton,title="Recall Protocol"
1188        Button recallProt,help={"Resets the panel to the file choices in  a previously saved protocol"}
1189        Button del_protocol,pos={7,562},size={110,20},proc=V_DeleteProtocolButton,title="Delete Protocol"
1190        Button del_protocol,help={"Use this to delete a previously saved protocol."}
1191        Button done_protocol,pos={285,562},size={45,20},proc=V_DoneProtocolButton,title="Done"
1192        Button done_protocol,help={"This button will close the panel. The panel can be recalled at any time from the SANS menu."}
1193        Button saveProtocol,pos={7,518},size={100,20},proc=V_SaveProtocolButton,title="Save Protocol"
1194        Button saveProtocol,help={"Saves the cerrent selections in the panel to a protocol which can be later recalled"}
1195        Button ReduceOne,pos={240,518},size={100,20},proc=V_ReduceOneButton,title="Reduce A File"
1196        Button ReduceOne,help={"Using the panel selections, the specified sample file will be reduced. If none is specified, the user will be prompted for a sample file"}
1197
1198EndMacro
1199
1200
1201
1202
1203
1204Function SAMFilePopMenuProc(pa) : PopupMenuControl
1205        STRUCT WMPopupAction &pa
1206
1207        switch( pa.eventCode )
1208                case 2: // mouse up
1209                        Variable popNum = pa.popNum
1210                        String popStr = pa.popStr
1211                        SVAR tempStr = root:Packages:NIST:VSANS:Globals:Protocols:gSAM
1212                        tempStr = popStr
1213                        break
1214                case -1: // control being killed
1215                        break
1216        endswitch
1217
1218        return 0
1219End
1220
1221
1222Function BKGFilePopMenuProc(pa) : PopupMenuControl
1223        STRUCT WMPopupAction &pa
1224
1225        switch( pa.eventCode )
1226                case 2: // mouse up
1227                        Variable popNum = pa.popNum
1228                        String popStr = pa.popStr
1229                        SVAR tempStr = root:Packages:NIST:VSANS:Globals:Protocols:gBGD
1230                        tempStr = popStr
1231                        break
1232                case -1: // control being killed
1233                        break
1234        endswitch
1235
1236        return 0
1237End
1238
1239Function EMPFilePopMenuProc(pa) : PopupMenuControl
1240        STRUCT WMPopupAction &pa
1241
1242        switch( pa.eventCode )
1243                case 2: // mouse up
1244                        Variable popNum = pa.popNum
1245                        String popStr = pa.popStr
1246                        SVAR tempStr = root:Packages:NIST:VSANS:Globals:Protocols:gEMP
1247                        tempStr = popStr
1248                        break
1249                case -1: // control being killed
1250                        break
1251        endswitch
1252
1253        return 0
1254End
1255
1256Function DIVFilePopMenuProc(pa) : PopupMenuControl
1257        STRUCT WMPopupAction &pa
1258
1259        switch( pa.eventCode )
1260                case 2: // mouse up
1261                        Variable popNum = pa.popNum
1262                        String popStr = pa.popStr
1263                        SVAR tempStr = root:Packages:NIST:VSANS:Globals:Protocols:gDIV
1264                        tempStr = popStr
1265                        break
1266                case -1: // control being killed
1267                        break
1268        endswitch
1269
1270        return 0
1271End
1272
1273Function MSKFilePopMenuProc(pa) : PopupMenuControl
1274        STRUCT WMPopupAction &pa
1275
1276        switch( pa.eventCode )
1277                case 2: // mouse up
1278                        Variable popNum = pa.popNum
1279                        String popStr = pa.popStr
1280                        SVAR tempStr = root:Packages:NIST:VSANS:Globals:Protocols:gMASK
1281                        tempStr = popStr
1282                        break
1283                case -1: // control being killed
1284                        break
1285        endswitch
1286
1287        return 0
1288End
1289
1290////activated when user checks/unchecks the box
1291////either prompts for a file using a standard dialog, or removes the current file
1292//Function V_DrkCheckProc(ctrlName,checked) : CheckBoxControl
1293//      String ctrlName
1294//      Variable checked                //Desired state, not previous state
1295//
1296//      SVAR drkStr=root:Packages:NIST:VSANS:Globals:Protocols:gDRK
1297//      if(checked==1)
1298//              //print "Unchecked on call"
1299//              //this just asks for the filename, doesn't open the file
1300//              String msgStr="Select the DRK file",fullPath="",fileStr=""
1301//              Variable refnum
1302//             
1303//              Open/D/R/T="????"/M=(msgStr)/P=catPathName refNum
1304//              fullPath = S_FileName           //fname is the full path
1305//              if(cmpstr(fullpath,"")==0)
1306//                      //user cancelled
1307//                      CheckBox prot_check_6,value=0           //keep box unchecked
1308//                      return(0)
1309//              Endif
1310//              fileStr=V_GetFileNameFromPathNoSemi(fullPath)
1311//              //Print fileStr
1312//              //update the global string
1313//              drkStr = ReplaceStringByKey("DRK",drkStr,fileStr,"=",",")
1314//              drkStr = ReplaceNumberByKey("DRKMODE", drkStr, 10 ,"=",",")
1315//      else
1316//              //print "checked on call"
1317//              drkStr="DRK=none,DRKMODE=0,"            //change the global
1318//      endif
1319//     
1320//End
1321
1322
1323Function V_ShowProtoHelp(ctrlName) : ButtonControl
1324        String ctrlName
1325        DisplayHelpTopic/Z/K=1 "VSANS Data Reduction Tutorial[VSANS Reduction Protocol]"
1326        if(V_flag !=0)
1327                DoAlert 0,"The VSANS Data Reduction Tutorial Help file could not be found"
1328        endif
1329End
1330
1331//button action procedure to get the type of average requested by the user
1332//presented as a missing parameter dialog, which is really user-UN-friendly
1333//and will need to be re-thought. Defaults of dialog are set for normal
1334//circular average, so typically click "continue" and proceed
1335//
1336Function V_SetAverageParamsButtonProc(ctrlName) : ButtonControl
1337        String ctrlName
1338       
1339//      Execute "V_GetAvgInfo_Full()"
1340        Execute "V_GetAvgInfo()"
1341       
1342        //set the global string
1343        SVAR tempStr = root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr
1344        String/G root:Packages:NIST:VSANS:Globals:Protocols:gAVE = tempStr
1345
1346End
1347
1348// TODO
1349// -- this is a trimmed down version of the "full" set of averaging options
1350//    add to this as needed as I figure out what functionality is appropriate
1351//
1352//procedure called by protocol panel to ask user for average type choices
1353// somewhat confusing and complex, but may be as good as it gets.
1354//
1355//Proc V_GetAvgInfo(av_typ,autoSave,autoName,autoPlot,side,phi,dphi,width,QCtr,QDelta)
1356Proc V_GetAvgInfo(av_typ,autoSave,autoName,binType)
1357        String av_typ,autoSave,AutoName,binType
1358//      Variable phi=0,dphi=10,width=10,Qctr = 0.01,qDelta=10
1359
1360//      Prompt av_typ, "Type of Average",popup,"Circular;Sector;Rectangular;Annular;2D_ASCII;QxQy_ASCII;PNG_Graphic;Sector_PlusMinus;"
1361        Prompt av_typ, "Type of Average",popup,"Circular;"
1362
1363// comment out above line in DEMO_MODIFIED version, and uncomment the line below (to disable PNG save)
1364//      Prompt av_typ, "Type of Average",popup,"Circular;Sector;Rectangular;Annular;2D_ASCII;QxQy_ASCII"
1365        Prompt autoSave,"Save files to disk?",popup,"Yes - Concatenate;Yes - Individual;No"
1366        Prompt autoName,"Auto-Name files?",popup,"Auto;Manual"
1367//      Prompt autoPlot,"Plot the averaged Data?",popup,"Yes;No"
1368//      Prompt side,"Include detector halves?",popup,"both;right;left"
1369//      Prompt phi,"Orientation Angle (-90,90) degrees (Rectangular or Sector)"
1370//      Prompt dphi, "Azimuthal range (0,45) degrees (Sector only)"
1371//      Prompt width, "Width of Rectangular average (1,128)"
1372//      Prompt Qctr, "q-value of center of annulus"
1373//      Prompt Qdelta,"Pixel width of annulus"
1374        Prompt binType,"Binning Type?",popup,ksBinTypeStr
1375
1376        //assign results of dialog to key=value string, semicolon separated
1377        //do only what is necessary, based on av_typ
1378        String/G root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr=""
1379
1380        // TODO:
1381        // hard wired value
1382        String autoPlot = "No"
1383       
1384               
1385        // all averages need these values
1386        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "AVTYPE=" + av_typ + ";"
1387        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "SAVE=" + autoSave + ";"
1388        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "NAME=" + autoName + ";"
1389        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "PLOT=" + autoPlot + ";"
1390        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "BINTYPE=" + binType + ";"
1391       
1392//      if(cmpstr(av_typ,"Sector")==0 || cmpstr(av_typ,"Sector_PlusMinus")==0)
1393//              root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "SIDE=" + side + ";"
1394//              root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "PHI=" + num2str(phi) + ";"
1395//              root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "DPHI=" + num2str(dphi) + ";"
1396//      Endif
1397//     
1398//      if(cmpstr(av_typ,"Rectangular")==0)
1399//              root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "SIDE=" + side + ";"
1400//              root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "PHI=" + num2str(phi) + ";"
1401//              root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "WIDTH=" + num2str(width) + ";"
1402//      Endif
1403//     
1404//      if(cmpstr(av_typ,"Annular")==0)
1405//              root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "QCENTER=" + num2str(QCtr) + ";"
1406//              root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "QDELTA=" + num2str(QDelta) + ";"
1407//      Endif
1408End
1409
1410
1411// TODO
1412// -- this is the original(SANS) version, and needs to be updated for VSANS as the averaging options are
1413//    worked out
1414//
1415//procedure called by protocol panel to ask user for average type choices
1416// somewhat confusing and complex, but may be as good as it gets.
1417//
1418Proc V_GetAvgInfo_Full(av_typ,autoSave,autoName,autoPlot,side,phi,dphi,width,QCtr,QDelta)
1419        String av_typ,autoSave,AutoName,autoPlot,side
1420        Variable phi=0,dphi=10,width=10,Qctr = 0.01,qDelta=10
1421        Prompt av_typ, "Type of Average",popup,"Circular;Sector;Rectangular;Annular;2D_ASCII;QxQy_ASCII;PNG_Graphic;Sector_PlusMinus;"
1422// comment out above line in DEMO_MODIFIED version, and uncomment the line below (to disable PNG save)
1423//      Prompt av_typ, "Type of Average",popup,"Circular;Sector;Rectangular;Annular;2D_ASCII;QxQy_ASCII"
1424        Prompt autoSave,"Save files to disk?",popup,"Yes;No"
1425        Prompt autoName,"Auto-Name files?",popup,"Auto;Manual"
1426        Prompt autoPlot,"Plot the averaged Data?",popup,"Yes;No"
1427        Prompt side,"Include detector halves?",popup,"both;right;left"
1428        Prompt phi,"Orientation Angle (-90,90) degrees (Rectangular or Sector)"
1429        Prompt dphi, "Azimuthal range (0,45) degrees (Sector only)"
1430        Prompt width, "Width of Rectangular average (1,128)"
1431        Prompt Qctr, "q-value of center of annulus"
1432        Prompt Qdelta,"Pixel width of annulus"
1433
1434        //assign results of dialog to key=value string, semicolon separated
1435        //do only what is necessary, based on av_typ
1436        String/G root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr=""
1437       
1438        // all averages need these four values
1439        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "AVTYPE=" + av_typ + ";"
1440        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "SAVE=" + autoSave + ";"
1441        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "NAME=" + autoName + ";"
1442        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "PLOT=" + autoPlot + ";"
1443       
1444        if(cmpstr(av_typ,"Sector")==0 || cmpstr(av_typ,"Sector_PlusMinus")==0)
1445                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "SIDE=" + side + ";"
1446                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "PHI=" + num2str(phi) + ";"
1447                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "DPHI=" + num2str(dphi) + ";"
1448        Endif
1449       
1450        if(cmpstr(av_typ,"Rectangular")==0)
1451                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "SIDE=" + side + ";"
1452                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "PHI=" + num2str(phi) + ";"
1453                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "WIDTH=" + num2str(width) + ";"
1454        Endif
1455       
1456        if(cmpstr(av_typ,"Annular")==0)
1457                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "QCENTER=" + num2str(QCtr) + ";"
1458                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "QDELTA=" + num2str(QDelta) + ";"
1459        Endif
1460End
1461
1462
1463//prompts the user to pick a previously created protocol from a popup list
1464//of given the option to create a new protocol
1465//the chosen protocol is passed back to the calling procedure by a global string
1466//the popup is presented as a missing parameter dialog (called with empty parameter list)
1467//
1468// MAXROWS is present to exclude the PanelNameW from appearing as a protocol
1469Proc V_PickAProtocol(protocol)
1470        String Protocol
1471        Prompt Protocol "Pick A Protocol",popup, V_RecallableProtocols()
1472       
1473        String/G  root:Packages:NIST:VSANS:Globals:Protocols:gProtoStr = protocol
1474End
1475
1476Proc V_DeleteAProtocol(protocol)
1477        String Protocol
1478//      Prompt Protocol "Delete A Protocol",popup, WaveList("*",";","TEXT:1")
1479        Prompt Protocol "Delete A Protocol",popup, V_DeletableProtocols()
1480
1481        String/G  root:Packages:NIST:VSANS:Globals:Protocols:gProtoStr = protocol
1482End
1483
1484Function/S V_DeletableProtocols()
1485        String list=WaveList("*",";","TEXT:1,MAXROWS:13")
1486
1487        list= RemoveFromList("Base", list  , ";")
1488        list= RemoveFromList("DoAll", list  , ";")
1489        list= RemoveFromList("CreateNew", list  , ";")
1490        list= RemoveFromList("tempProtocol", list  , ";")
1491        list= RemoveFromList("wTTmpWrite", list  , ";")
1492        if(cmpstr(list,"")==0)
1493                list = "_no_protocols_;"
1494        endif
1495       
1496        return(list)
1497End
1498
1499Function/S V_RecallableProtocols()
1500        String list=WaveList("*",";","TEXT:1,MAXROWS:13")
1501
1502//      list= RemoveFromList("Base", list  , ";")
1503//      list= RemoveFromList("DoAll", list  , ";")
1504        list= RemoveFromList("CreateNew", list  , ";")
1505        list= RemoveFromList("tempProtocol", list  , ";")
1506        list= RemoveFromList("wTTmpWrite", list  , ";")
1507        if(cmpstr(list,"")==0)
1508                list = "_no_protocols_;"
1509        endif
1510       
1511        return(list)
1512End
1513
1514
1515//missing parameter dialog to solicit user for a waveStr for the protocol
1516//about to be created
1517//name is passed back as a global string and calling procedure is responsible for
1518//checking for wave conflicts and valid names
1519//
1520Proc V_AskForName(protocol)
1521        String Protocol
1522        Prompt Protocol "Enter a new name for your protocol (no extension)"
1523       
1524        String/G  root:Packages:NIST:VSANS:Globals:Protocols:gNewStr = protocol
1525End
1526
1527//this is a lengthy procedure for sequentially polling the user about what data
1528//reduction steps they want to be performed during the protocol
1529//ensures that a valid protocol name was chosen, then fills out each "item"
1530//(6 total) needed for reduction
1531//it the user cancels at any point, the partial protocol will be deleted
1532//
1533Function V_ProtocolQuestionnaire(ctrlName)
1534        String ctrlName
1535
1536        String filename,cmd
1537        Variable notDone,refnum
1538       
1539        //prompt for name of new protocol wave to save
1540        do
1541                Execute "V_AskForName()"
1542                SVAR newProtoStr = root:Packages:NIST:VSANS:Globals:Protocols:gNewStr
1543               
1544                //make sure it's a valid IGOR name
1545                newProtoStr = CleanupName(newProtoStr,0)        //strict naming convention
1546                String/G root:Packages:NIST:VSANS:Globals:Protocols:gNewStr=newProtoStr         //reassign, if changed
1547                //Print "newProtoStr = ",newProtoStr
1548               
1549                SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
1550                if(WaveExists( $("root:Packages:NIST:VSANS:Globals:Protocols:" + newProtoStr) ) == 1)
1551                        //wave already exists
1552                        DoAlert 0,"that name is already in use. Please pick a new name"
1553                        notDone = 1
1554                else
1555                        //name is  good
1556                        notDone = 0
1557                Endif
1558        while(notDone)
1559       
1560        //Print "protocol questionnaire is "+newProtocol
1561       
1562        //make a new text wave (12 points) and fill it in, in response to questions
1563        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols //(redundant - full wave specs are used)
1564        Make/O/T/N=(kNumProtocolSteps) $("root:Packages:NIST:VSANS:Globals:Protocols:" + newProtoStr)
1565        Wave/T newProtocol = $("root:Packages:NIST:VSANS:Globals:Protocols:" + newProtoStr)
1566        newProtocol = ""
1567       
1568        //ask the questions
1569        /////
1570        //*****Multiple files in these lists are full paths/filenames which may or may not
1571        //have semicolon version numbers in the filename. Therefore, construct the list with
1572        //COMMAS as separators - to avoid messy parsing
1573        ///////
1574       
1575        String fileFilters = "VSANS Data Files (*.ngv,*.h5):.ngv,.h5;"
1576//      fileFilters += "HTML Files (*.htm,*.html):.htm,.html;"
1577        fileFilters += "All Files:.*;"
1578//////////////////////////
1579        String drkStr="",fileStr=""
1580       
1581       
1582//////////////////////////     
1583//      DoAlert 1,"Do you want to correct your data for DRK (beam off) counts?"
1584//      if(V_flag == 1)         //1=yes
1585//              //prompt for DRK  file, but don't actually open it (/D flag)
1586//              Open/D/R/F=fileFilters/M="Select the DRK file"/P=catPathName refnum
1587//              //check for cancel
1588//              if(strlen(S_filename)==0)
1589//                      //user cancelled, abort
1590//                      KillWaves/Z newProtocol
1591//                      SetDataFolder root:
1592//                      Abort "Incomplete protocol has been deleted"
1593//              Endif
1594//              //assign filename (just the name) to [6]
1595//              fileStr = V_GetFileNameFromPathNoSemi(S_filename)
1596//              drkStr = "DRK=none,DRKMODE=0,"
1597//              drkStr = ReplaceStringByKey("DRK",drkStr,fileStr,"=",",")
1598//              drkStr = ReplaceNumberByKey("DRKMODE", drkStr, 10 ,"=",",")     
1599//              newProtocol[6] = drkStr
1600//      else
1601//              //no Work.DRK desired
1602//              newProtocol[6] = "DRK=none,DRKMODE=0,"
1603//      Endif
1604//     
1605////////////
1606       
1607       
1608// TODO:
1609// -- there is a lag in the V_pick() routine as it greps through all of the files. Several seconds even when there
1610//   are 20-ish files. Pre-search for the strings? When to refresh them for new data?   
1611/////////////////
1612        DoAlert 1,"Do you want to subtract background from your data?"
1613        if(V_flag == 1)         //1=yes
1614               
1615                Prompt filename,"BKG File",popup,V_PickBGDButton("")
1616                DoPrompt "Select File",filename
1617                if (V_Flag)
1618                        return 0                                                                        // user canceled
1619                endif
1620//              //assign filename to [0]
1621                newProtocol[0] = V_GetFileNameFromPathNoSemi(fileName)
1622       
1623               
1624// OLD way, using an open file dialog   
1625// and allowing for multiple files to be added together
1626//     
1627//              //prompt for background file, but don't actually open it (/D flag)
1628//              Open/D/R/F=fileFilters/M="Select the Background data file"/P=catPathName refnum
1629//              //check for cancel
1630//              if(strlen(S_filename)==0)
1631//                      //user cancelled, abort
1632//                      KillWaves/Z newProtocol
1633//                      SetDataFolder root:
1634//                      Abort "Incomplete protocol has been deleted"
1635//              Endif
1636//              //assign filename (full path) to [0]
1637//              newProtocol[0] = V_GetFileNameFromPathNoSemi(S_filename)
1638               
1639//              notDone=1
1640//              do
1641//                      //prompt for additional background files
1642//                      DoAlert 1,"Do you want to add another background file?"
1643//                      if(V_flag == 1)         //yes
1644//                              Open/D/R/F=fileFilters/M="Select another Background data file"/P=catPathName refnum
1645//                              //check for cancel
1646//                              if(strlen(S_filename)==0)
1647//                                      //user cancelled, abort ********maybe just break out of the loop here
1648//                                      KillWaves/Z newProtocol
1649//                                      SetDataFolder root:
1650//                                      Abort "Incomplete protocol has been deleted"
1651//                              Endif
1652//                              //assign filename (full path) to [0]
1653//                              newProtocol[0] += "," + V_GetFileNameFromPathNoSemi(S_filename)         //***COMMA separated list
1654//                              notDone = 1             //keep going
1655//                      else
1656//                              notDone = 0                     //no more to add
1657//                      Endif
1658//              While(notDone)
1659//////
1660
1661        else            //no background desired
1662                newProtocol[0] = "none"
1663        Endif
1664       
1665       
1666////////////////////// 
1667        DoAlert 1,"Do you want to subtract empty cell scattering from your data?"
1668        if(V_flag == 1)         //1=yes
1669               
1670                Prompt filename,"EMP File",popup,V_PickEMPButton("")
1671                DoPrompt "Select File",filename
1672                if (V_Flag)
1673                        return 0                                                                        // user canceled
1674                endif
1675//              //assign filename to [1]
1676                newProtocol[1] = V_GetFileNameFromPathNoSemi(fileName)         
1677       
1678
1679               
1680//              //prompt for Empty cell file, but don't actually open it (/D flag)
1681//              Open/D/R/F=fileFilters/M="Select the Empty Cell data file"/P=catPathName refnum
1682//              //check for cancel
1683//              if(strlen(S_filename)==0)
1684//                      //user cancelled, abort
1685//                      KillWaves/Z newProtocol
1686//                      SetDataFolder root:
1687//                      Abort "Incomplete protocol has been deleted"
1688//              Endif
1689//              //assign filename (full path) to [1]
1690//              newProtocol[1] = V_GetFileNameFromPathNoSemi(S_filename)
1691//             
1692//              notDone=1
1693//              do
1694//                      //prompt for additional Empty Cell files
1695//                      DoAlert 1,"Do you want to add another Empty Cell file?"
1696//                      if(V_flag == 1)         //yes
1697//                              Open/D/R/F=fileFilters/M="Select another Empty Cell data file"/P=catPathName refnum
1698//                              //check for cancel
1699//                              if(strlen(S_filename)==0)
1700//                                      //user cancelled, abort ********maybe just break out of the loop here
1701//                                      KillWaves/Z newProtocol
1702//                                      SetDataFolder root:
1703//                                      Abort "Incomplete protocol has been deleted"
1704//                              Endif
1705//                              //assign filename (full path) to [1]
1706//                              newProtocol[1] += "," + V_GetFileNameFromPathNoSemi(S_filename)         //***COMMA separated list
1707//                              notDone = 1             //keep going
1708//                      else
1709//                              notDone = 0                     //no more to add
1710//                      Endif
1711//              While(notDone)
1712
1713
1714        else            //no background desired
1715                newProtocol[1] = "none"
1716        Endif
1717       
1718       
1719//////////////////////////
1720        DoAlert 1,"Do you want to correct your data for detector sensitivity?"
1721       
1722        if(V_flag == 1)         //1=yes
1723               
1724                Prompt filename,"DIV File",popup,V_PickDIVButton("")
1725                DoPrompt "Select File",filename
1726                if (V_Flag)
1727                        return 0                                                                        // user canceled
1728                endif
1729//              //assign filename to [2]
1730                newProtocol[2] = V_GetFileNameFromPathNoSemi(fileName)
1731               
1732//              //prompt for DIV  file, but don't actually open it (/D flag)
1733//              Open/D/R/F=fileFilters/M="Select the detector sensitivity file"/P=catPathName refnum
1734//              //check for cancel
1735//              if(strlen(S_filename)==0)
1736//                      //user cancelled, abort
1737//                      KillWaves/Z newProtocol
1738//                      SetDataFolder root:
1739//                      Abort "Incomplete protocol has been deleted"
1740//              Endif
1741//              //assign filename (full path) to [2]
1742//              newProtocol[2] = V_GetFileNameFromPathNoSemi(S_filename)
1743               
1744               
1745        else
1746                //no Work.DIV desired
1747                newProtocol[2] = "none"
1748        Endif   
1749//////////////////////////
1750        DoAlert 1,"Do you want to mask your files before averaging?"
1751       
1752        if(V_flag == 1)         //1=yes
1753       
1754                Prompt filename,"MASK File",popup,V_PickMASKButton("")
1755                DoPrompt "Select File",filename
1756                if (V_Flag)
1757                        return 0                                                                        // user canceled
1758                endif
1759//              //assign filename to [3]
1760                newProtocol[3] = V_GetFileNameFromPathNoSemi(fileName)
1761                       
1762//              //prompt for mask  file, but don't actually open it (/D flag)
1763//              Open/D/R/F=fileFilters/M="Select the mask file"/P=catPathName refnum
1764//              //check for cancel
1765//              if(strlen(S_filename)==0)
1766//                      //user cancelled, abort
1767//                      KillWaves/Z newProtocol
1768//                      SetDataFolder root:
1769//                      Abort "Incomplete protocol has been deleted"
1770//              Endif
1771//              //assign filename (full path) to [3]
1772//              newProtocol[3] = V_GetFileNameFromPathNoSemi(S_filename)
1773               
1774               
1775        else
1776                //no MASK desired
1777                newProtocol[3] = "none"
1778        Endif   
1779       
1780        //absolute scaling
1781       
1782        //////////////////////////
1783        //ABS parameters stored as keyword=value string
1784        DoAlert 1,"Do you want absolute scaling?"
1785        if(V_flag == 1)         //1=yes
1786                //missing param - prompt for values, put in semicolon-separated list
1787                Execute "V_AskForAbsoluteParams_Quest()"
1788                SVAR absStr =  root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr
1789                newProtocol[4] = absStr
1790        else
1791                //no absolute scaling desired
1792                newProtocol[4] = "none"
1793        Endif   
1794       
1795        //type of average, plot?, auto/manual naming/saving... put in semicolon separated string
1796        //of KEY=<value> format for easy parsing
1797        //Kewords are: AVTYPE,PHI,DPHI,PLOT,SAVE,NAME,SIDE,WIDTH
1798        //note that AVTYPE,NAME,SIDE have string values, others have numerical values
1799        ///////////////////////
1800        DoAlert 1,"Do you want to average your data to I vs. q?"
1801        if(V_flag == 1)         //1=yes
1802                String/G root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr = ""
1803                Execute "V_GetAvgInfo()"                //will put up missing paramter dialog and do all the work
1804                //:gAvgInfo is reset by the Proc(), copy this string tot he protocol
1805                SVAR tempStr=root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr
1806               
1807                //get a file path for saving files, if desired
1808                /////no - save files to the same data folder as the one with the raw data
1809                //then only one path to manage.
1810                //String yesNo = StringByKey("SAVE", tempStr,"=", ";")
1811                //if(cmpstr("Yes",yesNo) == 0)          //0=yes
1812                        //NewPath/C/M="Select Folder"/O Save_path               //Save_path is the symbolic path
1813                //Endif
1814
1815                newProtocol[5] = tempStr
1816                KillStrings/Z tempStr
1817        else
1818                //no averaging desired
1819                newProtocol[5] = "AVTYPE=none"
1820        Endif
1821       
1822        //returns the name of the newly created (= currently in use) protocol wave through a global
1823        String/G root:Packages:NIST:VSANS:Globals:Protocols:gProtoStr = newProtoStr
1824       
1825        //reset the panel based on the protocol textwave (currently a string)
1826        V_ResetToSavedProtocol(newProtoStr)
1827       
1828        SetDataFolder root:
1829       
1830        return(0)
1831End
1832
1833
1834// TODO
1835// -- this function may not work properly for VSANS, but I haven't tested it yet
1836// -- I'd rather have some sort of display to show the current content of the WORK folders
1837//
1838// -- the global string fileList does not exist, so this will always fail and return zero
1839//
1840//
1841//function to check the work files (to see what's already there)
1842//and compare that with the files that are supposed to be there, according to the
1843//current protocol (to save unnecessary time re-loading files)
1844//
1845//the "type" folder is checked for all files in the list req(ested)Files
1846//note that the list of files is a full path:name;ver, while the
1847//fileList in the folder is just the name (or a list of names)
1848//
1849//returns 0 false, if files are NOT present
1850//or 1 = true, yes, the files are there as requested
1851//
1852Function V_AreFilesThere(type,reqFiles)
1853        String type,reqFiles
1854       
1855        //in general, reqFiles is a list of full paths to files - which MAY include semicolon version numbers
1856        //reqFiles MUST be constructed with COMMAS as list separators, to avoid disaster
1857        //when the version numbers are interpreted as filenames
1858       
1859        //get the number of files requested
1860        Variable nReq,nCur,match,ii
1861        nReq = ItemsInList(reqFiles,",")
1862       
1863        //get the name of the file currently in BGD - in the global fileList
1864        //fileList has NAMES ONLY - since it was derived from the file header
1865        String testStr
1866        testStr = "root:Packages:NIST:"+type+":fileList"
1867        if(Exists(testStr) == 2)                //2 if string variable exists
1868                SVAR curFiles = $testStr
1869        else
1870                //no files currently in type folder, return zero
1871                Return (0)
1872        Endif
1873        //get the number of files already in folder
1874        nCur = ItemsInList(curFiles,";")
1875        If(nCur != nReq)
1876                Return (0)              //quit now, the wrong number of files present
1877        Endif
1878        //right number of files... are the names right...
1879        //check for a match (case-sensitive!!) of each requested file in the curFile string
1880        //need to extract filenames from reqFiles, since they're the full path and name
1881       
1882        ii=0
1883        do
1884                testStr = StringFromList(ii,reqFiles,",")       //testStr is the Nth full path and filename
1885                //testStr = GetFileNameFromPathNoSemi(testStr)  //testStr will now be just the filename
1886                match = stringmatch(curFiles,testStr)
1887                If(!match)
1888                        Return (0)              //req file was not found in curFile list - get out now
1889                Endif
1890                ii+=1
1891        while(ii<nreq)
1892       
1893        Return (1)              //indicate that files are OK, no changes needed
1894End
1895
1896
1897//
1898//will add the files specified in the protocol to the "type" folder
1899//will add multiple files together if more than one file is requested
1900//(list is a comma delimited list of filenames, with NO path information)
1901//
1902// This routine NOW DOES check for the possibility that the filenames may have ";vers" from the
1903// VAX - data should be picked up from Charlotte, where it won't have version numbers.
1904//
1905Function V_AddFilesInList(type,list)
1906        String type,list
1907       
1908        //type is the work folder to put the data into, and list is a COMMA delimited list of paths/names
1909        Variable num,ii,err=0,refNum
1910        String filename,pathStr=""
1911        PathInfo catPathName                    //this is where the files are
1912        pathstr=S_path
1913       
1914        num = ItemsInList(list,",")             // comma delimited list
1915       
1916        ii=0
1917        do
1918                //FindValidFilename only needed in case of vax version numbers
1919                filename = pathStr + V_FindValidFilename(StringFromList(ii,list,","))
1920                Open/Z/R refnum as filename
1921                if(V_flag != 0)         //file not found
1922                        //Print "file not found AddFilesInList()"
1923                        //Print filename
1924                        err = 1
1925                        return(err)
1926                Endif
1927                Close refnum            //file was found and opened, so close it
1928               
1929//              Abort "Find equivalent to ReadHeaderAndData(filename)"
1930//              ReadHeaderAndData(filename)
1931                err = V_LoadHDF5Data(filename,"RAW")   
1932               
1933                if(ii == 0)
1934                        //first pass, wipe out the old contents of the work file
1935                        err =  V_Raw_to_work(type)
1936                else
1937                        err = V_Add_raw_to_work(type)
1938                Endif
1939                ii+=1
1940        while(ii<num)
1941        return(err)
1942End
1943
1944//function will reduce a sample file (or ask for file(s))
1945//using the protocol named as "protoStr" in the Protocols subfolder
1946//samStr is the file(s) or "ask" to force prompt
1947//sequentially proceeds through flowchart, doing reduction steps as needed
1948//show Schematic to debug what steps/values were used
1949//
1950//function is long, but straightforward logic
1951//
1952Function V_ExecuteProtocol(protStr,samStr)
1953        String protStr,samStr
1954        //protStr is the full path to the selected protocol wave
1955        //samStr is either "ask" or the name ONLY ofthe desired sample data file(s) (NO PATH)
1956        WAVE/T prot = $protStr
1957        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
1958       
1959        Variable filesOK,err,notDone
1960        String activeType, msgStr, junkStr, pathStr=""
1961        PathInfo catPathName                    //this is where the files are
1962        pathStr=S_path
1963       
1964//      NVAR useXMLOutput = root:Packages:NIST:gXML_Write
1965       
1966        //Parse the instructions in the prot wave
1967        //0 - bkg
1968        //1 - emp
1969        //2 - div
1970        //3 - mask
1971        //4 - abs params c2-c5
1972        //5 - average params
1973        //6 = DRK file (**out of sequence)
1974        //7 = beginning trim points
1975        //8 = end trim points
1976        //9 = unused
1977        //10 = unused
1978        //11 = unused
1979
1980// for VSANS, DIV is used on each data file as it is converted to WORK, so it needs to be
1981//  the first thing in place, before any data or backgrounds are loaded
1982
1983
1984//
1985// TODO:
1986// x- this is no longer done after the COR step, and CAL is not produced as output of DIV       
1987// x- needs to be aware of the file name passed in
1988// x- PromptForPath does not exist in VSANS. Need a better (automated) way to find the file.
1989
1990//check for work.div file (prot[2])
1991//load in if needed
1992// no math is done here, DIV is applied as files are converted to WORK (the first operation in VSANS)
1993//
1994        String divFileName = ""
1995
1996        If(cmpstr("none",prot[2])!=0)           // if !0, then there's a file requested
1997                If(cmpstr("ask",prot[2]) == 0)
1998                        //ask user for file
1999//                       junkStr = PromptForPath("Select the detector sensitivity file")
2000                        Prompt divFileName,"DIV File",popup,V_PickDIVButton("")
2001                        DoPrompt "Select File",divFileName
2002
2003                        If(strlen(divFileName)==0)
2004                                SetDataFolder root:
2005                                Abort "No file selected, data reduction aborted"
2006                        Endif
2007                        V_LoadHDF5Data(divFileName,"DIV")
2008                else
2009                        //assume it's a path, and that the first (and only) item is the path:file
2010                        //list processing is necessary to remove any final comma
2011                        junkStr = pathStr + StringFromList(0, prot[2],"," )
2012                        V_LoadHDF5Data(junkStr,"DIV")
2013                Endif
2014       
2015        else
2016        // DIV step is being skipped
2017                NVAR gDoDIVCor = root:Packages:NIST:VSANS:Globals:gDoDIVCor
2018                Variable saved_gDoDIVCor = gDoDIVCor
2019                gDoDIVCor = 0                   // protocol says to turn it off for now (reset later)
2020        Endif
2021
2022
2023// TODO:
2024// -- currently does not allow adding RAW data files together, so no parsing is done
2025//       -- NOTE detector corrections (including DIV) are done at the V_Raw_to_Work() step
2026//   So if the DIV is not part of the protocol, be sure to set/reset the global preference
2027//
2028        //prompt for sam data => read raw data, add to sam folder
2029        //or parse file(s) from the input paramter string
2030        activeType = "SAM"
2031        msgStr = "Select sample data"
2032        //Ask for SAM file or parse
2033        do
2034                if((cmpstr(samStr,"ask") == 0) || (cmpstr(samStr,"")==0) )              //zero if strings are equal
2035                        err = V_LoadHDF5Data("","RAW")          //will prompt for file
2036                        if(err)
2037                                PathInfo/S catPathName
2038                                Abort "reduction sequence aborted"
2039                        endif
2040                        V_UpdateDisplayInformation("RAW")                       //display the new type of data that was loaded
2041                        err =  V_Raw_to_work(activeType)                //this is the first file (default)
2042                        //Ask for another SAM file
2043                        do
2044                                DoAlert 1,"Do you want to add another Sample file?"
2045                                if(V_flag == 1)         //yes
2046                                        err = V_LoadHDF5Data("","RAW")          //will prompt for file
2047                                        if(err)
2048                                                PathInfo/S catPathName
2049                                                Abort "reduction sequence aborted"
2050                                        endif
2051                                        V_UpdateDisplayInformation("RAW")                       //display the new type of data that was loaded
2052                                        err = V_Add_raw_to_work(activeType)
2053                                        notDone = 1
2054                                else
2055                                        notDone = 0
2056                                endif
2057                        while(notDone)
2058                        break
2059                Endif
2060                //"none" is not an option - you always need a sample file - "none" will never return zero
2061                //if not "ask" AND not "none" then try to parse the filenames
2062                If((cmpstr(samStr,"none") != 0) && (cmpstr(samStr,"ask") != 0))
2063                        //filesOK = AreFilesThere(activeType,samStr)            //return 1 if correct files are already there
2064                        filesOK = 0             // Feb 2008, always force a reload of files. Maybe slow, but always correct
2065                        if(!filesOK)
2066                                //add the correct file(s) to SAM
2067                               
2068                                // TODO: only one file is allowed currently
2069                                err = V_AddFilesInList(activeType,samStr)
2070                               
2071                                if(err)
2072                                        //Print "samstr = ",samStr
2073                                        Abort "SAM file not found, reset SAM file"
2074                                Endif
2075                        Endif
2076                Endif
2077        While(0)
2078        // TODO
2079        // -- this may not be the most reliable way to pass the file name (for naming of the saved file later)
2080        SVAR file_name = root:file_Name
2081        String samFileLoaded = file_name                //keep a copy of the sample file loaded
2082       
2083        //always update
2084        V_UpdateDisplayInformation(ActiveType)
2085       
2086        //check for bkg file  -- "ask" might not fail - "ask?" will - ? not allowed in VAX filenames
2087        // add if needed
2088        //use a "case" statement
2089        msgStr = "Select background file"
2090        activeType = "BGD"
2091        do
2092                if(cmpstr(prot[0],"ask") == 0)          //zero if strings are equal
2093                        err = V_LoadHDF5Data("","RAW")          //will prompt for file
2094                        if(err)
2095                                PathInfo/S catPathName
2096                                Abort "reduction sequence aborted"
2097                        endif
2098                        V_UpdateDisplayInformation("RAW")                       //display the new type of data that was loaded
2099                        err =  V_Raw_to_work(activeType)                //this is the first file (default)
2100                        //Ask for another BGD file
2101                        do
2102                                DoAlert 1,"Do you want to add another Background file?"
2103                                if(V_flag == 1)         //yes
2104                                        err = V_LoadHDF5Data("","RAW")          //will prompt for file
2105                                        if(err)
2106                                                PathInfo/S catPathName
2107                                                Abort "reduction sequence aborted"
2108                                        endif
2109                                        V_UpdateDisplayInformation("RAW")                       //display the new type of data that was loaded
2110                                        err = V_Add_raw_to_work(activeType)
2111                                        notDone = 1
2112                                else
2113                                        notDone = 0
2114                                endif
2115                        while(notDone)
2116                        V_UpdateDisplayInformation(ActiveType)  //update before breaking from loop
2117                        break
2118                Endif
2119                If(cmpstr(prot[0],"none") == 0)
2120                        //clean out the BKG folder?
2121                        //KillDataFolder root:BKG
2122                        //NewDataFolder/O root:BKG
2123                        break
2124                Endif
2125                //if not "ask" AND not "none" then try to parse the filenames
2126                If((cmpstr(prot[0],"none") != 0) && (cmpstr(prot[0],"ask") != 0))
2127                        //filesOK = AreFilesThere(activeType,prot[0])
2128                        filesOK = 0             // Feb 2008, always force a reload of files. Maybe slow, but always correct
2129                        if(!filesOK)
2130                                //add the correct file(s) to BGD
2131                                string bgdStr = prot[0]
2132                                err = V_AddFilesInList(activeType,bgdStr)
2133                                If(err)
2134                                        Abort "BGD file not found. Reset BGD file list"
2135                                Endif
2136                        Endif
2137                        V_UpdateDisplayInformation(ActiveType)          //update before breaking from loop
2138                Endif
2139        While(0)
2140       
2141       
2142        //check for emp file (prot[1])
2143        // add if needed
2144        msgStr = "Select empty cell data"
2145        activeType = "EMP"
2146        do
2147                if(cmpstr(prot[1],"ask") == 0)
2148                        err = V_LoadHDF5Data("","RAW")          //will prompt for file
2149                        if(err)
2150                                PathInfo/S catPathName
2151                                Abort "reduction sequence aborted"
2152                        endif
2153                        V_UpdateDisplayInformation("RAW")                       //display the new type of data that was loaded
2154                        err =  V_Raw_to_work(activeType)                //this is the first file (default)
2155                        //Ask for another EMP file
2156                        do
2157                                DoAlert 1,"Do you want to add another Empty Cell file?"
2158                                if(V_flag == 1)         //yes
2159                                        err = V_LoadHDF5Data("","RAW")          //will prompt for file
2160                                        if(err)
2161                                                PathInfo/S catPathName
2162                                                Abort "reduction sequence aborted"
2163                                        endif
2164                                        V_UpdateDisplayInformation("RAW")                       //display the new type of data that was loaded
2165                                        err = V_Add_raw_to_work(activeType)
2166                                        notDone = 1
2167                                else
2168                                        notDone = 0
2169                                endif
2170                        while(notDone)
2171                        V_UpdateDisplayInformation(ActiveType)          //update before breaking from loop
2172                        break
2173                Endif
2174                If(cmpstr(prot[1],"none") == 0)
2175                        //clean out the EMP folder?
2176                        //KillDataFolder root:Packages:NIST:EMP
2177                        //NewDataFolder/O root:Packages:NIST:EMP
2178                        break
2179                Endif
2180                //if not "ask" AND not "none" then try to parse the filenames
2181                If((cmpstr(prot[1],"none") != 0) && (cmpstr(prot[1],"ask") != 0))
2182                        //filesOK = AreFilesThere(activeType,prot[1])
2183                        filesOK = 0             // Feb 2008, always force a reload of files. Maybe slow, but always correct
2184                        if(!filesOK)
2185                                //add the correct file(s) to BGD
2186                                err = V_AddFilesInList(activeType,prot[1])
2187                                If(err)
2188                                        Abort "EMP file not found. Reset EMP file list"
2189                                Endif
2190                        Endif
2191                        V_UpdateDisplayInformation(ActiveType)  //update before breaking from loop
2192                Endif
2193        While(0)
2194       
2195        //do the CORRECT step based on the answers to emp and bkg subtraction
2196        //by setting the proper"mode"
2197        //1 = both emp and bgd subtraction
2198        //2 = only bgd subtraction
2199        //3 = only emp subtraction
2200        //4 = no subtraction
2201        //additional modes 091301
2202        //11 = emp, bgd, drk
2203        //12 = bgd and drk
2204        //13 = emp and drk
2205        //14 = no subtractions
2206        //work.drk is from proto[6]
2207        //
2208        //subtracting just the DRK data is NOT an option - it doesnt' really make any physical sense
2209        // - in this case, DRK is skipped (equivalent to mode==4)
2210        // automatically accounts for attenuators given the lookup tables and the
2211        //desired subtractions
2212        //Attenuator lookup tables are alredy implemented (NG1 = NG7)
2213        //
2214
2215
2216/////// DRK is SKIPPED
2217       
2218//      //read in the DRK data if necessary
2219//      //only one file, assumed to be RAW data
2220//      //
2221//      String fname="",drkStr=""
2222//      drkStr=StringByKey("DRK",prot[6],"=",",")
2223//      if(cmpstr(drkStr,"none") != 0)
2224//              err = ReadHeaderAndData( (pathStr+drkStr) )
2225//              if(err)
2226//                      PathInfo/S catPathName
2227//                      Abort "reduction sequence aborted"
2228//              endif
2229//              err = V_Raw_to_Work_NoNorm("DRK")
2230//      endif
2231
2232
2233       
2234        //dispatch to the proper "mode" of Correct()
2235        Variable mode=4,val
2236        do
2237                if( (cmpstr("none",prot[0]) == 0)       && (cmpstr("none",prot[1]) == 0) )
2238                        //no subtraction (mode = 4),
2239                        mode = 4
2240                Endif
2241                If((cmpstr(prot[0],"none") != 0) && (cmpstr(prot[1],"none") == 0))
2242                        //subtract BGD only
2243                        mode=2
2244                Endif
2245                If((cmpstr(prot[0],"none") == 0) && (cmpstr(prot[1],"none") != 0))
2246                        //subtract EMP only
2247                        mode=3
2248                Endif
2249                If((cmpstr(prot[0],"none") != 0) && (cmpstr(prot[1],"none") != 0))
2250                        // bkg and emp subtraction are to be done (BOTH not "none")
2251                        mode=1
2252                Endif
2253                activeType = "COR"
2254                //add in DRK mode (0= no used, 10 = used)
2255                val = NumberByKey("DRKMODE",prot[6],"=","," )
2256                mode += val
2257//              print "mode = ",mode
2258                err = V_Correct(mode)
2259                if(err)
2260                        SetDataFolder root:
2261                        Abort "error in Correct, called from executeprotocol, normal cor"
2262                endif
2263                V_UpdateDisplayInformation(ActiveType)          //update before breaking from loop
2264        While(0)
2265
2266
2267////////////////////////////////////////////////////////
2268
2269// TODO:
2270// -- calculation works, needs proper inputs (solid angle aware)
2271// --   Open beam method needs to be verified in V_AskForAbsoluteParams_Quest()
2272        Variable c2,c3,c4,c5,kappa_err
2273        //do absolute scaling if desired
2274//              DoAlert 0,"Abs step incomplete"
2275
2276        if(cmpstr("none",prot[4])!=0)
2277                if(cmpstr("ask",prot[4])==0)
2278                        //get the params from the user
2279                        Execute "V_AskForAbsoluteParams_Quest()"
2280                        //then from the list
2281                        SVAR junkAbsStr = root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr
2282                        c2 = NumberByKey("TSTAND", junkAbsStr, "=", ";")        //parse the list of values
2283                        c3 = NumberByKey("DSTAND", junkAbsStr, "=", ";")
2284                        c4 = NumberByKey("IZERO", junkAbsStr, "=", ";")
2285                        c5 = NumberByKey("XSECT", junkAbsStr, "=", ";")
2286                        kappa_err = NumberByKey("SDEV", junkAbsStr, "=", ";")
2287                else
2288                        //get the parames from the list
2289                        c2 = NumberByKey("TSTAND", prot[4], "=", ";")   //parse the list of values
2290                        c3 = NumberByKey("DSTAND", prot[4], "=", ";")
2291                        c4 = NumberByKey("IZERO", prot[4], "=", ";")
2292                        c5 = NumberByKey("XSECT", prot[4], "=", ";")
2293                        kappa_err = NumberByKey("SDEV", prot[4], "=", ";")
2294                Endif
2295                //get the sample trans and thickness from the activeType folder
2296                Variable c0 = V_getSampleTransmission(activeType)               //sample transmission
2297                Variable c1 = V_getSampleThickness(activeType)          //sample thickness
2298               
2299                err = V_Absolute_Scale(activeType,c0,c1,c2,c3,c4,c5,kappa_err)
2300                if(err)
2301                        SetDataFolder root:
2302                        Abort "Error in V_Absolute_Scale(), called from V_ExecuteProtocol"
2303                endif
2304                activeType = "ABS"
2305                V_UpdateDisplayInformation(ActiveType)                  //update before breaking from loop
2306        Endif
2307
2308//
2309// TODO
2310//              x- fill in the "ask" step
2311//  -- none is OK, except if the kill fails for any reason
2312// x- the regular case of the file name specified by the protocol works correctly
2313// x- don't create a null mask if not used, it will handle the error and print out that the mask is missing
2314
2315//mask data if desired (this is done automatically when the data is binned to I(q)) and is
2316//not done explicitly here
2317       
2318        //check for mask
2319        //doesn't change the activeType
2320        String mskFileName=""
2321       
2322        if(cmpstr("none",prot[3])!=0)
2323                If(cmpstr("ask",prot[3])==0)
2324                        //get file from user
2325                        // TODO
2326                        // x- fill in the get file prompt, and handle the result
2327                        Prompt mskFileName,"MASK File",popup,V_PickMASKButton("")
2328                        DoPrompt "Select File",mskFileName
2329//                      if (V_Flag)
2330//                              return 0                                                                        // user cancelled
2331//                      endif
2332
2333                        If(strlen(mskFileName)==0)              //use cancelled
2334                                //if none desired, make sure that the old mask is deleted
2335                                KillDataFolder/Z root:Packages:NIST:VSANS:MSK:
2336                                NewDataFolder/O root:Packages:NIST:VSANS:MSK
2337                               
2338                                DoAlert 0,"No Mask file selected, data not masked"
2339                        else
2340                                //read in the file from the selection
2341                                V_LoadHDF5Data(mskFileName,"MSK")
2342                        Endif
2343                else
2344                        //just read it in from the protocol
2345                        //list processing is necessary to remove any final comma
2346                        mskFileName = pathStr + StringFromList(0, prot[3],"," )
2347                        V_LoadHDF5Data(mskFileName,"MSK")
2348                Endif
2349               
2350        else
2351                //if none desired, make sure that the old mask is deleted
2352// TODO
2353// x- clean out the data folder
2354// x- note that V_KillNamedDataFolder() points to RawVSANS, and won't work
2355// -- what happens if the kill fails? need error handling
2356//
2357                KillDataFolder/Z root:Packages:NIST:VSANS:MSK:
2358                NewDataFolder/O root:Packages:NIST:VSANS:MSK
2359
2360        Endif
2361       
2362
2363        // average/save data as specified
2364        //Parse the keyword=<Value> string as needed, based on AVTYPE
2365       
2366        //average/plot first
2367        String av_type = StringByKey("AVTYPE",prot[5],"=",";")
2368        If(cmpstr(av_type,"none") != 0)
2369                If (cmpstr(av_type,"")==0)              //if the key could not be found... (if "ask" the string)
2370                        //get the averaging parameters from the user, as if the set button was hit in the panel
2371                        V_SetAverageParamsButtonProc("dummy")           //from "ProtocolAsPanel"
2372                        SVAR tempAveStr = root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr
2373                        av_type = StringByKey("AVTYPE",tempAveStr,"=",";")
2374                else
2375                        //there is info in the string, use the protocol
2376                        //set the global keyword-string to prot[5]
2377                        String/G root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr = prot[5]
2378                Endif
2379        Endif
2380       
2381        //convert the folder to linear scale before averaging, then revert by calling the window hook
2382        // (not needed for VSANS, data is always linear scale)
2383
2384        // bin and plot the data
2385       
2386        // TODO
2387// -- this switch does nothing -- fill it in
2388//       x- need to convert BINTYPE keyword into a numerical value to pass
2389//
2390
2391        String binTypeStr = StringByKey("BINTYPE",prot[5],"=",";")
2392        // plotting is not really necessary, and the graph may not be open - so skip for now?
2393        Variable binType
2394        binType = V_BinTypeStr2Num(binTypeStr)
2395        if(binType == 0)
2396                        Abort "Binning mode not found in V_QBinAllPanels() "// when no case matches
2397        endif
2398
2399
2400//
2401// TODO:
2402// -- do I calculate the proper resolution here? I've already decoded the binning type
2403//   and the averaging type has been specified by the protocol
2404// -- if I calculate the resolution here, then the Trimming routines must be updated
2405//    to trim the resolution waves also. This positioning may work for
2406//    pinhole resolution, but anything using the matrix method - it won't work - and I'll need
2407//    a different solution
2408//
2409        strswitch(av_type)      //dispatch to the proper routine to average to 1D data
2410                case "none":           
2411                        //still do nothing
2412                        break                   
2413                case "2D_ASCII":       
2414                        //do nothing
2415                        break
2416                case "QxQy_ASCII":
2417                        //do nothing
2418                        break
2419                case "PNG_Graphic":
2420                        //do nothing
2421                        break
2422                case "Rectangular":
2423//                      RectangularAverageTo1D(activeType)
2424                        break
2425                case "Annular":
2426//                      AnnularAverageTo1D(activeType)
2427                        break
2428                case "Circular":
2429
2430                        V_QBinAllPanels_Circular(activeType,binType)            // this does a default circular average
2431                        break
2432                case "Sector":
2433//                      CircularAverageTo1D(activeType)
2434                        break
2435                case "Sector_PlusMinus":
2436//                      Sector_PlusMinus1D(activeType)
2437                        break
2438                default:       
2439                        //do nothing
2440        endswitch
2441
2442// TODO
2443// x- this call will bin the active type, then the next call bins the active type
2444// x- then later, I dispatch to bin the active type... 
2445// x- !!!need to split out the panel draw and the binning calls from V_PlotData_Panel
2446//
2447        V_PlotData_Panel()              //this brings the plot window to the front, or draws it (ONLY)
2448        V_Update1D_Graph(activeType,binType)            //update the graph, data was already binned
2449       
2450///// end of averaging dispatch
2451
2452
2453// TODO
2454// x- how do I get the sample file name?
2455//    local variable samFileLoaded is the file name loaded (contains the extension)
2456//     
2457        //save data if desired
2458        String fullpath = "", newfileName=""
2459        String saveType = StringByKey("SAVE",prot[5],"=",";")           //does user want to save data?
2460        If( (cmpstr(saveType[0,2],"Yes")==0) && (cmpstr(av_type,"none") != 0) )         
2461                //then save
2462                newFileName = RemoveEnding(samFileLoaded,".nxs.ngv")
2463               
2464                //pick ABS or AVE extension
2465                String exten = activeType
2466                if(cmpstr(exten,"ABS") != 0)
2467                        exten = "AVE"
2468                endif
2469                if(cmpstr(av_type,"2D_ASCII") == 0)
2470                        exten = "ASC"
2471                endif
2472                if(cmpstr(av_type,"QxQy_ASCII") == 0)
2473                        exten = "DAT"
2474                endif
2475               
2476//              // add an "x" to the file extension if the output is XML
2477//              // currently (2010), only for ABS and AVE (1D) output
2478//              if( cmpstr(exten,"ABS") == 0 || cmpstr(exten,"AVE") == 0 )
2479//                      if(useXMLOutput == 1)
2480//                              exten += "x"
2481//                      endif
2482//              endif
2483                               
2484                //Path is catPathName, symbolic path
2485                //if this doesn't exist, a dialog will be presented by setting dialog = 1
2486                //
2487                //
2488                Variable dialog = 0
2489
2490// TODO
2491// -- need to define nBeg and nEnd somewhere
2492// -- currently hard-wired
2493// --do I need to define these "per-panel"?             
2494               
2495                PathInfo/S catPathName
2496                String item = StringByKey("NAME",prot[5],"=",";")               //Auto or Manual naming
2497                String autoname = StringByKey("AUTONAME",prot[5],"=",";")               //autoname -  will get empty string if not present
2498                If((cmpstr(item,"Manual")==0) || (cmpstr(newFileName,"") == 0))
2499                        //manual name if requested or if no name can be derived from header
2500                        fullPath = newfileName + "."+ exten //puts possible new name or null string in dialog
2501                        dialog = 1              //force dialog for user to enter name
2502                else
2503                        //auto-generate name and prepend path - won't put up any dialogs since it has all it needs
2504                        //use autoname if present
2505                        if (cmpstr(autoname,"") != 0)
2506                                fullPath = S_Path + autoname + "." +exten
2507                        else
2508                                fullPath = S_Path + newFileName+"." + exten
2509                        endif   
2510                Endif
2511                //
2512                strswitch(av_type)     
2513                        case "Annular":
2514//                              WritePhiave_W_Protocol(activeType,fullPath,dialog)
2515                                break
2516                        case "2D_ASCII":
2517//                              Fast2DExport(activeType,fullPath,dialog)
2518                                break
2519                        case "QxQy_ASCII":
2520//                              QxQy_Export(activeType,fullPath,dialog)
2521                                break
2522                        case "PNG_Graphic":
2523//                              SaveAsPNG(activeType,fullpath,dialog)
2524                                break
2525                        default:
2526//                              if (useXMLOutput == 1)
2527//                                      WriteXMLWaves_W_Protocol(activeType,fullPath,dialog)
2528//                              else
2529//                                      WriteWaves_W_Protocol(activeType,fullpath,dialog)
2530//                              endif
2531//
2532// TODO:
2533// -- fill in all of the cases, default is only the "standard" circular average I(q)
2534// -- get the trim strings from somewhere-- from the file or from the protocol??
2535//   then replace the null strings being passed
2536
2537                                if(cmpstr(saveType,"Yes - Concatenate")==0)
2538                                        V_Trim1DDataStr(activeType,binType,prot[7],prot[8])                     // TODO -- passing null strings uses global or default trim values
2539//                                      V_Trim1DData(activeType,binType,nBeg,nEnd)
2540                                        V_ConcatenateForSave("root:Packages:NIST:VSANS:",activeType,"",binType)         // this removes q=0 point, concatenates, sorts
2541                                        V_Write1DData("root:Packages:NIST:VSANS:",activeType,newFileName+"."+exten)             //don't pass the full path, just the name
2542                                else
2543                                        // remove the q=0 point from the back detector, if it's there
2544                                        // does not trim any of the data
2545                                        V_RemoveQ0_B(activeType)
2546                                        V_Write1DData_ITX("root:Packages:NIST:VSANS:",activeType,newFileName,binType)
2547                                endif
2548
2549                endswitch
2550               
2551                Print "data written to:  "+ newFileName+"."+exten
2552        Endif
2553       
2554        //done with everything in protocol list
2555       
2556       
2557        // reset any global preferences that I had changed
2558        gDoDIVCor = saved_gDoDIVCor
2559       
2560       
2561        Return(0)
2562End
2563
2564
2565
2566
2567
2568//missing parameter dialog to solicit the 4 absolute intensity parameters
2569//from the user
2570//values are passed back as a global string variable (keyword=value)
2571//
2572Proc V_AskForAbsoluteParams(c2,c3,c4,c5,I_err)
2573        Variable c2=1,c3=1,c4=1e8,c5=1,I_err=1
2574        Prompt c2, "Standard Transmission"
2575        Prompt c3, "Standard Thickness (cm)"
2576        Prompt c4, "I(0) from standard fit (normalized to 1E8 monitor cts)"
2577        Prompt c5, "Standard Cross-Section (cm-1)"
2578        Prompt I_err, "error in I(q=0) (one std dev)"
2579       
2580        String/G root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr=""
2581       
2582        root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr = "TSTAND="+num2str(c2)
2583        root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr +=  ";" + "DSTAND="+num2str(c3)
2584        root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr +=  ";" + "IZERO="+num2str(c4)
2585        root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr +=  ";" + "XSECT="+num2str(c5)
2586        root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr +=  ";" + "SDEV="+num2str(I_err)
2587       
2588End
2589
2590
2591//
2592// TODO
2593// -- fill in all of the functionality for calculation from direct beam
2594//  and verify that the calculations are numerically correct
2595//
2596//asks the user for absolute scaling information. the user can either
2597//enter the necessary values in manually (missing parameter dialog)
2598//or the user can select an empty beam file from a standard open dialog
2599//if an empty beam file is selected, the "kappa" value is automatically calculated
2600//in either case, the global keyword=value string is set.
2601//
2602Function V_AskForAbsoluteParams_Quest()
2603       
2604        Variable err,loc,refnum
2605        //ask user if he wants to use a transmision file for absolute scaling
2606        //or if he wants to enter his own information
2607        err = V_UseStdOrEmpForABS()
2608        //DoAlert 1,"<Yes> to enter your own values, <No> to select an empty beam flux file"
2609        If ( err==1 )
2610                //secondary standard selected, prompt for values
2611                Execute "V_AskForAbsoluteParams()"              //missing parameters
2612        else
2613                //empty beam flux file selected, prompt for file, and use this to calculate KAPPA
2614                Variable kappa=1
2615                Variable kappa_err
2616                       
2617                //get the necessary variables for the calculation of kappa
2618                Variable countTime,monCnt,sdd,pixel
2619                String detStr,junkStr,errStr
2620
2621                Variable empAttenFactor,        emp_atten_err
2622               
2623                //get the XY box and files
2624                Variable x1,x2,y1,y2,emptyCts,empty_ct_err
2625                String emptyFileName,tempStr,divFileName
2626               
2627                // TODO
2628                // x- need an empty beam file name
2629                //
2630                Prompt emptyFileName,"Empty Beam File",popup,V_PickEMPBeamButton("")
2631                DoPrompt "Select File",emptyFileName
2632                if (V_Flag)
2633                        return 0                                                                        // user canceled
2634                endif
2635
2636                //need the detector sensitivity file - make a guess, allow to override
2637                Prompt divFileName,"DIV File",popup,V_PickDIVButton("")
2638                DoPrompt "Select File",divFileName
2639                if (V_Flag)
2640                        return 0                                                                        // user canceled
2641                endif
2642                V_LoadHDF5Data(divFileName,"DIV")
2643
2644
2645                WAVE xyBoxW = V_getBoxCoordinates(emptyFileName)
2646                // TODO
2647                // -- need to get the panel string for the sum.
2648                // -- the detector string is currently hard-wired
2649                detStr = "B"
2650
2651               
2652                // load in the data, and use all of the corrections, especially DIV
2653                // (be sure the corrections are actually set to "on", don't assume that they are)
2654                // save preferences for file loading
2655                Variable savDivPref,savSAPref
2656                NVAR gDoDIVCor = root:Packages:NIST:VSANS:Globals:gDoDIVCor
2657                savDivPref = gDoDIVCor
2658                NVAR gDoSolidAngleCor = root:Packages:NIST:VSANS:Globals:gDoSolidAngleCor
2659                savSAPref = gDoSolidAngleCor
2660               
2661                // set local preferences
2662                gDoDIVCor = 1
2663                gDoSolidAngleCor = 1
2664               
2665                V_LoadAndPlotRAW_wName(emptyFileName)
2666                // convert raw->SAM
2667                V_Raw_to_work("SAM")
2668                V_UpdateDisplayInformation("SAM")       
2669               
2670                // and determine box sum and error
2671                // store these locally
2672                emptyCts = V_SumCountsInBox(xyBoxW[0],xyBoxW[1],xyBoxW[2],xyBoxW[3],empty_ct_err,"SAM",detStr)
2673
2674                Print "empty counts = ",emptyCts
2675                Print "empty err/counts = ",empty_ct_err/emptyCts
2676
2677                //              TODO
2678                // -- get all of the proper values for the calculation
2679                // -- verify the calculation (no solid angle needed)
2680               
2681                // get the attenuation factor for the empty beam
2682                empAttenFactor = V_getAttenuator_transmission(emptyFileName)
2683                emp_atten_err = V_getAttenuator_trans_err(emptyFileName)
2684               
2685                countTime = V_getCount_time(emptyFileName)
2686               
2687                // TODO
2688                // -- not sure if this is the correct monitor count to use, but I do know to use "SAM"
2689                //   rather than the file.
2690                monCnt = V_getBeamMonNormData("SAM")
2691               
2692               
2693               
2694//              kappa = detCnt/countTime/attenTrans*1.0e8/(monCnt/countTime)*(pixel/sdd)^2
2695                kappa = emptyCts/countTime/empAttenFactor*1.0e8/(monCnt/countTime)
2696               
2697                kappa_err = (empty_ct_err/emptyCts)^2 + (emp_atten_err/empAttenFactor)^2
2698                kappa_err = sqrt(kappa_err) * kappa
2699               
2700                // TODO
2701                // -- set the parameters in the global string
2702                junkStr = num2str(kappa)
2703                errStr = num2Str(kappa_err)
2704                Execute "V_AskForAbsoluteParams(1,1,"+junkStr+",1,"+errStr+")"          //no missing parameters, no dialog
2705               
2706
2707                Printf "Kappa was (maybe) successfully calculated as = %g +/- %g (%g %)\r",kappa,kappa_err,(kappa_err/kappa)*100
2708       
2709                // restore preferences on exit
2710                gDoDIVCor = savDivPref
2711                gDoSolidAngleCor = savSAPref
2712
2713        Endif
2714       
2715End
2716
2717Function V_UserSelectBox_Continue(ctrlName) :buttonControl
2718        String ctrlName
2719       
2720        DoWindow/K junkWindow           //kill panel
2721end
2722
2723Function V_SelectABS_XYBox(x1,x2,y1,y2)
2724        Variable &x1,&x2,&y1,&y2
2725       
2726        Variable err=0
2727       
2728        Variable/G root:V_marquee=1             //sets the sneaky bit to automatically update marquee coords
2729        Variable/G root:V_left,root:V_right,root:V_bottom,root:V_top    //must be global for auto-update
2730        DoWindow/F SANS_Data
2731        NewPanel/K=2 /W=(139,341,382,432) as "Select the primary beam"
2732        DoWindow/C junkWindow
2733        AutoPositionWindow/E/M=1/R=SANS_Data
2734       
2735        Drawtext 21,20 ,"Select the primary beam with the"
2736        DrawText 21,40, "marquee and press continue"
2737        Button button0,pos={80,58},size={92,20},title="Continue"
2738        Button button0,proc=V_UserSelectBox_Continue
2739       
2740        PauseForUser junkWindow,SANS_Data
2741       
2742        DoWindow/F SANS_Data
2743
2744        //GetMarquee left,bottom                        //not needed
2745        NVAR V_left=V_left
2746        NVAR V_right=V_right
2747        NVAR V_bottom=V_bottom
2748        NVAR V_top=V_top
2749       
2750        x1 = V_left
2751        x2 = V_right
2752        y1 = V_bottom
2753        y2 = V_top
2754//      Print "new values,before rounding = ",x1,x2,y1,y2
2755
2756// TODO -- replace this call
2757//      KeepSelectionInBounds(x1,x2,y1,y2)
2758        //Print "new values = ",x1,x2,y1,y2
2759       
2760        KillVariables/Z root:V_Marquee,root:V_left,root:V_right,root:V_bottom,root:V_top
2761        if((x1-x2)==0 || (y1-y2)==0)
2762                err=1
2763        endif
2764        return(err)
2765End
2766
2767Function V_UseStdOrEmpForABS()
2768               
2769        NewPanel/K=2 /W=(139,341,402,448) as "Absolute Scaling"
2770        DoWindow/C junkABSWindow
2771        ModifyPanel cbRGB=(57346,65535,49151)
2772        SetDrawLayer UserBack
2773        SetDrawEnv fstyle= 1
2774        DrawText 21,20,"Method of absolute calibration"
2775        Button button0,pos={52,33},size={150,20},proc=V_UserSelectABS_Continue,title="Empty Beam Flux"
2776        Button button1,pos={52,65},size={150,20},proc=V_UserSelectABS_Continue,title="Secondary Standard"
2777       
2778        PauseForUser junkABSWindow
2779        NVAR val = root:Packages:NIST:VSANS:Globals:tmpAbsVal
2780        return(val)
2781End
2782
2783//returns 0 if button0 (empty beam flux)
2784// or 1 if secondary standard
2785Function V_UserSelectABS_Continue(ctrlName) :buttonControl
2786        String ctrlName
2787       
2788        variable val=0
2789        If(cmpstr(ctrlName,"button0")==0)
2790                val=0           
2791        else
2792                val=1
2793        endif
2794//      print "val = ",ctrlName,val
2795        Variable/G root:Packages:NIST:VSANS:Globals:tmpAbsVal = val
2796        DoWindow/K junkABSWindow                //kill panel
2797        return(0)
2798end
2799
2800
2801Function V_TrimDataProtoButton(ctrlName) :buttonControl
2802        String ctrlName
2803       
2804        Execute "V_CombineDataGraph()"
2805        return(0)
2806end
2807
2808//
2809// export protocol to a data file
2810//
2811//
2812Function V_ExportFileProtocol(ctrlName) : ButtonControl
2813        String ctrlName
2814// get a list of protocols
2815        String Protocol=""
2816        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
2817        Prompt Protocol "Pick A Protocol",popup, V_DeletableProtocols()
2818        DoPrompt "Pick A Protocol to Export",Protocol
2819        if(V_flag==1)
2820                //Print "user cancel"
2821                SetDatafolder root:
2822                return(1)
2823        endif
2824
2825        String fileName = V_DoSaveFileDialog("pick the file to write to")
2826        print fileName
2827//     
2828        if(strlen(fileName) == 0)
2829                return(0)
2830        endif
2831
2832        V_writeReductionProtocolWave(fileName,$("root:Packages:NIST:VSANS:Globals:Protocols:"+Protocol) )
2833
2834        setDataFolder root:
2835        return(0)
2836
2837End
2838
2839//
2840// imports a protocol from a file on disk into the protocols folder
2841//
2842//
2843Function V_ImportFileProtocol(ctrlName) : ButtonControl
2844        String ctrlName
2845
2846//      SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
2847
2848        String fullPath,fileName
2849        fullPath = DoOpenFileDialog("Import Protocol from file")
2850        print fullPath
2851//     
2852        if(strlen(fullPath) == 0)
2853                return(0)
2854        endif
2855       
2856        fileName = ParseFilePath(0, fullPath, ":", 1, 0)                        //just the file name at the end of the full path
2857       
2858        Wave/T tmpW = V_getReductionProtocolWave(fileName)
2859        if(numpnts(tmpW) == 0)
2860                DoAlert 0,"No protocol wave has been saved to this data file"
2861                return(0)
2862        endif
2863       
2864        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
2865        String newName
2866        newName = CleanupName(fileName,0) + "_proto"
2867        duplicate/o tmpw $newName
2868       
2869       
2870        SetDataFolder root:
2871        return(0)
2872end
2873
2874
2875// currently not used - and not updated to 12 point protocols (5/2017)
2876//
2877//save the protocol as an IGOR text wave (.itx)
2878//
2879//
2880Function V_ExportProtocol(ctrlName) : ButtonControl
2881        String ctrlName
2882// get a list of protocols
2883        String Protocol=""
2884        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
2885        Prompt Protocol "Pick A Protocol",popup, WaveList("*",";","")
2886        DoPrompt "Pick A Protocol to Export",Protocol
2887        if(V_flag==1)
2888                //Print "user cancel"
2889                SetDatafolder root:
2890                return(1)
2891        endif
2892//get the selection, or exit
2893        Wave/T pW= $protocol
2894        Make/O/T/N=13 tw
2895// save in the proper format (must write manually, for demo version)
2896        tw[0] = "IGOR"
2897        tw[1] = "WAVES/T \t"+protocol
2898        tw[2] = "BEGIN"
2899        tw[3,10] = "\t\""+pW[p-3]+"\""
2900        tw[11] = "END"
2901        tw[12] = "X SetScale/P x 0,1,\"\","+protocol+"; SetScale y 0,0,\"\","+protocol
2902       
2903        Variable refnum
2904        String fullPath
2905       
2906        PathInfo/S catPathName
2907        fullPath = DoSaveFileDialog("Export Protocol as",fname=Protocol,suffix="")
2908        If(cmpstr(fullPath,"")==0)
2909                //user cancel, don't write out a file
2910                Close/A
2911                Abort "no Protocol file was written"
2912        Endif
2913
2914        //actually open the file
2915        Open refNum as fullpath+".itx"
2916       
2917        wfprintf refnum, "%s\r", tw
2918        Close refnum
2919        //Print "all is well  ",protocol
2920        KillWaves/Z tw
2921        setDataFolder root:
2922        return(0)
2923
2924End
2925
2926
2927// currently not used - and not updated to 12 point protocols (5/2017)
2928//imports a protocol from disk into the protocols folder
2929//
2930// will overwrite existing protocols if necessary
2931//
2932//
2933Function V_ImportProtocol(ctrlName) : ButtonControl
2934        String ctrlName
2935
2936        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
2937
2938        String fullPath
2939       
2940        PathInfo/S catPathName
2941        fullPath = DoOpenFileDialog("Import Protocol")
2942        If(cmpstr(fullPath,"")==0)
2943                //user cancel, don't write out a file
2944                Close/A
2945                Abort "no protocol was loaded"
2946        Endif
2947       
2948        LoadWave/O/T fullPath
2949       
2950        SetDataFolder root:
2951        return(0)
2952end
Note: See TracBrowser for help on using the repository browser.