source: sans/SANSReduction/trunk/Put in User Procedures/SANS_Reduction_v5.00/ProtocolAsPanel.ipf @ 260

Last change on this file since 260 was 260, checked in by srkline, 15 years ago

Changed the IgorVersion? pragma to = 6.0. No turning back now.

File size: 75.1 KB
Line 
1#pragma rtGlobals=1             // Use modern global access method.
2#pragma version=5.0
3#pragma IgorVersion=6.0
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:myGlobals:gAllowDRK)
890        SetVariable drkStr,pos={120,363},size={150,15},title="."
891        SetVariable drkStr,help={"DRK detector count file"},disable = (!root:myGlobals: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/K=1 "SANS Data Reduction Tutorial[Build a Data Reduction Protocol]"
935End
936
937//button action procedure to get the type of average requested by the user
938//presented as a missing parameter dialog, which is really user-UN-friendly
939//and will need to be re-thought. Defaults of dialog are set for normal
940//circular average, so typically click "continue" and proceed
941//
942Function SetAverageParamsButtonProc(ctrlName) : ButtonControl
943        String ctrlName
944       
945        Execute "GetAvgInfo()"
946       
947        //set the global string
948        SVAR tempStr = root:myGlobals:Protocols:gAvgInfoStr
949        String/G root:myGlobals:Protocols:gAVE = tempStr
950
951End
952
953//procedure called by protocol panel to ask user for average type choices
954// somewhat confusing and complex, but may be as good as it gets.
955//
956Proc GetAvgInfo(av_typ,autoSave,autoName,autoPlot,side,phi,dphi,width,QCtr,QDelta)
957        String av_typ,autoSave,AutoName,autoPlot,side
958        Variable phi=0,dphi=10,width=10,Qctr = 0.01,qDelta=10
959        Prompt av_typ, "Type of Average",popup,"Circular;Sector;Rectangular;Annular;2D_ASCII;QxQy_ASCII;PNG_Graphic"
960// comment out above line in DEMO_MODIFIED version, and uncomment the line below (to disable PNG save)
961//      Prompt av_typ, "Type of Average",popup,"Circular;Sector;Rectangular;Annular;2D_ASCII;QxQy_ASCII"
962        Prompt autoSave,"Save files to disk?",popup,"Yes;No"
963        Prompt autoName,"Auto-Name files?",popup,"Auto;Manual"
964        Prompt autoPlot,"Plot the averaged Data?",popup,"Yes;No"
965        Prompt side,"Include detector halves?",popup,"both;right;left"
966        Prompt phi,"Orientation Angle (-90,90) degrees (Rectangular or Sector)"
967        Prompt dphi, "Azimuthal range (0,45) degrees (Sector only)"
968        Prompt width, "Width of Rectangular average (1,128)"
969        Prompt Qctr, "q-value of center of annulus"
970        Prompt Qdelta,"Pixel width of annulus"
971
972        //assign results of dialog to key=value string, semicolon separated
973        //do only what is necessary, based on av_typ
974        String/G root:myGlobals:Protocols:gAvgInfoStr=""
975       
976        // all averages need these four values
977        root:myGlobals:Protocols:gAvgInfoStr += "AVTYPE=" + av_typ + ";"
978        root:myGlobals:Protocols:gAvgInfoStr += "SAVE=" + autoSave + ";"
979        root:myGlobals:Protocols:gAvgInfoStr += "NAME=" + autoName + ";"
980        root:myGlobals:Protocols:gAvgInfoStr += "PLOT=" + autoPlot + ";"
981       
982        if(cmpstr(av_typ,"Sector")==0)
983                root:myGlobals:Protocols:gAvgInfoStr += "SIDE=" + side + ";"
984                root:myGlobals:Protocols:gAvgInfoStr += "PHI=" + num2str(phi) + ";"
985                root:myGlobals:Protocols:gAvgInfoStr += "DPHI=" + num2str(dphi) + ";"
986        Endif
987       
988        if(cmpstr(av_typ,"Rectangular")==0)
989                root:myGlobals:Protocols:gAvgInfoStr += "SIDE=" + side + ";"
990                root:myGlobals:Protocols:gAvgInfoStr += "PHI=" + num2str(phi) + ";"
991                root:myGlobals:Protocols:gAvgInfoStr += "WIDTH=" + num2str(width) + ";"
992        Endif
993       
994        if(cmpstr(av_typ,"Annular")==0)
995                root:myGlobals:Protocols:gAvgInfoStr += "QCENTER=" + num2str(QCtr) + ";"
996                root:myGlobals:Protocols:gAvgInfoStr += "QDELTA=" + num2str(QDelta) + ";"
997        Endif
998End
999
1000//not used????
1001//checks the syntax of all of the file fields in the panel
1002Function CheckProtocolSyntax(ctrlName) : ButtonControl
1003        String ctrlName
1004       
1005        String retStr=""
1006        //SAM
1007        SVAR list = root:myGlobals:Protocols:gSAM
1008        retStr = ParseRunNumberList(list)
1009        if(strlen(retStr)==0)
1010                //error
1011                Print "SAM Syntax Error"
1012                return(1)
1013        else
1014                list = retStr
1015                Print "SAM syntax OK"
1016        Endif
1017
1018        //MASK
1019        SVAR list = root:myGlobals:Protocols:gMASK
1020        retStr = ParseRunNumberList(list)
1021       
1022End
1023//*************
1024
1025
1026
1027//
1028// Procedure files for creating and executing a data reduction protocol
1029//
1030//**** ONLY invoked from the MAIN PANEL**** NOT REALLY EVER USED ******
1031//Procedure for reducing a sample file (multiple added files) with a specified
1032//protocol. User may create a new protocol, and will be prompted
1033//for information "questionnare-style" where the user must know the
1034//filenames for empty cell, background...etc.. as they will be presented
1035//with standard file open dialogs to select each file desired for use in the
1036//new protocol
1037//once a protocol is selected (or created) the uer is propmted for sample data
1038// and the file is processed through the protocol.
1039//
1040Proc ReduceAFile()
1041
1042        String protocolName="",waveStr="",samStr = "ask"
1043        Variable err
1044       
1045        //pick a protocol wave from the Protocols folder
1046        //must switch to protocols folder to get wavelist (missing parameter)
1047        SetDataFolder root:myGlobals:Protocols
1048        PickAProtocol()
1049       
1050        //get the selected protocol wave choice through a global string variable
1051        protocolName = root:myGlobals:Protocols:gProtoStr
1052       
1053        //If "CreateNew" was selected, go to the questionnare, to make a new set
1054        //and put the name of the new Protocol wave in gProtoStr
1055        if(cmpstr("CreateNew",protocolName) == 0)
1056                ProtocolQuestionnare()
1057                protocolName = root:myGlobals:Protocols:gProtoStr
1058        Endif
1059       
1060        //give the full path:name to the executeProtocol function
1061        waveStr = "root:myGlobals:Protocols:"+protocolName
1062        //samStr is set at top to "ask", since this is the action always desired from "ReduceAFile"
1063       
1064        ExecuteProtocol(waveStr,samStr)
1065       
1066        //return data folder to root before Macro is done
1067        SetDataFolder root:
1068       
1069End
1070
1071
1072//prompts the user to pick a previously created protocol from a popup list
1073//of given the option to create a new protocol
1074//the chosen protocol is passed back to the calling procedure by a global string
1075//the popup is presented as a missing parameter dialog (called with empty parameter list)
1076//
1077Proc PickAProtocol(protocol)
1078        String Protocol
1079        Prompt Protocol "Pick A Protocol",popup, WaveList("*",";","")
1080       
1081        String/G  root:myGlobals:Protocols:gProtoStr = protocol
1082End
1083
1084Proc DeleteAProtocol(protocol)
1085        String Protocol
1086//      Prompt Protocol "Delete A Protocol",popup, WaveList("*",";","")
1087        Prompt Protocol "Delete A Protocol",popup, DeletableProtocols()
1088
1089        String/G  root:myGlobals:Protocols:gProtoStr = protocol
1090End
1091
1092Function/S DeletableProtocols()
1093        String list=WaveList("*",";","")
1094
1095        list= RemoveFromList("Base", list  , ";")
1096        list= RemoveFromList("DoAll", list  , ";")
1097        list= RemoveFromList("CreateNew", list  , ";")
1098        list= RemoveFromList("tempProtocol", list  , ";")
1099        if(cmpstr(list,"")==0)
1100                list = "_no_protocols_;"
1101        endif
1102       
1103        return(list)
1104End
1105
1106//missing paramater dialog to solicit user for a waveStr for the protocol
1107//about to be created
1108//name is passed back as a global string and calling procedure is responsible for
1109//checking for wave conflicts and valid names
1110//
1111Proc AskForName(protocol)
1112        String Protocol
1113        Prompt Protocol "Enter a new name for your protocol (no extension)"
1114       
1115        String/G  root:myGlobals:Protocols:gNewStr = protocol
1116End
1117
1118//this is a lengthy procedure for sequentially polling the user about what data
1119//reduction steps they want to be performed during the protocol
1120//ensures that a valid protocol name was chosen, then fills out each "item"
1121//(6 total) needed for reduction
1122//it the user cancels at any point, the partial protocol will be deleted
1123//
1124Function ProtocolQuestionnare()
1125        String filename,cmd
1126        Variable notDone,refnum
1127       
1128        //prompt for name of new protocol wave to save
1129        do
1130                Execute "AskForName()"
1131                SVAR newProtoStr = root:myGlobals:Protocols:gNewStr
1132               
1133                //make sure it's a valid IGOR name
1134                newProtoStr = CleanupName(newProtoStr,0)        //strict naming convention
1135                String/G root:myGlobals:Protocols:gNewStr=newProtoStr           //reassign, if changed
1136                //Print "newProtoStr = ",newProtoStr
1137               
1138                SetDataFolder root:myGlobals:Protocols
1139                if(WaveExists( $("root:myGlobals:Protocols:" + newProtoStr) ) == 1)
1140                        //wave already exists
1141                        DoAlert 0,"that name is already in use. Please pick a new name"
1142                        notDone = 1
1143                else
1144                        //name is  good
1145                        notDone = 0
1146                Endif
1147        while(notDone)
1148       
1149        //Print "protocol questionnare is "+newProtocol
1150       
1151        //make a new text wave (6 points) and fill it in, in response to questions
1152        SetDataFolder root:myGlobals:Protocols //(redundant - full wave specs are used)
1153        Make/O/T/N=8 $("root:myGlobals:Protocols:" + newProtoStr)
1154        Wave/T newProtocol = $("root:myGlobals:Protocols:" + newProtoStr)
1155       
1156        //ask the questions
1157        /////
1158        //*****Multiple files in these lists are full paths/filenames which may or may not
1159        //have semicolon version numbers in the filename. Therefore, construct the list with
1160        //COMMAS as separators - to avoid messy parsing
1161        ///////
1162       
1163       
1164//////////////////////////
1165        String drkStr="",fileStr=""
1166        DoAlert 1,"Do you want to correct your data for DRK (beam off) counts?"
1167        if(V_flag == 1)         //1=yes
1168                //prompt for DRK  file, but don't actually open it (/D flag)
1169                Open/D/R/T="TEXT????"/M="Select the DRK file"/P=catPathName refnum
1170                //check for cancel
1171                if(strlen(S_filename)==0)
1172                        //user cancelled, abort
1173                        KillWaves/Z newProtocol
1174                        SetDataFolder root:
1175                        Abort "Incomplete protocol has been deleted"
1176                Endif
1177                //assign filename (just the name) to [6]
1178                fileStr = GetFileNameFromPathNoSemi(S_filename)
1179                drkStr = "DRK=none,DRKMODE=0,"
1180                drkStr = ReplaceStringByKey("DRK",drkStr,fileStr,"=",",")
1181                drkStr = ReplaceNumberByKey("DRKMODE", drkStr, 10 ,"=",",")     
1182                newProtocol[6] = drkStr
1183        else
1184                //no Work.DRK desired
1185                newProtocol[6] = "DRK=none,DRKMODE=0,"
1186        Endif
1187       
1188////////////
1189       
1190/////////////////
1191        DoAlert 1,"Do you want to subtract background from your data?"
1192        if(V_flag == 1)         //1=yes
1193                //prompt for background file, but don't actually open it (/D flag)
1194                Open/D/R/T="TEXT????"/M="Select the Background data file"/P=catPathName refnum
1195                //check for cancel
1196                if(strlen(S_filename)==0)
1197                        //user cancelled, abort
1198                        KillWaves/Z newProtocol
1199                        SetDataFolder root:
1200                        Abort "Incomplete protocol has been deleted"
1201                Endif
1202                //assign filename (full path) to [0]
1203                newProtocol[0] = GetFileNameFromPathNoSemi(S_filename)
1204               
1205                notDone=1
1206                do
1207                        //prompt for additional background files
1208                        DoAlert 1,"Do you want to add another background file?"
1209                        if(V_flag == 1)         //yes
1210                                Open/D/R/T="TEXT????"/M="Select another Background data file"/P=catPathName refnum
1211                                //check for cancel
1212                                if(strlen(S_filename)==0)
1213                                        //user cancelled, abort ********maybe just break out of the loop here
1214                                        KillWaves/Z newProtocol
1215                                        SetDataFolder root:
1216                                        Abort "Incomplete protocol has been deleted"
1217                                Endif
1218                                //assign filename (full path) to [0]
1219                                newProtocol[0] += "," + GetFileNameFromPathNoSemi(S_filename)           //***COMMA separated list
1220                                notDone = 1             //keep going
1221                        else
1222                                notDone = 0                     //no more to add
1223                        Endif
1224                While(notDone)
1225        else            //no background desired
1226                newProtocol[0] = "none"
1227        Endif
1228////////////////////// 
1229        DoAlert 1,"Do you want to subtract empty cell scattering from your data?"
1230        if(V_flag == 1)         //1=yes
1231                //prompt for Empty cell file, but don't actually open it (/D flag)
1232                Open/D/R/T="TEXT????"/M="Select the Empty Cell data file"/P=catPathName refnum
1233                //check for cancel
1234                if(strlen(S_filename)==0)
1235                        //user cancelled, abort
1236                        KillWaves/Z newProtocol
1237                        SetDataFolder root:
1238                        Abort "Incomplete protocol has been deleted"
1239                Endif
1240                //assign filename (full path) to [1]
1241                newProtocol[1] = GetFileNameFromPathNoSemi(S_filename)
1242               
1243                notDone=1
1244                do
1245                        //prompt for additional Empty Cell files
1246                        DoAlert 1,"Do you want to add another Empty Cell file?"
1247                        if(V_flag == 1)         //yes
1248                                Open/D/R/T="TEXT????"/M="Select another Empty Cell data file"/P=catPathName refnum
1249                                //check for cancel
1250                                if(strlen(S_filename)==0)
1251                                        //user cancelled, abort ********maybe just break out of the loop here
1252                                        KillWaves/Z newProtocol
1253                                        SetDataFolder root:
1254                                        Abort "Incomplete protocol has been deleted"
1255                                Endif
1256                                //assign filename (full path) to [1]
1257                                newProtocol[1] += "," + GetFileNameFromPathNoSemi(S_filename)           //***COMMA separated list
1258                                notDone = 1             //keep going
1259                        else
1260                                notDone = 0                     //no more to add
1261                        Endif
1262                While(notDone)
1263        else            //no background desired
1264                newProtocol[1] = "none"
1265        Endif
1266//////////////////////////
1267        DoAlert 1,"Do you want to correct your data for detector sensitivity?"
1268        if(V_flag == 1)         //1=yes
1269                //prompt for DIV  file, but don't actually open it (/D flag)
1270                Open/D/R/T="TEXT????"/M="Select the detector sensitivity file"/P=catPathName refnum
1271                //check for cancel
1272                if(strlen(S_filename)==0)
1273                        //user cancelled, abort
1274                        KillWaves/Z newProtocol
1275                        SetDataFolder root:
1276                        Abort "Incomplete protocol has been deleted"
1277                Endif
1278                //assign filename (full path) to [2]
1279                newProtocol[2] = GetFileNameFromPathNoSemi(S_filename)
1280        else
1281                //no Work.DIV desired
1282                newProtocol[2] = "none"
1283        Endif   
1284//////////////////////////
1285        DoAlert 1,"Do you want to mask your files before averaging?"
1286        if(V_flag == 1)         //1=yes
1287                //prompt for mask  file, but don't actually open it (/D flag)
1288                Open/D/R/T="TEXT????MASK"/M="Select the mask file"/P=catPathName refnum
1289                //check for cancel
1290                if(strlen(S_filename)==0)
1291                        //user cancelled, abort
1292                        KillWaves/Z newProtocol
1293                        SetDataFolder root:
1294                        Abort "Incomplete protocol has been deleted"
1295                Endif
1296                //assign filename (full path) to [3]
1297                newProtocol[3] = GetFileNameFromPathNoSemi(S_filename)
1298        else
1299                //no MASK desired
1300                newProtocol[3] = "none"
1301        Endif   
1302       
1303        //absolute scaling
1304       
1305        //////////////////////////
1306        //ABS parameters stored as keyword=value string
1307        DoAlert 1,"Do you want absolute scaling?"
1308        if(V_flag == 1)         //1=yes
1309                //missing param - prompt for values, put in semicolon-separated list
1310                Execute "AskForAbsoluteParams_Quest()"
1311                SVAR absStr =  root:myGlobals:Protocols:gAbsStr
1312                newProtocol[4] = absStr
1313        else
1314                //no absolute scaling desired
1315                newProtocol[4] = "none"
1316        Endif   
1317       
1318        //type of average, plot?, auto/manual naming/saving... put in semicolon separated string
1319        //of KEY=<value> format for easy parsing
1320        //Kewords are: AVTYPE,PHI,DPHI,PLOT,SAVE,NAME,SIDE,WIDTH
1321        //note that AVTYPE,NAME,SIDE have string values, others have numerical values
1322        ///////////////////////
1323        DoAlert 1,"Do you want to average your data to I vs. q?"
1324        if(V_flag == 1)         //1=yes
1325                String/G root:myGlobals:Protocols:gAvgInfoStr = ""
1326                Execute "GetAvgInfo()"          //will put up missing paramter dialog and do all the work
1327                //:gAvgInfo is reset by the Proc(), copy this string tot he protocol
1328                SVAR tempStr=root:myGlobals:Protocols:gAvgInfoStr
1329               
1330                //get a file path for saving files, if desired
1331                /////no - save files to the same data folder as the one with the raw data
1332                //then only one path to manage.
1333                //String yesNo = StringByKey("SAVE", tempStr,"=", ";")
1334                //if(cmpstr("Yes",yesNo) == 0)          //0=yes
1335                        //NewPath/C/M="Select Folder"/O Save_path               //Save_path is the symbolic path
1336                //Endif
1337
1338                newProtocol[5] = tempStr
1339                KillStrings/Z tempStr
1340        else
1341                //no averaging desired
1342                newProtocol[5] = "AVTYPE=none"
1343        Endif
1344       
1345        //returns the name of the newly created (= currently in use) protocol wave through a global
1346        String/G root:myGlobals:Protocols:gProtoStr = newProtoStr
1347End
1348
1349//function to check the work files (to see what's already there)
1350//and compare that with the files that are supposed to be there, according to the
1351//current protocol (to save unnecessary time re-loading files)
1352//
1353//the "type" folder is checked for all files in the list req(ested)Files
1354//note that the list of files is a full path:name;ver, while the
1355//fileList in the folder is just the name (or a list of names)
1356//
1357//returns 0 false, if files are NOT present
1358//or 1 = true, yes, the files are there as requested
1359//
1360Function AreFilesThere(type,reqFiles)
1361        String type,reqFiles
1362       
1363        //in general, reqFiles is a list of full paths to files - which MAY include semicolon version numbers
1364        //reqFiles MUST be constructed with COMMAS as list separators, to avoid disaster
1365        //when the version numbers are interpreted as filenames
1366       
1367        //get the number of files requested
1368        Variable nReq,nCur,match,ii
1369        nReq = ItemsInList(reqFiles,",")
1370       
1371        //get the name of the file currently in BGD - in the global fileList
1372        //fileList has NAMES ONLY - since it was derived from the file header
1373        String testStr
1374        testStr = "root:"+type+":fileList"
1375        if(Exists(testStr) == 2)                //2 if string variable exists
1376                SVAR curFiles = $testStr
1377        else
1378                //no files currently in type folder, return zero
1379                Return (0)
1380        Endif
1381        //get the number of files already in folder
1382        nCur = ItemsInList(curFiles,";")
1383        If(nCur != nReq)
1384                Return (0)              //quit now, the wrong number of files present
1385        Endif
1386        //right number of files... are the names right...
1387        //check for a match (case-sensitive!!) of each requested file in the curFile string
1388        //need to extract filenames from reqFiles, since they're the full path and name
1389       
1390        ii=0
1391        do
1392                testStr = StringFromList(ii,reqFiles,",")       //testStr is the Nth full path and filename
1393                //testStr = GetFileNameFromPathNoSemi(testStr)  //testStr will now be just the filename
1394                match = stringmatch(curFiles,testStr)
1395                If(!match)
1396                        Return (0)              //req file was not found in curFile list - get out now
1397                Endif
1398                ii+=1
1399        while(ii<nreq)
1400       
1401        Return (1)              //indicate that files are OK, no changes needed
1402End
1403
1404//will add the files specified in the protocol to the "type" folder
1405//will add multiple files together if more than one file is requested
1406//(list is a comma delimited list of filenames, with NO path information)
1407//
1408// This routine NOW DOES check for the possibility that the filenames may have ";vers" from the
1409// VAX - data should be picked up from Charlotte, where it won't have version numbers.
1410//
1411Function AddFilesInList(type,list)
1412        String type,list
1413       
1414        //type is the work folder to put the data into, and list is a COMMA delimited list of paths/names
1415        Variable num,ii,err=0,refNum
1416        String filename,pathStr=""
1417        PathInfo catPathName                    //this is where the files are
1418        pathstr=S_path
1419       
1420        num = ItemsInList(list,",")             // comma delimited list
1421       
1422        ii=0
1423        do
1424                //FindValidFilename only needed in case of vax version numbers
1425                filename = pathStr + FindValidFilename(StringFromList(ii,list,","))
1426                Open/Z/R refnum as filename
1427                if(V_flag != 0)         //file not found
1428                        //Print "file not found AddFilesInList()"
1429                        //Print filename
1430                        err = 1
1431                        return(err)
1432                Endif
1433                Close refnum            //file was found and opened, so close it
1434                ReadHeaderAndData(filename)
1435                if(ii == 0)
1436                        //first pass, wipe out the old contents of the work file
1437                        err =  Raw_to_work(type)
1438                else
1439                        err = Add_raw_to_work(type)
1440                Endif
1441                ii+=1
1442        while(ii<num)
1443        return(err)
1444End
1445
1446//function will reduce a sample file (or ask for file(s))
1447//using the protocol named as "protoStr" in the Protocols subfolder
1448//samStr is the file(s) or "ask" to force prompt
1449//sequentially proceeds through flowchart, doing reduction steps as needed
1450//show Schematic to debug what steps/values were used
1451//
1452//function is long, but straightforward logic
1453//
1454Function ExecuteProtocol(protStr,samStr)
1455        String protStr,samStr
1456        //protStr is the full path to the selected protocol wave
1457        //samStr is either "ask" or the name ONLY ofthe desired sample data file(s) (NO PATH)
1458        WAVE/T prot = $protStr
1459        SetDataFolder root:myGlobals:Protocols
1460       
1461        Variable filesOK,err,notDone
1462        String activeType, msgStr, junkStr, pathStr=""
1463        PathInfo catPathName                    //this is where the files are
1464        pathStr=S_path
1465       
1466       
1467        //Parse the instructions in the prot wave
1468        //0 - bkg
1469        //1 - emp
1470        //2 - div
1471        //3 - mask
1472        //4 - abs params c2-c5
1473        //5 - average params
1474        //6 = DRK file (**out of sequence)
1475       
1476        //prompt for sam data => read raw data, add to sam folder
1477        //or parse file(s) from the input paramter string
1478        activeType = "SAM"
1479        msgStr = "Select sample data"
1480        //Ask for SAM file or parse
1481        do
1482                if((cmpstr(samStr,"ask") == 0) || (cmpstr(samStr,"")==0) )              //zero if strings are equal
1483                        err = LoadRawSANSData(msgStr)           //will prompt for file
1484                        if(err)
1485                                PathInfo/S catPathName
1486                                Abort "reduction sequence aborted"
1487                        endif
1488                        UpdateDisplayInformation("RAW")                 //display the new type of data that was loaded
1489                        err =  Raw_to_work(activeType)          //this is the first file (default)
1490                        //Ask for another SAM file
1491                        do
1492                                DoAlert 1,"Do you want to add another Sample file?"
1493                                if(V_flag == 1)         //yes
1494                                        err = LoadRawSANSData(msgStr)           //will prompt for file
1495                                        if(err)
1496                                                PathInfo/S catPathName
1497                                                Abort "reduction sequence aborted"
1498                                        endif
1499                                        UpdateDisplayInformation("RAW")                 //display the new type of data that was loaded
1500                                        err = Add_raw_to_work(activeType)
1501                                        notDone = 1
1502                                else
1503                                        notDone = 0
1504                                endif
1505                        while(notDone)
1506                        break
1507                Endif
1508                //"none" is not an option - you always need a sample file - "none" will never return zero
1509                //if not "ask" AND not "none" then try to parse the filenames
1510                If((cmpstr(samStr,"none") != 0) && (cmpstr(samStr,"ask") != 0))
1511                        //filesOK = AreFilesThere(activeType,samStr)            //return 1 if correct files are already there
1512                        filesOK = 0             // Feb 2008, always force a reload of files. Maybe slow, but always correct
1513                        if(!filesOK)
1514                                //add the correct file(s) to SAM
1515                                err = AddFilesInList(activeType,samStr)
1516                                if(err)
1517                                        //Print "samstr = ",samStr
1518                                        Abort "SAM file not found, reset SAM file"
1519                                Endif
1520                        Endif
1521                Endif
1522        While(0)
1523        //always update
1524        UpdateDisplayInformation(ActiveType)
1525       
1526        //check for bkg file  -- "ask" might not fail - "ask?" will - ? not allowed in VAX filenames
1527        // add if needed
1528        //use a "case" statement
1529        msgStr = "Select background file"
1530        activeType = "BGD"
1531        do
1532                if(cmpstr(prot[0],"ask") == 0)          //zero if strings are equal
1533                        err = LoadRawSANSData(msgStr)           //will prompt for file
1534                        if(err)
1535                                PathInfo/S catPathName
1536                                Abort "reduction sequence aborted"
1537                        endif
1538                        UpdateDisplayInformation("RAW")                 //display the new type of data that was loaded
1539                        err =  Raw_to_work(activeType)          //this is the first file (default)
1540                        //Ask for another BGD file
1541                        do
1542                                DoAlert 1,"Do you want to add another Background file?"
1543                                if(V_flag == 1)         //yes
1544                                        err = LoadRawSANSData(msgStr)           //will prompt for file
1545                                        if(err)
1546                                                PathInfo/S catPathName
1547                                                Abort "reduction sequence aborted"
1548                                        endif
1549                                        UpdateDisplayInformation("RAW")                 //display the new type of data that was loaded
1550                                        err = Add_raw_to_work(activeType)
1551                                        notDone = 1
1552                                else
1553                                        notDone = 0
1554                                endif
1555                        while(notDone)
1556                        UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1557                        break
1558                Endif
1559                If(cmpstr(prot[0],"none") == 0)
1560                        //clean out the BKG folder?
1561                        //KillDataFolder root:BKG
1562                        //NewDataFolder/O root:BKG
1563                        break
1564                Endif
1565                //if not "ask" AND not "none" then try to parse the filenames
1566                If((cmpstr(prot[0],"none") != 0) && (cmpstr(prot[0],"ask") != 0))
1567                        //filesOK = AreFilesThere(activeType,prot[0])
1568                        filesOK = 0             // Feb 2008, always force a reload of files. Maybe slow, but always correct
1569                        if(!filesOK)
1570                                //add the correct file(s) to BGD
1571                                err = AddFilesInList(activeType,prot[0])
1572                                If(err)
1573                                        Abort "BGD file not found. Reset BGD file list"
1574                                Endif
1575                        Endif
1576                        UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1577                Endif
1578        While(0)
1579       
1580       
1581        //check for emp file (prot[1])
1582        // add if needed
1583        msgStr = "Select empty cell data"
1584        activeType = "EMP"
1585        do
1586                if(cmpstr(prot[1],"ask") == 0)
1587                        err = LoadRawSANSData(msgStr)           //will prompt for file
1588                        if(err)
1589                                PathInfo/S catPathName
1590                                Abort "reduction sequence aborted"
1591                        endif
1592                        UpdateDisplayInformation("RAW")                 //display the new type of data that was loaded
1593                        err =  Raw_to_work(activeType)          //this is the first file (default)
1594                        //Ask for another EMP file
1595                        do
1596                                DoAlert 1,"Do you want to add another Empty Cell file?"
1597                                if(V_flag == 1)         //yes
1598                                        err = LoadRawSANSData(msgStr)           //will prompt for file
1599                                        if(err)
1600                                                PathInfo/S catPathName
1601                                                Abort "reduction sequence aborted"
1602                                        endif
1603                                        UpdateDisplayInformation("RAW")                 //display the new type of data that was loaded
1604                                        err = Add_raw_to_work(activeType)
1605                                        notDone = 1
1606                                else
1607                                        notDone = 0
1608                                endif
1609                        while(notDone)
1610                        UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1611                        break
1612                Endif
1613                If(cmpstr(prot[1],"none") == 0)
1614                        //clean out the EMP folder?
1615                        //KillDataFolder root:EMP
1616                        //NewDataFolder/O root:EMP
1617                        break
1618                Endif
1619                //if not "ask" AND not "none" then try to parse the filenames
1620                If((cmpstr(prot[1],"none") != 0) && (cmpstr(prot[1],"ask") != 0))
1621                        //filesOK = AreFilesThere(activeType,prot[1])
1622                        filesOK = 0             // Feb 2008, always force a reload of files. Maybe slow, but always correct
1623                        if(!filesOK)
1624                                //add the correct file(s) to BGD
1625                                err = AddFilesInList(activeType,prot[1])
1626                                If(err)
1627                                        Abort "EMP file not found. Reset EMP file list"
1628                                Endif
1629                        Endif
1630                        UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1631                Endif
1632        While(0)
1633       
1634        //do the CORRECT step based on the answers to emp and bkg subtraction
1635        //by setting the proper"mode"
1636        //1 = both emp and bgd subtraction
1637        //2 = only bgd subtraction
1638        //3 = only emp subtraction
1639        //4 = no subtraction
1640        //additional modes 091301
1641        //11 = emp, bgd, drk
1642        //12 = bgd and drk
1643        //13 = emp and drk
1644        //14 = no subtractions
1645        //work.drk is from proto[6]
1646        //
1647        //subtracting just the DRK data is NOT an option - it doesnt' really make any physical sense
1648        // - in this case, DRK is skipped (equivalent to mode==4)
1649        // automatically accounts for attenuators given the lookup tables and the
1650        //desired subtractions
1651        //Attenuator lookup tables are alredy implemented (NG1 = NG7)
1652        //
1653       
1654        //read in the DRK data if necessary
1655        //only one file, assumed to be RAW data
1656        //
1657        String fname="",drkStr=""
1658        drkStr=StringByKey("DRK",prot[6],"=",",")
1659        if(cmpstr(drkStr,"none") != 0)
1660                err = ReadHeaderAndData( (pathStr+drkStr) )
1661                if(err)
1662                        PathInfo/S catPathName
1663                        Abort "reduction sequence aborted"
1664                endif
1665                err = Raw_to_Work_NoNorm("DRK")
1666        endif
1667       
1668        //dispatch to the proper "mode" of Correct()
1669        Variable mode=4,val
1670        do
1671                if( (cmpstr("none",prot[0]) == 0)       && (cmpstr("none",prot[1]) == 0) )
1672                        //no subtraction (mode = 4),
1673                        mode = 4
1674                Endif
1675                If((cmpstr(prot[0],"none") != 0) && (cmpstr(prot[1],"none") == 0))
1676                        //subtract BGD only
1677                        mode=2
1678                Endif
1679                If((cmpstr(prot[0],"none") == 0) && (cmpstr(prot[1],"none") != 0))
1680                        //subtract EMP only
1681                        mode=3
1682                Endif
1683                If((cmpstr(prot[0],"none") != 0) && (cmpstr(prot[1],"none") != 0))
1684                        // bkg and emp subtraction are to be done (BOTH not "none")
1685                        mode=1
1686                Endif
1687                activeType = "COR"
1688                //add in DRK mode (0= no used, 10 = used)
1689                val = NumberByKey("DRKMODE",prot[6],"=","," )
1690                mode += val
1691//              print "mode = ",mode
1692                err = Correct(mode)
1693                if(err)
1694                        SetDataFolder root:
1695                        Abort "error in Correct, called from executeprotocol, normal cor"
1696                endif
1697                UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1698        While(0)
1699       
1700        //check for work.div file (prot[2])
1701        //add if needed
1702        // can't properly check the filename - so for now add and divide, if anything other than "none"
1703        //do/skip divide step based on div answer
1704        If(cmpstr("none",prot[2])!=0)           // if !0, then there's a file requested
1705                If(cmpstr("ask",prot[2]) == 0)
1706                        //ask user for file
1707                         junkStr = PromptForPath("Select the detector sensitivity file")
1708                        If(strlen(junkStr)==0)
1709                                SetDataFolder root:
1710                                Abort "No file selected, data reduction aborted"
1711                        Endif
1712                         ReadHeaderAndWork("DIV", junkStr)
1713                else
1714                        //assume it's a path, and that the first (and only) item is the path:file
1715                        //list processing is necessary to remove any final comma
1716                        junkStr = pathStr + StringFromList(0, prot[2],"," )
1717                        ReadHeaderAndWork("DIV",junkStr)
1718                Endif
1719                //got a DIV file, select the proper type of work data to DIV (= activeType)
1720                err = Divide_work(activeType)           //returns err = 1 if data doesn't exist in specified folders
1721                If(err)
1722                        SetDataFolder root:
1723                        Abort "data missing in DIV step, call from executeProtocol"
1724                Endif
1725                activeType = "CAL"
1726                UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1727        Endif
1728       
1729        Variable c2,c3,c4,c5
1730        //do absolute scaling if desired
1731        if(cmpstr("none",prot[4])!=0)
1732                if(cmpstr("ask",prot[4])==0)
1733                        //get the params from the user
1734                        Execute "AskForAbsoluteParams_Quest()"
1735                        //then from the list
1736                        SVAR junkAbsStr = root:myGlobals:Protocols:gAbsStr
1737                        c2 = NumberByKey("TSTAND", junkAbsStr, "=", ";")        //parse the list of values
1738                        c3 = NumberByKey("DSTAND", junkAbsStr, "=", ";")
1739                        c4 = NumberByKey("IZERO", junkAbsStr, "=", ";")
1740                        c5 = NumberByKey("XSECT", junkAbsStr, "=", ";")
1741                else
1742                        //get the parames from the list
1743                        c2 = NumberByKey("TSTAND", prot[4], "=", ";")   //parse the list of values
1744                        c3 = NumberByKey("DSTAND", prot[4], "=", ";")
1745                        c4 = NumberByKey("IZERO", prot[4], "=", ";")
1746                        c5 = NumberByKey("XSECT", prot[4], "=", ";")
1747                Endif
1748                //get the sample trans and thickness from the activeType folder
1749                String destStr = "root:"+activeType+":realsread"
1750                Wave dest = $destStr
1751                Variable c0 = dest[4]           //sample transmission
1752                Variable c1 = dest[5]           //sample thickness
1753               
1754                err = Absolute_Scale(activeType,c0,c1,c2,c3,c4,c5)
1755                if(err)
1756                        SetDataFolder root:
1757                        Abort "Error in Absolute_Scale(), called from executeProtocol"
1758                endif
1759                activeType = "ABS"
1760                UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1761        Endif
1762       
1763        //check for mask
1764        //add mask if needed
1765        // can't properly check the filename - so for now always add
1766        //doesn't change the activeType
1767        if(cmpstr("none",prot[3])!=0)
1768                If(cmpstr("ask",prot[3])==0)
1769                        //get file from user
1770                        junkStr = PromptForPath("Select Mask file")
1771                        If(strlen(junkStr)==0)
1772                                //no selection of mask file is not a fatal error, keep going, and let cirave()
1773                                //make a "null" mask
1774                                //if none desired, make sure that the old mask is deleted
1775                                //junkStr = GetDataFolder(1)
1776                                //SetDataFolder root:MSK
1777                                KillWaves/Z root:MSK:data
1778                                //SetDataFolder junkStr
1779                                DoAlert 0,"No Mask file selected, data not masked"
1780                        else
1781                                //read in the file from the dialog
1782                                ReadMCID_MASK(junkStr)
1783                        Endif
1784                else
1785                        //just read it in from the protocol
1786                        //list processing is necessary to remove any final comma
1787                        junkStr = pathStr + StringFromList(0, prot[3],"," )
1788                        ReadMCID_MASK(junkStr)
1789                Endif
1790        else
1791                //if none desired, make sure that the old mask is deleted
1792                //junkStr = GetDataFolder(1)
1793                //SetDataFolder root:MSK
1794                KillWaves/Z root:MSK:data
1795                //SetDataFolder junkStr
1796        Endif
1797       
1798        //mask data if desired (this is done automatically  in the average step) and is
1799        //not done explicitly here (if no mask in MSK folder, a null mask is created and "used")
1800       
1801        // average/save data as specified
1802       
1803        //Parse the keyword=<Value> string as needed, based on AVTYPE
1804       
1805        //average/plot first
1806        String av_type = StringByKey("AVTYPE",prot[5],"=",";")
1807        If(cmpstr(av_type,"none") != 0)
1808                If (cmpstr(av_type,"")==0)              //if the key could not be found... (if "ask" the string)
1809                        //get the averaging parameters from the user, as if the set button was hit
1810                        //in the panel
1811                        SetAverageParamsButtonProc("dummy")             //from "ProtocolAsPanel"
1812                        SVAR tempAveStr = root:myGlobals:Protocols:gAvgInfoStr
1813                        av_type = StringByKey("AVTYPE",tempAveStr,"=",";")
1814                else
1815                        //there is info in the string, use the protocol
1816                        //set the global keyword-string to prot[5]
1817                        String/G root:myGlobals:Protocols:gAvgInfoStr = prot[5]
1818                Endif
1819        Endif
1820       
1821        //convert the folder to linear scale before averaging, then revert by calling the window hook
1822        ConvertFolderToLinearScale(activeType)
1823       
1824        strswitch(av_type)      //dispatch to the proper routine to average to 1D data
1825                case "none":           
1826                        //still do nothing
1827                        break                   
1828                case "2D_ASCII":       
1829                        //do nothing
1830                        break
1831                case "QxQy_ASCII":
1832                        //do nothing
1833                        break
1834                case "PNG_Graphic":
1835                        //do nothing
1836                        break
1837                case "Rectangular":
1838                        RectangularAverageTo1D(activeType)
1839                        break
1840                case "Annular":
1841                        AnnularAverageTo1D(activeType)
1842                        break
1843                case "Circular":
1844                        CircularAverageTo1D(activeType)
1845                        break
1846                case "Sector":
1847                        CircularAverageTo1D(activeType)
1848                        break
1849                default:       
1850                        //do nothing
1851        endswitch
1852///// end of averaging dispatch
1853        // put data back on log or lin scale as set by default
1854        fRawWindowHook()
1855       
1856        //save data if desired
1857        String fullpath = "", newfileName=""
1858        String item = StringByKey("SAVE",prot[5],"=",";")               //does user want to save data?
1859        If( (cmpstr(item,"Yes")==0) && (cmpstr(av_type,"none") != 0) )         
1860                //then save
1861                //get name from textwave of the activeType dataset
1862                String textStr = "root:"+activeType+":textread"
1863                Wave/T textPath = $textStr
1864                If(WaveExists(textPath) == 1)
1865                        newFileName = GetNameFromHeader(textPath[0])
1866                else
1867                        newFileName = ""                        //if the header is missing?
1868                        //Print "can't read the header - newfilename is null"
1869                Endif
1870               
1871                //pick ABS or AVE extension
1872                String exten = activeType
1873                if(cmpstr(exten,"ABS") != 0)
1874                        exten = "AVE"
1875                endif
1876                if(cmpstr(av_type,"2D_ASCII") == 0)
1877                        exten = "ASC"
1878                endif
1879                if(cmpstr(av_type,"QxQy_ASCII") == 0)
1880                        exten = "DAT"
1881                endif
1882               
1883                //Path is catPathName, symbolic path
1884                //if this doesn't exist, a dialog will be presented by setting dialog = 1
1885                Variable dialog = 0
1886                PathInfo/S catPathName
1887                item = StringByKey("NAME",prot[5],"=",";")              //Auto or Manual naming
1888                If((cmpstr(item,"Manual")==0) || (cmpstr(newFileName,"") == 0))
1889                        //manual name if requested or if no name can be derived from header
1890                        fullPath = newfileName + "."+ exten //puts possible new name or null string in dialog
1891                        dialog = 1              //force dialog for user to enter name
1892                else
1893                        //auto-generate name and prepend path - won't put up any dialogs since it has all it needs
1894                        fullPath = S_Path + newFileName+ "." + exten   
1895                Endif
1896                //
1897                strswitch(av_type)     
1898                        case "Annular":
1899                                WritePhiave_W_Protocol(activeType,fullPath,dialog)
1900                                break
1901                        case "2D_ASCII":
1902                                Fast2DExport(activeType,fullPath,dialog)
1903                                break
1904                        case "QxQy_ASCII":
1905                                QxQy_Export(activeType,fullPath,dialog)
1906                                break
1907                        case "PNG_Graphic":
1908                                SaveAsPNG(activeType,fullpath,dialog)
1909                                break
1910                        default:
1911                                WriteWaves_W_Protocol(activeType,fullpath,dialog)
1912                endswitch
1913               
1914                //Print "data written to:  "+ fullpath
1915        Endif
1916       
1917        //done with everything in protocol list
1918        Return(0)
1919End
1920
1921//updates the currently displayed information to the data in "type"
1922//data folder - changes the title of the window and the global of the
1923//currently displayed data type - the recreation macro does the work
1924//
1925Function UpdateDisplayInformation(type)
1926        String type
1927
1928        String newTitle = "WORK_"+type
1929        DoWindow/F SANS_Data
1930        DoWindow/T SANS_Data, newTitle
1931        KillStrings/Z newTitle
1932       
1933        //need to update the display with "data" from the correct dataFolder
1934        //reset the current displaytype to "type"
1935        String/G root:myGlobals:gDataDisplayType=Type
1936       
1937        fRawWindowHook()
1938       
1939        //no error
1940        Return(0)
1941End
1942
1943//missing parameter dialog to solicit the 4 absolute intensity parameters
1944//from the user
1945//values are passed back as a global string variable (keyword=value)
1946//
1947Proc AskForAbsoluteParams(c2,c3,c4,c5)
1948        Variable c2=0.95,c3=0.1,c4=1,c5=32.0
1949        Prompt c2, "Standard Transmission"
1950        Prompt c3, "Standard Thickness (cm)"
1951        Prompt c4, "I(0) from standard fit (normalized to 1E8 monitor cts)"
1952        Prompt c5, "Standard Cross-Section (cm-1)"
1953       
1954        String/G root:myGlobals:Protocols:gAbsStr=""
1955       
1956        root:myGlobals:Protocols:gAbsStr = "TSTAND="+num2str(c2)
1957        root:myGlobals:Protocols:gAbsStr +=  ";" + "DSTAND="+num2str(c3)
1958        root:myGlobals:Protocols:gAbsStr +=  ";" + "IZERO="+num2str(c4)
1959        root:myGlobals:Protocols:gAbsStr +=  ";" + "XSECT="+num2str(c5)
1960       
1961End
1962
1963//asks the user for absolute scaling information. the user can either
1964//enter the 4 necessary values in manually (missing parameter dialog)
1965//or the user can select an empty beam file from a standard open dialog
1966//if an empty beam file is selected, the "kappa" value is automatically calculated
1967//in either case, the global keyword=value string is set.
1968//
1969//Proc AskForAbsoluteParams_Quest()
1970Function AskForAbsoluteParams_Quest()   
1971       
1972        Variable err, isNG5=0,loc,refnum
1973        //ask user if he wants to use a transmision file for absolute scaling
1974        //or if he wants to enter his own information
1975        err = UseStdOrEmpForABS()
1976        //DoAlert 1,"<Yes> to enter your own values, <No> to select an empty beam flux file"
1977        If ( err==1 )
1978                //secondary standard selected, prompt for values
1979                Execute "AskForAbsoluteParams()"                //missing parameters
1980        else
1981                //empty beam flux file selected, prompt for file, and use this to calculate KAPPA
1982                Variable kappa=1
1983               
1984                //ask for file and read it into RAW
1985                //will cancel if no file is selected
1986                err = LoadRawSANSData("select the empty beam file")             //reads the RAW data
1987                UpdateDisplayInformation("RAW")                 //display the new type of data that was loaded
1988                if(err)
1989                        PathInfo/S catPathName
1990                        Abort "reduction sequence aborted"
1991                endif
1992                       
1993                Wave/T tw=$"root:RAW:TextRead"
1994                Wave rw=$"root:RAW:RealsRead"
1995                Wave iw=$"root:RAW:IntegersRead"
1996                String acctStr = tw[3]
1997                //NG5 attenuator transmission is assumed to be the same as the table for NG7
1998                       
1999                //get the necessary variables for the calculation of kappa
2000                Variable detCnt,countTime,attenTrans,monCnt,sdd,pixel
2001                String detStr=tw[9]
2002//              pixel = DetectorPixelResolution(acctStr,detStr)         //get the pixel size from the file information
2003                //note that reading the detector pixel size from the header ASSUMES SQUARE PIXELS! - Jan2008
2004                pixel = rw[10]/10                       // header value (X) is in mm, want cm here
2005       
2006                countTime = iw[1]
2007                //detCnt = rw[2]                //080802 -use sum of data, not scaler from header
2008                monCnt = rw[0]
2009                sdd = rw[18]
2010                sdd *=100               //convert from meters to cm
2011                               
2012                //lookup table for transmission factor
2013                //determine which instrument the measurement was done on from acctStr
2014                Variable lambda = rw[26]
2015                Variable attenNo = rw[3]
2016                attenTrans = AttenuationFactor(acctStr,lambda,attenNo)
2017                //Print "attenTrans = ",attenTrans
2018               
2019                //get the XY box, if needed
2020                Variable x1,x2,y1,y2
2021                String filename=tw[0],tempStr
2022                err = GetXYBoxFromFile(filename,x1,x2,y1,y2)            //xy's are passed/returned by reference
2023                Print x1,x2,y1,y2
2024
2025                if( ((x1-x2)==0) || ((y1-y2)==0) )      //need to re-select the box
2026                        err = SelectABS_XYBox(x1,x2,y1,y2)              //this will pause for user input
2027                        if(err)
2028                                Abort "Box not selected properly - Please re-set the ABS parameters"
2029                        Endif
2030                        //box is OK, write box values to file
2031                        PathInfo/S catPathName
2032                        String tempName = S_Path + FindValidFilename(filename)
2033                        WriteXYBoxToHeader(tempName,x1,x2,y1,y2)
2034                else
2035                        //give option to override
2036                        tempStr = "X=("+num2str(x1)+","+num2str(x2)+") Y=("+num2str(y1)+","+num2str(y2)+")"
2037                        DoAlert 1,"The current box is "+tempStr+".  Do you want to override these values?"
2038                        //Print v_flag
2039                        if(V_flag==1)   //1==yes, override
2040                                err = SelectABS_XYBox(x1,x2,y1,y2)
2041                                if(err)
2042                                        Abort "Box not selected properly -Please re-set the ABS parameters"
2043                                Endif
2044                        endif
2045                Endif
2046                Printf "Using Box X(%d,%d),Y(%d,%d)\r",x1,x2,y1,y2
2047               
2048                //need the detector sensitivity file - make a guess, allow to override
2049                String junkStr=""
2050                if(! waveexists($"root:DIV:data"))
2051                         junkStr = PromptForPath("Select the detector sensitivity file")
2052                        If(strlen(junkStr)==0 || CheckIfRawData(junkStr))               //raw check==1 if RAW, DIV is not
2053                                SetDataFolder root:
2054                                Abort "No DIV (PLEX) file selected. Please use setABSParams again, selecting the empty beam file and then the detector sensitivity (Plex_) file"
2055                        Endif
2056                         ReadHeaderAndWork("DIV", junkStr)
2057                endif
2058                //toggle SANS_Data to linear display if needed, so that we're working with linear scaled data
2059                ControlInfo/W=SANS_Data bisLog
2060                if(V_Flag==1)
2061                        Log_Lin("bisLog")       
2062                endif   
2063                Wave divData = $"root:div:Data"
2064                Wave data = $"root:raw:data"            //this will be the linear data
2065                // correct by detector sensitivity
2066                data /= divData
2067               
2068                // now do the sum, only in the box     
2069//              detCnt = sum($"root:raw:data", -inf, inf )
2070//              Print "box is now ",x1,x2,y1,y2
2071                detCnt = SumCountsInBox(x1,x2,y1,y2,"RAW")
2072                //             
2073                kappa = detCnt/countTime/attenTrans*1.0e8/(monCnt/countTime)*(pixel/sdd)^2
2074                junkStr = num2str(kappa)
2075                // set the parameters in the global string
2076                Execute "AskForAbsoluteParams(1,1,"+junkStr+",1)"               //no missing parameters, no dialog
2077               
2078                //should wipe out the data in the RAW folder, since it's not really RAW now
2079                DoWindow/K SANS_Data
2080                // SRK JUL 2006 don't clear the contents - just kill the window to force new data to be loaded
2081                // - obsucre bug if "ask" in ABS section of protocol clears RAW folder, then Q-axes can't be set from RAW:RealsRead
2082                //ClearDataFolder("RAW")
2083                Print "Kappa was successfully calculated as = ",kappa   
2084        Endif
2085       
2086End
2087
2088Function UserSelectBox_Continue(ctrlName) :buttonControl
2089        String ctrlName
2090       
2091        DoWindow/K junkWindow           //kill panel
2092end
2093
2094Function SelectABS_XYBox(x1,x2,y1,y2)
2095        Variable &x1,&x2,&y1,&y2
2096       
2097        Variable err=0
2098       
2099        Variable/G root:V_marquee=1             //sets the sneaky bit to automatically update marquee coords
2100        Variable/G root:V_left,root:V_right,root:V_bottom,root:V_top    //must be global for auto-update
2101        DoWindow/F SANS_Data
2102        NewPanel/K=2 /W=(139,341,382,432) as "Select the primary beam"
2103        DoWindow/C junkWindow
2104        AutoPositionWindow/E/M=1/R=SANS_Data
2105       
2106        Drawtext 21,20 ,"Select the primary beam with the"
2107        DrawText 21,40, "marquee and press continue"
2108        Button button0,pos={80,58},size={92,20},title="Continue"
2109        Button button0,proc=UserSelectBox_Continue
2110       
2111        PauseForUser junkWindow,SANS_Data
2112       
2113        DoWindow/F SANS_Data
2114
2115        //GetMarquee left,bottom                        //not needed
2116        NVAR V_left=V_left
2117        NVAR V_right=V_right
2118        NVAR V_bottom=V_bottom
2119        NVAR V_top=V_top
2120       
2121        x1 = V_left
2122        x2 = V_right
2123        y1 = V_bottom
2124        y2 = V_top
2125//      Print "new values,before rounding = ",x1,x2,y1,y2
2126        KeepSelectionInBounds(x1,x2,y1,y2)
2127        //Print "new values = ",x1,x2,y1,y2
2128       
2129        KillVariables/Z root:V_Marquee,root:V_left,root:V_right,root:V_bottom,root:V_top
2130        if((x1-x2)==0 || (y1-y2)==0)
2131                err=1
2132        endif
2133        return(err)
2134End
2135
2136Function UseStdOrEmpForABS()
2137               
2138        NewPanel/K=2 /W=(139,341,402,448) as "Absolute Scaling"
2139        DoWindow/C junkABSWindow
2140        ModifyPanel cbRGB=(57346,65535,49151)
2141        SetDrawLayer UserBack
2142        SetDrawEnv fstyle= 1
2143        DrawText 21,20,"Method of absolute calibration"
2144        Button button0,pos={52,33},size={150,20},proc=UserSelectABS_Continue,title="Empty Beam Flux"
2145        Button button1,pos={52,65},size={150,20},proc=UserSelectABS_Continue,title="Secondary Standard"
2146       
2147        PauseForUser junkABSWindow
2148        NVAR val = root:myGlobals:tmpAbsVal
2149        return(val)
2150End
2151
2152//returns 0 if button0 (empty beam flux)
2153// or 1 if secondary standard
2154Function UserSelectABS_Continue(ctrlName) :buttonControl
2155        String ctrlName
2156       
2157        variable val=0
2158        If(cmpstr(ctrlName,"button0")==0)
2159                val=0           
2160        else
2161                val=1
2162        endif
2163//      print "val = ",ctrlName,val
2164        Variable/G root:myGlobals:tmpAbsVal = val
2165        DoWindow/K junkABSWindow                //kill panel
2166        return(0)
2167end
2168
2169
2170//save the protocol as an IGOR text wave (.itx)
2171//
2172//
2173Function ExportProtocol(ctrlName) : ButtonControl
2174        String ctrlName
2175// get a list of protocols
2176        String Protocol=""
2177        SetDataFolder root:myGlobals:Protocols
2178        Prompt Protocol "Pick A Protocol",popup, WaveList("*",";","")
2179        DoPrompt "Pick A Protocol to Export",Protocol
2180        if(V_flag==1)
2181                //Print "user cancel"
2182                SetDatafolder root:
2183                return(1)
2184        endif
2185//get the selection, or exit
2186        Wave/T pW= $protocol
2187        Make/O/T/N=13 tw
2188// save in the proper format (must write manually, for demo version)
2189        tw[0] = "IGOR"
2190        tw[1] = "WAVES/T \t"+protocol
2191        tw[2] = "BEGIN"
2192        tw[3,10] = "\t\""+pW[p-3]+"\""
2193        tw[11] = "END"
2194        tw[12] = "X SetScale/P x 0,1,\"\","+protocol+"; SetScale y 0,0,\"\","+protocol
2195       
2196        Variable refnum
2197        String fullPath
2198       
2199        PathInfo/S catPathName
2200        fullPath = DoSaveFileDialog("Export Protocol as")
2201        If(cmpstr(fullPath,"")==0)
2202                //user cancel, don't write out a file
2203                Close/A
2204                Abort "no Protocol file was written"
2205        Endif
2206
2207        //actually open the file
2208        Open refNum as fullpath+".itx"
2209       
2210        wfprintf refnum, "%s\r", tw
2211        Close refnum
2212        //Print "all is well  ",protocol
2213        KillWaves/Z tw
2214        setDataFolder root:
2215        return(0)
2216
2217End
2218
2219//imports a protocol from disk into the protocols folder
2220//
2221// will overwrite existing protocols if necessary
2222//
2223//
2224Function ImportProtocol(ctrlName) : ButtonControl
2225        String ctrlName
2226
2227        SetDataFolder root:myGlobals:Protocols
2228
2229        String fullPath
2230       
2231        PathInfo/S catPathName
2232        fullPath = DoOpenFileDialog("Import Protocol")
2233        If(cmpstr(fullPath,"")==0)
2234                //user cancel, don't write out a file
2235                Close/A
2236                Abort "no protocol was loaded"
2237        Endif
2238       
2239        LoadWave/O/T fullPath
2240       
2241        SetDataFolder root:
2242        return(0)
2243end
Note: See TracBrowser for help on using the repository browser.