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

Last change on this file since 1166 was 1166, checked in by srkline, 3 years ago

changed the file extension on VSANS QxQyASCII output to have the panel tag in th
e middle of the name to keep the .DAT extension visible for sasView

Changed the behavior of the VSANS averaging protocol. When "saving file" is selceted, choices are either to concatenate or individual. concatenate has NOT been changed. Individual save will now save each individual detector panel data in as
eparate file with the detectr panel string tagged on the end. This replaces the
tedious procedure of multiple mask files an multiple reduction passes.

The save as ITX function is still available through a menu option but is current
ly not an option for a protocol.

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