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

Last change on this file since 740 was 710, checked in by srkline, 12 years ago

Added /Z flag to suppress errors when checking status of XML files (NIST_XML)

Added more user functions to exclude from function popup list (PlotUtilsMacro?)

Invariant extrapolation at low q Guinier now takes an inital guess for the scale of the average of the dat points that are being fit. Initial guess of the slope is still -1000.

HFIR utils updated with a better value for the beamstop position when indentifying transmission runs

SASCALC and MultiScatter_MonteCarlo updated to include the wavelength spread as part of the simulation. Also added an empirical estimate of the countrate of (combined) empty quartz cell and blocked beam scattering. Simulation done in 1D - but the results are not shown, simply reported in the command window at this point. More can be done with this in the future, as we figure out how to present this.

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