source: sans/Dev/trunk/NCNR_User_Procedures/Reduction/SANS/ProtocolAsPanel.ipf @ 683

Last change on this file since 683 was 665, checked in by srkline, 13 years ago

Made preferences a common panel (moved to PlotUtilsMacro?.ipf and globals to root:Packages:NIST:) and added menu items for all packages. Many files had to be modified so that the preferences could be properly accessed

File Open dialog now is set to "All files" so that XML can be selected. I think that all open access that doesn't already have the full path go through this common function.

File size: 77.0 KB
Line 
1#pragma rtGlobals=1             // Use modern global access method.
2#pragma version=5.0
3#pragma IgorVersion=6.1
4
5//************************
6//      Vers. 1.2 092101
7//
8//7/2001 converted protocols to simply use the filenames, rather than the path:filename
9//this should allow portability of the protocols between machines
10//**ALL** protocols now depend on the path "catPathName"
11//
12//procedure files for construction of protocols interactively,
13//selecting files from the CAT/VSHORT table, rather than picking blindly
14//from a dialog - the process of selecting/setting files is not as
15//transparent as it could be for new users
16//
17//*************************
18//////////////////////////////////
19//
20//              KEYWORD=<value> lists used in protocol definitions
21//
22//              KEYWORDS are ALWAYS capitalized, and yes, it does matter
23//
24//              for ABSOLUTE parameters
25//              (4) possible keywords, all with numerical values
26//              TSTAND=value            transmission of the standard
27//              DSTAND=value            thickness of the standard, in centimeters
28//              IZERO=value             I(q=0) value for the standard, in normalized neutron counts
29//              XSECT=value             calibrated cross-section of the standard sample
30//
31//              For calibration with a transmission file, set TSTAND, DSTAND, and XSECT to 1.0
32//              and set IZERO to KAPPA (defined in Tania's handout, or in documentation of MRED_KAP on VAX)
33//
34//
35//              For AVERAGE and for DRAWING
36//                      DRAWING routines only use a subset of the total list, since saving, naming, etc. don't apply
37//              (10) possible keywords, some numerical, some string values
38//              AVTYPE=string           string from set {Circular,Annular,Rectangular,Sector,2D_ASCII,QxQy_ASCII,PNG_Graphic}
39//              PHI=value                       azimuthal angle (-90,90)
40//              DPHI=value                      +/- angular range around phi for average
41//              WIDTH=value             total width of rectangular section, in pixels
42//              SIDE=string             string from set {left,right,both} **note NOT capitalized
43//              QCENTER=value           q-value (1/A) of center of annulus for annular average
44//              QDELTA=value            total width of annulus centered at QCENTER
45//              PLOT=string             string from set {Yes,No} = truth of generating plot of averaged data
46//              SAVE=string             string from set {Yes,No} = truth of saving averaged data to disk
47//              NAME=string             string from set {Auto,Manual} = Automatic name generation or Manual(dialog)
48//
49//
50//              For work.DRK usage:
51//              **the list is COMMA delimited, soparator is =
52//              DRK=none,DRKMODE=0,
53//              DRK=name                        is the name of the file, must be a full name, expected to be raw data
54//              DRKMODE=value           is a numeric value (0 or 10 to add to the Correct(mode) switch (unused?)
55//
56//////////////////////////////////
57
58
59//main entry procedure for initialzing and displaying the protocol panel
60// initilaizes folders and globals as needed
61//
62Proc ReductionProtocolPanel()
63        DoWindow/F ProtocolPanel
64        if(V_flag==0)
65                InitProtocolPanel()
66                ProtocolPanel()
67        Endif
68End
69
70//initialization procedure for the protocol panel
71//note that :gAbsStr is also shared (common global) to that used in
72//the questionnare form of the protcol (see protocol.ipf)
73//
74//0901, uses 8 points in protocol wave
75Proc InitProtocolPanel()
76
77        //set up the global variables needed for the protocol panel
78        //global strings to put in a temporary protocol textwave
79        Variable ii=0,nsteps=8
80        String waveStr="tempProtocol"
81        SetDataFolder root:myGlobals:Protocols
82        Make/O/T/N=(nsteps) $"root:myGlobals:Protocols:tempProtocol" = ""
83
84        String/G root:myGlobals:Protocols:gSAM="ask"
85        String/G root:myGlobals:Protocols:gBGD="ask"
86        String/G root:myGlobals:Protocols:gEMP="ask"
87        String/G root:myGlobals:Protocols:gDIV="ask"
88        String/G root:myGlobals:Protocols:gMASK="ask"
89        String/G root:myGlobals:Protocols:gAbsStr="ask"
90        String/G root:myGlobals:Protocols:gAVE="AVTYPE=Circular;SAVE=Yes;NAME=Auto;PLOT=Yes;"
91        String/G root:myGlobals:Protocols:gDRK="DRK=none,DRKMODE=0,"
92       
93        SetDataFolder root:
94       
95End
96
97//button control to create a CAT/SHORT notebook listing of all data files
98//in the selected folder (catPathName)
99//
100Function DoCatShort(ctrlName) : ButtonControl
101        String ctrlName
102
103        Execute "BuildCatVeryShortTable()"
104       
105End
106
107//button procedure to reset the panel seletctions/checks...etc...
108//to reflect the choices in a previously saved protocol
109// - parses through the protocol and resets the appropriate global strings and
110//updates the panel display
111//
112Function RecallProtocolButton(ctrlName) : ButtonControl
113        String ctrlName
114
115        //will reset panel values based on a previously saved protocol
116        //pick a protocol wave from the Protocols folder
117        //MUST move to Protocols folder to get wavelist
118        SetDataFolder root:myGlobals:Protocols
119        Execute "PickAProtocol()"
120       
121        //get the selected protocol wave choice through a global string variable
122        SVAR protocolName = root:myGlobals:Protocols:gProtoStr
123
124        //If "CreateNew" was selected, ask user to try again
125        if(cmpstr("CreateNew",protocolName) == 0)
126                Abort "CreateNew is for making a new Protocol. Select a previously saved Protocol"
127        Endif
128       
129        //reset the panel based on the protocol textwave (currently a string)
130        ResetToSavedProtocol(protocolName)
131       
132        SetDataFolder root:
133        return(0)
134End
135
136//deletes the selected protocol from the list and from memory
137//
138Function DeleteProtocolButton(ctrlName) : ButtonControl
139        String ctrlName
140
141        //put up a list of protocols and pick one
142        SetDataFolder root:myGlobals:Protocols
143//      Execute "DeleteAProtocol()"
144        String Protocol=""
145        Prompt Protocol "Delete A Protocol",popup, DeletableProtocols()
146        DoPrompt "Select protocol to delete",protocol
147        If(V_flag==1)
148                return(0)
149        endif
150
151        //If "CreateNew, Base, DoAll, or tempProtocol" was selected, do nothing
152        strswitch(protocol)
153                case "CreateNew":
154                        break
155                case "DoAll":
156                        break
157                case "Base":
158                        break
159                case "tempProtocol":
160                        break
161                default:
162                        //delete the protocol
163                        KillWaves/Z $protocol
164        endswitch
165       
166        SetDataFolder root:
167        return(0)
168End
169
170
171//function that actually parses the protocol specified by nameStr
172//which is just the name of the wave, without a datafolder path
173//
174Function ResetToSavedProtocol(nameStr)
175        String nameStr
176       
177        //allow special cases of Base and DoAll Protocols to be recalled to panel - since they "ask"
178        //and don't need paths
179       
180        String catPathStr
181        PathInfo catPathName
182        catPathStr=S_path
183       
184        //SetDataFolder root:myGlobals:Protocols                //on windows, data folder seems to get reset (erratically) to root:
185        Wave/T w=$("root:myGlobals:Protocols:" + nameStr)
186       
187        String fullPath="",comma=",",list="",nameList="",PathStr="",item=""
188        Variable ii=0,numItems,checked,specialProtocol
189       
190        if((cmpstr(nameStr,"Base")==0) || (cmpstr(nameStr,"DoAll")==0))
191                specialProtocol = 1
192        else
193                specialProtocol = 0
194        Endif
195       
196        //background
197        checked = 1
198        nameList = w[0]
199        If(cmpstr(nameList,"none") ==0)
200                checked = 0
201        Endif
202
203        //set the global string to display and checkbox
204        String/G root:myGlobals:Protocols:gBGD = nameList
205        CheckBox prot_check win=ProtocolPanel,value=checked
206       
207        //empty
208        checked = 1
209        nameList = w[1]
210        If(cmpstr(nameList,"none") ==0)
211                checked = 0
212        Endif
213
214        //set the global string to display and checkbox
215        String/G root:myGlobals:Protocols:gEMP = nameList
216        CheckBox prot_check_1 win=ProtocolPanel,value=checked
217       
218        //DIV file
219        checked = 1
220        nameList = w[2]
221        If(cmpstr(nameList,"none") ==0)
222                checked = 0
223        Endif
224
225        //set the global string to display and checkbox
226        String/G root:myGlobals:Protocols:gDIV = nameList
227        CheckBox prot_check_2 win=ProtocolPanel,value=checked
228       
229        //Mask file
230        checked = 1
231        nameList = w[3]
232        If(cmpstr(nameList,"none") ==0)
233                checked = 0
234        Endif
235
236        //set the global string to display and checkbox
237        String/G root:myGlobals:Protocols:gMASK = nameList
238        CheckBox prot_check_3 win=ProtocolPanel,value=checked
239       
240        //4 = abs parameters
241        list = w[4]
242        numItems = ItemsInList(list,";")
243        checked = 1
244        if(numitems == 4)
245                //correct number of parameters, assume ok
246                String/G root:myGlobals:Protocols:gAbsStr = list
247                CheckBox prot_check_9 win=ProtocolPanel,value=checked
248        else
249                item = StringFromList(0,list,";")
250                if(cmpstr(item,"none")==0)
251                        checked = 0
252                        list = "none"
253                        String/G root:myGlobals:Protocols:gAbsStr = list
254                        CheckBox prot_check_9 win=ProtocolPanel,value=checked
255                else
256                        //force to "ask"
257                        checked = 1
258                        String/G root:myGlobals:Protocols:gAbsStr = "ask"
259                        CheckBox prot_check_9 win=ProtocolPanel,value=checked
260                Endif
261        Endif
262       
263        //5 = averaging choices
264        list = w[5]
265        item = StringByKey("AVTYPE",list,"=",";")
266        if(cmpstr(item,"none") == 0)
267                checked = 0
268                String/G root:myGlobals:Protocols:gAVE = "none"
269                CheckBox prot_check_5 win=ProtocolPanel,value=checked
270        else
271                checked = 1
272                String/G root:myGlobals:Protocols:gAVE = list
273                CheckBox prot_check_5 win=ProtocolPanel,value=checked
274        Endif
275       
276        //6 = DRK choice
277        list = w[6]
278        item = StringByKey("DRK",list,"=",",")
279        //print list,item
280        if(cmpstr(item,"none") == 0)
281                checked = 0
282                String/G root:myGlobals:Protocols:gDRK = list
283                CheckBox prot_check_6 win=ProtocolPanel,value=checked
284        else
285                checked = 1
286                String/G root:myGlobals:Protocols:gDRK = list
287                CheckBox prot_check_6 win=ProtocolPanel,value=checked
288        Endif
289       
290        //7 = unused
291       
292        //all has been reset, get out
293        Return (0)
294End
295
296//button action procedure that simply closes the panel
297//
298Function DoneProtocolButton(ctrlName) : ButtonControl
299        String ctrlName
300
301        //will gracefully close and exit the protocol panel
302       
303        DoWindow/K ProtocolPanel
304End
305
306//button action procedure that saves the current choices on the panel
307//as a named protocol, for later recall
308//asks for a valid name, then creates a protocol from the panel choices
309//creates a wave, and sets the current protocol name to this new protocol
310//
311//now allows the user the choice to overwrite a protocol
312//
313Function SaveProtocolButton(ctrlName) : ButtonControl
314        String ctrlName
315
316        Variable notDone=1, newProto=1
317        //will prompt for protocol name, and save the protocol as a text wave
318        //prompt for name of new protocol wave to save
319        do
320                Execute "AskForName()"
321                SVAR newProtocol = root:myGlobals:Protocols:gNewStr
322               
323                //make sure it's a valid IGOR name
324                newProtocol = CleanupName(newProtocol,0)        //strict naming convention
325                String/G root:myGlobals:Protocols:gNewStr=newProtocol           //reassign, if changed
326                Print "newProtocol = ",newProtocol
327               
328                SetDataFolder root:myGlobals:Protocols
329                if(WaveExists( $("root:myGlobals:Protocols:" + newProtocol) ) == 1)
330                        //wave already exists
331                        DoAlert 1,"That name is already in use. Do you wish to overwrite the existing protocol?"
332                        if(V_Flag==1)
333                                notDone = 0
334                                newProto = 0
335                        else
336                                notDone = 1
337                        endif
338                else
339                        //name is good
340                        notDone = 0
341                Endif
342        while(notDone)
343       
344        //current data folder is  root:myGlobals:Protocols
345        if(newProto)
346                Make/O/T/N=8 $("root:myGlobals:Protocols:" + newProtocol)
347        Endif
348       
349        MakeProtocolFromPanel( $("root:myGlobals:Protocols:" + newProtocol) )
350        String/G  root:myGlobals:Protocols:gProtoStr = newProtocol
351       
352        //the data folder WAS changed above, this must be reset to root:
353        SetDatafolder root:
354End
355
356//function that does the guts of reading the panel controls and globals
357//to create the necessary text fields for a protocol
358//Wave/T w (input) is an empty text wave of 8 elements for the protocol
359//on output, w[] is filled with the protocol strings as needed from the panel
360//
361Function MakeProtocolFromPanel(w)
362        Wave/T w
363       
364        //construct the protocol text wave form the panel
365        //it is to be parsed by ExecuteProtocol() for the actual data reduction
366        PathInfo catPathName                    //this is where the files came from
367        String pathstr=S_path,tempStr,curList
368        Variable checked,ii,numItems
369       
370        //look for checkbox, then take each item in list and prepend the path
371        //w[0] = background
372        ControlInfo/W=ProtocolPanel prot_check
373        checked = V_value
374        if(checked)
375                //build the list
376                //just read the global
377                SVAR str=root:myGlobals:Protocols:gBGD
378                if(cmpstr(str,"ask")==0)
379                        w[0] = str              //just ask
380                else
381                        tempstr = ParseRunNumberList(str)
382                        if(strlen(tempStr)==0)
383                                return(1)                               //error parsing list
384                        else
385                                w[0] = tempstr
386                                str = tempstr           //set the protocol and the global
387                        endif
388                endif
389        else
390                //none used - set textwave (and global?)
391                w[0] = "none"
392                String/G root:myGlobals:Protocols:gBGD = "none"
393        endif
394       
395        //w[1] = empty
396        ControlInfo/W=ProtocolPanel prot_check_1
397        checked = V_value
398        if(checked)
399                //build the list
400                //just read the global
401                SVAR str=root:myGlobals:Protocols:gEMP
402                if(cmpstr(str,"ask")==0)
403                        w[1] = str
404                else
405                        tempstr = ParseRunNumberList(str)
406                        if(strlen(tempStr)==0)
407                                return(1)
408                        else
409                                w[1] = tempstr
410                                str=tempStr
411                        endif
412                endif
413        else
414                //none used - set textwave (and global?)
415                w[1] = "none"
416                String/G root:myGlobals:Protocols:gEMP = "none"
417        endif
418       
419        //w[2] = div file
420        ControlInfo/W=ProtocolPanel prot_check_2
421        checked = V_value
422        if(checked)
423                //build the list
424                //just read the global
425                SVAR str=root:myGlobals:Protocols:gDIV
426                if(cmpstr(str,"ask")==0)
427                        w[2] = str
428                else
429                        tempStr = ParseRunNumberList(str)
430                        if(strlen(tempStr)==0)
431                                return(1)
432                        else
433                                w[2] = tempstr
434                                str=tempstr
435                        endif
436                endif
437        else
438                //none used - set textwave (and global?)
439                w[2] = "none"
440                String/G root:myGlobals:Protocols:gDIV = "none"
441        endif
442       
443        //w[3] = mask file
444        ControlInfo/W=ProtocolPanel prot_check_3
445        checked = V_value
446        if(checked)
447                //build the list
448                //just read the global
449                SVAR str=root:myGlobals:Protocols:gMASK
450                if(cmpstr(str,"ask")==0)
451                        w[3] = str
452                else
453                        tempstr = ParseRunNumberList(str)
454                        if(strlen(tempstr)==0)
455                                return(1)
456                        else
457                                w[3] = tempstr
458                                str = tempstr
459                        endif
460                endif
461        else
462                //none used - set textwave (and global?)
463                w[3] = "none"
464                String/G root:myGlobals:Protocols:gMASK = "none"
465        endif
466       
467        //w[4] = abs parameters
468        ControlInfo/W=ProtocolPanel prot_check_9
469        checked = V_value
470        if(checked)
471                //build the list
472                //just read the global
473                SVAR str=root:myGlobals:Protocols:gAbsStr
474                w[4] = str
475        else
476                //none used - set textwave (and global?)
477                w[4] = "none"
478                String/G root:myGlobals:Protocols:gAbsStr = "none"
479        endif
480       
481        //w[5] = averaging choices
482        ControlInfo/W=ProtocolPanel prot_check_5                        //do the average?
483        checked = V_value
484        if(checked)
485                //just read the global
486                SVAR avestr=root:myGlobals:Protocols:gAVE
487                w[5] = avestr
488        else
489                //none used - set textwave
490                w[5] = "AVTYPE=none;"
491        endif
492       
493        //w[6]
494        //work.DRK information
495        SVAR drkStr=root:myGlobals:Protocols:gDRK
496        w[6] = drkStr
497       
498        //w[7]
499        //currently unused
500        w[7] = ""
501       
502        return(0)
503End
504
505
506//button control function to set the background (SAM) file name to the
507//selected name in the CAT/SHORT window
508//the version number of the file need not be selected, it will be added later if needed
509//multiple SAMple files can be added together if the list is not reset
510//
511Function PickSAMButton(ctrlName) : ButtonControl
512        String ctrlName
513
514        //set the SAM file(s) as a global string
515        //multiple files are added as a COMMA separated list of files, w/extension
516        //global string is either null or contains filename(s) on entry
517       
518        //ask to reset the list?
519        DoAlert 1,"Reset the list of sample files?"
520        if(V_flag == 1)
521                String/G root:myGlobals:Protocols:gSAM = ""
522        Endif
523       
524        Variable catVSTableExists, num_sans_files
525        catVSTableExists = WinType("catVSTable")
526        //??BUG?? V_flag returns 1 even if no selection?
527        //check manually for null selection
528        //Print "local v_flag = ",num2str(V_flag)
529        Wave/T LocFilenames = $"root:myGlobals:CatVSHeaderInfo:Filenames"
530        if (catVSTableExists != 0)
531                GetSelection table,CatVSTable,7
532                if(strsearch(S_selection,"Filenames",0) == 0)
533                   //selection OK, add to list
534          Duplicate/O/R=[V_startRow,V_endRow] LocFilenames, filenames
535          Wave/T selectedFiles = $"filenames"
536          num_sans_files = numpnts(selectedFiles)
537                   SVAR temp = root:myGlobals:Protocols:gSAM
538          Variable ii=0
539          do
540            temp = temp+selectedFiles[ii]+","
541            ii+=1
542          while (ii < num_sans_files)
543      Else
544                                DoAlert 0,"Invalid selection from the File Catalog window"
545      Endif
546        else
547                //no selection
548                String/G root:myGlobals:Protocols:gSAM = "ask"
549                DoAlert 0,"No file selected from File Catalog table or no File Catalog table available"
550        Endif
551        return(0)
552End
553
554//button control to set the background (BGD) file name to the
555//selected name in the CAT/SHORT window
556//the version number of the file need not be selected, it will be added later if needed
557//multiple BGD files can be added together if the file list is not reset
558//
559Function PickBGDButton(ctrlName) : ButtonControl
560        String ctrlName
561
562        //set the BGD file(s) as a global string
563        //multiple files are added as a COMMA separated list of files, w/extension
564        //global string is either null or contains filename(s) on entry
565       
566        //ask to reset the list?
567        DoAlert 1,"Reset the list of background files?"
568        if(V_flag == 1)
569                String/G root:myGlobals:Protocols:gBGD = ""
570        Endif
571
572        Variable catVSTableExists, num_sans_files
573        catVSTableExists = WinType("CatVSTable")
574        //??BUG?? V_flag returns 1 even if no selection?
575        //check manually for null selection
576        //Print "local v_flag = ",num2str(V_flag)
577        Wave/T LocFilenames = $"root:myGlobals:CatVSHeaderInfo:Filenames"
578        if (catVSTableExists != 0)
579                GetSelection table,CatVSTable,7
580                if(strsearch(S_selection,"Filenames",0) == 0)
581           //selection OK, add to list
582                   Duplicate/O/R=[V_startRow,V_endRow] LocFilenames, filenames
583                   Wave/T selectedFiles = $"filenames"
584                   num_sans_files = numpnts(selectedFiles)
585                   SVAR temp = root:myGlobals:Protocols:gBGD
586                        Variable ii=0
587                        do
588                                temp = temp+selectedFiles[ii]+","
589                                ii+=1
590                        while (ii < num_sans_files)
591                Else
592                        DoAlert 0,"Invalid selection from the File Catalog table"
593                Endif
594        else
595                //no selection
596                DoAlert 0,"No file selected from File Catalog table or no File Catalog table available"
597        Endif
598       
599End
600
601//button control function to set the background (EMP) file name to the
602//selected name in the CAT/SHORT window
603//the version number of the file need not be selected, it will be added later if needed
604//multiple EMP files can be added together if the file list is not reset
605//
606Function PickEMPButton(ctrlName) : ButtonControl
607        String ctrlName
608
609        //ask to reset the list?
610        DoAlert 1,"Reset the list of empty cell files?"
611        if(V_flag == 1)
612                String/G root:myGlobals:Protocols:gEMP = ""
613        Endif
614       
615        Variable catVSTableExists, num_sans_files
616        catVSTableExists = WinType("catVSTable")
617        //??BUG?? V_flag returns 1 even if no selection?
618        //check manually for null selection
619        //Print "local v_flag = ",num2str(V_flag)
620        Wave/T LocFilenames = $"root:myGlobals:CatVSHeaderInfo:Filenames"
621        if (catVSTableExists != 0)
622                GetSelection table,CatVSTable,7
623                if(strsearch(S_selection,"Filenames",0) == 0)
624                   //selection OK, add to list
625                Duplicate/O/R=[V_startRow,V_endRow] LocFilenames, filenames
626        Wave/T selectedFiles = $"filenames"
627                num_sans_files = numpnts(selectedFiles)
628                SVAR temp = root:myGlobals:Protocols:gEMP
629                        Variable ii=0
630                        do
631                                temp = temp+selectedFiles[ii]+","
632                                ii+=1
633                        while (ii < num_sans_files)
634                Else
635                        DoAlert 0,"Invalid selection from the File Catalog table"
636                Endif
637        else
638                //no selection
639                DoAlert 0,"No file selected from File Catalog table or no File Catalog table available"
640        Endif
641       
642End
643
644//button control function to set the background (DIV) file name to the
645//selected name in the CAT/SHORT window
646//the version number of the file need not be selected, it will be added later if needed
647//there can only be one DIV file for a given protocol
648//
649Function PickDIVButton(ctrlName) : ButtonControl
650        String ctrlName
651
652        //alwys reset the list of DIV files, there can be only one
653        String/G root:myGlobals:Protocols:gDIV = ""
654        Variable catVSTableExists, num_sans_files
655        catVSTableExists = WinType("catVSTable")
656        //??BUG?? V_flag returns 1 even if no selection?
657        //check manually for null selection
658        //Print "local v_flag = ",num2str(V_flag)
659        Wave/T LocFilenames = $"root:myGlobals:CatVSHeaderInfo:Filenames"
660        if (catVSTableExists != 0)
661                GetSelection table,CatVSTable,7
662                if(strsearch(S_selection,"Filenames",0) == 0)
663                   //selection OK, add to list
664        Duplicate/O/R=[V_startRow,V_endRow] LocFilenames, filenames
665                Wave/T selectedFiles = $"filenames"
666           num_sans_files = numpnts(selectedFiles)           
667                   SVAR temp = root:myGlobals:Protocols:gDIV
668                        temp = selectedFiles[0]
669                Else
670                        DoAlert 0,"Invalid selection from the File Catalog table"
671                Endif
672        else
673                //no selection
674                DoAlert 0,"No file selected from File Catalog table or no File Catalog table available"
675        Endif
676       
677End
678
679//button control function to set the background (MSK) file name to the
680//selected name in the CAT/SHORT window
681//the version number of the file need not be selected, it will be added later if needed
682//there can only be one MSK file for a given protocol
683//
684Function PickMASKButton(ctrlName) : ButtonControl
685        String ctrlName
686       
687        //always reset the list of MASK files - ther can be only one
688        String/G root:myGlobals:Protocols:gMASK = ""
689       
690        Variable catVSTableExists, num_sans_files
691        catVSTableExists = WinType("catVSTable")
692        //??BUG?? V_flag returns 1 even if no selection?
693        //check manually for null selection
694        //Print "local v_flag = ",num2str(V_flag)
695        Wave/T LocFilenames = $"root:myGlobals:CatVSHeaderInfo:Filenames"
696        if (catVSTableExists != 0)
697                GetSelection table,CatVSTable,7
698                if(strsearch(S_selection,"Filenames",0) == 0)
699                        //selection OK, add to list
700                Duplicate/O/R=[V_startRow,V_endRow] LocFilenames, filenames
701                Wave/T selectedFiles = $"filenames"
702                num_sans_files = numpnts(selectedFiles)           
703                        SVAR temp = root:myGlobals:Protocols:gMASK
704                        temp = selectedFiles[0]
705        Else
706                        DoAlert 0,"Invalid selection from the File Catalog table"
707                Endif
708        else
709                //no selection
710                DoAlert 0,"No file selected from File Catalog table or no File Catalog table available"
711        Endif
712       
713End
714
715//button action function to reduce one file with the information specified on
716//the panel
717//a temporary protocol is created, even if the fields correspond to a named protocol
718//(only the protocol wave values are written to the data header, but the name is written to the
719//schematic - this could cause some unwanted confusion)
720//
721//if a sample file(s) is selected, only that file(s) will be reduced
722//if no file is selected, the user will be prompted with a standard open
723//dialog to select sample data file(s)
724//
725Function ReduceOneButton(ctrlName) : ButtonControl
726        String ctrlName
727
728        //parse the information on the panel and assign to tempProtocol wave (in protocol folder)
729        //and execute
730        String temp="root:myGlobals:Protocols:tempProtocol"
731        Wave/T w=$temp
732        Variable ii=0,num=8
733        do
734                w[ii] = ""
735                ii+=1
736        while(ii<num)
737       
738        MakeProtocolFromPanel(w)
739
740        //the "current" protocol is the "tempProtocol" that was parsed from the panel input
741        //set the global, so that the data writing routine can find the protocol wave (fatal otherwise)
742        String/G root:myGlobals:Protocols:gProtoStr="tempProtocol"
743       
744        PathInfo catPathName                    //this is where the files came from
745        String pathstr=S_path,samStr
746       
747        //take the string from the panel
748        SVAR tempStr = root:myGlobals:Protocols:gSAM
749       
750        if( (strlen(tempStr) == 0) || (cmpstr(tempStr,"ask")==0) )
751                //let user select the files
752                tempStr="ask"
753                ExecuteProtocol(temp,tempStr)
754                return(0)
755        Else
756                //parse the list of numbers
757                //send only the filenames, without paths
758                samStr = ParseRunNumberList(tempStr)
759                If(strlen(samStr)==0)
760                        DoAlert 0,"The SAM file number cound not be interpreted. Please enter a valid run number or filename"
761                        return(1)
762                endif
763                tempStr=samStr          //reset the global
764                ExecuteProtocol(temp,samStr)
765                return(0)
766        endif
767End
768
769
770//button action function will prompt user for absolute scaling parameters
771//either from an empty beam file or by manually entering the 4 required values
772//uses the same function and shared global string as the questionnare form of reduction
773//in "protocol.ipf" - the string is root:myGlobals:Protocols:gAbsStr
774//
775Function SetABSParamsButton(ctrlName) : ButtonControl
776        String ctrlName
777
778        //will prompt for a list of ABS parameters (4) through a global string variable
779       
780        Execute "AskForAbsoluteParams_Quest()"
781       
782End
783
784//simple button action procedure to bring the CAT/SHORT notebook window to the front
785//in case it's buried behind other windows
786//
787Function ShowCATButton(ctrlName) : ButtonControl
788        String ctrlName
789
790        DoWindow/F CatVSTable
791        if(V_flag==0)
792                DoAlert 0,"There is no File Catalog table window. Use the File Catalog table button to create one."
793        Endif
794       
795End
796
797//the panel recreation macro
798//
799Window ProtocolPanel()
800        PauseUpdate; Silent 1           // building window...
801        NewPanel /W=(553,48,851,500) /K=1 as "Data Reduction Protocol"
802        ModifyPanel cbRGB=(27589,43441,64159), fixedSize=1
803        SetDrawLayer UserBack
804        DrawLine 2,25,300,25
805        DrawLine 2,69,300,69
806        DrawLine 2,120,300,120
807        DrawLine 2,169,300,169
808        DrawLine 2,217,300,217
809        DrawLine 2,262,300,262
810        DrawLine 2,357,300,357
811        DrawLine 2,379,300,379
812        DrawLine 2,308,300,308
813        Button button0,pos={12,2},size={90,20},proc=DoCatShort,title="File Catalog"
814        Button button0,help={"Use this button to generate a catalog of raw data file headers. Select files from the list for EMP, BGD,..."}
815        Button button_help,pos={260,2},size={25,20},proc=ShowProtoHelp,title="?"
816        Button button_help,help={"Show the help file for setting up a reduction protocol"}
817        CheckBox prot_check,pos={5,75},size={74,14},title="Background"
818        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"}
819        CheckBox prot_check,value= 1
820        Button pick_bgd,pos={114,75},size={100,20},proc=PickBGDButton,title="set BGD file"
821        Button pick_bgd,help={"This button will set the file selected in the File Catalog table to be the background file."}
822        Button recallProt,pos={7,406},size={107,20},proc=RecallProtocolButton,title="Recall Protocol"
823        Button recallProt,help={"Resets the panel to the file choices in  a previously saved protocol"}
824        Button del_protocol,pos={7,428},size={110,20},proc=DeleteProtocolButton,title="Delete Protocol"
825        Button del_protocol,help={"Use this to delete a previously saved protocol."}
826        Button done_protocol,pos={225,428},size={45,20},proc=DoneProtocolButton,title="Done"
827        Button done_protocol,help={"This button will close the panel. The panel can be recalled at any time from the SANS menu."}
828        Button saveProtocol,pos={7,384},size={100,20},proc=SaveProtocolButton,title="Save Protocol"
829        Button saveProtocol,help={"Saves the cerrent selections in the panel to a protocol which can be later recalled"}
830        CheckBox prot_check_1,pos={5,127},size={71,14},title="Empty Cell"
831        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"}
832        CheckBox prot_check_1,value= 1
833        CheckBox prot_check_2,pos={6,175},size={72,14},title="Sensitivity"
834        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"}
835        CheckBox prot_check_2,value= 1
836        CheckBox prot_check_3,pos={9,268},size={43,14},title="Mask"
837        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"}
838        CheckBox prot_check_3,value= 1
839        Button pick_emp,pos={113,125},size={100,20},proc=PickEMPButton,title="set EMP file"
840        Button pick_emp,help={"This button will set the file selected in the File Catalog table to be the empty cell file."}
841        Button pick_DIV,pos={114,173},size={100,20},proc=PickDIVButton,title="set DIV file"
842        Button pick_DIV,help={"This button will set the file selected in the File Catalog table to be the sensitivity file."}
843        Button pick_MASK,pos={119,266},size={100,20},proc=PickMASKButton,title="set MASK file"
844        Button pick_MASK,help={"This button will set the file selected in the File Catalog table to be the mask file."}
845        SetVariable bgdStr,pos={7,98},size={250,15},title="file:"
846        SetVariable bgdStr,help={"Filename of the background file(s) to be used in the data reduction"}
847        SetVariable bgdStr,limits={-Inf,Inf,0},value= root:myGlobals:Protocols:gBGD
848        SetVariable empStr,pos={8,148},size={250,15},title="file:"
849        SetVariable empStr,help={"Filename of the empty cell file(s) to be used in the data reduction"}
850        SetVariable empStr,limits={-Inf,Inf,0},value= root:myGlobals:Protocols:gEMP
851        SetVariable divStr,pos={9,197},size={250,15},title="file:"
852        SetVariable divStr,help={"Filename of the detector sensitivity file to be used in the data reduction"}
853        SetVariable divStr,limits={-Inf,Inf,0},value= root:myGlobals:Protocols:gDIV
854        SetVariable maskStr,pos={9,289},size={250,15},title="file:"
855        SetVariable maskStr,help={"Filename of the mask file to be used in the data reduction"}
856        SetVariable maskStr,limits={-Inf,Inf,0},value= root:myGlobals:Protocols:gMASK
857        Button ReduceOne,pos={194,384},size={100,20},proc=ReduceOneButton,title="Reduce A File"
858        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"}
859        CheckBox prot_check_4,pos={5,30},size={53,14},title="Sample"
860        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"}
861        CheckBox prot_check_4,value= 1
862        Button pick_sam,pos={115,28},size={100,20},proc=PickSAMButton,title="set SAM file"
863        Button pick_sam,help={"This button will set the file selected in the File Catalog table to be the sample file"}
864        SetVariable samStr,pos={6,50},size={250,15},title="file:"
865        SetVariable samStr,help={"Filename of the sample file(s) to be used in the data reduction"}
866        SetVariable samStr,limits={-Inf,Inf,0},value= root:myGlobals:Protocols:gSAM
867        Button pick_ABS,pos={115,220},size={110,20},proc=SetABSParamsButton,title="set ABS params"
868        Button pick_ABS,help={"This button will prompt the user for absolute scaling parameters"}
869        CheckBox prot_check_9,pos={7,222},size={59,14},title="Absolute"
870        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"}
871        CheckBox prot_check_9,value= 1
872        SetVariable absStr,pos={7,243},size={250,15},title="parameters:"
873        SetVariable absStr,help={"Keyword-string of values necessary for absolute scaling of data. Remaining parameters are taken from the sample file."}
874        SetVariable absStr,limits={-Inf,Inf,0},value= root:myGlobals:Protocols:gAbsStr
875        Button show_cat,pos={120,2},size={120,20},proc=ShowCATButton,title="Show File Catalog"
876        Button show_cat,help={"Brings the current condensed File Catalog table to the front"}
877        CheckBox prot_check_5,pos={6,311},size={56,14},title="Average"
878        CheckBox prot_check_5,help={"If checked, the specified averaging will be performed at the end of the data reduction."}
879        CheckBox prot_check_5,value= 1
880        Button pick_AVE,pos={108,313},size={150,20},proc=SetAverageParamsButtonProc,title="set AVERAGE params"
881        Button pick_AVE,help={"Prompts the user for the type of 1-D averaging to perform, as well as saving options"}
882        SetVariable aveStr,pos={9,336},size={250,15},title="parameters:"
883        SetVariable aveStr,help={"Keyword-string of choices used for averaging and saving the 1-D data files"}
884        SetVariable aveStr,limits={-Inf,Inf,0},value= root:myGlobals:Protocols:gAVE
885        //only show DRK if user wants to see it
886        //if global = 1,then show => set disable = 0
887        CheckBox prot_check_6,pos={6,363},size={113,14},proc=DrkCheckProc,title="Use DRK correction"
888        CheckBox prot_check_6,help={"If checked, the selected file will be used for DRK correction. Typically this is NOT checked"}
889        CheckBox prot_check_6,value= 0,disable = (!root:Packages:NIST:gAllowDRK)
890        SetVariable drkStr,pos={120,363},size={150,15},title="."
891        SetVariable drkStr,help={"DRK detector count file"},disable = (!root:Packages:NIST:gAllowDRK)
892        SetVariable drkStr,limits={-Inf,Inf,0},value= root:myGlobals:Protocols:gDRK
893        Button export_button, size={60,20},pos={125,384},title="Export",proc=ExportProtocol
894        Button export_button, help={"Exports the protocol to disk for Importing into another experiment"}
895        Button import_button, size={60,20},pos={125,406},title="Import",proc=ImportProtocol
896        Button import_button,help={"Imports a protocol from disk for use in this experiment"}
897EndMacro
898
899//activated when user checks/unchecks the box
900//either prompts for a file using a standard dialog, or removes the current file
901Function DrkCheckProc(ctrlName,checked) : CheckBoxControl
902        String ctrlName
903        Variable checked                //Desired state, not previous state
904
905        SVAR drkStr=root:myGlobals:Protocols:gDRK
906        if(checked==1)
907                //print "Unchecked on call"
908                //this just asks for the filename, doesn't open the file
909                String msgStr="Select the DRK file",fullPath="",fileStr=""
910                Variable refnum
911               
912                Open/D/R/T="????"/M=(msgStr)/P=catPathName refNum
913                fullPath = S_FileName           //fname is the full path
914                if(cmpstr(fullpath,"")==0)
915                        //user cancelled
916                        CheckBox prot_check_6,value=0           //keep box unchecked
917                        return(0)
918                Endif
919                fileStr=GetFileNameFromPathNoSemi(fullPath)
920                //Print fileStr
921                //update the global string
922                drkStr = ReplaceStringByKey("DRK",drkStr,fileStr,"=",",")
923                drkStr = ReplaceNumberByKey("DRKMODE", drkStr, 10 ,"=",",")
924        else
925                //print "checked on call"
926                drkStr="DRK=none,DRKMODE=0,"            //change the global
927        endif
928       
929End
930
931
932Function ShowProtoHelp(ctrlName) : ButtonControl
933        String ctrlName
934        DisplayHelpTopic/Z/K=1 "SANS Data Reduction Tutorial[Build a Data Reduction Protocol]"
935        if(V_flag !=0)
936                DoAlert 0,"The SANS Data Reduction Tutorial Help file could not be found"
937        endif
938End
939
940//button action procedure to get the type of average requested by the user
941//presented as a missing parameter dialog, which is really user-UN-friendly
942//and will need to be re-thought. Defaults of dialog are set for normal
943//circular average, so typically click "continue" and proceed
944//
945Function SetAverageParamsButtonProc(ctrlName) : ButtonControl
946        String ctrlName
947       
948        Execute "GetAvgInfo()"
949       
950        //set the global string
951        SVAR tempStr = root:myGlobals:Protocols:gAvgInfoStr
952        String/G root:myGlobals:Protocols:gAVE = tempStr
953
954End
955
956//procedure called by protocol panel to ask user for average type choices
957// somewhat confusing and complex, but may be as good as it gets.
958//
959Proc GetAvgInfo(av_typ,autoSave,autoName,autoPlot,side,phi,dphi,width,QCtr,QDelta)
960        String av_typ,autoSave,AutoName,autoPlot,side
961        Variable phi=0,dphi=10,width=10,Qctr = 0.01,qDelta=10
962        Prompt av_typ, "Type of Average",popup,"Circular;Sector;Rectangular;Annular;2D_ASCII;QxQy_ASCII;PNG_Graphic"
963// comment out above line in DEMO_MODIFIED version, and uncomment the line below (to disable PNG save)
964//      Prompt av_typ, "Type of Average",popup,"Circular;Sector;Rectangular;Annular;2D_ASCII;QxQy_ASCII"
965        Prompt autoSave,"Save files to disk?",popup,"Yes;No"
966        Prompt autoName,"Auto-Name files?",popup,"Auto;Manual"
967        Prompt autoPlot,"Plot the averaged Data?",popup,"Yes;No"
968        Prompt side,"Include detector halves?",popup,"both;right;left"
969        Prompt phi,"Orientation Angle (-90,90) degrees (Rectangular or Sector)"
970        Prompt dphi, "Azimuthal range (0,45) degrees (Sector only)"
971        Prompt width, "Width of Rectangular average (1,128)"
972        Prompt Qctr, "q-value of center of annulus"
973        Prompt Qdelta,"Pixel width of annulus"
974
975        //assign results of dialog to key=value string, semicolon separated
976        //do only what is necessary, based on av_typ
977        String/G root:myGlobals:Protocols:gAvgInfoStr=""
978       
979        // all averages need these four values
980        root:myGlobals:Protocols:gAvgInfoStr += "AVTYPE=" + av_typ + ";"
981        root:myGlobals:Protocols:gAvgInfoStr += "SAVE=" + autoSave + ";"
982        root:myGlobals:Protocols:gAvgInfoStr += "NAME=" + autoName + ";"
983        root:myGlobals:Protocols:gAvgInfoStr += "PLOT=" + autoPlot + ";"
984       
985        if(cmpstr(av_typ,"Sector")==0)
986                root:myGlobals:Protocols:gAvgInfoStr += "SIDE=" + side + ";"
987                root:myGlobals:Protocols:gAvgInfoStr += "PHI=" + num2str(phi) + ";"
988                root:myGlobals:Protocols:gAvgInfoStr += "DPHI=" + num2str(dphi) + ";"
989        Endif
990       
991        if(cmpstr(av_typ,"Rectangular")==0)
992                root:myGlobals:Protocols:gAvgInfoStr += "SIDE=" + side + ";"
993                root:myGlobals:Protocols:gAvgInfoStr += "PHI=" + num2str(phi) + ";"
994                root:myGlobals:Protocols:gAvgInfoStr += "WIDTH=" + num2str(width) + ";"
995        Endif
996       
997        if(cmpstr(av_typ,"Annular")==0)
998                root:myGlobals:Protocols:gAvgInfoStr += "QCENTER=" + num2str(QCtr) + ";"
999                root:myGlobals:Protocols:gAvgInfoStr += "QDELTA=" + num2str(QDelta) + ";"
1000        Endif
1001End
1002
1003//not used????
1004//checks the syntax of all of the file fields in the panel
1005Function CheckProtocolSyntax(ctrlName) : ButtonControl
1006        String ctrlName
1007       
1008        String retStr=""
1009        //SAM
1010        SVAR list = root:myGlobals:Protocols:gSAM
1011        retStr = ParseRunNumberList(list)
1012        if(strlen(retStr)==0)
1013                //error
1014                Print "SAM Syntax Error"
1015                return(1)
1016        else
1017                list = retStr
1018                Print "SAM syntax OK"
1019        Endif
1020
1021        //MASK
1022        SVAR list = root:myGlobals:Protocols:gMASK
1023        retStr = ParseRunNumberList(list)
1024       
1025End
1026//*************
1027
1028
1029
1030//
1031// Procedure files for creating and executing a data reduction protocol
1032//
1033//**** ONLY invoked from the MAIN PANEL**** NOT REALLY EVER USED ******
1034//Procedure for reducing a sample file (multiple added files) with a specified
1035//protocol. User may create a new protocol, and will be prompted
1036//for information "questionnare-style" where the user must know the
1037//filenames for empty cell, background...etc.. as they will be presented
1038//with standard file open dialogs to select each file desired for use in the
1039//new protocol
1040//once a protocol is selected (or created) the uer is propmted for sample data
1041// and the file is processed through the protocol.
1042//
1043Proc ReduceAFile()
1044
1045        String protocolName="",waveStr="",samStr = "ask"
1046        Variable err
1047       
1048        //pick a protocol wave from the Protocols folder
1049        //must switch to protocols folder to get wavelist (missing parameter)
1050        SetDataFolder root:myGlobals:Protocols
1051        PickAProtocol()
1052       
1053        //get the selected protocol wave choice through a global string variable
1054        protocolName = root:myGlobals:Protocols:gProtoStr
1055       
1056        //If "CreateNew" was selected, go to the questionnare, to make a new set
1057        //and put the name of the new Protocol wave in gProtoStr
1058        if(cmpstr("CreateNew",protocolName) == 0)
1059                ProtocolQuestionnare()
1060                protocolName = root:myGlobals:Protocols:gProtoStr
1061        Endif
1062       
1063        //give the full path:name to the executeProtocol function
1064        waveStr = "root:myGlobals:Protocols:"+protocolName
1065        //samStr is set at top to "ask", since this is the action always desired from "ReduceAFile"
1066       
1067        ExecuteProtocol(waveStr,samStr)
1068       
1069        //return data folder to root before Macro is done
1070        SetDataFolder root:
1071       
1072End
1073
1074
1075//prompts the user to pick a previously created protocol from a popup list
1076//of given the option to create a new protocol
1077//the chosen protocol is passed back to the calling procedure by a global string
1078//the popup is presented as a missing parameter dialog (called with empty parameter list)
1079//
1080Proc PickAProtocol(protocol)
1081        String Protocol
1082        Prompt Protocol "Pick A Protocol",popup, WaveList("*",";","")
1083       
1084        String/G  root:myGlobals:Protocols:gProtoStr = protocol
1085End
1086
1087Proc DeleteAProtocol(protocol)
1088        String Protocol
1089//      Prompt Protocol "Delete A Protocol",popup, WaveList("*",";","")
1090        Prompt Protocol "Delete A Protocol",popup, DeletableProtocols()
1091
1092        String/G  root:myGlobals:Protocols:gProtoStr = protocol
1093End
1094
1095Function/S DeletableProtocols()
1096        String list=WaveList("*",";","")
1097
1098        list= RemoveFromList("Base", list  , ";")
1099        list= RemoveFromList("DoAll", list  , ";")
1100        list= RemoveFromList("CreateNew", list  , ";")
1101        list= RemoveFromList("tempProtocol", list  , ";")
1102        if(cmpstr(list,"")==0)
1103                list = "_no_protocols_;"
1104        endif
1105       
1106        return(list)
1107End
1108
1109//missing paramater dialog to solicit user for a waveStr for the protocol
1110//about to be created
1111//name is passed back as a global string and calling procedure is responsible for
1112//checking for wave conflicts and valid names
1113//
1114Proc AskForName(protocol)
1115        String Protocol
1116        Prompt Protocol "Enter a new name for your protocol (no extension)"
1117       
1118        String/G  root:myGlobals:Protocols:gNewStr = protocol
1119End
1120
1121//this is a lengthy procedure for sequentially polling the user about what data
1122//reduction steps they want to be performed during the protocol
1123//ensures that a valid protocol name was chosen, then fills out each "item"
1124//(6 total) needed for reduction
1125//it the user cancels at any point, the partial protocol will be deleted
1126//
1127Function ProtocolQuestionnare()
1128        String filename,cmd
1129        Variable notDone,refnum
1130       
1131        //prompt for name of new protocol wave to save
1132        do
1133                Execute "AskForName()"
1134                SVAR newProtoStr = root:myGlobals:Protocols:gNewStr
1135               
1136                //make sure it's a valid IGOR name
1137                newProtoStr = CleanupName(newProtoStr,0)        //strict naming convention
1138                String/G root:myGlobals:Protocols:gNewStr=newProtoStr           //reassign, if changed
1139                //Print "newProtoStr = ",newProtoStr
1140               
1141                SetDataFolder root:myGlobals:Protocols
1142                if(WaveExists( $("root:myGlobals:Protocols:" + newProtoStr) ) == 1)
1143                        //wave already exists
1144                        DoAlert 0,"that name is already in use. Please pick a new name"
1145                        notDone = 1
1146                else
1147                        //name is  good
1148                        notDone = 0
1149                Endif
1150        while(notDone)
1151       
1152        //Print "protocol questionnare is "+newProtocol
1153       
1154        //make a new text wave (6 points) and fill it in, in response to questions
1155        SetDataFolder root:myGlobals:Protocols //(redundant - full wave specs are used)
1156        Make/O/T/N=8 $("root:myGlobals:Protocols:" + newProtoStr)
1157        Wave/T newProtocol = $("root:myGlobals:Protocols:" + newProtoStr)
1158       
1159        //ask the questions
1160        /////
1161        //*****Multiple files in these lists are full paths/filenames which may or may not
1162        //have semicolon version numbers in the filename. Therefore, construct the list with
1163        //COMMAS as separators - to avoid messy parsing
1164        ///////
1165       
1166       
1167//////////////////////////
1168        String drkStr="",fileStr=""
1169        DoAlert 1,"Do you want to correct your data for DRK (beam off) counts?"
1170        if(V_flag == 1)         //1=yes
1171                //prompt for DRK  file, but don't actually open it (/D flag)
1172                Open/D/R/T="TEXT????"/M="Select the DRK file"/P=catPathName refnum
1173                //check for cancel
1174                if(strlen(S_filename)==0)
1175                        //user cancelled, abort
1176                        KillWaves/Z newProtocol
1177                        SetDataFolder root:
1178                        Abort "Incomplete protocol has been deleted"
1179                Endif
1180                //assign filename (just the name) to [6]
1181                fileStr = GetFileNameFromPathNoSemi(S_filename)
1182                drkStr = "DRK=none,DRKMODE=0,"
1183                drkStr = ReplaceStringByKey("DRK",drkStr,fileStr,"=",",")
1184                drkStr = ReplaceNumberByKey("DRKMODE", drkStr, 10 ,"=",",")     
1185                newProtocol[6] = drkStr
1186        else
1187                //no Work.DRK desired
1188                newProtocol[6] = "DRK=none,DRKMODE=0,"
1189        Endif
1190       
1191////////////
1192       
1193/////////////////
1194        DoAlert 1,"Do you want to subtract background from your data?"
1195        if(V_flag == 1)         //1=yes
1196                //prompt for background file, but don't actually open it (/D flag)
1197                Open/D/R/T="TEXT????"/M="Select the Background data file"/P=catPathName refnum
1198                //check for cancel
1199                if(strlen(S_filename)==0)
1200                        //user cancelled, abort
1201                        KillWaves/Z newProtocol
1202                        SetDataFolder root:
1203                        Abort "Incomplete protocol has been deleted"
1204                Endif
1205                //assign filename (full path) to [0]
1206                newProtocol[0] = GetFileNameFromPathNoSemi(S_filename)
1207               
1208                notDone=1
1209                do
1210                        //prompt for additional background files
1211                        DoAlert 1,"Do you want to add another background file?"
1212                        if(V_flag == 1)         //yes
1213                                Open/D/R/T="TEXT????"/M="Select another Background data file"/P=catPathName refnum
1214                                //check for cancel
1215                                if(strlen(S_filename)==0)
1216                                        //user cancelled, abort ********maybe just break out of the loop here
1217                                        KillWaves/Z newProtocol
1218                                        SetDataFolder root:
1219                                        Abort "Incomplete protocol has been deleted"
1220                                Endif
1221                                //assign filename (full path) to [0]
1222                                newProtocol[0] += "," + GetFileNameFromPathNoSemi(S_filename)           //***COMMA separated list
1223                                notDone = 1             //keep going
1224                        else
1225                                notDone = 0                     //no more to add
1226                        Endif
1227                While(notDone)
1228        else            //no background desired
1229                newProtocol[0] = "none"
1230        Endif
1231////////////////////// 
1232        DoAlert 1,"Do you want to subtract empty cell scattering from your data?"
1233        if(V_flag == 1)         //1=yes
1234                //prompt for Empty cell file, but don't actually open it (/D flag)
1235                Open/D/R/T="TEXT????"/M="Select the Empty Cell data file"/P=catPathName refnum
1236                //check for cancel
1237                if(strlen(S_filename)==0)
1238                        //user cancelled, abort
1239                        KillWaves/Z newProtocol
1240                        SetDataFolder root:
1241                        Abort "Incomplete protocol has been deleted"
1242                Endif
1243                //assign filename (full path) to [1]
1244                newProtocol[1] = GetFileNameFromPathNoSemi(S_filename)
1245               
1246                notDone=1
1247                do
1248                        //prompt for additional Empty Cell files
1249                        DoAlert 1,"Do you want to add another Empty Cell file?"
1250                        if(V_flag == 1)         //yes
1251                                Open/D/R/T="TEXT????"/M="Select another Empty Cell data file"/P=catPathName refnum
1252                                //check for cancel
1253                                if(strlen(S_filename)==0)
1254                                        //user cancelled, abort ********maybe just break out of the loop here
1255                                        KillWaves/Z newProtocol
1256                                        SetDataFolder root:
1257                                        Abort "Incomplete protocol has been deleted"
1258                                Endif
1259                                //assign filename (full path) to [1]
1260                                newProtocol[1] += "," + GetFileNameFromPathNoSemi(S_filename)           //***COMMA separated list
1261                                notDone = 1             //keep going
1262                        else
1263                                notDone = 0                     //no more to add
1264                        Endif
1265                While(notDone)
1266        else            //no background desired
1267                newProtocol[1] = "none"
1268        Endif
1269//////////////////////////
1270        DoAlert 1,"Do you want to correct your data for detector sensitivity?"
1271        if(V_flag == 1)         //1=yes
1272                //prompt for DIV  file, but don't actually open it (/D flag)
1273                Open/D/R/T="TEXT????"/M="Select the detector sensitivity file"/P=catPathName refnum
1274                //check for cancel
1275                if(strlen(S_filename)==0)
1276                        //user cancelled, abort
1277                        KillWaves/Z newProtocol
1278                        SetDataFolder root:
1279                        Abort "Incomplete protocol has been deleted"
1280                Endif
1281                //assign filename (full path) to [2]
1282                newProtocol[2] = GetFileNameFromPathNoSemi(S_filename)
1283        else
1284                //no Work.DIV desired
1285                newProtocol[2] = "none"
1286        Endif   
1287//////////////////////////
1288        DoAlert 1,"Do you want to mask your files before averaging?"
1289        if(V_flag == 1)         //1=yes
1290                //prompt for mask  file, but don't actually open it (/D flag)
1291                Open/D/R/T="TEXT????MASK"/M="Select the mask file"/P=catPathName refnum
1292                //check for cancel
1293                if(strlen(S_filename)==0)
1294                        //user cancelled, abort
1295                        KillWaves/Z newProtocol
1296                        SetDataFolder root:
1297                        Abort "Incomplete protocol has been deleted"
1298                Endif
1299                //assign filename (full path) to [3]
1300                newProtocol[3] = GetFileNameFromPathNoSemi(S_filename)
1301        else
1302                //no MASK desired
1303                newProtocol[3] = "none"
1304        Endif   
1305       
1306        //absolute scaling
1307       
1308        //////////////////////////
1309        //ABS parameters stored as keyword=value string
1310        DoAlert 1,"Do you want absolute scaling?"
1311        if(V_flag == 1)         //1=yes
1312                //missing param - prompt for values, put in semicolon-separated list
1313                Execute "AskForAbsoluteParams_Quest()"
1314                SVAR absStr =  root:myGlobals:Protocols:gAbsStr
1315                newProtocol[4] = absStr
1316        else
1317                //no absolute scaling desired
1318                newProtocol[4] = "none"
1319        Endif   
1320       
1321        //type of average, plot?, auto/manual naming/saving... put in semicolon separated string
1322        //of KEY=<value> format for easy parsing
1323        //Kewords are: AVTYPE,PHI,DPHI,PLOT,SAVE,NAME,SIDE,WIDTH
1324        //note that AVTYPE,NAME,SIDE have string values, others have numerical values
1325        ///////////////////////
1326        DoAlert 1,"Do you want to average your data to I vs. q?"
1327        if(V_flag == 1)         //1=yes
1328                String/G root:myGlobals:Protocols:gAvgInfoStr = ""
1329                Execute "GetAvgInfo()"          //will put up missing paramter dialog and do all the work
1330                //:gAvgInfo is reset by the Proc(), copy this string tot he protocol
1331                SVAR tempStr=root:myGlobals:Protocols:gAvgInfoStr
1332               
1333                //get a file path for saving files, if desired
1334                /////no - save files to the same data folder as the one with the raw data
1335                //then only one path to manage.
1336                //String yesNo = StringByKey("SAVE", tempStr,"=", ";")
1337                //if(cmpstr("Yes",yesNo) == 0)          //0=yes
1338                        //NewPath/C/M="Select Folder"/O Save_path               //Save_path is the symbolic path
1339                //Endif
1340
1341                newProtocol[5] = tempStr
1342                KillStrings/Z tempStr
1343        else
1344                //no averaging desired
1345                newProtocol[5] = "AVTYPE=none"
1346        Endif
1347       
1348        //returns the name of the newly created (= currently in use) protocol wave through a global
1349        String/G root:myGlobals:Protocols:gProtoStr = newProtoStr
1350End
1351
1352//function to check the work files (to see what's already there)
1353//and compare that with the files that are supposed to be there, according to the
1354//current protocol (to save unnecessary time re-loading files)
1355//
1356//the "type" folder is checked for all files in the list req(ested)Files
1357//note that the list of files is a full path:name;ver, while the
1358//fileList in the folder is just the name (or a list of names)
1359//
1360//returns 0 false, if files are NOT present
1361//or 1 = true, yes, the files are there as requested
1362//
1363Function AreFilesThere(type,reqFiles)
1364        String type,reqFiles
1365       
1366        //in general, reqFiles is a list of full paths to files - which MAY include semicolon version numbers
1367        //reqFiles MUST be constructed with COMMAS as list separators, to avoid disaster
1368        //when the version numbers are interpreted as filenames
1369       
1370        //get the number of files requested
1371        Variable nReq,nCur,match,ii
1372        nReq = ItemsInList(reqFiles,",")
1373       
1374        //get the name of the file currently in BGD - in the global fileList
1375        //fileList has NAMES ONLY - since it was derived from the file header
1376        String testStr
1377        testStr = "root:Packages:NIST:"+type+":fileList"
1378        if(Exists(testStr) == 2)                //2 if string variable exists
1379                SVAR curFiles = $testStr
1380        else
1381                //no files currently in type folder, return zero
1382                Return (0)
1383        Endif
1384        //get the number of files already in folder
1385        nCur = ItemsInList(curFiles,";")
1386        If(nCur != nReq)
1387                Return (0)              //quit now, the wrong number of files present
1388        Endif
1389        //right number of files... are the names right...
1390        //check for a match (case-sensitive!!) of each requested file in the curFile string
1391        //need to extract filenames from reqFiles, since they're the full path and name
1392       
1393        ii=0
1394        do
1395                testStr = StringFromList(ii,reqFiles,",")       //testStr is the Nth full path and filename
1396                //testStr = GetFileNameFromPathNoSemi(testStr)  //testStr will now be just the filename
1397                match = stringmatch(curFiles,testStr)
1398                If(!match)
1399                        Return (0)              //req file was not found in curFile list - get out now
1400                Endif
1401                ii+=1
1402        while(ii<nreq)
1403       
1404        Return (1)              //indicate that files are OK, no changes needed
1405End
1406
1407//will add the files specified in the protocol to the "type" folder
1408//will add multiple files together if more than one file is requested
1409//(list is a comma delimited list of filenames, with NO path information)
1410//
1411// This routine NOW DOES check for the possibility that the filenames may have ";vers" from the
1412// VAX - data should be picked up from Charlotte, where it won't have version numbers.
1413//
1414Function AddFilesInList(type,list)
1415        String type,list
1416       
1417        //type is the work folder to put the data into, and list is a COMMA delimited list of paths/names
1418        Variable num,ii,err=0,refNum
1419        String filename,pathStr=""
1420        PathInfo catPathName                    //this is where the files are
1421        pathstr=S_path
1422       
1423        num = ItemsInList(list,",")             // comma delimited list
1424       
1425        ii=0
1426        do
1427                //FindValidFilename only needed in case of vax version numbers
1428                filename = pathStr + FindValidFilename(StringFromList(ii,list,","))
1429                Open/Z/R refnum as filename
1430                if(V_flag != 0)         //file not found
1431                        //Print "file not found AddFilesInList()"
1432                        //Print filename
1433                        err = 1
1434                        return(err)
1435                Endif
1436                Close refnum            //file was found and opened, so close it
1437                ReadHeaderAndData(filename)
1438                if(ii == 0)
1439                        //first pass, wipe out the old contents of the work file
1440                        err =  Raw_to_work(type)
1441                else
1442                        err = Add_raw_to_work(type)
1443                Endif
1444                ii+=1
1445        while(ii<num)
1446        return(err)
1447End
1448
1449//function will reduce a sample file (or ask for file(s))
1450//using the protocol named as "protoStr" in the Protocols subfolder
1451//samStr is the file(s) or "ask" to force prompt
1452//sequentially proceeds through flowchart, doing reduction steps as needed
1453//show Schematic to debug what steps/values were used
1454//
1455//function is long, but straightforward logic
1456//
1457Function ExecuteProtocol(protStr,samStr)
1458        String protStr,samStr
1459        //protStr is the full path to the selected protocol wave
1460        //samStr is either "ask" or the name ONLY ofthe desired sample data file(s) (NO PATH)
1461        WAVE/T prot = $protStr
1462        SetDataFolder root:myGlobals:Protocols
1463       
1464        Variable filesOK,err,notDone
1465        String activeType, msgStr, junkStr, pathStr=""
1466        PathInfo catPathName                    //this is where the files are
1467        pathStr=S_path
1468       
1469        NVAR useXMLOutput = root:Packages:NIST:gXML_Write
1470       
1471        //Parse the instructions in the prot wave
1472        //0 - bkg
1473        //1 - emp
1474        //2 - div
1475        //3 - mask
1476        //4 - abs params c2-c5
1477        //5 - average params
1478        //6 = DRK file (**out of sequence)
1479       
1480        //prompt for sam data => read raw data, add to sam folder
1481        //or parse file(s) from the input paramter string
1482        activeType = "SAM"
1483        msgStr = "Select sample data"
1484        //Ask for SAM file or parse
1485        do
1486                if((cmpstr(samStr,"ask") == 0) || (cmpstr(samStr,"")==0) )              //zero if strings are equal
1487                        err = LoadRawSANSData(msgStr)           //will prompt for file
1488                        if(err)
1489                                PathInfo/S catPathName
1490                                Abort "reduction sequence aborted"
1491                        endif
1492                        UpdateDisplayInformation("RAW")                 //display the new type of data that was loaded
1493                        err =  Raw_to_work(activeType)          //this is the first file (default)
1494                        //Ask for another SAM file
1495                        do
1496                                DoAlert 1,"Do you want to add another Sample file?"
1497                                if(V_flag == 1)         //yes
1498                                        err = LoadRawSANSData(msgStr)           //will prompt for file
1499                                        if(err)
1500                                                PathInfo/S catPathName
1501                                                Abort "reduction sequence aborted"
1502                                        endif
1503                                        UpdateDisplayInformation("RAW")                 //display the new type of data that was loaded
1504                                        err = Add_raw_to_work(activeType)
1505                                        notDone = 1
1506                                else
1507                                        notDone = 0
1508                                endif
1509                        while(notDone)
1510                        break
1511                Endif
1512                //"none" is not an option - you always need a sample file - "none" will never return zero
1513                //if not "ask" AND not "none" then try to parse the filenames
1514                If((cmpstr(samStr,"none") != 0) && (cmpstr(samStr,"ask") != 0))
1515                        //filesOK = AreFilesThere(activeType,samStr)            //return 1 if correct files are already there
1516                        filesOK = 0             // Feb 2008, always force a reload of files. Maybe slow, but always correct
1517                        if(!filesOK)
1518                                //add the correct file(s) to SAM
1519                                err = AddFilesInList(activeType,samStr)
1520                                if(err)
1521                                        //Print "samstr = ",samStr
1522                                        Abort "SAM file not found, reset SAM file"
1523                                Endif
1524                        Endif
1525                Endif
1526        While(0)
1527        //always update
1528        UpdateDisplayInformation(ActiveType)
1529       
1530        //check for bkg file  -- "ask" might not fail - "ask?" will - ? not allowed in VAX filenames
1531        // add if needed
1532        //use a "case" statement
1533        msgStr = "Select background file"
1534        activeType = "BGD"
1535        do
1536                if(cmpstr(prot[0],"ask") == 0)          //zero if strings are equal
1537                        err = LoadRawSANSData(msgStr)           //will prompt for file
1538                        if(err)
1539                                PathInfo/S catPathName
1540                                Abort "reduction sequence aborted"
1541                        endif
1542                        UpdateDisplayInformation("RAW")                 //display the new type of data that was loaded
1543                        err =  Raw_to_work(activeType)          //this is the first file (default)
1544                        //Ask for another BGD file
1545                        do
1546                                DoAlert 1,"Do you want to add another Background file?"
1547                                if(V_flag == 1)         //yes
1548                                        err = LoadRawSANSData(msgStr)           //will prompt for file
1549                                        if(err)
1550                                                PathInfo/S catPathName
1551                                                Abort "reduction sequence aborted"
1552                                        endif
1553                                        UpdateDisplayInformation("RAW")                 //display the new type of data that was loaded
1554                                        err = Add_raw_to_work(activeType)
1555                                        notDone = 1
1556                                else
1557                                        notDone = 0
1558                                endif
1559                        while(notDone)
1560                        UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1561                        break
1562                Endif
1563                If(cmpstr(prot[0],"none") == 0)
1564                        //clean out the BKG folder?
1565                        //KillDataFolder root:BKG
1566                        //NewDataFolder/O root:BKG
1567                        break
1568                Endif
1569                //if not "ask" AND not "none" then try to parse the filenames
1570                If((cmpstr(prot[0],"none") != 0) && (cmpstr(prot[0],"ask") != 0))
1571                        //filesOK = AreFilesThere(activeType,prot[0])
1572                        filesOK = 0             // Feb 2008, always force a reload of files. Maybe slow, but always correct
1573                        if(!filesOK)
1574                                //add the correct file(s) to BGD
1575                                err = AddFilesInList(activeType,prot[0])
1576                                If(err)
1577                                        Abort "BGD file not found. Reset BGD file list"
1578                                Endif
1579                        Endif
1580                        UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1581                Endif
1582        While(0)
1583       
1584       
1585        //check for emp file (prot[1])
1586        // add if needed
1587        msgStr = "Select empty cell data"
1588        activeType = "EMP"
1589        do
1590                if(cmpstr(prot[1],"ask") == 0)
1591                        err = LoadRawSANSData(msgStr)           //will prompt for file
1592                        if(err)
1593                                PathInfo/S catPathName
1594                                Abort "reduction sequence aborted"
1595                        endif
1596                        UpdateDisplayInformation("RAW")                 //display the new type of data that was loaded
1597                        err =  Raw_to_work(activeType)          //this is the first file (default)
1598                        //Ask for another EMP file
1599                        do
1600                                DoAlert 1,"Do you want to add another Empty Cell file?"
1601                                if(V_flag == 1)         //yes
1602                                        err = LoadRawSANSData(msgStr)           //will prompt for file
1603                                        if(err)
1604                                                PathInfo/S catPathName
1605                                                Abort "reduction sequence aborted"
1606                                        endif
1607                                        UpdateDisplayInformation("RAW")                 //display the new type of data that was loaded
1608                                        err = Add_raw_to_work(activeType)
1609                                        notDone = 1
1610                                else
1611                                        notDone = 0
1612                                endif
1613                        while(notDone)
1614                        UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1615                        break
1616                Endif
1617                If(cmpstr(prot[1],"none") == 0)
1618                        //clean out the EMP folder?
1619                        //KillDataFolder root:Packages:NIST:EMP
1620                        //NewDataFolder/O root:Packages:NIST:EMP
1621                        break
1622                Endif
1623                //if not "ask" AND not "none" then try to parse the filenames
1624                If((cmpstr(prot[1],"none") != 0) && (cmpstr(prot[1],"ask") != 0))
1625                        //filesOK = AreFilesThere(activeType,prot[1])
1626                        filesOK = 0             // Feb 2008, always force a reload of files. Maybe slow, but always correct
1627                        if(!filesOK)
1628                                //add the correct file(s) to BGD
1629                                err = AddFilesInList(activeType,prot[1])
1630                                If(err)
1631                                        Abort "EMP file not found. Reset EMP file list"
1632                                Endif
1633                        Endif
1634                        UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1635                Endif
1636        While(0)
1637       
1638        //do the CORRECT step based on the answers to emp and bkg subtraction
1639        //by setting the proper"mode"
1640        //1 = both emp and bgd subtraction
1641        //2 = only bgd subtraction
1642        //3 = only emp subtraction
1643        //4 = no subtraction
1644        //additional modes 091301
1645        //11 = emp, bgd, drk
1646        //12 = bgd and drk
1647        //13 = emp and drk
1648        //14 = no subtractions
1649        //work.drk is from proto[6]
1650        //
1651        //subtracting just the DRK data is NOT an option - it doesnt' really make any physical sense
1652        // - in this case, DRK is skipped (equivalent to mode==4)
1653        // automatically accounts for attenuators given the lookup tables and the
1654        //desired subtractions
1655        //Attenuator lookup tables are alredy implemented (NG1 = NG7)
1656        //
1657       
1658        //read in the DRK data if necessary
1659        //only one file, assumed to be RAW data
1660        //
1661        String fname="",drkStr=""
1662        drkStr=StringByKey("DRK",prot[6],"=",",")
1663        if(cmpstr(drkStr,"none") != 0)
1664                err = ReadHeaderAndData( (pathStr+drkStr) )
1665                if(err)
1666                        PathInfo/S catPathName
1667                        Abort "reduction sequence aborted"
1668                endif
1669                err = Raw_to_Work_NoNorm("DRK")
1670        endif
1671       
1672        //dispatch to the proper "mode" of Correct()
1673        Variable mode=4,val
1674        do
1675                if( (cmpstr("none",prot[0]) == 0)       && (cmpstr("none",prot[1]) == 0) )
1676                        //no subtraction (mode = 4),
1677                        mode = 4
1678                Endif
1679                If((cmpstr(prot[0],"none") != 0) && (cmpstr(prot[1],"none") == 0))
1680                        //subtract BGD only
1681                        mode=2
1682                Endif
1683                If((cmpstr(prot[0],"none") == 0) && (cmpstr(prot[1],"none") != 0))
1684                        //subtract EMP only
1685                        mode=3
1686                Endif
1687                If((cmpstr(prot[0],"none") != 0) && (cmpstr(prot[1],"none") != 0))
1688                        // bkg and emp subtraction are to be done (BOTH not "none")
1689                        mode=1
1690                Endif
1691                activeType = "COR"
1692                //add in DRK mode (0= no used, 10 = used)
1693                val = NumberByKey("DRKMODE",prot[6],"=","," )
1694                mode += val
1695//              print "mode = ",mode
1696                err = Correct(mode)
1697                if(err)
1698                        SetDataFolder root:
1699                        Abort "error in Correct, called from executeprotocol, normal cor"
1700                endif
1701                UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1702        While(0)
1703       
1704        //check for work.div file (prot[2])
1705        //add if needed
1706        // can't properly check the filename - so for now add and divide, if anything other than "none"
1707        //do/skip divide step based on div answer
1708        If(cmpstr("none",prot[2])!=0)           // if !0, then there's a file requested
1709                If(cmpstr("ask",prot[2]) == 0)
1710                        //ask user for file
1711                         junkStr = PromptForPath("Select the detector sensitivity file")
1712                        If(strlen(junkStr)==0)
1713                                SetDataFolder root:
1714                                Abort "No file selected, data reduction aborted"
1715                        Endif
1716                         ReadHeaderAndWork("DIV", junkStr)
1717                else
1718                        //assume it's a path, and that the first (and only) item is the path:file
1719                        //list processing is necessary to remove any final comma
1720                        junkStr = pathStr + StringFromList(0, prot[2],"," )
1721                        ReadHeaderAndWork("DIV",junkStr)
1722                Endif
1723                //got a DIV file, select the proper type of work data to DIV (= activeType)
1724                err = Divide_work(activeType)           //returns err = 1 if data doesn't exist in specified folders
1725                If(err)
1726                        SetDataFolder root:
1727                        Abort "data missing in DIV step, call from executeProtocol"
1728                Endif
1729                activeType = "CAL"
1730                UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1731        Endif
1732       
1733        Variable c2,c3,c4,c5
1734        //do absolute scaling if desired
1735        if(cmpstr("none",prot[4])!=0)
1736                if(cmpstr("ask",prot[4])==0)
1737                        //get the params from the user
1738                        Execute "AskForAbsoluteParams_Quest()"
1739                        //then from the list
1740                        SVAR junkAbsStr = root:myGlobals:Protocols:gAbsStr
1741                        c2 = NumberByKey("TSTAND", junkAbsStr, "=", ";")        //parse the list of values
1742                        c3 = NumberByKey("DSTAND", junkAbsStr, "=", ";")
1743                        c4 = NumberByKey("IZERO", junkAbsStr, "=", ";")
1744                        c5 = NumberByKey("XSECT", junkAbsStr, "=", ";")
1745                else
1746                        //get the parames from the list
1747                        c2 = NumberByKey("TSTAND", prot[4], "=", ";")   //parse the list of values
1748                        c3 = NumberByKey("DSTAND", prot[4], "=", ";")
1749                        c4 = NumberByKey("IZERO", prot[4], "=", ";")
1750                        c5 = NumberByKey("XSECT", prot[4], "=", ";")
1751                Endif
1752                //get the sample trans and thickness from the activeType folder
1753                String destStr = "root:Packages:NIST:"+activeType+":realsread"
1754                Wave dest = $destStr
1755                Variable c0 = dest[4]           //sample transmission
1756                Variable c1 = dest[5]           //sample thickness
1757               
1758                err = Absolute_Scale(activeType,c0,c1,c2,c3,c4,c5)
1759                if(err)
1760                        SetDataFolder root:
1761                        Abort "Error in Absolute_Scale(), called from executeProtocol"
1762                endif
1763                activeType = "ABS"
1764                UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1765        Endif
1766       
1767        //check for mask
1768        //add mask if needed
1769        // can't properly check the filename - so for now always add
1770        //doesn't change the activeType
1771        if(cmpstr("none",prot[3])!=0)
1772                If(cmpstr("ask",prot[3])==0)
1773                        //get file from user
1774                        junkStr = PromptForPath("Select Mask file")
1775                        If(strlen(junkStr)==0)
1776                                //no selection of mask file is not a fatal error, keep going, and let cirave()
1777                                //make a "null" mask
1778                                //if none desired, make sure that the old mask is deleted
1779                                //junkStr = GetDataFolder(1)
1780                                //SetDataFolder root:Packages:NIST:MSK
1781                                KillWaves/Z root:Packages:NIST:MSK:data
1782                                //SetDataFolder junkStr
1783                                DoAlert 0,"No Mask file selected, data not masked"
1784                        else
1785                                //read in the file from the dialog
1786                                ReadMCID_MASK(junkStr)
1787                        Endif
1788                else
1789                        //just read it in from the protocol
1790                        //list processing is necessary to remove any final comma
1791                        junkStr = pathStr + StringFromList(0, prot[3],"," )
1792                        ReadMCID_MASK(junkStr)
1793                Endif
1794        else
1795                //if none desired, make sure that the old mask is deleted
1796                //junkStr = GetDataFolder(1)
1797                //SetDataFolder root:Packages:NIST:MSK
1798                KillWaves/Z root:Packages:NIST:MSK:data
1799                //SetDataFolder junkStr
1800        Endif
1801       
1802        //mask data if desired (this is done automatically  in the average step) and is
1803        //not done explicitly here (if no mask in MSK folder, a null mask is created and "used")
1804       
1805        // average/save data as specified
1806       
1807        //Parse the keyword=<Value> string as needed, based on AVTYPE
1808       
1809        //average/plot first
1810        String av_type = StringByKey("AVTYPE",prot[5],"=",";")
1811        If(cmpstr(av_type,"none") != 0)
1812                If (cmpstr(av_type,"")==0)              //if the key could not be found... (if "ask" the string)
1813                        //get the averaging parameters from the user, as if the set button was hit
1814                        //in the panel
1815                        SetAverageParamsButtonProc("dummy")             //from "ProtocolAsPanel"
1816                        SVAR tempAveStr = root:myGlobals:Protocols:gAvgInfoStr
1817                        av_type = StringByKey("AVTYPE",tempAveStr,"=",";")
1818                else
1819                        //there is info in the string, use the protocol
1820                        //set the global keyword-string to prot[5]
1821                        String/G root:myGlobals:Protocols:gAvgInfoStr = prot[5]
1822                Endif
1823        Endif
1824       
1825        //convert the folder to linear scale before averaging, then revert by calling the window hook
1826        ConvertFolderToLinearScale(activeType)
1827       
1828        strswitch(av_type)      //dispatch to the proper routine to average to 1D data
1829                case "none":           
1830                        //still do nothing
1831                        break                   
1832                case "2D_ASCII":       
1833                        //do nothing
1834                        break
1835                case "QxQy_ASCII":
1836                        //do nothing
1837                        break
1838                case "PNG_Graphic":
1839                        //do nothing
1840                        break
1841                case "Rectangular":
1842                        RectangularAverageTo1D(activeType)
1843                        break
1844                case "Annular":
1845                        AnnularAverageTo1D(activeType)
1846                        break
1847                case "Circular":
1848                        CircularAverageTo1D(activeType)
1849                        break
1850                case "Sector":
1851                        CircularAverageTo1D(activeType)
1852                        break
1853                default:       
1854                        //do nothing
1855        endswitch
1856///// end of averaging dispatch
1857        // put data back on log or lin scale as set by default
1858        fRawWindowHook()
1859       
1860        //save data if desired
1861        String fullpath = "", newfileName=""
1862        String item = StringByKey("SAVE",prot[5],"=",";")               //does user want to save data?
1863        If( (cmpstr(item,"Yes")==0) && (cmpstr(av_type,"none") != 0) )         
1864                //then save
1865                //get name from textwave of the activeType dataset
1866                String textStr = "root:Packages:NIST:"+activeType+":textread"
1867                Wave/T textPath = $textStr
1868                String tempFilename = samStr
1869                If(WaveExists(textPath) == 1)
1870#if (exists("QUOKKA")==6)
1871                        newFileName = ReplaceString(".nx.hdf", tempFilename, "")
1872#elif (exists("HFIR")==6)
1873                        newFileName = ReplaceString(".xml",textPath[0],"")              //removes 4 chars
1874                        newFileName = ReplaceString("SANS",newFileName,"")              //removes 4 more chars = 8
1875                        newFileName = ReplaceString("exp",newFileName,"")                       //removes 3 more chars = 11
1876                        newFileName = ReplaceString("scan",newFileName,"")              //removes 4 more chars = 15, should be enough?
1877#else
1878                        newFileName = UpperStr(GetNameFromHeader(textPath[0]))          //NCNR data drops here, trims to 8 chars
1879#endif
1880                else
1881                        newFileName = ""                        //if the header is missing?
1882                        //Print "can't read the header - newfilename is null"
1883                Endif
1884               
1885                //pick ABS or AVE extension
1886                String exten = activeType
1887                if(cmpstr(exten,"ABS") != 0)
1888                        exten = "AVE"
1889                endif
1890                if(cmpstr(av_type,"2D_ASCII") == 0)
1891                        exten = "ASC"
1892                endif
1893                if(cmpstr(av_type,"QxQy_ASCII") == 0)
1894                        exten = "DAT"
1895                endif
1896               
1897                // add an "x" to the file extension if the output is XML
1898                // currently (2010), only for ABS and AVE (1D) output
1899                if( cmpstr(exten,"ABS") == 0 || cmpstr(exten,"AVE") == 0 )
1900                        if(useXMLOutput == 1)
1901                                exten += "x"
1902                        endif
1903                endif
1904                               
1905                //Path is catPathName, symbolic path
1906                //if this doesn't exist, a dialog will be presented by setting dialog = 1
1907                Variable dialog = 0
1908                PathInfo/S catPathName
1909                item = StringByKey("NAME",prot[5],"=",";")              //Auto or Manual naming
1910                If((cmpstr(item,"Manual")==0) || (cmpstr(newFileName,"") == 0))
1911                        //manual name if requested or if no name can be derived from header
1912                        fullPath = newfileName + "."+ exten //puts possible new name or null string in dialog
1913                        dialog = 1              //force dialog for user to enter name
1914                else
1915                        //auto-generate name and prepend path - won't put up any dialogs since it has all it needs
1916                        fullPath = S_Path + newFileName+ "." + exten   
1917                Endif
1918                //
1919                strswitch(av_type)     
1920                        case "Annular":
1921                                WritePhiave_W_Protocol(activeType,fullPath,dialog)
1922                                break
1923                        case "2D_ASCII":
1924                                Fast2DExport(activeType,fullPath,dialog)
1925                                break
1926                        case "QxQy_ASCII":
1927                                QxQy_Export(activeType,fullPath,dialog)
1928                                break
1929                        case "PNG_Graphic":
1930                                SaveAsPNG(activeType,fullpath,dialog)
1931                                break
1932                        default:
1933                                if (useXMLOutput == 1)
1934                                        WriteXMLWaves_W_Protocol(activeType,fullPath,dialog)
1935                                else
1936                                        WriteWaves_W_Protocol(activeType,fullpath,dialog)
1937                                endif
1938                endswitch
1939               
1940                //Print "data written to:  "+ fullpath
1941        Endif
1942       
1943        //done with everything in protocol list
1944        Return(0)
1945End
1946
1947//updates the currently displayed information to the data in "type"
1948//data folder - changes the title of the window and the global of the
1949//currently displayed data type - the recreation macro does the work
1950//
1951Function UpdateDisplayInformation(type)
1952        String type
1953
1954        String newTitle = "WORK_"+type
1955        DoWindow/F SANS_Data
1956        DoWindow/T SANS_Data, newTitle
1957        KillStrings/Z newTitle
1958       
1959        //need to update the display with "data" from the correct dataFolder
1960        //reset the current displaytype to "type"
1961        String/G root:myGlobals:gDataDisplayType=Type
1962       
1963        fRawWindowHook()
1964       
1965        //no error
1966        Return(0)
1967End
1968
1969//missing parameter dialog to solicit the 4 absolute intensity parameters
1970//from the user
1971//values are passed back as a global string variable (keyword=value)
1972//
1973Proc AskForAbsoluteParams(c2,c3,c4,c5)
1974        Variable c2=0.95,c3=0.1,c4=1,c5=32.0
1975        Prompt c2, "Standard Transmission"
1976        Prompt c3, "Standard Thickness (cm)"
1977        Prompt c4, "I(0) from standard fit (normalized to 1E8 monitor cts)"
1978        Prompt c5, "Standard Cross-Section (cm-1)"
1979       
1980        String/G root:myGlobals:Protocols:gAbsStr=""
1981       
1982        root:myGlobals:Protocols:gAbsStr = "TSTAND="+num2str(c2)
1983        root:myGlobals:Protocols:gAbsStr +=  ";" + "DSTAND="+num2str(c3)
1984        root:myGlobals:Protocols:gAbsStr +=  ";" + "IZERO="+num2str(c4)
1985        root:myGlobals:Protocols:gAbsStr +=  ";" + "XSECT="+num2str(c5)
1986       
1987End
1988
1989//asks the user for absolute scaling information. the user can either
1990//enter the 4 necessary values in manually (missing parameter dialog)
1991//or the user can select an empty beam file from a standard open dialog
1992//if an empty beam file is selected, the "kappa" value is automatically calculated
1993//in either case, the global keyword=value string is set.
1994//
1995//Proc AskForAbsoluteParams_Quest()
1996Function AskForAbsoluteParams_Quest()   
1997       
1998        Variable err, isNG5=0,loc,refnum
1999        //ask user if he wants to use a transmision file for absolute scaling
2000        //or if he wants to enter his own information
2001        err = UseStdOrEmpForABS()
2002        //DoAlert 1,"<Yes> to enter your own values, <No> to select an empty beam flux file"
2003        If ( err==1 )
2004                //secondary standard selected, prompt for values
2005                Execute "AskForAbsoluteParams()"                //missing parameters
2006        else
2007                //empty beam flux file selected, prompt for file, and use this to calculate KAPPA
2008                Variable kappa=1
2009               
2010                //ask for file and read it into RAW
2011                //will cancel if no file is selected
2012                err = LoadRawSANSData("select the empty beam file")             //reads the RAW data
2013                UpdateDisplayInformation("RAW")                 //display the new type of data that was loaded
2014                if(err)
2015                        PathInfo/S catPathName
2016                        Abort "reduction sequence aborted"
2017                endif
2018                       
2019                Wave/T tw=$"root:Packages:NIST:RAW:TextRead"
2020                Wave rw=$"root:Packages:NIST:RAW:RealsRead"
2021                Wave iw=$"root:Packages:NIST:RAW:IntegersRead"
2022                String acctStr = tw[3]
2023                //NG5 attenuator transmission is assumed to be the same as the table for NG7
2024                       
2025                //get the necessary variables for the calculation of kappa
2026                Variable detCnt,countTime,attenTrans,monCnt,sdd,pixel
2027                String detStr=tw[9]
2028//              pixel = DetectorPixelResolution(acctStr,detStr)         //get the pixel size from the file information
2029                //note that reading the detector pixel size from the header ASSUMES SQUARE PIXELS! - Jan2008
2030                pixel = rw[10]/10                       // header value (X) is in mm, want cm here
2031       
2032                countTime = iw[2]
2033                //detCnt = rw[2]                //080802 -use sum of data, not scaler from header
2034                monCnt = rw[0]
2035                sdd = rw[18]
2036                sdd *=100               //convert from meters to cm
2037                               
2038                //lookup table for transmission factor
2039                //determine which instrument the measurement was done on from acctStr
2040                Variable lambda = rw[26]
2041                Variable attenNo = rw[3]
2042                attenTrans = AttenuationFactor(acctStr,lambda,attenNo)
2043                //Print "attenTrans = ",attenTrans
2044               
2045                //get the XY box, if needed
2046                Variable x1,x2,y1,y2
2047                String filename=tw[0],tempStr
2048                PathInfo/S catPathName
2049                String tempName = S_Path + FindValidFilename(filename)
2050                err = GetXYBoxFromFile(tempName,x1,x2,y1,y2)            //xy's are passed/returned by reference
2051                Print x1,x2,y1,y2
2052
2053                if( ((x1-x2)==0) || ((y1-y2)==0) )      //need to re-select the box
2054                        err = SelectABS_XYBox(x1,x2,y1,y2)              //this will pause for user input
2055                        if(err)
2056                                Abort "Box not selected properly - Please re-set the ABS parameters"
2057                        Endif
2058                        //box is OK, write box values to file
2059                        WriteXYBoxToHeader(tempName,x1,x2,y1,y2)
2060                else
2061                        //give option to override
2062                        tempStr = "X=("+num2str(x1)+","+num2str(x2)+") Y=("+num2str(y1)+","+num2str(y2)+")"
2063                        DoAlert 1,"The current box is "+tempStr+".  Do you want to override these values?"
2064                        //Print v_flag
2065                        if(V_flag==1)   //1==yes, override
2066                                err = SelectABS_XYBox(x1,x2,y1,y2)
2067                                if(err)
2068                                        Abort "Box not selected properly -Please re-set the ABS parameters"
2069                                Endif
2070                        endif
2071                Endif
2072                Printf "Using Box X(%d,%d),Y(%d,%d)\r",x1,x2,y1,y2
2073               
2074                //need the detector sensitivity file - make a guess, allow to override
2075                String junkStr=""
2076                if(! waveexists($"root:Packages:NIST:DIV:data"))
2077                        junkStr = PromptForPath("Select the detector sensitivity file")
2078                        Print junkStr
2079#if(exists("HFIR")==6)
2080                        if(strlen(junkStr)==0 || !CheckIfDIVData(junkStr))              //if either is false, exit
2081                                //Print strlen(junkStr)
2082                                //Print CheckIfDIVData(junkStr)
2083                                SetDataFolder root:
2084                                Abort "No DIV (PLEX) file selected. Please use setABSParams again, selecting the empty beam file and then the detector sensitivity (Plex_) file"
2085                        endif
2086#else
2087                        if(strlen(junkStr)==0 || CheckIfRawData(junkStr))               //for NCNR, not raw is sufficient, but better in the future to confirm it is DIV if either is false, exit
2088                                SetDataFolder root:
2089                                Abort "No DIV (PLEX) file selected. Please use setABSParams again, selecting the empty beam file and then the detector sensitivity (Plex_) file"
2090                        endif
2091#endif
2092                        ReadHeaderAndWork("DIV", junkStr)
2093                endif
2094                //toggle SANS_Data to linear display if needed, so that we're working with linear scaled data
2095                ControlInfo/W=SANS_Data bisLog
2096                if(V_Flag==1)
2097                        Log_Lin("bisLog")       
2098                endif   
2099                Wave divData = $"root:Packages:NIST:div:Data"
2100                Wave data = $"root:Packages:NIST:raw:data"              //this will be the linear data
2101                // correct by detector sensitivity
2102                data /= divData
2103               
2104                // now do the sum, only in the box     
2105//              detCnt = sum($"root:Packages:NIST:raw:data", -inf, inf )
2106//              Print "box is now ",x1,x2,y1,y2
2107                detCnt = SumCountsInBox(x1,x2,y1,y2,"RAW")
2108                if(cmpstr(tw[9],"ILL   ")==0)
2109                        detCnt /= 4             // for cerca detector, header is right, sum(data) is 4x too large this is usually corrected in the Add step
2110                        pixel *= 1.04                   // correction for true pixel size of the Cerca
2111                endif
2112                //             
2113                kappa = detCnt/countTime/attenTrans*1.0e8/(monCnt/countTime)*(pixel/sdd)^2
2114                junkStr = num2str(kappa)
2115                // set the parameters in the global string
2116                Execute "AskForAbsoluteParams(1,1,"+junkStr+",1)"               //no missing parameters, no dialog
2117               
2118                //should wipe out the data in the RAW folder, since it's not really RAW now
2119                DoWindow/K SANS_Data
2120                // SRK JUL 2006 don't clear the contents - just kill the window to force new data to be loaded
2121                // - obsucre bug if "ask" in ABS section of protocol clears RAW folder, then Q-axes can't be set from RAW:RealsRead
2122                //ClearDataFolder("RAW")
2123                Print "Kappa was successfully calculated as = ",kappa   
2124        Endif
2125       
2126End
2127
2128Function UserSelectBox_Continue(ctrlName) :buttonControl
2129        String ctrlName
2130       
2131        DoWindow/K junkWindow           //kill panel
2132end
2133
2134Function SelectABS_XYBox(x1,x2,y1,y2)
2135        Variable &x1,&x2,&y1,&y2
2136       
2137        Variable err=0
2138       
2139        Variable/G root:V_marquee=1             //sets the sneaky bit to automatically update marquee coords
2140        Variable/G root:V_left,root:V_right,root:V_bottom,root:V_top    //must be global for auto-update
2141        DoWindow/F SANS_Data
2142        NewPanel/K=2 /W=(139,341,382,432) as "Select the primary beam"
2143        DoWindow/C junkWindow
2144        AutoPositionWindow/E/M=1/R=SANS_Data
2145       
2146        Drawtext 21,20 ,"Select the primary beam with the"
2147        DrawText 21,40, "marquee and press continue"
2148        Button button0,pos={80,58},size={92,20},title="Continue"
2149        Button button0,proc=UserSelectBox_Continue
2150       
2151        PauseForUser junkWindow,SANS_Data
2152       
2153        DoWindow/F SANS_Data
2154
2155        //GetMarquee left,bottom                        //not needed
2156        NVAR V_left=V_left
2157        NVAR V_right=V_right
2158        NVAR V_bottom=V_bottom
2159        NVAR V_top=V_top
2160       
2161        x1 = V_left
2162        x2 = V_right
2163        y1 = V_bottom
2164        y2 = V_top
2165//      Print "new values,before rounding = ",x1,x2,y1,y2
2166        KeepSelectionInBounds(x1,x2,y1,y2)
2167        //Print "new values = ",x1,x2,y1,y2
2168       
2169        KillVariables/Z root:V_Marquee,root:V_left,root:V_right,root:V_bottom,root:V_top
2170        if((x1-x2)==0 || (y1-y2)==0)
2171                err=1
2172        endif
2173        return(err)
2174End
2175
2176Function UseStdOrEmpForABS()
2177               
2178        NewPanel/K=2 /W=(139,341,402,448) as "Absolute Scaling"
2179        DoWindow/C junkABSWindow
2180        ModifyPanel cbRGB=(57346,65535,49151)
2181        SetDrawLayer UserBack
2182        SetDrawEnv fstyle= 1
2183        DrawText 21,20,"Method of absolute calibration"
2184        Button button0,pos={52,33},size={150,20},proc=UserSelectABS_Continue,title="Empty Beam Flux"
2185        Button button1,pos={52,65},size={150,20},proc=UserSelectABS_Continue,title="Secondary Standard"
2186       
2187        PauseForUser junkABSWindow
2188        NVAR val = root:myGlobals:tmpAbsVal
2189        return(val)
2190End
2191
2192//returns 0 if button0 (empty beam flux)
2193// or 1 if secondary standard
2194Function UserSelectABS_Continue(ctrlName) :buttonControl
2195        String ctrlName
2196       
2197        variable val=0
2198        If(cmpstr(ctrlName,"button0")==0)
2199                val=0           
2200        else
2201                val=1
2202        endif
2203//      print "val = ",ctrlName,val
2204        Variable/G root:myGlobals:tmpAbsVal = val
2205        DoWindow/K junkABSWindow                //kill panel
2206        return(0)
2207end
2208
2209
2210//save the protocol as an IGOR text wave (.itx)
2211//
2212//
2213Function ExportProtocol(ctrlName) : ButtonControl
2214        String ctrlName
2215// get a list of protocols
2216        String Protocol=""
2217        SetDataFolder root:myGlobals:Protocols
2218        Prompt Protocol "Pick A Protocol",popup, WaveList("*",";","")
2219        DoPrompt "Pick A Protocol to Export",Protocol
2220        if(V_flag==1)
2221                //Print "user cancel"
2222                SetDatafolder root:
2223                return(1)
2224        endif
2225//get the selection, or exit
2226        Wave/T pW= $protocol
2227        Make/O/T/N=13 tw
2228// save in the proper format (must write manually, for demo version)
2229        tw[0] = "IGOR"
2230        tw[1] = "WAVES/T \t"+protocol
2231        tw[2] = "BEGIN"
2232        tw[3,10] = "\t\""+pW[p-3]+"\""
2233        tw[11] = "END"
2234        tw[12] = "X SetScale/P x 0,1,\"\","+protocol+"; SetScale y 0,0,\"\","+protocol
2235       
2236        Variable refnum
2237        String fullPath
2238       
2239        PathInfo/S catPathName
2240        fullPath = DoSaveFileDialog("Export Protocol as")
2241        If(cmpstr(fullPath,"")==0)
2242                //user cancel, don't write out a file
2243                Close/A
2244                Abort "no Protocol file was written"
2245        Endif
2246
2247        //actually open the file
2248        Open refNum as fullpath+".itx"
2249       
2250        wfprintf refnum, "%s\r", tw
2251        Close refnum
2252        //Print "all is well  ",protocol
2253        KillWaves/Z tw
2254        setDataFolder root:
2255        return(0)
2256
2257End
2258
2259//imports a protocol from disk into the protocols folder
2260//
2261// will overwrite existing protocols if necessary
2262//
2263//
2264Function ImportProtocol(ctrlName) : ButtonControl
2265        String ctrlName
2266
2267        SetDataFolder root:myGlobals:Protocols
2268
2269        String fullPath
2270       
2271        PathInfo/S catPathName
2272        fullPath = DoOpenFileDialog("Import Protocol")
2273        If(cmpstr(fullPath,"")==0)
2274                //user cancel, don't write out a file
2275                Close/A
2276                Abort "no protocol was loaded"
2277        Endif
2278       
2279        LoadWave/O/T fullPath
2280       
2281        SetDataFolder root:
2282        return(0)
2283end
Note: See TracBrowser for help on using the repository browser.