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

Last change on this file since 1112 was 1112, checked in by srkline, 4 years ago

a few bug fixes

added menu options to apply the median filter and/or the read noise subtraction to the raw data for troubleshooting/simple analysis rather than needing to convert to normalized WORK data.

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