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

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

Added the angle dependent transmission correction to the data correction in the raw_to_work step, in 2D

added a testing file that can generate fake event data, read, write, and decode it. Read is based on GBLoadWave. Hoepfully I'll not need to write an XOP. manipulation of the 64 bit words are done with simple bit shifts and logic.

also added are a number of error checking routines to improve behavior when wave, folders, etc. are missing.

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