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

Last change on this file since 1042 was 1042, checked in by srkline, 6 years ago

moved dead time correction to before the solid angle correction, so that the dead time would be correcting counts, not counts per solid angle

added a routine to kill all of the waves and folders possible, if the overall DF kill failed. This is to prevent stray folders and waves from being present if different data files are loaded - since different data blocks are present for say, 3He data, data with temperature logging, etc.
This kill routine is used every time, before raw data is loaded, DIV or MASK loaded, or data is converted to WORK.

changed the "Save I(q)" button on the data display panel to save as ITX format, since the data has not been processed, and data can more easily be used for trimming input.

picking protocols in dialogs now excludes/includes appropriate waves

menus are consolidated

Fixed bug in SANS macros where the DRK[] item in the protocol could be null, and force the read of a DRK file, even if it was not desired.

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