source: sans/Dev/trunk/NCNR_User_Procedures/Reduction/SANS/ANSTO_Utils.ipf @ 795

Last change on this file since 795 was 795, checked in by srkline, 11 years ago

Changes to SANS reduction that apply to other Facilities:

These changes are related to the propagation of errors in 2D, on a
per-pixel basis. These changes only affect the errors that are reported in
the QxQy? ASCII file output. The 1D code is unaffected.

If these changes are not implemented, then errors of zero will be substitued as defaults
for these experimental errors.

Upon data loading, an error matrix, linear_data_error is generated and filled with
error values appropriate for Poisson statistics (not simply sqrt(n)).

4 functions in FACILITY_DataReadWrite.ipf have been added, and they are rather
self-explanatory:

In FACILITY_Utils.ipf, the AttenuatorTransmission?() function now returns
an additional parameter, atten_err, which is one standard deviation of the
attenuator transmission value. It returns a default error=0 (which is
correct if no attenuation is used). Facilities can fill this function in
with their own estimates for the uncertainty in the attenutator transmission.

File size: 29.4 KB
Line 
1#pragma rtGlobals=1             // Use modern global access method.
2#pragma version=5.0
3#pragma IgorVersion=6.1
4
5// this file contains globals and functions that are specific to a
6// particular facility or data file format
7// branched out 29MAR07 - SRK
8//
9// functions are either labeled with the procedure file that calls them,
10// or noted that they are local to this file
11
12
13// initializes globals that are specific to a particular facility
14// - number of XY pixels
15// - pixexl resolution [cm]
16// - detector deadtime constant [s]
17//
18// called by Initialize.ipf
19//
20Function InitFacilityGlobals()
21
22        //Detector -specific globals
23        Variable/G root:myGlobals:gNPixelsX=192                                 // number of X and Y pixels
24        Variable/G root:myGlobals:gNPixelsY=192
25       
26        // pixel dimensions are now read directly from the file header.
27//      Variable/G root:myGlobals:PixelResDefault = 0.5                 //pixel resolution in cm
28       
29        Variable/G root:myGlobals:DeadtimeDefault = 3.4e-6              //deadtime in seconds ???nha
30
31        Variable/G root:myGlobals:apOff = 5.0           // (cm) distance from sample aperture to sample position
32
33End
34
35
36//**********************
37// Resolution calculation - used by the averaging routines
38// to calculate the resolution function at each q-value
39// - the return value is not used
40//
41// equivalent to John's routine on the VAX Q_SIGMA_AVE.FOR
42// Incorporates eqn. 3-15 from J. Appl. Cryst. (1995) v. 28 p105-114
43//
44// - 21 MAR 07 uses projected BS diameter on the detector
45// - APR 07 still need to add resolution with lenses. currently there is no flag in the
46//          raw data header to indicate the presence of lenses.
47//
48// - Aug 07 - added input to switch calculation based on lenses (==1 if in)
49//
50// - called by CircSectAvg.ipf and RectAnnulAvg.ipf
51//
52// passed values are read from RealsRead
53// except DDet and apOff, which are set from globals before passing
54//
55//
56Function/S getResolution(inQ,lambda,lambdaWidth,DDet,apOff,S1,S2,L1,L2,BS,del_r,usingLenses,SigmaQ,QBar,fSubS)
57        Variable inQ, lambda, lambdaWidth, DDet, apOff, S1, S2, L1, L2, BS, del_r,usingLenses
58        Variable &fSubS, &QBar, &SigmaQ         //these are the output quantities at the input Q value
59       
60        //lots of calculation variables
61        Variable a2, q_small, lp, v_lambda, v_b, v_d, vz, yg, v_g
62        Variable r0, delta, inc_gamma, fr, fv, rmd, v_r1, rm, v_r
63
64        //Constants
65        Variable vz_1 = 3.956e5         //velocity [cm/s] of 1 A neutron
66        Variable g = 981.0                              //gravity acceleration [cm/s^2]
67
68        String results
69        results ="Failure"
70
71        S1 *= 0.5*0.1                   //convert to radius and [cm]
72        S2 *= 0.5*0.1
73
74        L1 *= 100.0                     // [cm]
75        L1 -= apOff                             //correct the distance
76
77        L2 *= 100.0
78        L2 += apOff
79        del_r *= 0.1                            //width of annulus, convert mm to [cm]
80       
81        BS *= 0.5*0.1                   //nominal BS diameter passed in, convert to radius and [cm]
82        // 21 MAR 07 SRK - use the projected BS diameter, based on a point sample aperture
83        Variable LB
84        LB = 20.1 + 1.61*BS                     //distance in cm from beamstop to anode plane (empirical)
85        BS = bs + bs*lb/(l2-lb)         //adjusted diameter of shadow from parallax
86       
87        //Start resolution calculation
88        a2 = S1*L2/L1 + S2*(L1+L2)/L1
89        q_small = 2.0*Pi*(BS-a2)*(1.0-lambdaWidth)/(lambda*L2)
90        lp = 1.0/( 1.0/L1 + 1.0/L2)
91
92        v_lambda = lambdaWidth^2/6.0
93       
94//      if(usingLenses==1)                      //SRK 2007
95        if(usingLenses != 0)                    //SRK 2008 allows for the possibility of different numbers of lenses in header
96                v_b = 0.25*(S1*L2/L1)^2 +0.25*(2/3)*(lambdaWidth/lambda)^2*(S2*L2/lp)^2         //correction to 2nd term
97        else
98                v_b = 0.25*(S1*L2/L1)^2 +0.25*(S2*L2/lp)^2              //original form
99        endif
100       
101        v_d = (DDet/2.3548)^2 + del_r^2/12.0
102        vz = vz_1 / lambda
103        yg = 0.5*g*L2*(L1+L2)/vz^2
104        v_g = 2.0*(2.0*yg^2*v_lambda)                                   //factor of 2 correction, B. Hammouda, 2007
105
106        r0 = L2*tan(2.0*asin(lambda*inQ/(4.0*Pi) ))
107        delta = 0.5*(BS - r0)^2/v_d
108
109        if (r0 < BS)
110                inc_gamma=exp(gammln(1.5))*(1-gammp(1.5,delta))
111        else
112                inc_gamma=exp(gammln(1.5))*(1+gammp(1.5,delta))
113        endif
114
115        fSubS = 0.5*(1.0+erf( (r0-BS)/sqrt(2.0*v_d) ) )
116        if (fSubS <= 0.0)
117                fSubS = 1.e-10
118        endif
119        fr = 1.0 + sqrt(v_d)*exp(-1.0*delta) /(r0*fSubS*sqrt(2.0*Pi))
120        fv = inc_gamma/(fSubS*sqrt(Pi)) - r0^2*(fr-1.0)^2/v_d
121
122        rmd = fr*r0
123        v_r1 = v_b + fv*v_d +v_g
124
125        rm = rmd + 0.5*v_r1/rmd
126        v_r = v_r1 - 0.5*(v_r1/rmd)^2
127        if (v_r < 0.0)
128                v_r = 0.0
129        endif
130        QBar = (4.0*Pi/lambda)*sin(0.5*atan(rm/L2))
131        SigmaQ = QBar*sqrt(v_r/rmd^2 +v_lambda)
132
133        results = "success"
134        Return results
135End
136
137
138//Utility function that returns the detector resolution (in cm)
139//Global values are set in the Initialize procedure
140//
141// - called by CircSectAvg.ipf, RectAnnulAvg.ipf, and ProtocolAsPanel.ipf
142//
143// fileStr is passed as TextRead[3]
144// detStr is passed as TextRead[9]
145//
146// *** as of Jan 2008, depricated. Now detector pixel sizes are read from the file header
147// rw[10] = x size (mm); rw[13] = y size (mm)
148//
149// depricated - pixel dimensions are read directly from the file header
150Function xDetectorPixelResolution(fileStr,detStr)
151        String fileStr,detStr
152       
153        Variable DDet
154
155        //your code here
156       
157        return(DDet)
158End
159
160//Utility function that returns the detector deadtime (in seconds)
161//Global values are set in the Initialize procedure
162//
163// - called by WorkFileUtils.ipf
164//
165// fileStr is passed as TextRead[3] and is the filename
166// detStr is passed as TextRead[9] and is an identifier for the detector
167//
168// [dateAndTimeStr] is optional, and could be used as a switch for
169// different historical detector configurations
170Function DetectorDeadtime(fileStr,detStr,[dateAndTimeStr])
171        String fileStr,detStr,dateAndTimeStr
172       
173        Variable deadtime
174       
175// your code here
176
177        return(deadtime)
178End
179
180
181//given a filename of a SANS data filename of the form
182//QKKNNNNNNN.nx.hdf
183//returns the prefix
184Function/S GetPrefixStrFromFile(item)
185        String item
186        String invalid = ""     //"" is not a valid run prefix, since it's text
187        Variable num=-1
188       
189        //find the "dot"
190        String runStr=""
191       
192        Variable pos = strsearch(item,".",0)
193        if(pos == -1)
194                //"dot" not found
195                return (invalid)
196        else
197                //found, skip the three characters preceeding it
198                if (pos <=7)
199                        //not enough characters
200                        return (invalid)
201                else
202                        runStr = item[0,pos-8]
203                        return (runStr)
204                Endif
205        Endif
206End
207
208Function/S RunDigitString(num)
209        Variable num
210       
211        String numStr=""
212
213        //make 7 digit string from run number
214        sprintf numStr,"%07u",num
215       
216        //Print "numstr = ",numstr
217        return(numstr)
218End
219
220
221// item is a filename
222//
223// this function extracts some sort of number from the file
224// presumably some sort of automatically incrementing run number set by the
225// acquisition system
226//
227// this run number should be a unique identifier for the file
228//
229Function GetRunNumFromFile(item)
230        String item
231
232        Variable invalid = -1
233        Variable num=-1         // an invalid return value
234       
235        String runStr=""
236        Variable pos = strsearch(item,".",0)
237        if(pos == -1)
238                //"dot" not found
239                return (invalid)
240        else
241                //found, get the three characters preceeding it
242                if (pos <=6)
243                        //not enough characters
244                        return (invalid)
245                else
246                        runStr = item[pos-7,pos-1]
247                        //convert to a number
248                        num = str2num(runStr)
249                        //if valid, return it
250                        if (num == NaN)
251                                //7 characters were not a number
252                                return (invalid)
253                        else
254                                //run was OK
255                                return (num)
256                        Endif
257                Endif
258        Endif   
259        return (num)
260End
261
262// item is a filename
263//
264// this function extracts some sort of number from the file
265// presumably some sort of automatically incrementing run number set by the
266// acquisition system
267//
268// this run number should be a unique identifier for the file
269//
270// same as GetRunNumFromFile(0), just with a string return
271//
272// "ABC" returned as an invalid result
273Function/S GetRunNumStrFromFile(item)
274        String item
275       
276        String invalid = "ABC"  //"ABC" is not a valid run number, since it's text
277        String retStr
278        retStr=invalid
279       
280        String runStr = ""
281        Variable pos = strsearch(item,".",0)
282        if(pos == -1)
283                //"dot" not found
284                return (invalid)
285        else
286                //found, get the three characters preceeding it
287                if (pos <=6)
288                        //not enough characters
289                        return (invalid)
290                else
291                        runStr = item[pos-7,pos-1]
292                        return (runStr)
293                Endif
294        Endif
295End
296
297//returns a string containing the full path to the file containing the
298//run number "num". The null string is returned if no valid file can be found.
299//
300//
301// search in the path "catPathName" (hard-wired), will abort if this path does not exist
302//the file returned will be a RAW SANS data file, other types of files are
303//filtered out.
304//
305// called by Buttons.ipf and Transmission.ipf, and locally by parsing routines
306//
307Function/S FindFileFromRunNumber(num)
308        Variable num
309       
310        String fullName="",partialName="",item="",numStr=""
311       
312        //make sure that path exists
313        PathInfo catPathName
314        String path = S_path
315        if (V_flag == 0)
316                Abort "folder path does not exist - use Pick Path button"
317        Endif
318
319        //make 7 digit string from run number
320        sprintf numStr,"%07u",num
321
322        //partialname = "QKK"+tmp_num+".nx.hdf"
323
324        String list="",newList="",testStr=""
325
326        list = IndexedFile(catPathName,-1,"????")       //get all files in folder
327        //find (the) one with the number in the run # location in the name
328        Variable numItems,ii,runFound,isRAW
329        numItems = ItemsInList(list,";")                //get the new number of items in the list
330        ii=0
331        do
332                //parse through the list in this order:
333                // 1 - does item contain run number (as a string) "QKKXXXXXXX.nx.hdf"
334                // 2 - exclude by isRaw? (to minimize disk access)
335                item = StringFromList(ii, list  ,";" )
336                if(strlen(item) != 0)
337                        //find the run number, if it exists as a three character string
338                        testStr = GetRunNumStrFromFile(item)
339                        runFound= cmpstr(numStr,testStr)        //compare the three character strings, 0 if equal
340                        if(runFound == 0)
341                                //the run Number was found
342                                //build valid filename
343                                partialName = FindValidFileName(item)
344                                if(strlen(partialName) != 0)            //non-null return from FindValidFileName()
345                                        fullName = path + partialName
346                                        //check if RAW, if so,this must be the file!
347                                        isRAW = CheckIfRawData(fullName)
348                                        if(isRaw)
349                                                //stop here
350                                                return(fullname)
351                                        Endif
352                                Endif
353                        Endif
354                Endif
355                ii+=1
356        while(ii<numItems)              //process all items in list
357        Return ("")     //null return if file not found in list
358End
359
360//function to test a file to see if it is a RAW SANS file
361//
362// returns truth 0/1
363//
364// called by many procedures (both external and local)
365//
366Function CheckIfRawData(fname)
367        String fname
368        Variable value = 0
369       
370        Variable hdfID,hdfgID
371        Variable isNXHDF = 0
372       
373        //nha. look for non-NeXus files
374        if (strsearch(fname, "nx.hdf", 0) >= 0)
375                isNXHDF = 1
376        endif
377
378        if(isNXHDF == 1)
379                //Need to actually determine if file is RAW data.
380                HDF5OpenFile/Z hdfID as fname
381                HDF5OpenGroup/Z hdfID, "/data", hdfgID
382                if (V_Flag == 0)
383                        //DIV file (with nx.hdf suffix)
384                        value = 0
385                else
386                        //Some other nx.hdf file
387                        value = 1
388                endif
389                HDF5CloseGroup/Z hdfgID
390                HDF5CloseFile/Z hdfID
391        else
392                value = 0
393        endif
394       
395        return(value)
396End
397
398Function isScatFile(fname)
399        String fname
400        Variable isTrans, isEmp
401        Variable value =1
402       
403        isTrans = isTransFile(fname)
404        isEmp = isEmpFile(fname)
405       
406        if(isTrans)
407                value = 0
408        endif
409        if(isEmp)
410                value = 0
411        endif
412        return(value)
413End
414
415Function isEmpFile(fName)
416        String fname
417
418        variable err
419        string dfName = ""
420        variable value = 0
421       
422        err = hdfRead(fname, dfName)
423        //err not handled here
424
425        Wave/T wSampleName = $(dfName+":sample:name")
426        String sampleName = wSampleName[0]
427       
428        if (cmpstr(sampleName,"MT beam")==0)
429                value = 1
430        endif
431       
432        return(value)
433End
434
435
436// function returns 1 if file is a transmission file, 0 if not
437//
438// called by Transmission.ipf, CatVSTable.ipf, NSORT.ipf
439//
440Function isTransFile(fName)
441        String fname
442
443// nha. TO DO. entry1 will have to change when the new naming convention for nxentry is implemented.
444
445        variable err
446        string dfName = ""
447        variable value = 0
448       
449        err = hdfRead(fname, dfName)
450        //err not handled here
451
452        Wave wTransmission_Flag = $(dfName+":sample:TransmissionFlag") //is only being set after 27/5/2009. ???
453        value = wTransmission_Flag[0]
454//     
455//   AJJ June 2nd 2010 - Unclear that this check is correct. Certainly BSPosXmm is not correct parameter in current data format...
456//      if (value == 0)
457//      //workaround - determine by bsx position
458//      Wave wBSX = $(dfName+":instrument:beam_stop:geometry:position:BSPosXmm")
459//      variable bsx = wBSX[0]
460//             
461//              if (bsx >= -10 )
462//                      value = 1
463//              endif
464//      endif
465
466        return(value)
467End
468
469
470//function to remove all spaces from names when searching for filenames
471//the filename (as saved) will never have interior spaces (TTTTTnnn_AB _Bnnn)
472//but the text field in the header may
473//
474//returns a string identical to the original string, except with the interior spaces removed
475//
476// local function for file name manipulation
477//
478// no change needed here
479Function/S RemoveAllSpaces(str)
480        String str
481       
482        String tempstr = str
483        Variable ii,spc,len             //should never be more than 2 or 3 trailing spaces in a filename
484        ii=0
485        do
486                len = strlen(tempStr)
487                spc = strsearch(tempStr," ",0)          //is the last character a space?
488                if (spc == -1)
489                        break           //no more spaces found, get out
490                endif
491                str = tempstr
492                tempStr = str[0,(spc-1)] + str[(spc+1),(len-1)] //remove the space from the string
493        While(1)        //should never be more than 2 or 3
494       
495        If(strlen(tempStr) < 1)
496                tempStr = ""            //be sure to return a null string if problem found
497        Endif
498       
499        //Print strlen(tempstr)
500       
501        Return(tempStr)
502               
503End
504
505
506//Function attempts to find valid filename from partial name by checking for
507// the existence of the file on disk
508//
509// returns a valid filename (No path prepended) or a null string
510//
511// called by any functions, both external and local
512//
513Function/S FindValidFilename(partialName)
514        String PartialName
515       
516        String retStr=""
517       
518        //try name with no changes - to allow for ABS files that have spaces in the names 12APR04
519        retStr = ValidFileString(partialName)
520        if(cmpstr(retStr,"") !=0)
521                //non-null return
522                return(retStr)
523        Endif
524       
525        //if the partial name is derived from the file header, there can be spaces at the beginning
526        //or in the middle of the filename - depending on the prefix and initials used
527        //
528        //remove any leading spaces from the name before starting
529        partialName = RemoveAllSpaces(partialName)
530       
531        //try name with no spaces
532        retStr = ValidFileString(partialName)
533        if(cmpstr(retStr,"") !=0)
534                //non-null return
535                return(retStr)
536        Endif
537       
538        //try all UPPERCASE
539        partialName = UpperStr(partialName)
540        retStr = ValidFileString(partialName)
541        if(cmpstr(retStr,"") !=0)
542                //non-null return
543                return(retStr)
544        Endif
545       
546        //try all lowercase (ret null if failure)
547        partialName = LowerStr(partialName)
548        retStr = ValidFileString(partialName)
549        if(cmpstr(retStr,"") !=0)
550                //non-null return
551                return(retStr)
552        else
553                return(retStr)
554        Endif
555
556End
557
558// Function checks for the existence of a file
559// partialName;vers (to account for VAX filenaming conventions)
560// The partial name is tried first with no version number
561//
562// *** the PATH is hard-wired to catPathName (which is assumed to exist)
563// version numers up to ;10 are tried
564// only the "name;vers" is returned if successful. The path is not prepended
565//
566// local function
567//
568Function/S ValidFileString(partialName)
569        String partialName
570       
571        String tempName = "",msg=""
572        Variable ii,refnum
573       
574        ii=0
575        do
576                if(ii==0)
577                        //first pass, try the partialName
578                        tempName = partialName
579                        Open/Z/R/T="????TEXT"/P=catPathName refnum tempName     //Does open file (/Z flag)
580                        if(V_flag == 0)
581                                //file exists
582                                Close refnum            //YES needed,
583                                break
584                        endif
585                else
586                        tempName = partialName + ";" + num2str(ii)
587                        Open/Z/R/T="????TEXT"/P=catPathName refnum tempName
588                        if(V_flag == 0)
589                                //file exists
590                                Close refnum
591                                break
592                        endif
593                Endif
594                ii+=1
595                //print "ii=",ii
596        while(ii<11)
597        //go get the selected bits of information, using tempName, which exists
598        if(ii>=11)
599                //msg = partialName + " not found. is version number > 11?"
600                //DoAlert 0, msg
601                //PathInfo catPathName
602                //Print S_Path
603                Return ("")             //use null string as error condition
604        Endif
605       
606        Return (tempName)
607End
608
609
610//returns a string containing filename (WITHOUT the ;vers)
611//the input string is a full path to the file (Mac-style, still works on Win in IGOR)
612//with the folders separated by colons
613//
614// called by MaskUtils.ipf, ProtocolAsPanel.ipf, WriteQIS.ipf
615//
616// NEEDS NO CHANGES
617//
618Function/S GetFileNameFromPathNoSemi(fullPath)
619        String fullPath
620       
621        Variable offset1,offset2
622        String filename=""
623        //String PartialPath
624        offset1 = 0
625        do
626                offset2 = StrSearch(fullPath, ":", offset1)
627                if (offset2 == -1)                              // no more colons ?
628                        fileName = FullPath[offset1,strlen(FullPath) ]
629                        //PartialPath = FullPath[0, offset1-1]
630                        break
631                endif
632                offset1 = offset2+1
633        while (1)
634       
635        //remove version number from name, if it's there - format should be: filename;N
636        filename =  StringFromList(0,filename,";")              //returns null if error
637       
638        Return filename
639End
640
641//returns a string containing filename (INCLUDING the ;vers)
642//the input string is a full path to the file (Mac-style, still works on Win in IGOR)
643//with the folders separated by colons
644//
645// local, currently unused
646//
647// NEEDS NO CHANGES
648//
649Function/S GetFileNameFromPathKeepSemi(fullPath)
650        String fullPath
651       
652        Variable offset1,offset2
653        String filename
654        //String PartialPath
655        offset1 = 0
656        do
657                offset2 = StrSearch(fullPath, ":", offset1)
658                if (offset2 == -1)                              // no more colons ?
659                        fileName = FullPath[offset1,strlen(FullPath) ]
660                        //PartialPath = FullPath[0, offset1-1]
661                        break
662                endif
663                offset1 = offset2+1
664        while (1)
665       
666        //keep version number from name, if it's there - format should be: filename;N
667       
668        Return filename
669End
670
671//given the full path and filename (fullPath), strips the data path
672//(Mac-style, separated by colons) and returns this path
673//this partial path is the same string that would be returned from PathInfo, for example
674//
675// - allows the user to save to a different path than catPathName
676//
677// called by WriteQIS.ipf
678//
679// NEEDS NO CHANGES
680//
681Function/S GetPathStrFromfullName(fullPath)
682        String fullPath
683       
684        Variable offset1,offset2
685        //String filename
686        String PartialPath
687        offset1 = 0
688        do
689                offset2 = StrSearch(fullPath, ":", offset1)
690                if (offset2 == -1)                              // no more colons ?
691                        //fileName = FullPath[offset1,strlen(FullPath) ]
692                        PartialPath = FullPath[0, offset1-1]
693                        break
694                endif
695                offset1 = offset2+1
696        while (1)
697       
698        Return PartialPath
699End
700
701//given the filename trim or modify the filename to get a new
702//file string that can be used for naming averaged 1-d files
703//
704// called by ProtocolAsPanel.ipf and Tile_2D.ipf
705//
706Function/S GetNameFromHeader(fullName)
707// given the fully qualified path and filename ie. fullName, return just the filename
708        String fullName
709        String newName = ""
710
711        //your code here
712        newName = ParseFilePath(0, fullName, ":", 1, 0)
713
714        Return(newName)
715End
716
717//list (input) is a list, typically returned from IndexedFile()
718//which is semicolon-delimited, and may contain filenames from the VAX
719//that contain version numbers, where the version number appears as a separate list item
720//(and also as a non-existent file)
721//these numbers must be purged from the list, especially for display in a popup
722//or list processing of filenames
723//the function returns the list, cleaned of version numbers (up to 11)
724//raw data files will typically never have a version number other than 1.
725//
726// if there are no version numbers in the list, the input list is returned
727//
728// called by CatVSTable.ipf, NSORT.ipf, Transmission.ipf, WorkFileUtils.ipf
729//
730//
731// NO CHANGE NEEDED
732//
733Function/S RemoveVersNumsFromList(list)
734        String list
735       
736        //get rid of version numbers first (up to 11)
737        Variable ii,num
738        String item
739        num = ItemsInList(list,";")
740        ii=1
741        do
742                item = num2str(ii)
743                list = RemoveFromList(item, list ,";" )
744                ii+=1
745        while(ii<12)
746       
747        return (list)
748End
749
750//input is a list of run numbers, and output is a list of filenames (not the full path)
751//*** input list must be COMMA delimited***
752//output is equivalent to selecting from the CAT table
753//if some or all of the list items are valid filenames, keep them...
754//if an error is encountered, notify of the offending element and return a null list
755//
756//output is COMMA delimited
757//
758// this routine is expecting that the "ask", "none" special cases are handled elsewhere
759//and not passed here
760//
761// called by Marquee.ipf, MultipleReduce.ipf, ProtocolAsPanel.ipf
762//
763// NO CHANGE NEEDED
764//
765Function/S ParseRunNumberList(list)
766        String list
767       
768        String newList="",item="",tempStr=""
769        Variable num,ii,runNum
770       
771        //expand number ranges, if any
772        list = ExpandNumRanges(list)
773       
774        num=itemsinlist(list,",")
775       
776        for(ii=0;ii<num;ii+=1)
777                //get the item
778                item = StringFromList(ii,list,",")
779
780                tempStr=FindValidFilename(item) //returns filename if good, null if error
781               
782                if(strlen(tempstr)!=0)
783                        //valid name, add to list
784                        //Print "it's a file"
785                                if(strlen(newList)==0)
786                                        newList = tempStr
787                                else
788                                        newList += "," + tempStr
789                                endif           
790                        else
791                        //not a valid name
792                        //is it a number?
793                        runNum=str2num(item)
794                        //print runnum
795                        if(numtype(runNum) != 0)
796                                //not a number -  maybe an error                       
797                                DoAlert 0,"List item "+item+" is not a valid run number or filename. Please enter a valid number or filename."
798                                return("")
799                        else
800                                //a run number or an error
801                                tempStr = GetFileNameFromPathNoSemi( FindFileFromRunNumber(runNum) )
802                                if(strlen(tempstr)==0)
803                                        //file not found, error
804                                        DoAlert 0,"List item "+item+" is not a valid run number. Please enter a valid number."
805                                        return("")
806                                else
807                                        newList += tempStr + ","
808                                endif
809                        endif
810                endif
811        endfor          //loop over all items in list
812       
813        return(newList)
814End
815
816//takes a comma delimited list that MAY contain number range, and
817//expands any range of run numbers into a comma-delimited list...
818//and returns the new list - if not a range, return unchanged
819//
820// local function
821//
822// NO CHANGE NEEDED
823//
824Function/S ExpandNumRanges(list)
825        String list
826       
827        String newList="",dash="-",item,str
828        Variable num,ii,hasDash
829       
830        num=itemsinlist(list,",")
831//      print num
832        for(ii=0;ii<num;ii+=1)
833                //get the item
834                item = StringFromList(ii,list,",")
835                //does it contain a dash?
836                hasDash = strsearch(item,dash,0)                //-1 if no dash found
837                if(hasDash == -1)
838                        //not a range, keep it in the list
839                        newList += item + ","
840                else
841                        //has a dash (so it's a range), expand (or add null)
842                        newList += ListFromDash(item)           
843                endif
844        endfor
845       
846        return newList
847End
848
849//be sure to add a trailing comma to the return string...
850//
851// local function
852//
853// NO CHANGE NEEDED
854//
855Function/S ListFromDash(item)
856        String item
857       
858        String numList="",loStr="",hiStr=""
859        Variable lo,hi,ii
860       
861        loStr=StringFromList(0,item,"-")        //treat the range as a list
862        hiStr=StringFromList(1,item,"-")
863        lo=str2num(loStr)
864        hi=str2num(hiStr)
865        if( (numtype(lo) != 0) || (numtype(hi) !=0 ) || (lo > hi) )
866                numList=""
867                return numList
868        endif
869        for(ii=lo;ii<=hi;ii+=1)
870                numList += num2str(ii) + ","
871        endfor
872       
873        Return numList
874End
875
876
877//returns the proper attenuation factor based on the instrument
878//
879// filestr is passed from TextRead[3] = the default directory, used to identify the instrument
880// lam is passed from RealsRead[26]
881// AttenNo is passed from ReaslRead[3]
882//
883// Attenuation factor as defined here is <= 1
884//
885// Facilities can pass ("",1,attenuationFactor) and have this function simply
886// spit back the attenuationFactor (that was read into rw[3])
887//
888// called by Correct.ipf, ProtocolAsPanel.ipf, Transmission.ipf
889//
890// atten_err is one std. deviation, passed back by reference
891Function AttenuationFactor(fileStr,lam,attenNo,atten_err)
892        String fileStr //
893        Variable lam,attenNo, &atten_err
894       
895        Variable attenFactor=1
896
897        // your code here       
898        attenFactor = LookupAtten(lam,attenNo)
899
900        // Change April 2011 - now returns error in atten trans
901        atten_err = 0
902
903        return(attenFactor)
904End
905
906Function LookupAtten(lambda,attenNo)
907        Variable lambda, attenNo
908       
909        Variable trans
910        String attStr="root:myGlobals:Attenuators:att"+num2str(trunc(attenNo))
911        String lamStr = "root:myGlobals:Attenuators:lambda"
912       
913        if(attenNo == 0)
914                return (1)              //no attenuation, return trans == 1
915        endif
916       
917//      if( (lambda < 5) || (lambda > 5 ) )
918//              Abort "Wavelength out of calibration range (5A). You must manually enter the absolute parameters"
919//      Endif
920       
921        if(!(WaveExists($attStr)) || !(WaveExists($lamStr)) )
922                Execute "MakeAttenTable()"
923        Endif
924        //just in case creating the tables fails....
925        if(!(WaveExists($attStr)) || !(WaveExists($lamStr)) )
926                Abort "Attenuator lookup waves could not be found. You must manually enter the absolute parameters"
927        Endif
928       
929        //lookup the value by interpolating the wavelength
930        //the attenuator must always be an integer
931       
932
933        Wave att = $attStr
934        Wave lam = $lamstr
935        //nha - commented below out until we have attenuation factors over multiple lambda values
936        //trans = interp(lambda,lam,att)
937       
938//      Print "trans = ",trans
939        //nha - delete this line when multiple lambda values
940        trans = att
941       
942        return trans
943End
944
945Proc MakeAttenTable()
946
947        NewDataFolder/O root:myGlobals:Attenuators
948        //do explicitly to avoid data folder problems, redundant, but it must work without fail
949
950        //Quokka specific nha.
951        Variable num=12         
952       
953        Make/O/N=(num) root:myGlobals:Attenuators:att0
954        Make/O/N=(num) root:myGlobals:Attenuators:att1
955        Make/O/N=(num) root:myGlobals:Attenuators:att2
956        Make/O/N=(num) root:myGlobals:Attenuators:att3
957        Make/O/N=(num) root:myGlobals:Attenuators:att4
958        Make/O/N=(num) root:myGlobals:Attenuators:att5
959        Make/O/N=(num) root:myGlobals:Attenuators:att6
960        Make/O/N=(num) root:myGlobals:Attenuators:att7
961        Make/O/N=(num) root:myGlobals:Attenuators:att8
962        Make/O/N=(num) root:myGlobals:Attenuators:att9
963        Make/O/N=(num) root:myGlobals:Attenuators:att10
964        Make/O/N=(num) root:myGlobals:Attenuators:att11
965       
966        // epg
967        // note 5A only at this stage but other wavelengths as measured
968        // these values have to be re-determined as were measured on time and not monitor counts
969        //Make/O/N=(num) root:myGlobals:Attenuators:lambda={5}
970        Make/O/N=(num) root:myGlobals:Attenuators:lambda={4.94}
971
972        //Quokka attenuator factors. 19/1/09 nha
973        //20/3/09 nha updated to
974        //file://fianna/Sections/Bragg/Data_Analysis_Team/Project/P025 Quokka Commissioning DRV/3_Development/ATTest-timeseries.pdf
975        //updated by epg 13-02-2010 to reflect kwo measurements at g7
976       
977        root:myGlobals:Attenuators:att0 = {1}
978        root:myGlobals:Attenuators:att1 = {0.498782}
979        root:myGlobals:Attenuators:att2 = {0.176433}
980        root:myGlobals:Attenuators:att3 = {0.0761367}
981        root:myGlobals:Attenuators:att4 = {0.0353985}
982        root:myGlobals:Attenuators:att5 = {0.0137137}
983        root:myGlobals:Attenuators:att6 = {0.00614167}
984        root:myGlobals:Attenuators:att7 = {0.00264554}
985        root:myGlobals:Attenuators:att8 = {0.000994504}
986        root:myGlobals:Attenuators:att9 = {0.000358897}
987        root:myGlobals:Attenuators:att10 = {7.2845e-05}
988        root:myGlobals:Attenuators:att11 = {1.67827e-06}
989
990End
991
992//function called by the popups to get a file list of data that can be sorted
993// this procedure simply removes the raw data files from the string - there
994//can be lots of other junk present, but this is very fast...
995//
996// could also use the alternate procedure of keeping only file with the proper extension
997//
998// another possibility is to get a listing of the text files, but is unreliable on
999// Windows, where the data file must be .txt (and possibly OSX)
1000//
1001// called by FIT_Ops.ipf, NSORT.ipf, PlotUtils.ipf
1002//
1003// modify for specific facilities by changing the "*.SA1*","*.SA2*","*.SA3*" stringmatch
1004// items which are specific to NCNR
1005//
1006Function/S ReducedDataFileList(ctrlName)
1007        String ctrlName
1008
1009        String list="",newList="",item=""
1010        Variable num,ii
1011       
1012        //check for the path
1013        PathInfo catPathName
1014        if(V_Flag==0)
1015                DoAlert 0, "Data path does not exist - pick the data path from the button on the main panel"
1016                Return("")
1017        Endif
1018       
1019        list = IndexedFile(catpathName,-1,"????")
1020        num=ItemsInList(list,";")
1021        //print "num = ",num
1022        for(ii=(num-1);ii>=0;ii-=1)
1023                item = StringFromList(ii, list  ,";")
1024                //simply remove all that are not raw data files (SA1 SA2 SA3)
1025                if( !stringmatch(item,"*.SA1*") && !stringmatch(item,"*.SA2*") && !stringmatch(item,"*.SA3*") )
1026                        if( !stringmatch(item,".*") && !stringmatch(item,"*.pxp") && !stringmatch(item,"*.DIV"))                //eliminate mac "hidden" files, pxp, and div files
1027                                if (!stringmatch(item,"*.nx.hdf") && !stringmatch(item,"*.bin") && !stringmatch(item,"*.mask"))
1028                                        newlist += item + ";"
1029                                endif
1030                        endif
1031                endif
1032        endfor
1033        //remove VAX version numbers
1034        newList = RemoveVersNumsFromList(newList)
1035        //sort
1036        newList = SortList(newList,";",0)
1037
1038        return newlist
1039End
1040
1041// returns a list of raw data files in the catPathName directory on disk
1042// - list is SEMICOLON-delimited
1043//
1044// called by PatchFiles.ipf, Tile_2D.ipf
1045//
1046Function/S GetRawDataFileList()
1047       
1048        //nha. Reads Quokka file names 5/2/09
1049       
1050        //make sure that path exists
1051        PathInfo catPathName
1052        if (V_flag == 0)
1053                Abort "Folder path does not exist - use Pick Path button on Main Panel"
1054        Endif
1055
1056        String list=IndexedFile(catPathName,-1,"????")
1057        String newList="",item=""
1058        Variable num=ItemsInList(list,";"),ii
1059        for(ii=0;ii<num;ii+=1)
1060                item = StringFromList(ii, list  ,";")
1061                if( stringmatch(item,"*.nx.hdf") )
1062                        newlist += item + ";"
1063                endif
1064                //print "ii=",ii
1065        endfor
1066        newList = SortList(newList,";",0)
1067        return(newList)
1068       
1069        // your code here
1070       
1071        return(list)
1072End
1073
1074//**********************
1075// 2D resolution function calculation - in terms of X and Y
1076//
1077// based on notes from David Mildner, 2008
1078//
1079// the final NCNR version is located in NCNR_Utils.ipf
1080//
1081Function/S get2DResolution(inQ,phi,lambda,lambdaWidth,DDet,apOff,S1,S2,L1,L2,BS,del_r,usingLenses,r_dist,SigmaQX,SigmaQY,fSubS)
1082        Variable inQ, phi,lambda, lambdaWidth, DDet, apOff, S1, S2, L1, L2, BS, del_r,usingLenses,r_dist
1083        Variable &SigmaQX,&SigmaQY,&fSubS               //these are the output quantities at the input Q value
1084       
1085        return("Function Empty")
1086End
1087
1088// Return the filename that represents the previous or next file.
1089// Input is current filename and increment.
1090// Increment should be -1 or 1
1091// -1 => previous file
1092// 1 => next file
1093Function/S GetPrevNextRawFile(curfilename, prevnext)
1094        String curfilename
1095        Variable prevnext
1096
1097        String filename
1098       
1099        //get the run number
1100        Variable num = GetRunNumFromFile(curfilename)
1101               
1102        //find the next specified file by number
1103        fileName = FindFileFromRunNumber(num+prevnext)
1104
1105        if(cmpstr(fileName,"")==0)
1106                //null return, do nothing
1107                fileName = FindFileFromRunNumber(num)
1108        Endif
1109
1110//      print "in FU "+filename
1111
1112        Return filename
1113End
Note: See TracBrowser for help on using the repository browser.