source: sans/Dev/trunk/NCNR_User_Procedures/Reduction/SANS/HFIR_Utils.ipf @ 890

Last change on this file since 890 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: 32.5 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// initializes globals that are specific to a particular facility
13// - number of XY pixels
14// - pixexl resolution [cm]
15// - detector deadtime constant [s]
16//
17// called by Initialize.ipf
18//
19Function InitFacilityGlobals()
20
21        //Detector -specific globals
22        Variable/G root:myGlobals:gNPixelsX=192                                 // number of detector X and Y pixels
23        Variable/G root:myGlobals:gNPixelsY=192
24       
25        // pixel dimensions are now read directly from the file header.
26        Variable/G root:myGlobals:PixelResDefault = 0.51        //pixel resolution in cm
27        //No dead time measured for HFIR detector but the count rate is set very low. For now, set the detector perfect.
28        // This should be updated when the condition is changed.   JHC 09/02/09
29        Variable/G root:myGlobals:DeadtimeDefault =  0       //3.4e-6 (NIST value)      //deadtime in seconds
30
31        Variable/G root:myGlobals:apOff = 5.0           // (cm) distance from sample aperture to sample positio
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
139//Utility function that returns the detector resolution (in cm)
140//Global values are set in the Initialize procedure
141//
142// - called by CircSectAvg.ipf, RectAnnulAvg.ipf, and ProtocolAsPanel.ipf
143//
144// fileStr is passed as TextRead[3] and is the filename
145// detStr is passed as TextRead[9] and is an identifier for the detector
146//
147// depricated - pixel dimensions are read directly from the file header
148Function xDetectorPixelResolution(fileStr,detStr)
149        String fileStr,detStr
150       
151        Variable DDet
152        NVAR PixelResDefault = root:myGlobals:PixelResDefault
153        //your code here
154        DDet = PixelResDefault  //0.515 cm, typical for new ORNL detectors
155        return(DDet)
156End
157
158//Utility function that returns the detector deadtime (in seconds)
159//Global values are set in the Initialize procedure
160//
161// - called by WorkFileUtils.ipf
162//
163// fileStr is passed as TextRead[3] and is the filename
164// detStr is passed as TextRead[9] and is an identifier for the detector
165//
166// [dateAndTimeStr] is optional, and could be used as a switch for
167// different historical detector configurations
168Function DetectorDeadtime(fileStr,detStr,[dateAndTimeStr])
169        String fileStr,detStr,dateAndTimeStr
170       
171        Variable deadtime
172        NVAR DeadtimeDefault = root:myGlobals:DeadtimeDefault
173       
174        deadtime = DeadtimeDefault      //3.4e-6 seconds, typical for new ORNL detectors //???????????????????????????
175        return(deadtime)
176End
177
178
179
180// item is a filename
181//
182// this function extracts some sort of number from the file
183// presumably some sort of automatically incrementing run number set by the
184// acquisition system
185//
186// this run number should be a unique identifier for the file
187//Because HFIR data format is w/ 2X 4digit number. We add them to get a unique number => This will cause the arrow button not working.
188Function GetRunNumFromFile(item)
189        String item
190        Variable invalid = -1   //negative numbers are invalid
191        Variable num=-1
192       
193        //find the "dot"
194        String runStr=""
195        Variable pos = strsearch(item,".",0)
196        if(pos == -1)
197                //"dot" not found
198                return (invalid)
199        else
200                //found, get the nine characters preceeding it
201                if (pos <=8)
202                        //not enough characters
203                        return (invalid)
204                else
205                        Variable pos_bio = strsearch( LowerStr(item),"biosans",0)
206                        //if  (pos_bio== -1)
207                                runStr  = item[pos-9,pos-6]     //first 4 numbers
208                        //else
209                                runStr  += item[pos-4,pos-1]    //add last 4 numbers
210                        //endif
211                        //convert to a number
212                        num = str2num(runStr)
213                       
214                        //if valid, return it
215                        if (num == NaN)
216                                //8 characters were not a number
217                                return (invalid)
218                        else
219                                //run was OK
220                                return (num)
221                        Endif
222                Endif
223        Endif
224       
225End
226
227
228// item is a filename
229//
230// this function extracts some sort of number from the file
231// presumably some sort of automatically incrementing run number set by the
232// acquisition system
233//
234// this run number should be a unique identifier for the file
235//
236// same as GetRunNumFromFile(0), just with a string return
237//
238// "ABC" returned as an invalid result
239// XXXXSANS_expXX._scan1234_5678.xmp ==> "12345678"
240// -- result is an 8-character string
241//
242Function/S GetRunNumStrFromFile(item)   //,numposition)
243        String item
244        Variable numposition
245       
246        String invalid = "ABC"  //"ABC" is not a valid run number, since it's text
247        String retStr
248        retStr=invalid
249
250        //find the "dot"
251        Variable pos = strsearch( LowerStr(item),".xml",0)
252        if(pos == -1)
253                //"dotxml" not found
254                return (retStr)
255        else
256                pos = strsearch( LowerStr(item),"_scan",0)
257               
258                if  (pos == -1)
259                        //not a raw data file
260                        return (retStr)
261                else
262                        //Variable pos_bio = strsearch( LowerStr(item),"biosans_",0)  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
263                        //if  (numposition == 0)
264                                //Take the first four: //HiResSANS
265                                retStr = item[pos+5,pos+8]
266                        //else 
267                                //add the last four: //BioSANS
268                                retStr += item[pos+10,pos+13]
269                        //Endif
270                        return (retStr)
271                Endif
272        Endif
273       
274End
275
276//returns a string containing the full path to the file containing the
277//run number "num". The null string is returned if no valid file can be found.
278//
279//
280// search in the path "catPathName" (hard-wired), will abort if this path does not exist
281//the file returned will be a RAW SANS data file, other types of files are
282//filtered out.
283//
284// called by Buttons.ipf and Transmission.ipf, and locally by parsing routines
285//
286Function/S FindFileFromRunNumber(num)
287        Variable num
288
289        String fullName="",partialName="",item=""
290        //get list of raw data files in folder that match "num" (add leading zeros)
291        if( (num>99999999) || (num<0) )
292                //Print "error in  FindFileFromRunNumber(num), file number too large or too small"
293                Return ("")
294        Endif
295        //make a four character string of the run number
296        String numStr=""
297       
298        if(num > 9999999 && num < 100000000)
299                numStr = num2istr(num)
300        endif
301        if(num > 999999 && num < 10000000)
302                numStr = "0"+num2istr(num)
303        endif   
304        if(num > 99999 && num < 1000000)
305                numStr = "00"+num2istr(num)
306        endif   
307        if(num > 9999 && num < 100000)
308                numStr = "000"+num2istr(num)
309        endif
310        if(num > 999 && num < 10000)
311                numStr =  "0000"+num2istr(num)
312        endif
313        if(num > 99 && num < 1000)
314                numStr = "00000"+num2istr(num)
315        endif   
316        if(num > 9 && num < 100)
317                numStr = "000000"+num2istr(num)
318        endif   
319        if(num < 10 && num >0)
320                numStr = "0000000"+num2iStr(num)
321        endif
322        if(num == 0)
323                numStr = "00000000"
324        endif
325
326        //make sure that path exists
327        PathInfo catPathName
328        String path = S_path
329        if (V_flag == 0)
330                Abort "folder path does not exist - use Pick Path button"
331        Endif
332        String list="",newList="",testStr=""
333       
334        list = IndexedFile(catPathName,-1,"????")       //get all files in folder
335        //find (the) one with the number in the run # location in the name
336        Variable numItems,ii,runFound,isRAW
337        numItems = ItemsInList(list,";")                //get the new number of items in the list
338
339        ii=0
340        do
341                //parse through the list in this order:
342                // 1 - does item contain run number (as a string) "NAMESANS_expNN_scan####_####.xml" : Let's check the 8  nums.
343                // 2 - exclude by isRaw? (to minimize disk access)
344                item = StringFromList(ii, list  ,";" )
345               
346                if(strlen(item) != 0)
347                        //find the run number, if it exists as a 8 character string
348                        testStr = GetRunNumStrFromFile(item)    //0)
349                        runFound= cmpstr(numStr,testStr)        //compare the three character strings, 0 if equal
350                       
351                        if(runFound == 0)
352                                //the run Number was found
353                                //build valid filename
354                                partialName = FindValidFileName(item)
355                               
356                                if(strlen(partialName) != 0)            //non-null return from FindValidFileName()
357                                        fullName = path + partialName
358                                        //check if RAW, if so,this must be the file!
359                                        isRAW = CheckIfRawData(fullName)
360                                        if(isRaw)
361                                                //stop here
362                                                return(fullname)
363                                        Endif
364                                Endif
365                        Endif
366                       
367                Endif
368                ii+=1
369        while(ii<numItems)              //process all items in list
370        print "The run number (", numStr, " +- 1 ) does not exist... (Note: The run number is defined as 12345678 if the file name is NameSANS_exp##_scan1234_5678.xml)"
371        Return ("")     //null return if file not found in list
372End
373
374
375//make an (N) character string of the run number
376//Moved to facility utils
377//
378// same scheme to get 8-character string as in GetRunNumStrFromFile(item)
379//
380Function/S RunDigitString(num)
381        Variable num
382
383        String numStr=""
384
385        //make 8 digit string from run number
386        sprintf numStr,"%08u",num
387       
388        if(strlen(numStr) > 8)
389                return("")
390        else
391                return(numstr)
392        endif
393       
394End
395
396//given a filename of a SANS data filename of the form
397//TTTTTnnn.SAn_TTT_Txxx
398//returns the prefix "TTTTT" as some number of characters
399//returns "" as an invalid file prefix
400//
401// HFIR writes out files with a "prefix" of the following -- since there is really no "prefix"
402// like in the VAX scheme:
403//                      newFileName = ReplaceString(".xml",textPath[0],"")              //removes 4 chars
404//                      newFileName = ReplaceString("SANS",newFileName,"")              //removes 4 more chars = 8
405//                      newFileName = ReplaceString("exp",newFileName,"")                       //removes 3 more chars = 11
406//                      newFileName = ReplaceString("scan",newFileName,"")              //removes 4 more chars = 15, should be enough?
407//
408//
409// -- so the raw data:          BioSANS_exp9_scan1828_0001.xml
410// -- translates to:            Bio_9_1828_0001.AVE     
411//
412//
413// NCNR-specifc, does not really belong here - it's a beta procedure used for the
414// Combine Files Panel, and I'm not sure of how I'm really going to get this to work properly
415// since the .ABS file written is not of the form that NSORT->Set3NSORTFiles(low,med,hi,pref)
416// is trying to construct
417//
418// changed (Oct 2010) the naming for HFIR from ExecuteProtocol to:
419//                      newFileName = GetPrefixStrFromFile(textPath[0])+GetRunNumStrFromFile(textPath[0])
420// -- translates to:            BioSANS18280001.AVE
421//
422Function/S GetPrefixStrFromFile(item)
423        String item
424        String invalid = ""     //"" is not a valid run prefix, since it's text
425        Variable num=-1
426       
427        //find the "dash"
428        String runStr=""
429        Variable pos = strsearch(item,"_",0)
430        if(pos == -1)
431                //"dot" not found
432                return (invalid)
433        else
434                //found
435                if (pos <=3)
436                        //not enough characters
437                        return (invalid)
438                else
439                        runStr = item[0,pos-1]
440                        return (runStr)
441                Endif
442        Endif
443End
444
445
446
447//function to test a binary file to see if it is a RAW binary SANS file
448//first checks the total bytes in the file (which for raw data is 33316 bytes)
449//**note that the "DIV" file will also show up as a raw file by the run field
450//should be listed in CAT/SHORT and in patch windows
451//
452//Function then checks the file fname (full path:file) for "RAW" run.type field
453//if not found, the data is not raw data and zero is returned
454//
455// called by many procedures (both external and local)
456//
457Function CheckIfRawData(fname)
458        String fname
459             
460        String tempheadhfir                                           
461        Variable ind=0
462        Variable refNum
463       
464        //If not have .xml extension, return 0.
465        if (stringmatch(fname,"*.xml") <1)
466                print fname+": Failed. Not a *.xml file."
467                return 0                                //Not *.xml. Do nothing...
468        endif
469        //actually open the file
470        refNum = XmlOpenFile(fname)     
471        if (refNum < 0)
472                print "==> "+ fname+ "\r  ==> Failed to load: Not a standard xml file format or broken.. Please check the file if properly written..."
473                return 0                                //Not a xml file. Do nothing...
474        endif
475       
476        // Check if  it is the SPICE version = 1.1
477        Variable  item,i,ns = 0
478        String thislocation
479        if (refNum >0)
480                ns = str2num(XMLstrFmXpath(refNum, "//SPICErack/@SPICE_version","",""))
481        endif
482        XmlCloseFile(refNum,0)
483        if (ns <1.1)
484                ns =0
485        else
486                ns =1
487        endif
488       
489        return ns
490End
491
492// for HFIR data, both DIV and RAW are determined by looking for "*.xml"
493Function CheckIfDIVData(fname)
494        String fname
495        return(CheckIfRawData(fname))
496End
497
498// function returns 1 if file is a transmission file, 0 if not
499//
500// called by Transmission.ipf, CatVSTable.ipf, NSORT.ipf
501//
502// SRK MAR 2010 - apparently from what I can see in the files, the beam stop "out"
503// position is 25 mm for all four beam stop Y POSITIONS
504// - if one is larger, (in the hundreds of mm) then it's in, and the run is not a transmission
505// - so if all four y positions are less than (tol) 30 mm, call it a trans file
506//
507// there is a field for this in the header, write "True", so I don't need to guess again.
508// -- but this field is often incorrect - for some sample data ALL FILES were "True"
509// -- better to check the physical location every time
510//
511// tol changed to 401 per Gernot's experience 6/24/10
512//
513Function isTransFile(fName)   ///  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
514        String fname
515       
516        Variable beamtrap_1y=0,beamtrap_2y=0,beamtrap_3y=0,beamtrap_4y=0,tol=401
517        //Check by key "transsmission"
518//      if (stringmatch( getIsTrans(fName),"True")>0)
519//              return (1)
520//      else
521                //Check from beam stop motor position
522        //      if(your test here)
523                beamtrap_1y=getRealValueFromHeader(fname,"//Motor_Positions/trap_y_101mm","mm")
524                beamtrap_2y=getRealValueFromHeader(fname,"//Motor_Positions/trap_y_25mm","mm")
525                beamtrap_3y=getRealValueFromHeader(fname,"//Motor_Positions/trap_y_50mm","mm")
526                beamtrap_4y=getRealValueFromHeader(fname,"//Motor_Positions/trap_y_76mm","mm")
527
528                if (beamtrap_1y < tol && beamtrap_2y < tol && beamtrap_3y < tol && beamtrap_4y < tol)   
529                        //Write the flag ON
530                        Write_isTransmissionToHeader(fName,"True")
531                        return (1)
532                else
533                        //some other file
534                        Write_isTransmissionToHeader(fName,"False")
535                        return (0)
536                endif
537               
538//      endif
539
540        return (0)
541End
542
543
544
545//function to remove all spaces from names when searching for filenames
546//the filename (as saved) will never have interior spaces (TTTTTnnn_AB _Bnnn)
547//but the text field in the header WILL, if less than 3 characters were used for the
548//user's initials, and can have leading spaces if prefix was less than 5 characters
549//
550//returns a string identical to the original string, except with the interior spaces removed
551//
552// local function for file name manipulation
553//
554// NO CHANGE NEEDED
555//
556Function/S RemoveAllSpaces(str)
557        String str
558       
559        String tempstr = str
560        Variable ii,spc,len             //should never be more than 2 or 3 trailing spaces in a filename
561        ii=0
562        do
563                len = strlen(tempStr)
564                spc = strsearch(tempStr," ",0)          //is the last character a space?
565                if (spc == -1)
566                        break           //no more spaces found, get out
567                endif
568                str = tempstr
569                tempStr = str[0,(spc-1)] + str[(spc+1),(len-1)] //remove the space from the string
570        While(1)        //should never be more than 2 or 3
571       
572        If(strlen(tempStr) < 1)
573                tempStr = ""            //be sure to return a null string if problem found
574        Endif
575       
576        //Print strlen(tempstr)
577       
578        Return(tempStr)
579               
580End
581
582
583
584//Function attempts to find valid filename from partial name by checking for
585// the existence of the file on disk
586//
587// returns a valid filename (No path prepended) or a null string
588//
589// called by any functions, both external and local
590//
591Function/S FindValidFilename(partialName)
592        String PartialName
593       
594        String retStr=partialName
595
596        //your code here
597        //try name with no changes - to allow for ABS files that have spaces in the names 12APR04
598        retStr = ValidFileString(partialName)
599        if(cmpstr(retStr,"") !=0)
600                return(retStr)
601        endif
602       
603        //if the partial name is derived from the file header, there can be spaces at the beginning
604        //or in the middle of the filename - depending on the prefix and initials used
605        //
606        //remove any leading spaces from the name before starting
607        partialName = RemoveAllSpaces(partialName)
608       
609        //try name with no spaces
610        retStr = ValidFileString(partialName)
611        if(cmpstr(retStr,"") !=0)
612                //non-null return
613                return(retStr)
614        endif
615       
616        //try all UPPERCASE
617        partialName = UpperStr(partialName)
618        retStr = ValidFileString(partialName)
619        if(cmpstr(retStr,"") !=0)
620                //non-null return
621                return(retStr)
622        endif
623       
624        //try all lowercase (ret null if failure)
625        partialName = LowerStr(partialName)
626        retStr = ValidFileString(partialName)
627        if(cmpstr(retStr,"") !=0)
628                //non-null return
629                return(retStr)
630        else
631                return(retStr)
632        endif
633End
634
635// Function checks for the existence of a file
636
637// *** the PATH is hard-wired to catPathName (which is assumed to exist)
638// version numers up to ;10 are tried
639// only the "name;vers" is returned if successful. The path is not prepended
640//
641// local function
642//
643Function/S ValidFileString(partialName)
644        String partialName
645       
646        String tempName = "",msg=""
647        Variable ii,refnum
648
649        ii=0
650        do
651                if(ii==0)
652                        //first pass, try the partialName
653                        tempName = partialName
654                        Open/Z/R/T="????TEXT"/P=catPathName refnum tempName     //Does open file (/Z flag)
655                        if(V_flag == 0)
656                                //file exists
657                                Close refnum            //YES needed,
658                                break
659                        endif
660                else
661                        tempName = partialName + ";" + num2str(ii)
662                        Open/Z/R/T="????TEXT"/P=catPathName refnum tempName
663                        if(V_flag == 0)
664                                //file exists
665                                Close refnum
666                                break
667                        endif
668                Endif
669                ii+=1
670
671        while(ii<11)
672        //go get the selected bits of information, using tempName, which exists
673        if(ii>=11)
674                //msg = partialName + " not found. is version number > 11?"
675                //DoAlert 0, msg
676                //PathInfo catPathName
677                //Print S_Path
678                Return ("")             //use null string as error condition
679        Endif
680               
681        Return (tempName)
682End
683
684
685//returns a string containing filename (WITHOUT the ;vers)
686//the input string is a full path to the file (Mac-style, still works on Win in IGOR)
687//with the folders separated by colons
688//
689// called by MaskUtils.ipf, ProtocolAsPanel.ipf, WriteQIS.ipf
690//
691// NO CHANGE NEEDED
692//
693
694Function/S GetFileNameFromPathNoSemi(fullPath)
695        String fullPath
696       
697        Variable offset1,offset2
698        String filename=""
699        //String PartialPath
700        offset1 = 0
701        do
702                offset2 = StrSearch(fullPath, ":", offset1)
703                if (offset2 == -1)                              // no more colons ?
704                        fileName = FullPath[offset1,strlen(FullPath) ]
705                        //PartialPath = FullPath[0, offset1-1]
706                        break
707                endif
708                offset1 = offset2+1
709        while (1)
710       
711        //remove version number from name, if it's there - format should be: filename;N
712        filename =  StringFromList(0,filename,";")              //returns null if error
713       
714        Return filename
715End
716
717//returns a string containing filename (INCLUDING the ;vers)
718//the input string is a full path to the file (Mac-style, still works on Win in IGOR)
719//with the folders separated by colons
720//
721// local, currently unused
722//
723// NO CHANGE NEEDED
724//
725
726Function/S GetFileNameFromPathKeepSemi(fullPath)
727        String fullPath
728       
729        Variable offset1,offset2
730        String filename
731        //String PartialPath
732        offset1 = 0
733        do
734                offset2 = StrSearch(fullPath, ":", offset1)
735                if (offset2 == -1)                              // no more colons ?
736                        fileName = FullPath[offset1,strlen(FullPath) ]
737                        //PartialPath = FullPath[0, offset1-1]
738                        break
739                endif
740                offset1 = offset2+1
741        while (1)
742       
743        //keep version number from name, if it's there - format should be: filename;N
744       
745        Return filename
746End
747
748//given the full path and filename (fullPath), strips the data path
749//(Mac-style, separated by colons) and returns this path
750//this partial path is the same string that would be returned from PathInfo, for example
751//
752// - allows the user to save to a different path than catPathName
753//
754// called by WriteQIS.ipf
755//
756// NO CHANGE NEEDED
757//
758
759Function/S GetPathStrFromfullName(fullPath)
760        String fullPath
761       
762        Variable offset1,offset2
763        //String filename
764        String PartialPath
765        offset1 = 0
766        do
767                offset2 = StrSearch(fullPath, ":", offset1)
768                if (offset2 == -1)                              // no more colons ?
769                        //fileName = FullPath[offset1,strlen(FullPath) ]
770                        PartialPath = FullPath[0, offset1-1]
771                        break
772                endif
773                offset1 = offset2+1
774        while (1)
775       
776        Return PartialPath
777End
778
779//given the filename trim or modify the filename to get a new
780//file string that can be used for naming averaged 1-d files
781//
782// called by ProtocolAsPanel.ipf and Tile_2D.ipf
783//
784Function/S GetNameFromHeader(fName)
785        String fName
786        String temp, newName = ""
787        Variable spc,ii=0
788       
789        //filename is 31-33 characters INSTRNAMESANS_exp##_scan####_####.xml (where # : numbers)
790        //returns a null string if no name can be found
791        Variable iimax =  strlen(fName)
792        do
793                temp = fname[ii,iimax-1-4]              //characters ii,all of the name
794                spc = strsearch(temp," ",0)
795                if (spc == -1)
796                        break           //no more spaces found
797                endif
798                ii+=1
799        While(ii<iimax)
800       
801        If(strlen(temp) < 1)
802                newName = ""            //be sure to return a null string if problem found
803        else
804                newName = temp
805        Endif
806       
807        Return(newName)
808End
809
810//list (input) is a list, typically returned from IndexedFile()
811//which is semicolon-delimited, and may contain filenames from the VAX
812//that contain version numbers, where the version number appears as a separate list item
813//(and also as a non-existent file)
814//these numbers must be purged from the list, especially for display in a popup
815//or list processing of filenames
816//the function returns the list, cleaned of version numbers (up to 11)
817//raw data files will typically never have a version number other than 1.
818//
819// if there are no version numbers in the list, the input list is returned
820//
821// called by CatVSTable.ipf, NSORT.ipf, Transmission.ipf, WorkFileUtils.ipf
822//
823// NO CHANGE NEEDED
824//
825
826Function/S RemoveVersNumsFromList(list)
827        String list
828       
829        //get rid of version numbers first (up to 11)
830        Variable ii,num
831        String item
832        num = ItemsInList(list,";")
833        ii=1
834        do
835                item = num2str(ii)
836                list = RemoveFromList(item, list ,";" )
837                ii+=1
838        while(ii<12)
839       
840        return (list)
841End
842
843//input is a list of run numbers, and output is a list of filenames (not the full path)
844//*** input list must be COMMA delimited***
845//output is equivalent to selecting from the CAT table
846//if some or all of the list items are valid filenames, keep them...
847//if an error is encountered, notify of the offending element and return a null list
848//
849//output is COMMA delimited
850//
851// this routine is expecting that the "ask", "none" special cases are handled elsewhere
852//and not passed here
853//
854// called by Marquee.ipf, MultipleReduce.ipf, ProtocolAsPanel.ipf
855//
856// NO CHANGE NEEDED
857//
858
859Function/S ParseRunNumberList(list)
860        String list
861       
862        String newList="",item="",tempStr=""
863        Variable num,ii,runNum
864       
865        //expand number ranges, if any
866        list = ExpandNumRanges(list)
867       
868        num=itemsinlist(list,",")
869       
870        for(ii=0;ii<num;ii+=1)
871                //get the item
872                item = StringFromList(ii,list,",")
873                //is it already a valid filename?
874               
875                tempStr=FindValidFilename(item) //returns filename if good, null if error
876                if(strlen(tempstr)!=0)
877                        //valid name, add to list
878                        //Print "it's a file"
879                        newList += tempStr + ","
880                else
881                        //not a valid name
882                        //is it a number?
883                        runNum=str2num(item)
884
885                        if(numtype(runNum) != 0)
886                                //not a number -  maybe an error                       
887                                DoAlert 0,"List item "+item+" is not a valid run number or filename. Please enter a valid number or filename."
888                                return("")
889                        else
890                                //a run number or an error
891                                tempStr = GetFileNameFromPathNoSemi( FindFileFromRunNumber(runNum) )
892                                if(strlen(tempstr)==0)
893                                        //file not found, error
894                                        DoAlert 0,"List item "+item+" is not a valid run number. Please enter a valid number."
895                                        return("")
896                                else
897                                        newList += tempStr + ","
898                                endif
899                        endif
900                endif
901        endfor          //loop over all items in list
902
903        return(newList)
904End
905
906//takes a comma delimited list that MAY contain number range, and
907//expands any range of run numbers into a comma-delimited list...
908//and returns the new list - if not a range, return unchanged
909//
910// local function
911//
912// NO CHANGE NEEDED
913//
914
915Function/S ExpandNumRanges(list)
916        String list
917       
918        String newList="",dash="-",item,str
919        Variable num,ii,hasDash
920       
921        num=itemsinlist(list,",")
922
923        for(ii=0;ii<num;ii+=1)
924                //get the item
925                item = StringFromList(ii,list,",")
926                //does it contain a dash?
927                hasDash = strsearch(item,dash,0)                //-1 if no dash found
928                if(hasDash == -1)
929                        //not a range, keep it in the list
930                        newList += item + ","
931                else
932                        //has a dash (so it's a range), expand (or add null)
933                        newList += ListFromDash(item)           
934                endif
935        endfor
936       
937        return newList
938End
939
940//be sure to add a trailing comma to the return string...
941//
942// local function
943//
944// NO CHANGE NEEDED
945//
946Function/S ListFromDash(item)
947        String item
948       
949        String numList="",loStr="",hiStr=""
950        Variable lo,hi,ii
951       
952        loStr=StringFromList(0,item,"-")        //treat the range as a list
953        hiStr=StringFromList(1,item,"-")
954        lo=str2num(loStr)
955        hi=str2num(hiStr)
956        if( (numtype(lo) != 0) || (numtype(hi) !=0 ) || (lo > hi) )
957                numList=""
958                return numList
959        endif
960        for(ii=lo;ii<=hi;ii+=1)
961                numList += num2str(ii) + ","
962        endfor
963       
964        Return numList
965End
966
967
968//returns the proper attenuation factor based on the instrument
969//
970// filestr is passed from TextRead[3] = the default directory, used to identify the instrument
971// lam is passed from RealsRead[26]
972// AttenNo is passed from ReaslRead[3]
973//
974// Attenuation factor as defined here is <= 1
975//
976// Facilities can pass ("",1,attenuationFactor) and have this function simply
977// spit back the attenuationFactor (that was read into rw[3])
978//
979// called by Correct.ipf, ProtocolAsPanel.ipf, Transmission.ipf
980//
981// atten_err is one std. deviation, passed back by reference
982Function AttenuationFactor(fileStr,lam,attenuation, atten_err)
983        String fileStr
984        Variable lam,attenuation, &atten_err  //    0 =< attenuation <= 100 (%) : where no attenuator stands for 0.
985       
986        Variable attenFactor=1
987       
988        // your code here
989        attenFactor = 1- attenuation*0.01  //???Attenuate transmission
990
991        // Change April 2011 - now returns error in atten trans
992        atten_err = 0
993       
994        return(attenFactor)
995End
996
997//function called by the popups to get a file list of data that can be sorted
998// this procedure simply removes the raw data files from the string - there
999//can be lots of other junk present, but this is very fast...
1000//
1001// could also use the alternate procedure of keeping only file with the proper extension
1002//
1003// another possibility is to get a listing of the text files, but is unreliable on
1004// Windows, where the data file must be .txt (and possibly OSX)
1005//
1006// called by FIT_Ops.ipf, NSORT.ipf, PlotUtils.ipf
1007//
1008Function/S ReducedDataFileList(ctrlName)
1009        String ctrlName
1010
1011        String list="",newList="",item=""
1012        Variable num,ii
1013       
1014        //check for the path
1015        PathInfo catPathName
1016        if(V_Flag==0)
1017                DoAlert 0, "Data path does not exist - pick the data path from the button on the main panel"
1018                Return("")
1019        Endif
1020       
1021        list = IndexedFile(catpathName,-1,"????")
1022        num=ItemsInList(list,";")
1023
1024        for(ii=(num-1);ii>=0;ii-=1)
1025                item = StringFromList(ii, list  ,";")
1026                //simply remove all that are not raw data files (SA1 SA2 SA3)
1027                //if( !stringmatch(item,"*HiResSANS*.xml") && !stringmatch(item,"*BioSANS*.xml"))
1028                        if( !stringmatch(item,".*") && !stringmatch(item,"*.pxp") && !stringmatch(item,"*.DIV"))                //eliminate mac "hidden" files, pxp, and div files
1029                                newlist += (item) + ";"   
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// does it the "cheap" way, simply finding the ".SAn" in the file name
1045// = does not check for proper byte length.
1046//
1047// called by PatchFiles.ipf, Tile_2D.ipf
1048//
1049Function/S GetRawDataFileList()
1050       
1051        //make sure that path exists
1052        PathInfo catPathName
1053        if (V_flag == 0)
1054                Abort "Folder path does not exist - use Pick Path button on Main Panel"
1055        Endif
1056       
1057        String list=IndexedFile(catPathName,-1,"????")
1058        String newList="",item=""
1059        Variable num=ItemsInList(list,";"),ii
1060        for(ii=0;ii<num;ii+=1)
1061                item = StringFromList(ii, list  ,";")
1062                if( stringmatch(item,"*.xml") )
1063                        if (CheckIfRawData(S_path+item) >0)
1064                                newlist += item + ";"
1065                        endif
1066                endif
1067                // if condition is in here twice, not sure why since they are both "*.xml"
1068//              if( stringmatch(item,"*.xml") )
1069//                      if (CheckIfRawData(S_path+item) >0)
1070//                              newlist += item + ";"
1071//                      endif
1072//              endif
1073        endfor
1074        newList = SortList(newList,";",0)
1075        return(newList)
1076End
1077
1078//**********************
1079// 2D resolution function calculation - in terms of X and Y
1080//
1081// based on notes from David Mildner, 2008
1082//
1083// the final NCNR version is located in NCNR_Utils.ipf
1084//
1085Function/S get2DResolution(inQ,phi,lambda,lambdaWidth,DDet,apOff,S1,S2,L1,L2,BS,del_r,usingLenses,r_dist,SigmaQX,SigmaQY,fSubS)
1086        Variable inQ, phi,lambda, lambdaWidth, DDet, apOff, S1, S2, L1, L2, BS, del_r,usingLenses,r_dist
1087        Variable &SigmaQX,&SigmaQY,&fSubS               //these are the output quantities at the input Q value
1088       
1089        return("Function Empty")
1090End
1091
1092
1093
1094
1095// Return the filename that represents the previous or next file.
1096// Input is current filename and increment.
1097// Increment should be -1 or 1
1098// -1 => previous file
1099// 1 => next file
1100Function/S GetPrevNextRawFile(curfilename, prevnext)
1101        String curfilename
1102        Variable prevnext
1103
1104        String filename
1105       
1106        //get the run number
1107        Variable num = GetRunNumFromFile(curfilename)
1108               
1109        //find the next specified file by number
1110        fileName = FindPrevNextRawFile(curfilename, prevnext)
1111
1112        if(cmpstr(fileName,"")==0)
1113                //null return, do nothing
1114                fileName = FindFileFromRunNumber(num)
1115        Endif
1116
1117        //print "in FU "+filename
1118
1119        Return filename
1120End
1121
1122// Find next or previous file name w/ current file name given.
1123// Sort the list of files and get the next/previous file name.
1124Function/S FindPrevNextRawFile(curfilename, prevnext)
1125        String curfilename
1126        Variable prevnext
1127       
1128        String fullName="",partialName="",item="", list=""
1129        Variable numItems,isRAW
1130                       
1131        //make sure that path exists
1132        PathInfo catPathName
1133        String path = S_path
1134       
1135        if (V_flag == 0)
1136                Abort "folder path does not exist - use Pick Path button"
1137        Endif
1138
1139       
1140        list = SortList(IndexedFile(catPathName,-1,"????"),";") //get all files in folder and make sure it is sorted.
1141       
1142        //find (the) one with the number in the run # location in the name
1143
1144        numItems = ItemsInList(list,";")                //get the new number of items in the list
1145        //index of curfilename
1146        Variable index = WhichListItem(curfilename,list,";",0,0)
1147        //get the prenextitem in the list
1148        item = StringFromList(index+prevnext, list  ,";")
1149        partialName = FindValidFileName(item)
1150       
1151        if(strlen(partialName) != 0)            //non-null return from FindValidFileName()
1152                fullName = path + partialName
1153                //check if RAW, if so,this must be the file!
1154                isRAW = CheckIfRawData(fullName)
1155                if(isRaw)
1156                        //stop here
1157                        return(fullname)
1158                Endif
1159        Endif
1160
1161        print "Please type 'scan number(s)' from your file name..."
1162        Return ("")     //null return if file not found in list
1163End
1164
Note: See TracBrowser for help on using the repository browser.