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

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

additions to the reduction for new corrections to the tube detectors for the angle dependent efficiency and the angle dependent tube shadowing. Calculations have been added, new folder for the efficiency has been added, and preference checkboxes have been updated.

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