source: trunk/User Procedures/Nika/NI1_InstrumentSupport.ipf @ 1175

Last change on this file since 1175 was 1175, checked in by ilavsky, 9 months ago

12IDB improvements

File size: 119.4 KB
Line 
1#pragma TextEncoding = "UTF-8"
2#pragma rtGlobals=3             // Use modern global access method.
3//#pragma rtGlobals=1           // Use modern global access method.
4#pragma version=1.22
5
6//*************************************************************************\
7//* Copyright (c) 2005 - 2021, Argonne National Laboratory
8//* This file is distributed subject to a Software License Agreement found
9//* in the file LICENSE that is included with this distribution.
10//*************************************************************************/
11
12//1.22 added all options to mask reading of goldavergae command line, lots of options.
13//1.21 fixes to 12ID support, unexpected stuff in theor configuration file found.
14//version 1.2 adds support for 12ID-C SAXS camera with Gold detector
15//version 1.1 adds support for ALS RSoXS data - sfot X-ray energy beamlione at ALS.
16//version 1.0 original release, Instrument support for SSRLMatSAXS
17//*******************************************************************************************************************************************
18//*******************************************************************************************************************************************
19//*******************************************************************************************************************************************
20//RSoXS support
21
22
23Function NI1_RSoXSCreateGUI()
24        //IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
25        DoWIndow NI1A_Convert2Dto1DPanel
26        if(!V_Flag)
27                NI1A_Convert2Dto1DMainPanel()
28        endif
29        NI1_RSoXSInitialize()
30        DoWIndow NI1_RSoXSMainPanel
31        if(V_Flag)
32                DoWIndow/F NI1_RSoXSMainPanel
33        else
34                NI1_RSoXSMainPanelFnct()
35        endif
36end
37//************************************************************************************************************
38//************************************************************************************************************
39//************************************************************************************************************
40//************************************************************************************************************
41
42Function NI1_RSoXSFindI0File()
43        variable refNum, i
44        string LineContent
45        //IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
46        NVAR ColumnNamesLineNo = root:Packages:Nika_RSoXS:ColumnNamesLineNo
47        SVAR I0ColumnLabels = root:Packages:Nika_RSoXS:I0ColumnLabels
48        SVAR I0FileNamePath = root:Packages:Nika_RSoXS:I0FileNamePath
49        Open /R /T=".txt" refNum
50        I0FileNamePath = S_fileName
51        //it is opened for reading, now lets find the stuff we need.
52        i=-1
53        Do
54                i+=1  //line we are reading now
55                FReadLine  refNum, LineContent                 
56        while(!GrepString(LineContent, "TEY signal" ))          //line containing kyeword TEY signal
57        close refNum
58        ColumnNamesLineNo = i
59        I0ColumnLabels = LineContent
60        //convert lisyt separated by tabs in list with ;
61        I0ColumnLabels = ReplaceString("\t", I0ColumnLabels, ";")
62        I0ColumnLabels = ReplaceString(" ", I0ColumnLabels, "_")
63        I0ColumnLabels = ReplaceString(")", I0ColumnLabels, "_")
64        I0ColumnLabels = ReplaceString("(", I0ColumnLabels, "_")
65        NI1_RSoXSSetPanelControls()
66end
67//************************************************************************************************************
68//************************************************************************************************************
69//************************************************************************************************************
70//************************************************************************************************************
71
72Function NI1_RSoXSSetPanelControls()
73        DoWIndow RSoXSMainPanel
74        //IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
75        if(V_Flag)
76                SVAR I0DataToLoad=root:Packages:Nika_RSoXS:I0DataToLoad
77                SVAR I0ColumnLabels=root:Packages:Nika_RSoXS:I0ColumnLabels
78                SVAR PhotoDiodeDatatoLoad = root:Packages:Nika_RSoXS:PhotoDiodeDatatoLoad               
79                PopupMenu I0DataToLoad,win=RSoXSMainPanel, mode=WhichListItem(I0DataToLoad, I0ColumnLabels)+1,value= #"root:Packages:Nika_RSoXS:I0ColumnLabels"
80                PopupMenu PhotoDiodeDatatoLoad,win=RSoXSMainPanel, mode=WhichListItem(PhotoDiodeDatatoLoad, I0ColumnLabels)+1,value= #"root:Packages:Nika_RSoXS:I0ColumnLabels"
81               
82               
83        endif
84
85end
86//************************************************************************************************************
87//************************************************************************************************************
88//************************************************************************************************************
89//************************************************************************************************************
90
91Function NI1_RSoXSLoadI0()
92        //this loads I0 records and deals with them.
93        //IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
94        string OldDf=getDataFOlder(1)
95        setDataFolder root:Packages:Nika_RSoXS
96        SVAR I0FileNamePath = root:Packages:Nika_RSoXS:I0FileNamePath
97        SVAR I0DataToLoad=root:Packages:Nika_RSoXS:I0DataToLoad
98        SVAR I0ColumnLabels=root:Packages:Nika_RSoXS:I0ColumnLabels
99        SVAR PhotoDiodeDatatoLoad = root:Packages:Nika_RSoXS:PhotoDiodeDatatoLoad       
100        NVAR ColumnNamesLineNo = root:Packages:Nika_RSoXS:ColumnNamesLineNo     
101        NVAR PhotoDiodeOffset = root:Packages:Nika_RSoXS:PhotoDiodeOffset       
102        NVAR I0Offset = root:Packages:Nika_RSoXS:I0Offset       
103
104        LoadWave/L={ColumnNamesLineNo, ColumnNamesLineNo+1, 0, 0, 0}/J/W/A/O I0FileNamePath
105        //polarization is in the file...
106        Wave/Z EPU_Polarization = root:Packages:Nika_RSoXS:EPU_Polarization
107        variable PolarizationLocal
108        NVAR PolarizationValue = root:Packages:Nika_RSoXS:PolarizationValue
109        if(!WaveExists(EPU_Polarization))
110                abort "Loaded waves seem incorrect"
111        else
112                if(PolarizationValue<0)
113                        PolarizationLocal = EPU_Polarization[0]
114                else
115                        PolarizationLocal = PolarizationValue
116                endif
117        endif
118        //Calculate CorrectionFactor and display a graph for users, just in case
119        Wave/Z Beamline_Energy=root:Packages:Nika_RSoXS:Beamline_Energy
120        Wave/Z Photodiode=$("root:Packages:Nika_RSoXS:"+PhotoDiodeDatatoLoad)
121        Wave/Z I0=$("root:Packages:Nika_RSoXS:"+I0DataToLoad)
122        if(WaveExists(Beamline_Energy)&&WaveExists(Photodiode)&&WaveExists(I0))
123//              KilLWIndow/Z I0andDiodeGraph
124//              Display /K=1/W=(468,386,1003,727) I0 vs Beamline_Energy as "I0 and Diode"
125//              DoWindow/C/R/T I0andDiodeGraph,"I0 and Diode"
126//              AppendToGraph/R Photodiode vs Beamline_Energy
127//              ModifyGraph mode=3
128//              ModifyGraph marker(Photodiode)=41
129//              ModifyGraph rgb(Photodiode)=(0,0,65535)
130//              ModifyGraph mirror(bottom)=1
131//              Label left "I0"
132//              Label bottom "Beamline energy [eV]"
133//              Label right "Diode"
134                //calcualte correction factor here for now.
135                Duplicate/O Photodiode, CorrectionFactor
136                CorrectionFactor=(Photodiode-PhotoDiodeOffset) * 2.4e10 / Beamline_Energy / (I0-I0Offset)                       //per instructions 
137
138                //Duplicate these data to proper        wave
139                Wave/Z CorrectionFactor=root:Packages:Nika_RSoXS:CorrectionFactor
140                Duplicate/O Beamline_Energy, $("root:Packages:Nika_RSoXS:Beamline_Energy"+"_pol"+num2str(PolarizationLocal))
141                Duplicate/O CorrectionFactor, $("root:Packages:Nika_RSoXS:CorrectionFactor"+"_pol"+num2str(PolarizationLocal))
142                Wave Beamline_Energy = $("root:Packages:Nika_RSoXS:Beamline_Energy"+"_pol"+num2str(PolarizationLocal))
143                Wave CorrectionFactor = $("root:Packages:Nika_RSoXS:CorrectionFactor"+"_pol"+num2str(PolarizationLocal))
144
145                KilLWIndow/Z $("CorrectionGraph_P"+num2str(PolarizationLocal))
146                Display /K=1/W=(468,386,1003,727) CorrectionFactor vs Beamline_Energy as "CorrectionFactor Polarization "+num2str(PolarizationLocal)
147                DoWindow/C/R $("CorrectionGraph_P"+num2str(PolarizationLocal))
148                ModifyGraph mirror=1
149                Label left "CorrectionGraph"
150                Label bottom "Beamline energy [eV]"
151        else
152                DoAlert /T="Did not find data" 0, "Please check wave names selections"
153        endif
154       
155       
156        setDataFolder OldDf
157end
158
159
160//************************************************************************************************************
161Function NI1_RSoXSFindCorrectionFactor(SampleName)
162        string sampleName
163
164        //IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
165        Wave/Z w2D = root:Packages:Convert2Dto1D:CCDImageToConvert
166        if(!WaveExists(w2D))
167                Abort "Image file not found " 
168        endif
169        string OldNOte=note(w2D)
170        //Mono Energy
171
172        //root:Packages:Convert2Dto1D:CorrectionFactor
173        variable Energy = NumberByKey("Mono Energy", OldNote , "=" , ";")
174        variable result = 10/Energy
175        print "Set Calibration Constant to 10/energy = "+num2str(result)
176        return result
177end
178
179
180//************************************************************************************************************
181//************************************************************************************************************
182Function NI1_RSoXSFindNormalFactor(SampleName)
183        string sampleName
184
185        //IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
186        Wave/Z w2D = root:Packages:Convert2Dto1D:CCDImageToConvert
187        if(!WaveExists(w2D))
188                Abort "Image file not found " 
189        endif
190        string OldNOte=note(w2D)
191        //Mono Energy
192        variable Energy = NumberByKey("Mono Energy", OldNote , "=" , ";")
193        variable PolarizationLocal = NumberByKey("EPU Polarization", OldNote , "=" , ";")
194        SVAR I0DataToLoad = root:Packages:Nika_RSoXS:I0DataToLoad
195        I0DataToLoad = ReplaceString("_", I0DataToLoad, " ")
196        variable SampleI0 = NumberByKey(I0DataToLoad, OldNote , "=" , ";")
197        variable SampleExposure = NumberByKey("EXPOSURE", OldNote , "=" , ";")
198        print "Sample I0 value is = "+num2str(SampleI0)
199        Wave/Z CorrectionFactor=$("root:Packages:Nika_RSoXS:CorrectionFactor_pol"+num2str(PolarizationLocal))
200        Wave/Z Beamline_Energy=$("root:Packages:Nika_RSoXS:Beamline_Energy_pol"+num2str(PolarizationLocal))
201        if(!WaveExists(Beamline_Energy)||!WaveExists(CorrectionFactor))
202                abort "Did not find Correction factor values, cannot continue"
203        endif
204        variable result = SampleExposure*SampleI0*CorrectionFactor[BinarySearchInterp(Beamline_Energy, Energy )]
205        print "Read Exposure time and I0 from image and Correction factor from file : CorrectionFactor_pol"+num2str(PolarizationLocal)+"  and got value = "+num2str(result)
206        return result
207end
208//************************************************************************************************************
209//************************************************************************************************************
210//************************************************************************************************************
211//************************************************************************************************************
212
213Function NI1_RSoXSInitialize()
214
215        //IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
216        string OldDf=GetDataFolder(1)
217        newDataFOlder/O root:Packages
218        newDataFolder/O/S root:Packages:Nika_RSoXS
219       
220        string/g ListOfVariables
221        string/g ListOfStrings
222
223        ListOfVariables="UseRSoXSCodeModifications;"
224        ListOfVariables+="ColumnNamesLineNo;OrderSorterValue;PolarizationValue;PhotoDiodeOffset;I0Offset;"
225        ListOfStrings="I0DataToLoad;PhotoDiodeDataToLoad;I0ColumnLabels;I0FileNamePath;"
226       
227        variable i
228        //and here we create them
229        for(i=0;i<itemsInList(ListOfVariables);i+=1)   
230                IN2G_CreateItem("variable",StringFromList(i,ListOfVariables))
231        endfor         
232                                                                               
233        for(i=0;i<itemsInList(ListOfStrings);i+=1)     
234                IN2G_CreateItem("string",StringFromList(i,ListOfStrings))
235        endfor 
236       
237        SVAR I0ColumnLabels
238        if(strlen(I0ColumnLabels)<3)
239                I0ColumnLabels="---;"
240        endif
241        SVAR I0DataToLoad
242        SVAR PhotoDiodeDataToLoad
243        if(strlen(I0DataToLoad)<3)
244                I0DataToLoad="AI_3_Izero"
245        endif
246        if(strlen(PhotoDiodeDataToLoad)<3)
247                PhotoDiodeDataToLoad="Photodiode"
248        endif
249        NVAR PolarizationValue
250        if(PolarizationValue==0)
251                PolarizationValue=-1
252        endif
253       
254       
255       
256        setDataFolder OldDf
257end
258//************************************************************************************************************
259//************************************************************************************************************
260//************************************************************************************************************
261//************************************************************************************************************
262
263Function NI1_RSoXSMainPanelFnct() : Panel
264        PauseUpdate             // building window...
265        NewPanel /K=1/W=(464,54,908,300) as "RSoXS Data reduction panel"
266        DoWIndow/C NI1_RSoXSMainPanel
267        SetDrawLayer UserBack
268        SetDrawEnv fstyle= 3,textrgb= (0,0,65535)
269        DrawText 70,31,"\\Zr125Controls for RSoXS Data reduction"
270        CheckBox UseRSoXSCodeModifications,pos={12.00,42.00},size={124.00,16.00},proc=NI1_RSoXSCheckProc,title="Use RSoXS modifications"
271        CheckBox UseRSoXSCodeModifications,variable= root:Packages:Nika_RSoXS:UseRSoXSCodeModifications
272        Button FindI0DataFile,pos={219.00,35.00},size={182.00,23.00},proc=NI1_RSoXSButtonProc,title="Find I0 Data file"
273        Button FindI0DataFile,help={"Locate I0 containing text file and check teh content. "}
274        SetVariable PolarizationValue,pos={45.00,129.00},size={151.00,15.00},bodyWidth=70,proc=NI1_RSoXSSetVarProc,title="Polarization Value"
275        SetVariable PolarizationValue,help={"Polarization value, -1 reads from the file"}
276        SetVariable PolarizationValue,limits={-1,360,1},value= root:Packages:Nika_RSoXS:PolarizationValue
277        SetVariable ColumnNamesLineNo,pos={16.00,87.00},size={180.00,15.00},bodyWidth=70,proc=NI1_RSoXSSetVarProc,title="Line with Column Names"
278        SetVariable ColumnNamesLineNo,help={"No of column with names"}
279        SetVariable ColumnNamesLineNo,limits={0,inf,1},value= root:Packages:Nika_RSoXS:ColumnNamesLineNo
280        SetVariable OrderSorterValue,pos={41.00,107.00},size={155.00,15.00},bodyWidth=70,proc=NI1_RSoXSSetVarProc,title="Order Sorter Value"
281        SetVariable OrderSorterValue,help={"Order sorter value"}
282        SetVariable OrderSorterValue,limits={0,inf,1},value= root:Packages:Nika_RSoXS:OrderSorterValue
283        PopupMenu I0DataToLoad,pos={229.00,83.00},size={167.00,23.00},bodyWidth=100,proc=NI1_RSoXSPopMenuProc,title="I0 data to load"
284        PopupMenu I0DataToLoad,help={"Which column contains I0 data?"}
285        PopupMenu I0DataToLoad,mode=1,popvalue="AI_3_Izero",value= #"root:Packages:Nika_RSoXS:I0ColumnLabels"
286        PopupMenu PhotoDiodeDatatoLoad,pos={214.00,110.00},size={183.00,23.00},bodyWidth=100,proc=NI1_RSoXSPopMenuProc,title="Diode data to load"
287        PopupMenu PhotoDiodeDatatoLoad,help={"Which Column contains diode data?"}
288        PopupMenu PhotoDiodeDatatoLoad,mode=1,popvalue="Photodiode",value= #"root:Packages:Nika_RSoXS:I0ColumnLabels"
289        SetVariable PhotoDiodeOffset,pos={44.00,148.00},size={152.00,15.00},bodyWidth=70,proc=NI1_RSoXSSetVarProc,title="Photodiode offset"
290        SetVariable PhotoDiodeOffset,help={"Diode offset intensity - dark current"}
291        SetVariable PhotoDiodeOffset,limits={0,inf,1},value= root:Packages:Nika_RSoXS:PhotoDiodeOffset
292        SetVariable I0Offset,pos={85.00,168.00},size={111.00,15.00},bodyWidth=70,proc=NI1_RSoXSSetVarProc,title="I0 offset"
293        SetVariable I0Offset,help={"I0 offset intensity - dark current"}
294        SetVariable I0Offset,limits={0,inf,1},value= root:Packages:Nika_RSoXS:I0Offset
295        Button LoadI0Data,pos={222.00,153.00},size={174.00,29.00},proc=NI1_RSoXSButtonProc,title="Load and display I0 data"
296        Button LoadI0Data,help={"This will read I0 data from the file and display a graph. It overwrtites any prior I0 data. "}
297        SetVariable I0FileNamePath,pos={19.00,63.00},size={385.00,15.00},bodyWidth=351,disable=2,proc=NI1_RSoXSSetVarProc,title="I0 file: "
298        SetVariable I0FileNamePath,help={"No of column with names"},frame=0
299        SetVariable I0FileNamePath,limits={0,inf,1},value= root:Packages:Nika_RSoXS:I0FileNamePath,noedit= 1
300EndMacro
301
302
303//************************************************************************************************************
304//************************************************************************************************************
305//************************************************************************************************************
306//************************************************************************************************************
307
308Function NI1_RSoXSCheckProc(cba) : CheckBoxControl
309        STRUCT WMCheckboxAction &cba
310
311        switch( cba.eventCode )
312                case 2: // mouse up
313                        Variable checked = cba.checked
314                        if(stringmatch(cba.ctrlName,"UseRSoXSCodeModifications"))
315                                //do what needs to be done when we are using this code...
316                                if(checked)
317                                        NI1_RSoXSConfigureNika()
318                                        NI1_RSoXSGenerateHelpNbk()
319                                else
320                                        KillWIndow/Z RSoXS_Instructions
321                                endif
322                        endif
323                       
324                       
325                        break
326                case -1: // control being killed
327                        break
328        endswitch
329
330        return 0
331End
332
333
334
335//************************************************************************************************************
336//************************************************************************************************************
337//************************************************************************************************************
338//************************************************************************************************************
339Function NI1_RSoXSGenerateHelpNbk()
340
341        DoWIndow RSoXS_Instructions
342        if(V_Flag)
343                DoWIndow/F RSoXS_Instructions
344        else
345                String nb = "RSoXS_Instructions"
346                NewNotebook/N=$nb/F=1/V=1/K=1/ENCG={2,1}/W=(455,300,1300,1000)
347                Notebook $nb defaultTab=36
348                Notebook $nb showRuler=1, rulerUnits=2, updating={1, 1}
349                Notebook $nb newRuler=Normal, justification=0, margins={0,0,468}, spacing={0,0,0}, tabs={}, rulerDefaults={"Helvetica",11,0,(0,0,0)}
350                Notebook $nb ruler=Normal, fStyle=1, text="Basic user instructions for RSoXS Data reduction panel\r"
351                Notebook $nb fStyle=-1, text="\r"
352                Notebook $nb text="Setting up 'Main 2D to 1D conversion panel'\r"
353                Notebook $nb text="1) Select 'Use RSoXS modifications' on the 'RSoXS Data reduction panel'. This will initialize basic sett"
354                Notebook $nb text="ings for RSoXS data reduction. \r"
355                Notebook $nb text="\r"
356                Notebook $nb text="2) Load I0 reference by selecting 'Find I0 Data file' on the 'RSoXS Data reduction panel'. Navigate to t"
357                Notebook $nb text="he desired text file and double click to select. 'Line with Column Names' should automatically fill in t"
358                Notebook $nb text="o be 15 and the Polarization Value will be set to -1 (This will read the polarization from the I0 file u"
359                Notebook $nb text="nder the 'EPU Polarization' header. Otherwise you can manually set a value here). Select an I0 monitor t"
360                Notebook $nb text="o be used under 'I0 data to load' (Ai_3_Izero is the default) and the 'Diode data to load' will be autom"
361                Notebook $nb text="atically set as 'Photodiode'. Offsets for Photodiode and I0 energies are available for advanced users.\r"
362                Notebook $nb text="\r"
363                Notebook $nb text="Select 'Load and display I0 data' to store the correction factor for a given polarization. Repeat with a"
364                Notebook $nb text="s many I0s as you require. Correction factors will be overwritten upon importing a new I0 with repeat po"
365                Notebook $nb text="larization value.\r"
366                Notebook $nb text="\r"
367                Notebook $nb text="3) On the 'Main 2D to 1D conversion panel' select Em/Dk and locate appropriate RSoXS data for dark backg"
368                Notebook $nb text="round subtraction. For a given data series, select a scan corresponding to each exposure time and click "
369                Notebook $nb text="'Load Dark Field.' When loading an image the exposure time will be read in the file header and matched w"
370                Notebook $nb text="ith an appropriate dark for subtraction.\r"
371                Notebook $nb text="\r"
372                Notebook $nb text="4) On the 'Main 2D to 1D conversion panel' click 'Select data path' and navigate to the folder containin"
373                Notebook $nb text="g RSoXS data. \r"
374                Notebook $nb text="\r"
375                Notebook $nb text="Final user options before data reduction\r"
376                Notebook $nb text="From here, it is up to the user to decide on an appropriate mask, geometry, and sector averages for the "
377                Notebook $nb text="given file to be imported.\r"
378                Notebook $nb text="\r"
379                Notebook $nb text="Creating a mask: Under the 'SAS 2D' menu select 'Create Mask' and follow instructions from the NIKA user"
380                Notebook $nb text=" manual. On the 'Main 2D to 1D conversion panel' be sure to select 'Use Mask' under the 'Mask' tab.\r"
381                Notebook $nb text="\r"
382                Notebook $nb text="Beam center and geometry refinement: Under the 'SAS 2D' menu select 'Beam centering and geometry cor.' a"
383                Notebook $nb text="nd follow instructions from the NIKA user manual.\r"
384                Notebook $nb text="\r"
385                Notebook $nb text="Sectors: On the 'Main 2D to 1D conversion panel' select 'Sect.' and check the box 'Use?' Basic data redu"
386                Notebook $nb text="ction will have the following boxes checked: 'Do Circular Average?', 'Create 1D graph', 'Store data in I"
387                Notebook $nb text="gor experiment', 'Overwrite Existing data if exist?', and 'Use input data name for output?'.\r"
388                Notebook $nb text="\r"
389                Notebook $nb text="Processing data\r"
390                Notebook $nb text="Finally, to process data: click 'Process sel, files individually', select one or more images in the list"
391                Notebook $nb text="box on the 'Main 2D to 1D conversion panel', and click 'Process image(s)'"
392                Notebook $nb selection={startOfFile, startOfFile }, findText={"",1}             
393        endif
394end
395//************************************************************************************************************
396//************************************************************************************************************
397//************************************************************************************************************
398//************************************************************************************************************
399Function NI1_RSoXSSetVarProc(sva) : SetVariableControl
400        STRUCT WMSetVariableAction &sva
401
402        switch( sva.eventCode )
403                case 1: // mouse up
404                case 2: // Enter key
405                case 3: // Live update
406                        Variable dval = sva.dval
407                        String sval = sva.sval
408                        if(stringMatch(sva.ctrlName,"ColumnNamesLineNo"))
409                                        //do something
410                        endif
411                        if(stringMatch(sva.ctrlName,"OrderSorterValue"))
412                                        //do something
413                        endif
414                        if(stringMatch(sva.ctrlName,"PolarizationValue"))
415                                        //do something
416                        endif
417                        if(stringMatch(sva.ctrlName,"PhotoDiodeOffset"))
418                                        //do something
419                        endif
420                        if(stringMatch(sva.ctrlName,"I0Offset"))
421                                        //do something
422                        endif
423                       
424                        break
425                case -1: // control being killed
426                        break
427        endswitch
428
429        return 0
430End
431
432//************************************************************************************************************
433//************************************************************************************************************
434//************************************************************************************************************
435//************************************************************************************************************
436Function NI1_RSoXSButtonProc(ba) : ButtonControl
437        STRUCT WMButtonAction &ba
438
439        switch( ba.eventCode )
440                case 2: // mouse up
441                        // click code here
442                        if(StringMatch(ba.ctrlName,"FindI0DataFile"))
443                                //FInd the I0 text file.
444                                NI1_RSoXSFindI0File()
445                        endif
446                        if(StringMatch(ba.ctrlName,"LoadI0Data"))
447                                //FInd the I0 text file.
448                                NI1_RSoXSLoadI0()
449                        endif
450
451
452
453
454                        break
455                case -1: // control being killed
456                        break
457        endswitch
458
459        return 0
460End
461
462
463//************************************************************************************************************
464//************************************************************************************************************
465//************************************************************************************************************
466//************************************************************************************************************
467Function NI1_RSoXSPopMenuProc(pa) : PopupMenuControl
468        STRUCT WMPopupAction &pa
469
470        switch( pa.eventCode )
471                case 2: // mouse up
472                        Variable popNum = pa.popNum
473                        String popStr = pa.popStr
474                        if(Stringmatch(pa.ctrlname,"I0DataToLoad"))
475                                SVAR I0DataToLoad=root:Packages:Nika_RSoXS:I0DataToLoad
476                                I0DataToLoad= popStr
477                       
478                        endif
479                        if(Stringmatch(pa.ctrlname,"PhotoDiodeDatatoLoad"))
480                                SVAR PhotoDiodeDatatoLoad = root:Packages:Nika_RSoXS:PhotoDiodeDatatoLoad
481                                PhotoDiodeDatatoLoad = popStr
482                        endif
483
484
485                        break
486                case -1: // control being killed
487                        break
488        endswitch
489
490        return 0
491end
492//************************************************************************************************************
493//************************************************************************************************************
494//************************************************************************************************************
495//************************************************************************************************************
496
497Function NI1_RSoXSConfigureNika()
498        //IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
499
500//                              NVAR UseSampleTransmission = root:Packages:Convert2Dto1D:UseSampleTransmission
501//                              NVAR UseEmptyField = root:Packages:Convert2Dto1D:UseEmptyField
502                                NVAR UseI0ToCalibrate = root:Packages:Convert2Dto1D:UseI0ToCalibrate
503                                NVAR DoGeometryCorrection = root:Packages:Convert2Dto1D:DoGeometryCorrection
504//                              NVAR UseMonitorForEf = root:Packages:Convert2Dto1D:UseMonitorForEf
505//                              NVAR UseSampleTransmFnct = root:Packages:Convert2Dto1D:UseSampleTransmFnct
506                                NVAR UseSampleMonitorFnct = root:Packages:Convert2Dto1D:UseSampleMonitorFnct
507//                              NVAR UseEmptyMonitorFnct = root:Packages:Convert2Dto1D:UseEmptyMonitorFnct
508                                NVAR UseSampleCorrectFnct = root:Packages:Convert2Dto1D:UseSampleCorrectFnct
509                                NVAR UseCorrectionFactor = root:Packages:Convert2Dto1D:UseCorrectionFactor
510                                NVAR UseDarkField = root:Packages:Convert2Dto1D:UseDarkField
511                                NVAR UseSampleMeasTime = root:Packages:Convert2Dto1D:UseSampleMeasTime
512                                NVAR PixelSizeX = root:Packages:Convert2Dto1D:PixelSizeX
513                                NVAR PixelSizeY = root:Packages:Convert2Dto1D:PixelSizeY
514                               
515                                SVAR DataFileExtension=root:Packages:Convert2Dto1D:DataFileExtension
516                                SVAR BlankFileExtension=root:Packages:Convert2Dto1D:BlankFileExtension
517                                DataFileExtension="FITS"
518                                BlankFileExtension="FITS"
519                                DoWIndow NI1A_Convert2Dto1DPanel
520                                if(V_Flag)
521                                        SVAR ListOfKnownExtensions = root:Packages:Convert2Dto1D:ListOfKnownExtensions
522                                        PopupMenu Select2DDataType,win=NI1A_Convert2Dto1DPanel,popvalue=DataFileExtension,value= #"root:Packages:Convert2Dto1D:ListOfKnownExtensions"
523                                        PopupMenu Select2DDataType,win=NI1A_Convert2Dto1DPanel, mode=WhichListItem(DataFileExtension, ListOfKnownExtensions)+1
524                                endif
525                               
526                                PixelSizeX = 0.027
527                                PixelSizeY = 0.027
528                                UseSampleCorrectFnct = 1
529                                UseCorrectionFactor = 1
530                                UseSampleMeasTime=0
531                                UseDarkField = 1
532//                              UseSampleThickness = 1                 
533//                              UseSampleTransmission = 1
534//                              UseEmptyField = 1
535                                UseI0ToCalibrate = 1
536                                DoGeometryCorrection = 1
537//                              UseMonitorForEf = 1
538//                              UseSampleTransmFnct = 1
539                                UseSampleMonitorFnct = 1
540//                              UseEmptyMonitorFnct = 1
541//                              UseSampleThicknFnct = 1
542
543                                SVAR SampleCorrectFnct = root:Packages:Convert2Dto1D:SampleCorrectFnct
544                                SVAR SampleMonitorFnct = root:Packages:Convert2Dto1D:SampleMonitorFnct
545                                SVAR EmptyMonitorFnct = root:Packages:Convert2Dto1D:EmptyMonitorFnct
546                                SVAR SampleThicknFnct = root:Packages:Convert2Dto1D:SampleThicknFnct
547                               
548                                SampleCorrectFnct = "NI1_RSoXSFindCorrectionFactor"
549                                SampleMonitorFnct = "NI1_RSoXSFindNormalFactor"
550//                              EmptyMonitorFnct = "NI1_9IDCSFindEfI0"
551//                              SampleThicknFnct = "NI1_9IDCSFindThickness"
552
553end
554
555//************************************************************************************************************
556//************************************************************************************************************
557//************************************************************************************************************
558//************************************************************************************************************
559Function NI1_RSoXSCopyDarkOnImport()
560        //IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
561        Wave/Z DarkFieldData=root:Packages:Convert2Dto1D:DarkFieldData
562        if(WaveExists(DarkFieldData))
563                string oldNote=note(DarkFieldData)
564                variable ExposureTime = NumberByKey("EXPOSURE", OldNote , "=" , ";")
565                Duplicate/O DarkFieldData, $("DarkFieldData_"+ReplaceString(".", num2str(ExposureTime),"p"))
566                print "Imported Dark field and stored as :"+("DarkFieldData_"+ReplaceString(".", num2str(ExposureTime),"p"))
567        else
568                abort "Dark data to store do not exist"
569        endif
570
571end
572//************************************************************************************************************
573//************************************************************************************************************
574//************************************************************************************************************
575//************************************************************************************************************
576Function NI1_RSoXSRestoreDarkOnImport()
577        //IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
578        Wave CCDImageToConvert = root:Packages:Convert2Dto1D:CCDImageToConvert
579        string SampleNote=note(CCDImageToConvert)
580        variable SampleTime=NumberByKey("EXPOSURE", SampleNote , "=" , ";")
581        string ExpectedDarkname="DarkFieldData_"+ReplaceString(".", num2str(SampleTime),"p")
582        Wave/Z DarkFieldData=$("root:Packages:Convert2Dto1D:"+ExpectedDarkname)
583        if(WaveExists(DarkFieldData))
584                Duplicate/O DarkFieldData, $("DarkFieldData")
585                //string oldNote=note(DarkFieldData)
586                //variable ExposureTime = NumberByKey("EXPOSURE", OldNote , "=" , ";")
587                //Duplicate/O DarkFieldData, $("DarkFieldData_"+ReplaceString(".", num2str(ExposureTime),"p"))
588                print "Restored Dark field from file : "+ExpectedDarkname
589        else
590                abort "Dark data with needed Exposure time : "+num2str(SampleTime)+" do not exist"
591        endif
592
593end
594
595//************************************************************************************************************
596//************************************************************************************************************
597//************************************************************************************************************
598//************************************************************************************************************
599
600Function NI1_RSoXSLoadHeaderValues()
601        //IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
602        Wave CCDImageToConvert = root:Packages:Convert2Dto1D:CCDImageToConvert
603        string SampleNote=note(CCDImageToConvert)
604        variable SampleTime=NumberByKey("EXPOSURE", SampleNote , "=" , ";")
605        variable Energy=NumberByKey("Beamline Energy", SampleNote , "=" , ";")
606        variable Wavelength=12.3984/(Energy/1000)
607        NVAR WV = root:Packages:Convert2Dto1D:Wavelength
608        NVAR En = root:Packages:Convert2Dto1D:XrayEnergy
609        En= Energy/1000
610        Wv= Wavelength
611        NVAR SampleMeasurementTime = root:Packages:Convert2Dto1D:SampleMeasurementTime
612        SampleMeasurementTime = SampleTime
613end
614
615//************************************************************************************************************
616//************************************************************************************************************
617//************************************************************************************************************
618//************************************************************************************************************
619
620
621
622
623
624
625// TPA/XML  note support is here
626//*******************************************************************************************************************************************
627//*******************************************************************************************************************************************
628//*******************************************************************************************************************************************
629Function NI1_TPASetup()         //this will setup support for data with TPA/XML file format
630        string OldDFf=GetDataFolder(1)
631
632        //first initialize if user selects this without opening main window...
633        doWIndow NI1A_Convert2Dto1DPanel
634        if(!V_Flag)
635                NI1A_Convert2Dto1DMainPanel()           
636        endif
637        //set some parameters here:
638        NVAR UseSampleTransmission = root:Packages:Convert2Dto1D:UseSampleTransmission
639        NVAR UseSampleThickness = root:Packages:Convert2Dto1D:UseSampleThickness
640        NVAR UseEmptyField = root:Packages:Convert2Dto1D:UseEmptyField
641        NVAR UseI0ToCalibrate = root:Packages:Convert2Dto1D:UseI0ToCalibrate
642        NVAR DoGeometryCorrection = root:Packages:Convert2Dto1D:DoGeometryCorrection
643        NVAR UseMonitorForEf = root:Packages:Convert2Dto1D:UseMonitorForEf
644        NVAR UseSampleTransmFnct = root:Packages:Convert2Dto1D:UseSampleTransmFnct
645        NVAR UseSampleThicknFnct = root:Packages:Convert2Dto1D:UseSampleThicknFnct
646        NVAR UseSampleMonitorFnct = root:Packages:Convert2Dto1D:UseSampleMonitorFnct
647        NVAR UseEmptyMonitorFnct = root:Packages:Convert2Dto1D:UseEmptyMonitorFnct
648        NVAR XrayEnergy = root:Packages:Convert2Dto1D:XrayEnergy
649        NVAR Wavelength = root:Packages:Convert2Dto1D:Wavelength
650        NVAR PixelSizeX = root:Packages:Convert2Dto1D:PixelSizeX
651        NVAR PixelSizeY = root:Packages:Convert2Dto1D:PixelSizeY
652        NVAR SampleToCCDdistance = root:Packages:Convert2Dto1D:SampleToCCDdistance
653        NVAR BeamCenterX = root:Packages:Convert2Dto1D:BeamCenterX
654        NVAR BeamCenterY = root:Packages:Convert2Dto1D:BeamCenterY
655       
656        //XrayEnergy=8.333
657        //Wavelength=12.39842/8.333
658        //PixelSizeX = 0.08
659        //PixelSizeY = 0.08
660       
661        UseSampleTransmission = 1
662        UseSampleThickness = 1
663//      UseEmptyField = 1
664//      UseI0ToCalibrate = 1
665//      DoGeometryCorrection = 1
666//      UseMonitorForEf = 1
667        UseSampleTransmFnct = 1
668        UseSampleThicknFnct =1
669//      UseSampleMonitorFnct = 1
670//      UseEmptyMonitorFnct = 1
671        SVAR SampleTransmFnct = root:Packages:Convert2Dto1D:SampleTransmFnct
672        SVAR SampleThicknFnct = root:Packages:Convert2Dto1D:SampleThicknFnct
673        SVAR SampleMonitorFnct = root:Packages:Convert2Dto1D:SampleMonitorFnct
674        SVAR EmptyMonitorFnct = root:Packages:Convert2Dto1D:EmptyMonitorFnct
675
676        SampleTransmFnct = "NI1_TPAGetTranmsission"
677        SampleThicknFnct = "NI1_TPAGetThickness"
678        //SampleMonitorFnct = "NI1_SSRLGetSampleI0"
679        //EmptyMonitorFnct = "NI1_SSRLGetEmptyI0"
680        PopupMenu Select2DDataType win=NI1A_Convert2Dto1DPanel, popmatch="TPA/XML" //mode=22
681        PopupMenu SelectBlank2DDataType win=NI1A_Convert2Dto1DPanel, popmatch="TPA/XML" //mode=22
682        NI1A_PopMenuProc("Select2DDataType",1,"TPA/XML")
683        NI1A_PopMenuProc("SelectBlank2DDataType",1,"TPA/XML")
684       
685        Wave/Z image=root:Packages:Convert2Dto1D:CCDImageToConvert
686        if(WaveExists(image))
687                        string sampleNote=note(image)
688                        string ImageType=StringByKey("DataFileType", sampleNote , "=" , ";")
689                if(stringmatch(ImageType,"TPA/XML"))   
690                        DoAlert 1, "Found TPA Image loaded, do you want to read information from the header to Nika?"
691                        if(V_FLag==1)   //yes...       
692                                        Wavelength =NumberByKey("Lambda", sampleNote , "=" , ";")
693                                        XrayEnergy = 12.39842/Wavelength
694                                        SampleToCCDdistance =NumberByKey("Detector_Distance", sampleNote , "=" , ";")
695                                        BeamCenterX= NumberByKey("X0", sampleNote , "=" , ";")
696                                        BeamCenterY=NumberByKey("Y", sampleNote , "=" , ";") - NumberByKey("Y0", sampleNote , "=" , ";")
697                                        DoALert 0, "Parameters, paths and lookup functions for TPA/XML have been loaded"
698                        endif
699                else
700                        NI1A_ButtonProc("Select2DDataPath")
701                        NI1A_ButtonProc("SelectMaskDarkPath")
702                        DoAlert 0, "Please load TPA type image and rerun the same macro to load instrument parameters from the header"         
703                endif   
704        endif
705        if(!WaveExists(image))
706                        NI1A_ButtonProc("Select2DDataPath")
707                        NI1A_ButtonProc("SelectMaskDarkPath")
708                        DoAlert 0, "Please load TPA type image and rerun the same macro to load instrument parameters from the header"
709        endif
710
711
712end
713
714//*******************************************************************************************************************************************
715//*******************************************************************************************************************************************
716
717Function NI1_TPAGetTranmsission(fileName)
718        string fileName
719        //T = (ICpstsamp(sample) * ICpresamp(0))/(ICpresamp(sample) * ICpstsamp(0))
720        wave/Z CCDImageToConvert = root:Packages:Convert2Dto1D:CCDImageToConvert
721        //wave/Z EmptyData = root:Packages:Convert2Dto1D:EmptyData
722        if(!WaveExists(CCDImageToConvert))// || !WaveExists(EmptyData))
723                abort "Needed area data do not exist. Load Sample data before going further"
724        endif
725        string sampleNote=note(CCDImageToConvert)
726        //string emptyNote=note(EmptyData)
727        variable transmission=NumberByKey("Transmission", sampleNote , "=" , ";")
728        print "Found transmission = "+num2str(transmission)
729        return transmission
730end
731//*******************************************************************************************************************************************
732//*******************************************************************************************************************************************
733
734Function NI1_TPAGetThickness(fileName)
735        string fileName
736        //T = (ICpstsamp(sample) * ICpresamp(0))/(ICpresamp(sample) * ICpstsamp(0))
737        wave/Z CCDImageToConvert = root:Packages:Convert2Dto1D:CCDImageToConvert
738        //wave/Z EmptyData = root:Packages:Convert2Dto1D:EmptyData
739        if(!WaveExists(CCDImageToConvert))// || !WaveExists(EmptyData))
740                abort "Needed area data do not exist. Load Sample data before going further"
741        endif
742        string sampleNote=note(CCDImageToConvert)
743        //string emptyNote=note(EmptyData)
744        variable Thickness=NumberByKey("Thickness", sampleNote , "=" , ";")
745        print "Found Thickness = "+num2str(Thickness)
746        return Thickness
747end
748
749
750//*******************************************************************************************************************************************
751//*******************************************************************************************************************************************
752//*******************************************************************************************************************************************
753// SSRLMatSAXS support is here
754//*******************************************************************************************************************************************
755//*******************************************************************************************************************************************
756//*******************************************************************************************************************************************
757
758Function NI1_SSRLSetup()                //this will setup support for SSRLMatSAXS
759        string OldDFf=GetDataFolder(1)
760
761        //first initialize if user selects this without opening main window...
762        doWIndow NI1A_Convert2Dto1DPanel
763        if(!V_Flag)
764                NI1A_Convert2Dto1DMainPanel()           
765        endif
766        //set some parameters here:
767        NVAR UseSampleTransmission = root:Packages:Convert2Dto1D:UseSampleTransmission
768        NVAR UseEmptyField = root:Packages:Convert2Dto1D:UseEmptyField
769        NVAR UseI0ToCalibrate = root:Packages:Convert2Dto1D:UseI0ToCalibrate
770        NVAR DoGeometryCorrection = root:Packages:Convert2Dto1D:DoGeometryCorrection
771        NVAR UseMonitorForEf = root:Packages:Convert2Dto1D:UseMonitorForEf
772        NVAR UseSampleTransmFnct = root:Packages:Convert2Dto1D:UseSampleTransmFnct
773        NVAR UseSampleMonitorFnct = root:Packages:Convert2Dto1D:UseSampleMonitorFnct
774        NVAR UseEmptyMonitorFnct = root:Packages:Convert2Dto1D:UseEmptyMonitorFnct
775        NVAR XrayEnergy = root:Packages:Convert2Dto1D:XrayEnergy
776        NVAR Wavelength = root:Packages:Convert2Dto1D:Wavelength
777        NVAR PixelSizeX = root:Packages:Convert2Dto1D:PixelSizeX
778        NVAR PixelSizeY = root:Packages:Convert2Dto1D:PixelSizeY
779       
780        XrayEnergy=8.333
781        Wavelength=12.39842/8.333
782        PixelSizeX = 0.08
783        PixelSizeY = 0.08
784       
785        UseSampleTransmission = 1
786        UseEmptyField = 1
787        UseI0ToCalibrate = 1
788        DoGeometryCorrection = 1
789        UseMonitorForEf = 1
790        UseSampleTransmFnct = 1
791        UseSampleMonitorFnct = 1
792        UseEmptyMonitorFnct = 1
793        SVAR SampleTransmFnct = root:Packages:Convert2Dto1D:SampleTransmFnct
794        SVAR SampleMonitorFnct = root:Packages:Convert2Dto1D:SampleMonitorFnct
795        SVAR EmptyMonitorFnct = root:Packages:Convert2Dto1D:EmptyMonitorFnct
796
797        SampleTransmFnct = "NI1_SSRLGetTranmsission"
798        SampleMonitorFnct = "NI1_SSRLGetSampleI0"
799        EmptyMonitorFnct = "NI1_SSRLGetEmptyI0"
800        PopupMenu Select2DDataType win=NI1A_Convert2Dto1DPanel, popmatch="SSRLMatSAXS" //mode=22
801        PopupMenu SelectBlank2DDataType win=NI1A_Convert2Dto1DPanel, popmatch="SSRLMatSAXS" //mode=22
802        NI1A_PopMenuProc("Select2DDataType",1,"SSRLMatSAXS")
803        NI1A_PopMenuProc("SelectBlank2DDataType",1,"SSRLMatSAXS")
804        NI1A_ButtonProc("Select2DDataPath")
805        NI1A_ButtonProc("SelectMaskDarkPath")
806
807
808        DoALert 0, "Parameters, paths and lookup functions for SSRL Mat SAXS have been loaded"
809end
810
811//*******************************************************************************************************************************************
812//*******************************************************************************************************************************************
813
814Function NI1_SSRLGetTranmsission(fileName)
815        string fileName
816        //T = (ICpstsamp(sample) * ICpresamp(0))/(ICpresamp(sample) * ICpstsamp(0))
817        wave/Z CCDImageToConvert = root:Packages:Convert2Dto1D:CCDImageToConvert
818        wave/Z EmptyData = root:Packages:Convert2Dto1D:EmptyData
819        if(!WaveExists(CCDImageToConvert) || !WaveExists(EmptyData))
820                abort "Needed area data do not exist. Load Sample2D and Empty2D before going further"
821        endif
822        string sampleNote=note(CCDImageToConvert)
823        string emptyNote=note(EmptyData)
824        variable ICpstsampSa=NumberByKey("ICpstsamp", sampleNote , "=" , ";")
825        variable ICpresampEm=NumberByKey("ICpresamp", emptyNote , "=" , ";")
826        variable ICpresampSa=NumberByKey("ICpresamp", sampleNote , "=" , ";")
827        variable ICpstsampEm=NumberByKey("ICpstsamp", emptyNote , "=" , ";")
828        variable transmission 
829        transmission = ICpstsampSa * ICpresampEm / (ICpresampSa *ICpstsampEm)
830        print "Found transmission = "+num2str(transmission)
831        return transmission
832end
833//*******************************************************************************************************************************************
834//*******************************************************************************************************************************************
835
836
837Function NI1_SSRLGetSampleI0(fileName)
838        string fileName
839        wave/Z CCDImageToConvert = root:Packages:Convert2Dto1D:CCDImageToConvert
840        if(!WaveExists(CCDImageToConvert))
841                abort "Needed area data do not exist. Load Sample2D before going further"
842        endif
843        string sampleNote=note(CCDImageToConvert)
844        variable ICpresampSa=NumberByKey("ICpresamp", sampleNote , "=" , ";")
845        //variable secSa=NumberByKey("sec", sampleNote , "=" , ";")
846        print "Found I0 value for sample = "+num2str(ICpresampSa)       //*secSa)
847        return ICpresampSa      //*secSa
848
849end
850//*******************************************************************************************************************************************
851//*******************************************************************************************************************************************
852
853Function NI1_SSRLGetEmptyI0(fileName)
854        string fileName
855        wave/Z EmptyData = root:Packages:Convert2Dto1D:EmptyData
856        if(!WaveExists(EmptyData))
857                abort "Needed area data do not exist. Load Empty2D before going further"
858        endif
859        string sampleNote=note(EmptyData)
860        variable ICpresampEm=NumberByKey("ICpresamp", sampleNote , "=" , ";")
861        //variable secEm=NumberByKey("sec", sampleNote , "=" , ";")
862        print "Found I0 value for empty = "+num2str(ICpresampEm)//*secEm)
863        return ICpresampEm      //*secEm
864
865end
866
867//*******************************************************************************************************************************************
868//*******************************************************************************************************************************************
869//*******************************************************************************************************************************************
870//*******************************************************************************************************************************************
871//*******************************************************************************************************************************************
872//*******************************************************************************************************************************************
873//              APS 12ID-C camera with Gold detector
874
875Function NI1_12IDCLoadAndSetup()
876        //this is function to setup data reduction for APS 12ID-C station using Gold detector
877       
878        string OldDFf=GetDataFolder(1)
879        //first initialize
880        NI1A_Convert2Dto1DMainPanel()
881        NI1BC_InitCreateBmCntrFile()
882        NI1_12IDCHowTo()
883        setDataFOlder root:Packages:Convert2Dto1D:
884        //save the Spec file for #Z lines nad store the values for calibration...
885        string/g specCalibDataName=""
886        SVAR DataFileExtension=root:Packages:Convert2Dto1D:DataFileExtension
887        DataFileExtension = ".tif"
888        //Now we need to load lookup table witgh calibration numbers
889        NI1_12IDCReadSpecFile(100)              //assume 100 images is normal.
890        //set some usable energy, assume one of the first ones is useful
891        Wave MonoEnenergy = root:Packages:Nika_12IDCLookups:MonoEnenergy
892        NVAR Wavelength = root:Packages:Convert2Dto1D:Wavelength
893        NVAR XrayEnergy = root:Packages:Convert2Dto1D:XrayEnergy
894        XrayEnergy = MonoEnenergy[ceil(1*numpnts(MonoEnenergy)/10)]
895        Wavelength = 12.39841857/XrayEnergy
896        NI1_12IDCReadScriptFile()
897        //these are setting so user is processing files...     
898        NVAR  Displ=root:Packages:Convert2Dto1D:Process_DisplayAve
899        NVAR    Proc1= root:Packages:Convert2Dto1D:Process_Individually
900        NVAR    Proc2= root:Packages:Convert2Dto1D:Process_Average
901        NVAR    Proc3 = root:Packages:Convert2Dto1D:Process_AveNFiles
902        Displ = 0
903        Proc1 = 1
904        Proc2 = 0
905        Proc3 = 0
906        //default settings, change as needed
907        NVAR UseSubtractFixedOffset = root:Packages:Convert2Dto1D:UseSubtractFixedOffset
908        NVAR SubtractFixedOffset = root:Packages:Convert2Dto1D:SubtractFixedOffset
909        NVAR UseSectors = root:Packages:Convert2Dto1D:UseSectors
910        NVAR QvectormaxNumPnts = root:Packages:Convert2Dto1D:QvectormaxNumPnts
911        NVAR QBinningLogarithmic = root:Packages:Convert2Dto1D:QBinningLogarithmic
912        NVAR DoSectorAverages = root:Packages:Convert2Dto1D:DoSectorAverages
913        NVAR DoCircularAverage = root:Packages:Convert2Dto1D:DoCircularAverage
914        NVAR NumberOfSectors = root:Packages:Convert2Dto1D:NumberOfSectors
915        NVAR SectorsStartAngle = root:Packages:Convert2Dto1D:SectorsStartAngle
916        NVAR SectorsHalfWidth = root:Packages:Convert2Dto1D:SectorsHalfWidth
917        NVAR DisplayDataAfterProcessing = root:Packages:Convert2Dto1D:DisplayDataAfterProcessing
918        NVAR StoreDataInIgor = root:Packages:Convert2Dto1D:StoreDataInIgor
919        NVAR OverwriteDataIfExists = root:Packages:Convert2Dto1D:OverwriteDataIfExists
920        NVAR Use2Ddataname = root:Packages:Convert2Dto1D:Use2Ddataname
921        NVAR QvectorNumberPoints = root:Packages:Convert2Dto1D:QvectorNumberPoints
922        NVAR FIlesSortOrder=root:Packages:Convert2Dto1D:FIlesSortOrder
923       
924        SubtractFixedOffset = 200
925        UseSubtractFixedOffset=1
926        UseSectors = 1
927        FIlesSortOrder = 3     
928        QvectorNumberPoints=300
929        QBinningLogarithmic=1
930        QvectormaxNumPnts = 0
931        DoSectorAverages = 0
932        DoCircularAverage = 1
933        NumberOfSectors = 12
934        SectorsStartAngle = 0
935        SectorsHalfWidth = 10
936        DisplayDataAfterProcessing = 1
937        StoreDataInIgor = 1
938        OverwriteDataIfExists = 1
939        Use2Ddataname = 1
940       
941        NVAR UseQvector = root:Packages:Convert2Dto1D:UseQvector
942        NVAR UseDspacing = root:Packages:Convert2Dto1D:UseDspacing
943        NVAR UseTheta = root:Packages:Convert2Dto1D:UseTheta
944       
945        UseQvector = 1
946        UseDspacing = 0
947        UseTheta = 0
948       
949        NVAR ErrorCalculationsUseOld=root:Packages:Convert2Dto1D:ErrorCalculationsUseOld
950        NVAR ErrorCalculationsUseStdDev=root:Packages:Convert2Dto1D:ErrorCalculationsUseStdDev
951        NVAR ErrorCalculationsUseSEM=root:Packages:Convert2Dto1D:ErrorCalculationsUseSEM
952        ErrorCalculationsUseOld=0
953        ErrorCalculationsUseStdDev=0
954        ErrorCalculationsUseSEM=1
955        if(ErrorCalculationsUseOld)
956                print "Uncertainty calculation method is set to \"Old method (see manual for description)\""
957        elseif(ErrorCalculationsUseStdDev)
958                print "Uncertainty calculation method is set to \"Standard deviation (see manual for description)\""
959        else
960                print "Uncertainty calculation method is set to \"Standard error of mean (see manual for description)\""
961        endif
962        //
963               
964        NVAR UseSampleTransmission = root:Packages:Convert2Dto1D:UseSampleTransmission
965        NVAR UseEmptyField = root:Packages:Convert2Dto1D:UseEmptyField
966        NVAR UseI0ToCalibrate = root:Packages:Convert2Dto1D:UseI0ToCalibrate
967        NVAR DoGeometryCorrection = root:Packages:Convert2Dto1D:DoGeometryCorrection
968        NVAR UseMonitorForEf = root:Packages:Convert2Dto1D:UseMonitorForEf
969        NVAR UseSampleTransmFnct = root:Packages:Convert2Dto1D:UseSampleTransmFnct
970        NVAR UseSampleMonitorFnct = root:Packages:Convert2Dto1D:UseSampleMonitorFnct
971        NVAR UseEmptyMonitorFnct = root:Packages:Convert2Dto1D:UseEmptyMonitorFnct
972        NVAR UseSampleThickness = root:Packages:Convert2Dto1D:UseSampleThickness
973        NVAR UseSampleThicknFnct = root:Packages:Convert2Dto1D:UseSampleThicknFnct     
974
975        UseSampleThickness = 0                 
976        UseSampleTransmission = 1
977        UseEmptyField = 1
978        UseI0ToCalibrate = 1
979        DoGeometryCorrection = 1
980        UseMonitorForEf = 1
981        UseSampleTransmFnct = 1
982        UseSampleMonitorFnct = 1
983        UseEmptyMonitorFnct = 1
984        UseSampleThicknFnct = 0
985       
986        SVAR SampleTransmFnct = root:Packages:Convert2Dto1D:SampleTransmFnct
987        SVAR SampleMonitorFnct = root:Packages:Convert2Dto1D:SampleMonitorFnct
988        SVAR EmptyMonitorFnct = root:Packages:Convert2Dto1D:EmptyMonitorFnct
989        SVAR SampleThicknFnct = root:Packages:Convert2Dto1D:SampleThicknFnct
990       
991        SampleTransmFnct = "NI1_12IDCFindTrans"
992        SampleMonitorFnct = "NI1_12IDCFindI0"
993        EmptyMonitorFnct = "NI1_12IDCFindEmptyI0"
994        SampleThicknFnct = ""
995       
996
997        NI1A_SetCalibrationFormula()                   
998        NI1BC_UpdateBmCntrListBox()     
999        NI1A_UpdateDataListBox()       
1000        NI1A_UpdateEmptyDarkListBox()   
1001        //send user to Empty/Dark tab
1002        TabControl Convert2Dto1DTab win=NI1A_Convert2Dto1DPanel, value=3
1003        NI1A_TabProc("NI1A_Convert2Dto1DPanel",3)       
1004        setDataFolder OldDFf
1005end
1006//*******************************************************************************************************************************************
1007//*******************************************************************************************************************************************
1008//*******************************************************************************************************************************************
1009Function NI1_12IDCReadScriptFile()
1010
1011        Variable refNum,err=0, ReadParams=0, CreateMask=0
1012        String YesNoStrParams="No"
1013        String YesNoStrMask="No"
1014        OPEN/R/Z/P=Convert2Dto1DDataPath refNum as "goldnormengavg"
1015        if(V_Flag==0)
1016                String lineStr
1017                Variable count=0
1018                do
1019                        FreadLine refNum,lineStr
1020                        if(strlen(lineStr)<=0)
1021                                break
1022                        endif
1023                        if(strsearch(lineStr,"goldaverage",0)>=0 && !StringMatch(lineStr[0], "#"))
1024                                Prompt YesNoStrParams, "Load beamline parameters in Nika? (overwrites any existing params!)", popup, "No;Yes;"
1025                                Prompt YesNoStrMask, "NOT SUGGESTED: Create beamline defined mask? (overwrites any existing mask!)", popup, "No;Yes;"
1026                                DoPrompt "Beamline params & mask found, load in Nika?", YesNoStrParams, YesNoStrMask
1027                                if(V_Flag)
1028                                        abort
1029                                endif
1030                                if(stringMatch(YesNoStrParams,"Yes"))
1031                                        ReadParams=1
1032                                endif
1033                                if(stringMatch(YesNoStrMask,"Yes"))
1034                                        CreateMask=1
1035                                endif
1036                                NI1_12IDC_Parsegoldnormengavg(lineStr, ReadParams)
1037                                NI1_12IDC_ParsegoldMask(lineStr, CreateMask)
1038                        endif
1039                while(err==0)
1040        else
1041                print "goldnormengavg file not found, parameters not set..."
1042        endif           
1043        close refnum
1044end
1045//*******************************************************************************************************************************************
1046//*******************************************************************************************************************************************
1047
1048Function NI1_12IDC_ParsegoldMask(CommandLine, MakeMask)
1049        string CommandLine
1050        variable MakeMask
1051
1052//      CommandLine="goldaverage -o Averaged_norm -y -p 0.1465 -d 3775 -Z 10 -k $normval -e $energyval -r 0,0,2048,2048 -C      1090@1024,1000 -r    753,300,766,232 -r748,0,775,232 -r0,303,2048,318 -r1520,310,1545,440 -r90,1120,170,1177 -c14@774,309 774 311 $filename"
1053//      CommandLine="goldaverage -o Averaged_norm -y -p 0.1465 -d 3775 -Z 10 -k $normval -e $energyval -rect 120x80@20,30  -a10-1000@300,300 -R753,300,766,232 -A 100-200@500,500 774 311 $filename"
1054        Variable tempStart, tempEnd, NumLines, i
1055        String TempStr, TempStr2
1056        tempStart = 0
1057
1058        if(MakeMask)
1059                string OldDf=GetDataFOlder(1)
1060                //go to the right data folder... Create Mask image to work on...
1061                SetDataFolder   root:Packages:Convert2Dto1D:
1062                Wave/Z CCDImage=root:Packages:Convert2Dto1D:CCDImageToConvert
1063                if(!WaveExists(CCDImage))
1064                        DoAlert/T="CCD image not found, we need one to create mask", 0, "In next dialog select any one from tiff files you will be reducing. All we need is correct image size."
1065                        //print "Mask was not created, first load image and then try again"
1066                        ImageLoad/P=Convert2Dto1DDataPath/T=tiff/Q/O/N=M_ROIMask
1067                        //Make/O/B/U/N=(1024,1024) root:Packages:Convert2Dto1D:M_ROIMask
1068                        if(V_flag==0)           //return 0 if not succesuful.
1069                                print "Mask was not created, first load image and then try again"
1070                                SetDataFolder   OldDf
1071                                return 0
1072                        endif
1073                        wave M_ROIMask
1074                        Redimension/N=(-1,-1,0)         M_ROIMask                       //this is fix for 3 layer tiff files...
1075                else
1076                        Duplicate/O CCDImage, root:Packages:Convert2Dto1D:M_ROIMask             
1077                endif
1078                Wave Mask = root:Packages:Convert2Dto1D:M_ROIMask
1079                Mask = (Mask > 10) ? 1 : 0
1080                Redimension/B/U Mask
1081                //this is all enable mask...
1082                //now reduce spaces in CommandLine to max of one space.
1083                Do
1084                        CommandLine = ReplaceString("  ", CommandLine, " ")
1085                while (StringMatch(CommandLine, "*  *" ))
1086                //OK, now we shoudl have at most one space between commands and parameters.
1087                Do
1088                        tempStart=strsearch(CommandLine, "-", tempStart+1)
1089                        if(tempStart<0)
1090                                break
1091                        endif
1092                        TempStr = CommandLine[tempStart+1,tempStart+30]
1093                        if(GrepString(TempStr, "^rect"))                                        //rectangle, full word
1094                                TempStr =TempStr[4,inf]
1095                                tempEnd = strsearch(TempStr, " ", 6)
1096                                TempStr = TempStr[0,tempEnd]
1097                                print "Added Masked rect  :  "+TempStr
1098                                NI1_12IDC_AddRectangleMask(Mask,TempStr,1)
1099                        elseif(GrepString(TempStr, "^r"))                                       //rectangle, short
1100                                TempStr =TempStr[1,inf]
1101                                tempEnd = strsearch(TempStr, " ", 3)
1102                                TempStr = TempStr[0,tempEnd]
1103                                print "Added Masked rect  :  "+TempStr
1104                                NI1_12IDC_AddRectangleMask(Mask,TempStr,1)
1105                        elseif(GrepString(TempStr, "^negrect"))                 //negative rectangle, full negrect
1106                                TempStr =TempStr[7,inf]
1107                                tempEnd = strsearch(TempStr, " ", 9)
1108                                TempStr = TempStr[0,tempEnd]
1109                                print "Added unmasked rect  : "+TempStr
1110                                NI1_12IDC_AddRectangleMask(Mask,TempStr,0)
1111                        elseif(GrepString(TempStr, "^R"))                                       //negative rectangle, short negrect
1112                                TempStr =TempStr[1,inf]
1113                                tempEnd = strsearch(TempStr, " ", 3)
1114                                TempStr = TempStr[0,tempEnd]
1115                                print "Added unmasked rect  : "+TempStr
1116                                NI1_12IDC_AddRectangleMask(Mask,TempStr,0)
1117                        elseif(GrepString(TempStr, "^circle"))                  //circle, full word
1118                                TempStr =TempStr[6,inf]
1119                                tempEnd = strsearch(TempStr, " ", 8)
1120                                TempStr = TempStr[0,tempEnd]
1121                                print "Added Masked circle  : "+TempStr
1122                                NI1_12IDC_AddCircleMask(Mask,TempStr,1)
1123                        elseif(GrepString(TempStr, "^c"))                                       //circle, short
1124                                TempStr =TempStr[1,inf]
1125                                tempEnd = strsearch(TempStr, " ", 3)
1126                                TempStr = TempStr[0,tempEnd]
1127                                print "Added Masked circle  : "+TempStr
1128                                NI1_12IDC_AddCircleMask(Mask,TempStr,1)
1129                        elseif(GrepString(TempStr, "^negcircle"))               //negcircle, full word 
1130                                TempStr =TempStr[9,inf]
1131                                tempEnd = strsearch(TempStr, " ", 11)
1132                                TempStr = TempStr[0,tempEnd]
1133                                print "Added unmasked circle  : "+TempStr
1134                                NI1_12IDC_AddCircleMask(Mask,TempStr,0)
1135                        elseif(GrepString(TempStr, "^C"))                                                       //negcircle, short     
1136                                TempStr =TempStr[1,inf]
1137                                tempEnd = strsearch(TempStr, " ", 3)
1138                                TempStr = TempStr[0,tempEnd]
1139                                print "Added unMasked Circle  : "+TempStr
1140                                NI1_12IDC_AddCircleMask(Mask,TempStr,0)
1141                        elseif(GrepString(TempStr, "^annulus"))                                 //annulus
1142                                TempStr =TempStr[7,inf]
1143                                tempEnd = strsearch(TempStr, " ", 10)
1144                                TempStr = TempStr[0,tempEnd]
1145                                print "Added Masked annulus  : "+TempStr
1146                                NI1_12IDC_AddAnnulusMask(Mask,TempStr,1)
1147                        elseif(GrepString(TempStr, "^a"))                                                       //annulus
1148                                TempStr =TempStr[1,inf]
1149                                tempEnd = strsearch(TempStr, " ", 3)
1150                                TempStr = TempStr[0,tempEnd]
1151                                print "Added Masked a  : "+TempStr
1152                                NI1_12IDC_AddAnnulusMask(Mask,TempStr,1)
1153                        elseif(GrepString(TempStr, "^negannulus"))                              //negannulus
1154                                TempStr =TempStr[10,inf]
1155                                tempEnd = strsearch(TempStr, " ", 13)
1156                                TempStr = TempStr[0,tempEnd]
1157                                print "Added unMasked annulus  : "+TempStr
1158                                NI1_12IDC_AddAnnulusMask(Mask,TempStr,0)
1159                        elseif(GrepString(TempStr, "^A"))                                                       //negannulus
1160                                TempStr =TempStr[1,inf]
1161                                tempEnd = strsearch(TempStr, " ", 3)
1162                                TempStr = TempStr[0,tempEnd]
1163                                print "Added unMasked Annulus  : "+TempStr
1164                                NI1_12IDC_AddAnnulusMask(Mask,TempStr,0)
1165                        else
1166                                //print "Unknown command to creat emask : "+TempStr
1167                        endif
1168                while(tempStart>0)
1169               
1170                NVAR UseMask = root:Packages:Convert2Dto1D:UseMask
1171                UseMask=1
1172                SVAR CurrentMaskFileName = root:Packages:Convert2Dto1D:CurrentMaskFileName
1173                CurrentMaskFileName = "12ID-C beamline mask"
1174
1175                SetDataFolder   OldDf
1176       
1177endif   
1178       
1179
1180
1181       
1182//      string OldDf=getDataFolder(1)
1183//      SetDataFolder root:Packages:Nika_12IDCLookups
1184//
1185//      Variable tempStart, tempEnd, NumLines, i
1186//      String TempStr, TempStr2
1187//     
1188//      // goldaverage -o Averaged_norm -y -p 0.175 -d 2345 -Z 200 -k $normval -e $energyval -r146,915,158,980 -r143,980,164,1024 -r 0,908,1024,914 -c6@166,907 -c12@154,911 154 911 $filename
1189//      //need to create list of items, first rectangles
1190//      Make/O/N=(0,4) Rectangles
1191//      tempStart = 0
1192//      NumLines = 0
1193//      Do
1194//              tempStart=strsearch(CommandLine, "-r", tempStart+1)
1195//              tempEnd = strsearch(CommandLine, " ", tempStart+3)
1196//              if(tempEnd<0 || tempStart<0)
1197//                      BREAk
1198//              endif   
1199//              TempStr = CommandLine[tempStart,tempEnd]
1200//              TempStr = ReplaceString("-r",TempStr,"")+","
1201//              redimension/N=(NumLines+1, 4) Rectangles
1202//              Rectangles[NumLines][0]=str2num(stringFromList(0,TempStr,","))
1203//              Rectangles[NumLines][1]=str2num(stringFromList(1,TempStr,","))
1204//              Rectangles[NumLines][2]=str2num(stringFromList(2,TempStr,","))
1205//              Rectangles[NumLines][3]=str2num(stringFromList(3,TempStr,","))
1206//              print "Found Rectangular mask with corners of: "+num2str(Rectangles[NumLines][0])+" ; "+num2str(Rectangles[NumLines][1])+" ; "+num2str(Rectangles[NumLines][2])+" ; "+num2str(Rectangles[NumLines][3])
1207//              NumLines+=1
1208//      while(tempEnd>0 && strlen(TempStr)>1 )
1209//
1210//      //need to create list of items, second circles
1211//      Make/O/N=(0,3) Circles
1212//      tempStart = 0
1213//      NumLines = 0
1214//      Do
1215//              tempStart=strsearch(CommandLine, "-c", tempStart+1)
1216//              tempEnd = strsearch(CommandLine, " ", tempStart+3)
1217//              if(tempEnd<0 || tempStart<0)
1218//                      BREAk
1219//              endif   
1220//              TempStr = CommandLine[tempStart,tempEnd]
1221//              TempStr = ReplaceString("-c",TempStr,"")+","
1222//              TempStr2 = stringFromList(1,TempStr,"@")
1223//              redimension/N=(NumLines+1, 3) Circles
1224//              Circles[NumLines][0]=str2num(stringFromList(0,TempStr,"@"))
1225//              Circles[NumLines][1]=str2num(stringFromList(0,TempStr2,","))
1226//              Circles[NumLines][2]=str2num(stringFromList(1,TempStr2,","))
1227//              print "Found Circular mask with radius of: "+num2str(Circles[NumLines][0])+" ; and centers "+num2str(Circles[NumLines][1])+" ; "+num2str(Circles[NumLines][2])
1228//              NumLines+=1
1229//      while(tempEnd>0 && strlen(TempStr)>1 )
1230//      SetDataFolder   OldDf
1231//      if(MakeMask)
1232//              //here we will make mask... We need image to make copy of.
1233//              SetDataFolder   root:Packages:Convert2Dto1D:
1234//              Wave/Z CCDImage=root:Packages:Convert2Dto1D:CCDImageToConvert
1235//              if(!WaveExists(CCDImage))
1236//                      DoAlert/T="CCD image not found, we need one to create mask", 0, "In next dialog select any one from tiff files you will be reducing. All we need is correct image size."
1237//                      //print "Mask was not created, first load image and then try again"
1238//                      ImageLoad/P=Convert2Dto1DDataPath/T=tiff/Q/O/N=M_ROIMask
1239//                      //Make/O/B/U/N=(1024,1024) root:Packages:Convert2Dto1D:M_ROIMask
1240//                      if(V_flag==0)           //return 0 if not succesuful.
1241//                              print "Mask was not created, first load image and then try again"
1242//                              SetDataFolder   OldDf
1243//                              return 0
1244//                      endif
1245//                      wave M_ROIMask
1246//                      Redimension/N=(-1,-1,0)         M_ROIMask                       //this is fix for 3 layer tiff files...
1247//              else
1248//                      Duplicate/O CCDImage, root:Packages:Convert2Dto1D:M_ROIMask             
1249//              endif
1250//              Wave Mask = root:Packages:Convert2Dto1D:M_ROIMask
1251//              Mask = (Mask > 10) ? 1 : 0
1252//              Redimension/B/U Mask
1253//              //this is all enable mask...
1254//              //Now we need to add masked off areas...
1255//              print "Created new Mask based on beamline command file"
1256//              Rectangles = Rectangles[p][q]<dimsize(Mask,0) ? Rectangles[p][q] : Rectangles[p][q]-1                   //Staff uses 2048 index for mask, even though image is 0 to 2047 only. And now, they do NOT use 1 based pixel counting, they use 0 for first pixel...
1257//              For(i=0;i<dimSize(Rectangles,0);i+=1)
1258//                      Mask[Rectangles[i][0],Rectangles[i][2]][Rectangles[i][1],Rectangles[i][3]] = 0
1259//                      print "Added Rectangular mask with corners of: "+num2str(Rectangles[i][0])+" ; "+num2str(Rectangles[i][1])+" ; "+num2str(Rectangles[i][2])+" ; "+num2str(Rectangles[i][3])
1260//              endfor
1261//              For(i=0;i<dimSize(Circles,0);i+=1)
1262//                      Mask = sqrt((p-Circles[i][1])^2+(q-Circles[i][2])^2)>Circles[i][0] ? Mask[p][q] : 0
1263//                      print "Added Circular mask with radius of: "+num2str(Circles[i][0])+" ; and centers "+num2str(Circles[i][1])+" ; "+num2str(Circles[i][2])
1264//              endfor
1265//              NVAR UseMask = root:Packages:Convert2Dto1D:UseMask
1266//              UseMask=1
1267//              SVAR CurrentMaskFileName = root:Packages:Convert2Dto1D:CurrentMaskFileName
1268//              CurrentMaskFileName = "12ID-C beamline mask"
1269//              SetDataFolder   OldDf
1270//             
1271//      endif
1272end
1273
1274//GOLDAVERAGE (Version 1.4.4)
1275//
1276//Perform azimuthal averaging of gold data
1277//Each input file is averaged to produce a separate output file
1278//usage: goldaverage [OPTION]... CX CY GOLDFILE...
1279//
1280//-d DISTANCE
1281//-distance DISTANCE   specify sample-detector distance in mm (default 3050mm)
1282//-y
1283//-overwrite           force overwriting of duplicate output files
1284//-o OUTDIR
1285//-output OUTDIR       put output files in this directory (default 'Averaged')
1286//-Z OFFSET
1287//-offset OFFSET       specify an alternative image intensity offset (default=10)
1288//-help                Print extended help information & extra options
1289//-b BINSIZE
1290//-binsize BINSIZE   specify output bin size in camera pixels (default 1)
1291//-l
1292//-log               specify logarithmic bin sizes (default linear)
1293//-d DISTANCE
1294//-detector DISTANCE specify sample-detector distance in mm (default 3050mm)
1295//-p PIXELSIZE
1296//-pixelsize PIXELSIZE specify camera pixel size (default = 0.098mm, i.e. gold detector)
1297//-e ENERGY
1298//-energy ENERGY     specify photon energy in keV, overriding value stored in file header
1299//-q QBINSIZE
1300//-qpix QBINSIZE     specify q bin size (default is calculated from above parameters)
1301//-h
1302//-header            propagate the 'gold' header into the output file
1303//-approxq           use the 'old' style linear approximation for q
1304//-rmin MINVAL       specify a minimum bin number to be output (default = 0)
1305//-rmax MAXVAL       specify a maximum bin number of be output
1306//-labels            output column header labels in the output file
1307//-g PLOTCMDFILE
1308//-gnuplot PLOTCMDFILE output gnuplot commands to plot the averaged data into 'PLOTCMDFILE'
1309//-k NORMVAL
1310//-fixedscale NORMVAL override intensity normalization to use a constant 'NORMVAL'
1311//-K NORMKEY
1312//-headerscale NORMKEY intens norm uses header value (default 'ID12_SCLC1_COUNTS_03')
1313//Masking options:
1314//
1315//The program contains a mask array which governs which pixels are used
1316//in calculations.  The mask array is initialised to allow all pixels to
1317//be used, and various options can be specified to add and remove regions
1318//of pixels from the mask.  Options may be repeated and their cumulative effect
1319//is governed by the order in which they are given.
1320//
1321//-m maskfile
1322//-mask maskfile                 specify the name of a mask file and mask out those pixels
1323//                               masked in the maskfile.  The mask file can either be another
1324//                               gold image file or an RGB TIFF file
1325//                               If a TIFF file is used, any pixel whose RGB value is not a
1326//                               shade of gray will be considered masked.  This allows you to
1327//                               use goldconvert to convert a gold image file into a TIFF file
1328//                               which can then be edited with an image editor (such as the GIMP)
1329//                               where you can 'paint' the pixels that you want to exclude in some
1330//                               color (say red) while leaving the original gold image visible as
1331//                               a grayscale image in the unmasked pixel positions
1332//
1333//-M maskfile
1334//-negmask maskfile              specify the name of a mask file and unmask those pixels
1335//                               masked in the maskfile.  The format and interpretation of the
1336//                               mask file is described above
1337//
1338//-n
1339//-invert                        invert the current mask.  masked pixels become unmasked, and vice
1340//                               versa
1341//
1342//-r rectspec
1343//-rect rectspec                 Add a rectangle of masked pixels to the mask.  The rectangle can
1344//                               be given in two different forms e.g. '10,15,80,250' specifies a
1345//                               rectangle with 10 >= x > 80 and 15 >= y > 250 and
1346//                               e.g. '120x80@20,30' specifies a rectangle of width 120 pixels and
1347//                               height 80 pixels centered at x=20, y=30
1348//                               All coordinates must be integers
1349//
1350//-R rectspec
1351//-negrect rectspec              Remove a rectangle of masked pixels from the mask.  The rectangle
1352//                               coordinates are as given above
1353//
1354//-c radius@xcenter,ycenter
1355//-circle radius@xcenter,ycenter Add a circle of masked pixels to the mask.  The circle is specified
1356//                               by its radius and its center, which may be floating point
1357//                               values
1358//
1359//-C radius@xcenter,ycenter
1360//-negcircle radius@xcenter,ycenter   remove a circle of masked pixels from the mask.
1361//
1362//-a r1-r2@xcenter,ycenter
1363//-annulus r1-r2@xcenter,ycenter Add an annular region of pixels to the mask.  The annulus is
1364//                               specified by its inner and outer radii and its center, which
1365//                               may be floating point values.
1366//-A r1-r2@xcenter,ycenter
1367//-negannulus r1-r2@xcenter,ycenter   remove an annular region of masked pixels from the mask
1368
1369static Function NI1_12IDC_AddAnnulusMask(MaskWave,MaskSpecs,MaskIt)
1370                wave MaskWave           //thsi is Mask file
1371                string MaskSpecs                //thsi specifying mask location
1372                variable MaskIt                 //1 to mask off pixels, 0 to unmask pixels.
1373                //-a r1-r2@xcenter,ycenter
1374                //-annulus r1-r2@xcenter,ycenter Add an annular region of pixels to the mask.  The annulus is
1375                //                               specified by its inner and outer radii and its center, which
1376                //                               may be floating point values.
1377                //-A r1-r2@xcenter,ycenter
1378                //-negannulus r1-r2@xcenter,ycenter   remove an annular region of masked pixels from the mask
1379        variable Dim1Center, Dim2Center, RadiusS, RadiusL
1380        string RadiusSpecs = StringFromList(0, MaskSpecs+"@", "@")
1381        RadiusS = str2num(StringFromList(0, RadiusSpecs+"-", "-"))
1382        RadiusL = str2num(StringFromList(1, RadiusSpecs+"-", "-"))
1383        string CenterSpecs=StringFromList(1, MaskSpecs+"@", "@")
1384        Dim1Center = str2num(StringFromList(0, CenterSpecs+",", ","))
1385        Dim2Center = str2num(StringFromList(1, CenterSpecs+",", ","))
1386        if(RadiusS>RadiusL)
1387                variable tmp1=RadiusS
1388                RadiusS = RadiusL
1389                RadiusL = tmp1
1390        endif
1391
1392        Dim1Center = Dim1Center>0 ? Dim1Center : 0
1393        Dim2Center = Dim2Center>0 ? Dim2Center : 0
1394        Dim1Center = Dim1Center<DimSize(MaskWave,0) ? Dim1Center : DimSize(MaskWave,0)-1
1395        Dim2Center = Dim2Center<DimSize(MaskWave,1) ? Dim2Center : DimSize(MaskWave,1)-1
1396        if(MaskIt)
1397                Multithread MaskWave = (sqrt((p-Dim1Center)^2+(q-Dim2Center)^2)>RadiusS && sqrt((p-Dim1Center)^2+(q-Dim2Center)^2)>RadiusL) ? MaskWave[p][q] : 0
1398        else
1399                Multithread MaskWave = (sqrt((p-Dim1Center)^2+(q-Dim2Center)^2)>RadiusS && sqrt((p-Dim1Center)^2+(q-Dim2Center)^2)>RadiusL) ? MaskWave[p][q] : 1
1400        endif
1401end
1402
1403
1404static Function NI1_12IDC_AddCircleMask(MaskWave,MaskSpecs,MaskIt)
1405                wave MaskWave           //thsi is Mask file
1406                string MaskSpecs                //thsi specifying mask location
1407                variable MaskIt                 //1 to mask off pixels, 0 to unmask pixels.
1408//-circle radius@xcenter,ycenter Add a circle of masked pixels to the mask.  The circle is specified
1409//                               by its radius and its center, which may be floating point
1410//                               values  e.g.,  -circle 14@774,309
1411        variable Dim1Center, Dim2Center, Radius
1412        Radius = str2num(StringFromList(0, MaskSpecs+"@", "@"))
1413        string CenterSpecs=StringFromList(1, MaskSpecs+"@", "@")
1414        Dim1Center = str2num(StringFromList(0, CenterSpecs+",", ","))
1415        Dim2Center = str2num(StringFromList(1, CenterSpecs+",", ","))
1416
1417        Dim1Center = Dim1Center>0 ? Dim1Center : 0
1418        Dim2Center = Dim2Center>0 ? Dim2Center : 0
1419        Dim1Center = Dim1Center<DimSize(MaskWave,0) ? Dim1Center : DimSize(MaskWave,0)-1
1420        Dim2Center = Dim2Center<DimSize(MaskWave,1) ? Dim2Center : DimSize(MaskWave,1)-1
1421        if(MaskIt)
1422                Multithread MaskWave = sqrt((p-Dim1Center)^2+(q-Dim2Center)^2)>Radius ? MaskWave[p][q] : 0
1423        else
1424                Multithread MaskWave = sqrt((p-Dim1Center)^2+(q-Dim2Center)^2)>Radius ? MaskWave[p][q] : 1
1425        endif
1426end
1427
1428static Function NI1_12IDC_AddRectangleMask(MaskWave,MaskSpecs,MaskIt)
1429                wave MaskWave           //thsi is Mask file
1430                string MaskSpecs                //thsi specifying mask location
1431                variable MaskIt                 //1 to mask off pixels, 0 to unmask pixels.
1432//-r rectspec
1433//-rect rectspec                 Add a rectangle of masked pixels to the mask.  The rectangle can
1434//                               be given in two different forms e.g. '10,15,80,250' specifies a
1435//                               rectangle with 10 >= x > 80 and 15 >= y > 250 and
1436//                               e.g. '120x80@20,30' specifies a rectangle of width 120 pixels and
1437//                               height 80 pixels centered at x=20, y=30
1438//                               All coordinates must be integers
1439        variable Dim1Left, Dim2Left, Dim1Right, Dim2Right
1440        if(GrepString(MaskSpecs, "x"))          //this is e.g. '120x80@20,30' specifies a rectangle of width 120 pixels and
1441                string SizeSpecs=StringFromList(0, MaskSpecs+"@", "@")
1442                string CenterSpecs=StringFromList(1, MaskSpecs+"@", "@")
1443                variable width=str2num(StringFromList(0, SizeSpecs+"x", "x"))
1444                variable height=str2num(StringFromList(1, SizeSpecs+"x", "x"))
1445                variable dim1Center=str2num(StringFromList(0, CenterSpecs+",", ","))
1446                variable dim2Center=str2num(StringFromList(1, CenterSpecs+",", ","))
1447                Dim1Left = dim1Center - ceil(width/2)
1448                Dim2Left = dim2Center - ceil(height/2)
1449                Dim1Right = dim1Center + ceil(width/2)
1450                Dim2Right = dim2Center + ceil(height/2)
1451        else                    //assume '10,15,80,250' specifies a
1452                MaskSpecs = MaskSpecs+","
1453                Dim1Left = str2num(StringFromList(0, MaskSpecs, ","))
1454                Dim2Left = str2num(StringFromList(1, MaskSpecs, ","))
1455                Dim1Right = str2num(StringFromList(2, MaskSpecs, ","))
1456                Dim2Right = str2num(StringFromList(3, MaskSpecs, ","))
1457        endif
1458        if(Dim1Left>Dim1Right)
1459                variable tmp1=Dim1Left
1460                Dim1Left = Dim1Right
1461                Dim1Right = tmp1
1462        endif
1463        if(Dim2Left>Dim2Right)
1464                variable tmp2=Dim2Left
1465                Dim2Left = Dim2Right
1466                Dim2Right = tmp2
1467        endif
1468        Dim1Left = Dim1Left>0 ? Dim1Left : 0
1469        Dim2Left = Dim2Left>0 ? Dim2Left : 0
1470        Dim1Right = Dim1Right<DimSize(MaskWave,0) ? Dim1Right : DimSize(MaskWave,0)-1
1471        Dim2Right = Dim2Right<DimSize(MaskWave,1) ? Dim2Right : DimSize(MaskWave,1)-1
1472        if(MaskIt)
1473                MaskWave[Dim1Left,Dim1Right][Dim2Left,Dim2Right] = 0
1474        else
1475                MaskWave[Dim1Left,Dim1Right][Dim2Left,Dim2Right] = 1
1476        endif
1477end
1478
1479
1480
1481//*******************************************************************************************************************************************
1482//*******************************************************************************************************************************************
1483
1484Function NI1_12IDC_Parsegoldnormengavg(CommandLine, LoadInNIka)
1485        string CommandLine
1486        variable LoadInNIka
1487       
1488        Variable PixSize,Distance,n3,n4,n5,BCX,BCY
1489        String s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12,s13,s14,s15,s16
1490       
1491        // goldaverage -o Averaged_norm -y -p 0.175 -d 2345 -Z 200 -k $normval -e $energyval -r146,915,158,980 -r143,980,164,1024 -r 0,908,1024,914 -c6@166,907 -c12@154,911 154 911 $filename
1492                                                //s1,s2,s3,s4,s5,pixSize,s6,Distance,s6,n3,s7,s8,s9,s10,s11,s12,s13,s14,n4,n5,s16
1493        sscanf CommandLine,"%s %s %s %s %s %f %s %f %s %f %s %s %s %s %s %s %s %s %f %f %s",s1,s2,s3,s4,s5,pixSize,s6,Distance,s6,n3,s7,s8,s9,s10,s11,s12,s13,s14,n4,n5,s16
1494        //this shoudl get us Distacne and pix size.
1495        string ReadEndStr=ReplaceString(" ", CommandLine, ";")
1496        BCX=str2num(StringFromList((ItemsInList(ReadEndStr)-3), ReadEndStr))
1497        BCY=str2num(StringFromList((ItemsInList(ReadEndStr)-2), ReadEndStr))
1498        if(numType(BCX)==2 || numtype(BCY)==2 || numtype(pixSIze)==2)
1499                Print "bad format line: "+CommandLine           
1500        endif
1501        //the pixel size of the Gold detector is 0.175 micron
1502        NVAR PixelSizeX=root:Packages:Convert2Dto1D:PixelSizeX
1503        NVAR PixelSizeY = root:Packages:Convert2Dto1D:PixelSizeY
1504        NVAR SampleToCCDDistance =root:Packages:Convert2Dto1D:SampleToCCDDistance
1505        NVAR BcentX = root:Packages:Convert2Dto1D:BeamCenterX
1506        NVAR BcentY = root:Packages:Convert2Dto1D:BeamCenterY
1507        if(LoadInNIka)
1508                PixelSizeX = pixSize
1509                PixelSizeY = pixSize
1510                SampleToCCDDistance = Distance
1511                BcentX = BCX
1512                BcentY = BCY
1513                print "Loaded distacne from command file of : "+num2str(SampleToCCDDistance)+" mm"
1514                print "Loaded Pixel Size from command file of : "+num2str(PixelSizeX)+" mm"
1515                print "Loaded Beam Center X from command file of : "+num2str(BcentX)+" pix"
1516                print "Loaded Beam Center Y from command file of : "+num2str(BcentY)+" pix"     
1517        else
1518                print "Found distacne in command file  : "+num2str(Distance)+" mm"
1519                print "Found Pixel Size in command file  : "+num2str(pixSize)+" mm"
1520                print "Found Beam Center X in command file  : "+num2str(BCX)+" pix"
1521                print "Found Beam Center Y in command file  : "+num2str(BCY)+" pix"     
1522        endif
1523end
1524//*******************************************************************************************************************************************
1525//*******************************************************************************************************************************************
1526
1527Function NI1_12IDCReadSpecFile(NumFilesExpected)
1528        Variable NumFilesExpected
1529       
1530        string OldDFf
1531        OldDFf = getDataFolder(1)
1532
1533        Variable refNum,err=0
1534        string pathInforStrL
1535        OPEN/R/T="????"/M="Find spec file" refNum
1536        //abort
1537        //OPEN/R/F="All Files:.*;"/M="Find spec file" refNum
1538        //OPEN/R/M="Find spec file" refNum
1539        if(strlen(S_fileName)>0)
1540                //init paths to the place where this file is...
1541                SVAR specCalibDataName=root:Packages:Convert2Dto1D:specCalibDataName
1542                specCalibDataName = S_fileName
1543                pathInforStrL = RemoveListItem((ItemsInList(S_fileName,":")-1),S_fileName,":")
1544                NI1_12IDCinitSpecFileArrays(NumFilesExpected)                   // max number of expected atoms
1545                Wave ExpTime=root:Packages:Nika_12IDCLookups:ExpTime
1546                Wave/T tt=root:Packages:Nika_12IDCLookups:Filenames
1547                String lineStr
1548                Variable count=0
1549                do
1550                        FreadLine refNum,lineStr
1551                        if(strlen(lineStr)<=0)
1552                                //break
1553                                err=1
1554                        endif
1555                        if(strsearch(lineStr,"#Z",0)>=0)
1556                                NI1_12IDCprocessSpecLine(lineStr,count)
1557                                count+=1
1558                                if(NumFilesExpected<=count)
1559                                        NumFilesExpected+=100
1560                                        NI1_12IDCredimSpecFileArrays(NumFilesExpected)
1561                                endif
1562                        endif
1563                while(err==0)
1564                Close refNum
1565                // trim the waves to final sizes:
1566                NI1_12IDCredimSpecFileArrays(count)
1567        else
1568                //Close refNum
1569                abort
1570        endif
1571        NewPath/O/Q Convert2Dto1DDataPath, pathInforStrL               
1572        NewPath/O/Q Convert2Dto1DEmptyDarkPath, pathInforStrL           
1573        NewPath/O/Q Convert2Dto1DBmCntrPath, pathInforStrL
1574        NewPath/O/Q Convert2Dto1DMaskPath, pathInforStrL
1575       
1576        setDataFolder OldDFf
1577       
1578End
1579//*******************************************************************************************************************************************
1580//*******************************************************************************************************************************************
1581//*******************************************************************************************************************************************
1582
1583
1584Function NI1_12IDCinitSpecFileArrays(num)
1585        Variable num
1586       
1587        NewDataFolder/O/S root:Packages
1588        NewDataFolder/O/S Nika_12IDCLookups
1589       
1590        Make/O/D/n=(num) ExpTime=nan
1591        Make/O/D/n=(num) I0=nan
1592        Make/O/D/n=(num) ITR=nan
1593        Make/O/D/n=(num) I01=nan
1594        Make/O/D/n=(num) MP1=nan
1595        Make/O/D/n=(num) MP2=nan
1596        Make/O/D/n=(num) MP3=nan
1597        Make/O/D/n=(num) MP4=nan
1598        Make/O/D/n=(num) MP5=nan
1599        Make/O/D/n=(num) MonoEnenergy=nan
1600        Make/O/D/n=(num) LakeShoreTemp=nan
1601        Make/O/T/n=(num) TimeString=""
1602        Make/O/D/n=(num) UnixTime=nan
1603        Make/O/T/n=(num) Filenames=""
1604End
1605//*******************************************************************************************************************************************
1606//*******************************************************************************************************************************************
1607//*******************************************************************************************************************************************
1608
1609Function NI1_12IDCredimSpecFileArrays(num)
1610        Variable num
1611       
1612        NewDataFolder/O/S root:Packages
1613        NewDataFolder/O/S Nika_12IDCLookups
1614
1615        Wave ExpTime=root:Packages:Nika_12IDCLookups:ExpTime
1616        Wave I0=root:Packages:Nika_12IDCLookups:I0
1617        Wave ITR=root:Packages:Nika_12IDCLookups:ITR
1618        Wave I01=root:Packages:Nika_12IDCLookups:I01
1619        Wave MP1=root:Packages:Nika_12IDCLookups:MP1
1620        Wave MP2=root:Packages:Nika_12IDCLookups:MP2
1621        Wave MP3=root:Packages:Nika_12IDCLookups:MP3
1622        Wave MP4=root:Packages:Nika_12IDCLookups:MP4
1623        Wave MP5=root:Packages:Nika_12IDCLookups:MP5
1624        Wave MonoEnenergy=root:Packages:Nika_12IDCLookups:MonoEnenergy
1625        Wave LakeShoreTemp=root:Packages:Nika_12IDCLookups:LakeShoreTemp
1626        Wave UnixTime=root:Packages:Nika_12IDCLookups:UnixTime
1627        Redimension/E=1/N=(num) ExpTime, I0, ITR, I01, MP1, MP2, MP3, MP4, MP5, MonoEnenergy, LakeShoreTemp, UnixTime
1628        Wave/T Filenames=root:Packages:Nika_12IDCLookups:Filenames
1629        Wave/T TimeString=root:Packages:Nika_12IDCLookups:TimeString
1630        Redimension/E=1/N=(num) TimeString, Filenames
1631End
1632//*******************************************************************************************************************************************
1633//*******************************************************************************************************************************************
1634//*******************************************************************************************************************************************
1635
1636Function NI1_12IDCprocessSpecLine(lineStr,count)
1637        String lineStr
1638        Variable count
1639       
1640        Variable n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,untime
1641        String s1,s2,s3,s4,s5,s6,s7
1642       
1643        //sscanf lineStr,"%s %d %s %s %s %d %f %f %f %f %f %s",s1,n1,s2,s3,s4,n2,xx,yy,zz,n4,n5,s5
1644        sscanf lineStr,"%s %s %f %f %f %f %f %f %f %f %f %f %f %f %s %s %s %s %s %f",s1,s2,n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,s3,s4,s5,s6,s7,untime
1645        if(numType(n1)==2 || numtype(n2)==2 || numtype(untime)==2)
1646                Print "bad format line: "+lineStr               
1647        endif
1648        Wave ExpTime=root:Packages:Nika_12IDCLookups:ExpTime
1649        Wave I0=root:Packages:Nika_12IDCLookups:I0
1650        Wave ITR=root:Packages:Nika_12IDCLookups:ITR
1651        Wave I01=root:Packages:Nika_12IDCLookups:I01
1652        Wave MP1=root:Packages:Nika_12IDCLookups:MP1
1653        Wave MP2=root:Packages:Nika_12IDCLookups:MP2
1654        Wave MP3=root:Packages:Nika_12IDCLookups:MP3
1655        Wave MP4=root:Packages:Nika_12IDCLookups:MP4
1656        Wave MP5=root:Packages:Nika_12IDCLookups:MP5
1657        Wave MonoEnenergy=root:Packages:Nika_12IDCLookups:MonoEnenergy
1658        Wave LakeShoreTemp=root:Packages:Nika_12IDCLookups:LakeShoreTemp
1659        Wave UnixTime=root:Packages:Nika_12IDCLookups:UnixTime
1660        Wave/T Filenames=root:Packages:Nika_12IDCLookups:Filenames
1661        Wave/T TimeString=root:Packages:Nika_12IDCLookups:TimeString
1662        Filenames[count] = s2
1663        ExpTime[count] = n1-0.5
1664        I0[count] = n2
1665        ITR[count] = n3
1666        I01[count] = n4
1667        MP1[count] = n6
1668        MP2[count] = n7
1669        MP3[count] = n8
1670        MP4[count] = n9
1671        MP5[count] = n10
1672        MonoEnenergy[count] = n11
1673        LakeShoreTemp[count] = n12
1674        TimeString[count] = s3+" "+s4+" "+s5+" "+s6+" "+s7
1675        UnixTime[count] = untime
1676End
1677
1678//*******************************************************************************************************************************************
1679//*******************************************************************************************************************************************
1680//*******************************************************************************************************************************************
1681
1682Function NI1_12IDCFindI0(FileNameString)
1683        string FileNameString
1684        Wave/T Filenames=root:Packages:Nika_12IDCLookups:Filenames
1685        Wave I0=root:Packages:Nika_12IDCLookups:I0
1686        grep/INDX/Q/E=FileNameString Filenames 
1687        wave W_Index
1688        //let use this place to also insert energy
1689        Wave MonoEnenergy = root:Packages:Nika_12IDCLookups:MonoEnenergy
1690        NVAR Wavelength = root:Packages:Convert2Dto1D:Wavelength
1691        NVAR XrayEnergy = root:Packages:Convert2Dto1D:XrayEnergy
1692        XrayEnergy = MonoEnenergy[W_Index[0]]
1693        Wavelength = 12.39841857/XrayEnergy
1694        if(numpnts(W_Index)==1)
1695                return I0[W_Index[0]]
1696        else
1697                return nan
1698        endif
1699end
1700//*******************************************************************************************************************************************
1701//*******************************************************************************************************************************************
1702//*******************************************************************************************************************************************
1703
1704Function NI1_12IDCFindEmptyI0(FileNameString)
1705        string FileNameString
1706        SVAR CurrentEmptyName = root:Packages:Convert2Dto1D:CurrentEmptyName
1707        Wave/T Filenames=root:Packages:Nika_12IDCLookups:Filenames
1708        Wave I0=root:Packages:Nika_12IDCLookups:I0
1709        grep/INDX/Q/E=CurrentEmptyName Filenames       
1710        wave W_Index
1711        if(numpnts(W_Index)==1)
1712                return I0[W_Index[0]]
1713        else
1714                return nan
1715        endif
1716end
1717//*******************************************************************************************************************************************
1718//*******************************************************************************************************************************************
1719//*******************************************************************************************************************************************
1720
1721Function NI1_12IDCFindTrans(FileNameString)
1722        string FileNameString
1723        SVAR CurrentEmptyName = root:Packages:Convert2Dto1D:CurrentEmptyName
1724        Wave/T Filenames=root:Packages:Nika_12IDCLookups:Filenames
1725        Wave I0=root:Packages:Nika_12IDCLookups:I0
1726        Wave ITR =root:Packages:Nika_12IDCLookups:ITR
1727        grep/INDX/Q/E=CurrentEmptyName Filenames       
1728        wave W_Index
1729        variable I0E = I0[W_Index[0]]
1730        variable ITRE = ITR[W_Index[0]]
1731        grep/INDX/Q/E=FileNameString Filenames 
1732        wave W_Index
1733        variable I0S = I0[W_Index[0]]
1734        variable ITRS = ITR[W_Index[0]]
1735        variable Transm = (ITRS/I0S)/(ITRE/I0E)
1736       
1737        if(numtype(Transm)==0 && Transm>0)
1738                return Transm
1739        else
1740                return nan
1741        endif
1742end
1743//*******************************************************************************************************************************************
1744//*******************************************************************************************************************************************
1745
1746Function NI1_12IDCHowTo()
1747       
1748        doWIndow APS12IDC_Instructions
1749        if(V_Flag)
1750                DoWIndow/F APS12IDC_Instructions
1751        else
1752                String nb = "APS12IDC_Instructions"
1753                NewNotebook/N=$nb/F=1/V=1/K=1/ENCG={1,1}/W=(20,20,680,620) as "APS12IDC_Instructions"
1754                Notebook $nb defaultTab=36, magnification=125
1755                Notebook $nb showRuler=1, rulerUnits=2, updating={1, 1}
1756                Notebook $nb newRuler=Normal, justification=0, margins={0,0,468}, spacing={0,0,0}, tabs={}, rulerDefaults={"Helvetica",11,0,(0,0,0)}
1757                Notebook $nb newRuler=Title, justification=0, margins={0,0,468}, spacing={0,0,0}, tabs={}, rulerDefaults={"Geneva",12,3,(0,0,0)}
1758                Notebook $nb ruler=Title, text="Instructions for use of APS 12IDC special configuration\r"
1759                Notebook $nb ruler=Normal, text="\r"
1760                Notebook $nb text="\r"
1761                Notebook $nb text="1. Find and open your spec file, located in the same folder as your tiff images. Note, data collection records f"
1762                Notebook $nb text="or all images present in that spec file are loaded, this may take some time if there is lots of images recorded in that spec file."
1763                Notebook $nb text=" \r"
1764                Notebook $nb text="\r"
1765                Notebook $nb text="2. If the code can find  \"goldnormengavg\" file in this location, you will get dialog that \"Beamline para"
1766                Notebook $nb text="ms & mask was found\". Choices are \"Load beamline parameters\" and  \"Create beamline defined mask?\", default choice is NO.\r"
1767                Notebook $nb text="* If you select YES for \"Load beamline parameters\" code will load pixel size, distance and beam center.\r"
1768                Notebook $nb text="* If you select YES for \"Create beamline defined mask?\" code will replace any existing mask with beamline"
1769                Notebook $nb text=" defined mask.\r"
1770                Notebook $nb text="Select No if you changed parameters or mask against what beamline defined. \r"
1771                Notebook $nb text="\r"
1772                Notebook $nb text=">>>  MASK suggestion: Create new Mask in Nika, DO NOT reuse old beamline mask. Nika has easier to use tools to create the best possible mask. <<<\r"
1773                Notebook $nb text="\r"
1774                Notebook $nb text="note: X-ray energy is re-loaded for each image individually, when I0 is looked up by the lookup function"
1775                Notebook $nb text=". This guarantees, that during ASAXS each image is reduced with correct wavelength. \r"
1776                Notebook $nb text="\r"
1777                Notebook $nb text="3. If you choose to create Mask, you will get dialog to load any of the data images from this folder."
1778                Notebook $nb text="This is needed to identify 0 intensity pixels and mask them. Select any data containing image"
1779                Notebook $nb text=" in this folder. \r"
1780                Notebook $nb text="\r"
1781                Notebook $nb text="4. Next select correct Empty image in the Em/Dark tab. \r"
1782                Notebook $nb text="\r"
1783                Notebook $nb text="Nika should be configured - you may want to change method of data reduction (default is circular average with 300 log-spaced Q bins)"
1784                Notebook $nb text=" and output type (default is save data in Igor)...  \r"
1785                Notebook $nb text="\r"
1786                Notebook $nb text="Note: if you are still collecting data, you will need to go through this routine again after you callect new"
1787                Notebook $nb text=" images from the last time you loaded the spec file. "
1788                Notebook $nb text="\r"
1789                Notebook $nb text="\r"
1790                Notebook $nb text="Jan Ilavsky, 8/27/2018\r"
1791                Notebook $nb text="\r"
1792                Notebook $nb defaultTab=36, magnification=125
1793                Notebook $nb showRuler=1, rulerUnits=2, updating={1, 1}
1794                Notebook $nb newRuler=Normal, justification=0, margins={0,0,468}, spacing={0,0,0}, tabs={}, rulerDefaults={"Helvetica",11,0,(0,0,0)}
1795                Notebook $nb ruler=Normal, fStyle=2, text="Hint: watch history area for notes on what Nika has found and done. \r"
1796                Notebook $nb selection={startOfFile,startOfFile}
1797               
1798        endif
1799end
1800
1801//*******************************************************************************************************************************************
1802//                      end of 12ID-C camera support.
1803//*******************************************************************************************************************************************
1804//*******************************************************************************************************************************************
1805//*******************************************************************************************************************************************
1806
1807//*******************************************************************************************************************************************
1808//*******************************************************************************************************************************************
1809//              APS 12ID-B camera SAXS and WAXS (not test for PE yet)
1810
1811Function NI1_12IDBLoadAndSetup()
1812        //this is function to setup data reduction for APS 12ID-B station using SAXS and WAXS detectors
1813        //uses 12IDB_tif file type
1814       
1815        string OldDFf=GetDataFolder(1)
1816        //first initialize
1817        KillWindow/Z CCDImageToConvertFig
1818        NI1A_Convert2Dto1DMainPanel()
1819        NI1BC_InitCreateBmCntrFile()
1820        NI1_12IDBHowTo()
1821
1822        setDataFOlder root:Packages:Convert2Dto1D:
1823        NI1A_ButtonProc("Select2DDataPath")
1824        PathInfo Convert2Dto1DDataPath
1825        string DataFilePath=S_path
1826        NewPath/Q/O Convert2Dto1DEmptyDarkPath, S_path 
1827        String DoingWhat= StringFromList(ItemsInList(DataFilePath,":")-1, DataFilePath,":")
1828        //now we need to get idea, what the user wants to do.
1829        //Options: tif/nexus
1830        //SAXS/WAXS ?
1831        //Mask - which from selection or none?
1832        //Load parameters always or only first time.
1833        //now get user input and load parameters and mask...
1834        NI1_12IDBGetUserInput()
1835        NVAR APS12IDBProcMethod                         //0 for beamline method (no background), 1 for Nika standard (with background).
1836        NVAR APS12IDBReloadPars                         //Parameterrs - 0 for not reloading calibration parameters, 1 for reload with each data file.
1837        SVAR APS12IDBDataType                           // = "12IDB_tif"                //default for tiff files. May change to Nexus later when that is standard.
1838        //SVAR APS12IDBMask                     // = "---"                                      //default for none. User needs to create one in Nika
1839        //SVAR APS12IDBGeometry                 //SAXS or WAXS?
1840       
1841        SVAR DataFileExtension=root:Packages:Convert2Dto1D:DataFileExtension
1842        SVAR BlankFileExtension=root:Packages:Convert2Dto1D:BlankFileExtension
1843        BlankFileExtension = APS12IDBDataType
1844        //select the right type of data
1845        DataFileExtension = APS12IDBDataType
1846        PopupMenu Select2DDataType win=NI1A_Convert2Dto1DPanel, popmatch= APS12IDBDataType
1847
1848       
1849        //setup configuration hwo this will be dome here:
1850        NVAR UseSampleTransmission = root:Packages:Convert2Dto1D:UseSampleTransmission
1851        NVAR UseSampleThickness = root:Packages:Convert2Dto1D:UseSampleThickness
1852        NVAR UseEmptyField = root:Packages:Convert2Dto1D:UseEmptyField
1853        NVAR UseI0ToCalibrate = root:Packages:Convert2Dto1D:UseI0ToCalibrate
1854
1855        NVAR DoGeometryCorrection = root:Packages:Convert2Dto1D:DoGeometryCorrection
1856        NVAR UseMonitorForEf = root:Packages:Convert2Dto1D:UseMonitorForEf
1857        NVAR UseSampleTransmFnct = root:Packages:Convert2Dto1D:UseSampleTransmFnct
1858        NVAR UseSampleThicknFnct = root:Packages:Convert2Dto1D:UseSampleThicknFnct
1859        NVAR UseSampleMonitorFnct = root:Packages:Convert2Dto1D:UseSampleMonitorFnct
1860        NVAR UseEmptyMonitorFnct = root:Packages:Convert2Dto1D:UseEmptyMonitorFnct
1861        NVAR UseMonitorForEF=root:Packages:Convert2Dto1D:UseMonitorForEF
1862        NVAR XrayEnergy = root:Packages:Convert2Dto1D:XrayEnergy
1863        NVAR Wavelength = root:Packages:Convert2Dto1D:Wavelength
1864        NVAR PixelSizeX = root:Packages:Convert2Dto1D:PixelSizeX
1865        NVAR PixelSizeY = root:Packages:Convert2Dto1D:PixelSizeY
1866        NVAR SampleToCCDdistance = root:Packages:Convert2Dto1D:SampleToCCDdistance
1867        NVAR BeamCenterX = root:Packages:Convert2Dto1D:BeamCenterX
1868        NVAR BeamCenterY = root:Packages:Convert2Dto1D:BeamCenterY
1869        NVAR UseCorrectionFactor = root:Packages:Convert2Dto1D:UseCorrectionFactor
1870        NVAR CorrectionFactor = root:Packages:Convert2Dto1D:CorrectionFactor
1871        NVAR UseSolidAngle = root:Packages:Convert2Dto1D:UseSolidAngle
1872        SVAR SampleTransmFnct = root:Packages:Convert2Dto1D:SampleTransmFnct
1873        SVAR SampleThicknFnct = root:Packages:Convert2Dto1D:SampleThicknFnct
1874        SVAR SampleMonitorFnct = root:Packages:Convert2Dto1D:SampleMonitorFnct
1875        SVAR EmptyMonitorFnct = root:Packages:Convert2Dto1D:EmptyMonitorFnct
1876       
1877        NVAR ErrorCalculationsUseSEM = root:Packages:Convert2Dto1D:ErrorCalculationsUseSEM
1878        NVAR ErrorCalculationsUseStdDev = root:Packages:Convert2Dto1D:ErrorCalculationsUseStdDev
1879        NVAR ErrorCalculationsUseOld = root:Packages:Convert2Dto1D:ErrorCalculationsUseOld
1880       
1881        ErrorCalculationsUseOld = 0
1882        ErrorCalculationsUseStdDev = 0
1883        ErrorCalculationsUseSEM = 1
1884       
1885        if(APS12IDBProcMethod)
1886                UseSampleTransmission = 1
1887                UseSampleThickness = 0
1888                UseEmptyField = 1
1889                UseI0ToCalibrate = 1
1890                DoGeometryCorrection = 1
1891                UseMonitorForEf = 1
1892       
1893                UseSampleThicknFnct  =1
1894                UseSampleTransmFnct = 1
1895        //      UseSampleThicknFnct =1
1896                UseSampleMonitorFnct = 1
1897                UseEmptyMonitorFnct = 1
1898               
1899                UseCorrectionFactor = 0
1900                CorrectionFactor = 1
1901                UseSolidAngle = 0
1902               
1903                SampleTransmFnct = "NI1_12IDBGetTranmsission"
1904                SampleMonitorFnct = "NI1_12IDBGetSampleI0"
1905                EmptyMonitorFnct = "NI1_12IDBGetEmptyI0"
1906        else //no background subtraction
1907                UseSampleTransmission = 0
1908                UseSampleThickness = 0
1909                UseEmptyField = 0
1910                UseI0ToCalibrate = 1
1911                DoGeometryCorrection = 1
1912                UseMonitorForEf = 0
1913       
1914                UseSampleThicknFnct  = 0
1915                UseSampleTransmFnct = 0
1916        //      UseSampleThicknFnct =1
1917                UseSampleMonitorFnct = 1
1918                UseEmptyMonitorFnct = 0
1919
1920                UseCorrectionFactor = 1
1921                CorrectionFactor = 2.4e-06                      //this should be fudge factor 12IDB is using to correct data to 0.1-100 intensity range...
1922                UseSolidAngle = 1                                               //thsi is needed for that fudge factor above.
1923               
1924                SampleTransmFnct = ""
1925                SampleMonitorFnct = "NI1_12IDBGetSampleBS"
1926                EmptyMonitorFnct = ""
1927
1928        endif
1929
1930        //now configure Nika to produce some data...
1931        NVAR DisplayDataAfterProcessing = root:Packages:Convert2Dto1D:DisplayDataAfterProcessing
1932        DisplayDataAfterProcessing=1
1933        NVAR StoreDataInIgor = root:Packages:Convert2Dto1D:StoreDataInIgor
1934        StoreDataInIgor=1
1935        NVAR OverwriteDataIfExists = root:Packages:Convert2Dto1D:OverwriteDataIfExists
1936        OverwriteDataIfExists=1
1937        NVAR UseSectors=root:Packages:Convert2Dto1D:UseSectors
1938        UseSectors =1
1939        NVAR DoCircularAverage = root:Packages:Convert2Dto1D:DoCircularAverage
1940        DoCircularAverage = 1
1941       
1942        NVAR QvectorMaxNumPnts = root:Packages:Convert2Dto1D:QvectorMaxNumPnts
1943        NVAR QbinningLogarithmic = root:Packages:Convert2Dto1D:QbinningLogarithmic
1944        NVAR QvectorNumberPoints = root:Packages:Convert2Dto1D:QvectorNumberPoints
1945        if(stringmatch(DoingWhat,"SAXS"))
1946                QbinningLogarithmic=1
1947                //QvectorMaxNumPnts=0
1948                //QvectorNumberPoints = 600
1949                //these are set by configuration file now.
1950        else
1951                //WAXS
1952                QbinningLogarithmic=0
1953                QvectorMaxNumPnts=1
1954        endif
1955        if(APS12IDBProcMethod)
1956                //send user to Empty/Dark tab
1957                TabControl Convert2Dto1DTab win=NI1A_Convert2Dto1DPanel, value=3
1958                NI1A_TabProc("NI1A_Convert2Dto1DPanel",3)       
1959        else
1960                //send user to Empty/Dark tab
1961                TabControl Convert2Dto1DTab win=NI1A_Convert2Dto1DPanel, value=0
1962                NI1A_TabProc("NI1A_Convert2Dto1DPanel",0)       
1963        endif
1964        setDataFolder OldDFf
1965
1966end
1967
1968
1969//*******************************************************************************************************************************************
1970//*******************************************************************************************************************************************
1971//*******************************************************************************************************************************************
1972//*******************************************************************************************************************************************
1973
1974Function NI1_12IDBGetUserInput()                        //todo: some error handling...
1975                //should be able to find mask in current working folder
1976        string OldDFf=GetDataFolder(1)
1977        setDataFolder root:Packages:Convert2Dto1D:
1978        NVAR UseMask = root:Packages:Convert2Dto1D:UseMask
1979        //Init needed APS12IDB... Parameters
1980        variable/g APS12IDBProcMethod = 0                               //0 for beamline method (no background), 1 for Nika standard (with background).
1981        variable/g APS12IDBReloadPars = 0                               //Parameterrs - 0 for not reloading calibration parameters, 1 for reload with each data file.
1982        string/g APS12IDBDataType = "12IDB_tif"                 //default for tiff files. May change to Nexus later when that is standard.
1983        //string/g APS12IDBMask = "---"                                 //default for none. User needs to create one in Nika
1984        string/g APS12IDBGeometry = "SAXS"                              //SAXS or WAXS?
1985        //Get what we are using here...
1986        PathInfo Convert2Dto1DDataPath
1987        string DataFilePath=S_path
1988        //here we know what we are processing... Either the last folder is SAXS or WAXS
1989        string UsingWhat=StringFromList(ItemsInList(DataFilePath,":")-1, DataFilePath,":")
1990        if(StringMatch(UsingWhat, "SAXS"))
1991                APS12IDBGeometry = "SAXS"
1992        elseif(StringMatch(UsingWhat, "WAXS"))
1993                APS12IDBGeometry = "WAXS"
1994        else
1995                abort "Wrong folder with data selected, this folder is not called SAXS or WAXS"
1996        endif
1997        //now what type of files are we using?
1998        string ListOfTifFiles=IndexedFile(Convert2Dto1DDataPath, -1, ".tif")
1999        string ListOfHDF5Files=IndexedFile(Convert2Dto1DDataPath, -1, ".hdf")
2000        if(itemsInList(ListOfTifFiles)>0)
2001                APS12IDBDataType = "12IDB_tif"
2002        elseif(itemsInList(ListOfHDF5Files)>0)
2003                APS12IDBDataType = "Nexus"
2004        else
2005                abort "Unknown image data file type. Can read .tif or .hdf (Nexus) only."
2006        endif
2007        //get calibration files.
2008        //get the path to calibration and SAXS_mask2M.bmp or WAXS_mask2M.bpm, it is one level up...
2009        string MaskPathStr= RemoveFromList(UsingWhat, DataFilePath,":")
2010        NewPath/O/Q TempMaskUserPath, MaskPathStr
2011        string ListOfCalibrations=GrepList(IndexedFile(TempMaskUserPath, -1, ".txt"), "(?i)calibration_parameters")
2012        string SelectedCalibrationFile =RemoveEnding(GrepList(ListOfCalibrations,"(?i)"+UsingWhat), ";")                //this now should be saxs_calibration_parameters or waxs_calibration_parameters
2013        print SelectedCalibrationFile
2014        //get the mask files...
2015        //mask may or may not exist, we need to get user to pick one or tell us it does not exist...
2016        string ListOfBMPFiles=IndexedFile(TempMaskUserPath, -1, ".bmp")
2017        string SelectedMaskFile = RemoveEnding(GrepList(ListOfBMPFiles,"(?i)"+UsingWhat),";")
2018       
2019        string LoadCalibration
2020        string LoadMaskFile
2021        string AlwaysReloadParameters
2022        string ProcessingTypeStr
2023        //dialog...
2024       
2025        Prompt LoadCalibration, "Load calibration from "+SelectedCalibrationFile+"?", popup, "Yes;No;"
2026        if(strlen(SelectedMaskFile)>0)
2027                Prompt LoadMaskFile, "Load BMP Mask file "+SelectedMaskFile+"?", popup, "Yes;No;"
2028        else
2029                Prompt LoadMaskFile, "No Mask file found", popup, "No;"
2030        endif
2031        Prompt ProcessingTypeStr, "Subtract Empty/background ?", popup, "No;Yes;"
2032        Prompt AlwaysReloadParameters, "Reload geometry for each image ?", popup, "No;Yes;"
2033        DoPrompt "Setup parameters", ProcessingTypeStr, LoadCalibration, AlwaysReloadParameters, LoadMaskFile
2034        if(V_Flag)
2035                abort
2036        else
2037                //setup processing method
2038                if(stringMatch(ProcessingTypeStr,"Yes"))
2039                        APS12IDBProcMethod = 1                  //subtract background (materials SAXS common).
2040                else
2041                        APS12IDBProcMethod = 0                  //do not subtract background (bioSAXS common)
2042                endif
2043                //Reload metadata always?
2044                if(stringMatch(AlwaysReloadParameters,"Yes"))
2045                        APS12IDBReloadPars = 1                  //reload metadata with each image?
2046                else
2047                        APS12IDBReloadPars = 0                  //do not reload metadata with each image
2048                endif
2049                //mask...
2050                if(stringmatch(LoadMaskFile,"Yes"))
2051                        ImageLoad/T=bmp/Q/N=TMPBMPMask/Z/P=TempMaskUserPath SelectedMaskFile
2052                        if(V_Flag)
2053                                print ":Loaded succesfully mask file from "+MaskPathStr+SelectedMaskFile
2054                        else
2055                                DoALert/T="Could not load Mask file" 0, "Could not load selected file with mask, you need to create mask manually"
2056                                UseMask = 0
2057                        endif
2058                        Wave LoadedmaskImage = TMPBMPMask
2059                        ImageTransform rgb2gray LoadedmaskImage
2060                        Wave M_RGB2Gray
2061                        ImageTransform flipCols M_RGB2Gray                      //this is correct flip needed...
2062                        DoWIndow CCDImageToConvertFig
2063                        if(V_Flag)
2064                                RemoveImage/W=CCDImageToConvertFig/Z  M_ROIMask
2065                        endif
2066                        KillWaves/Z M_ROIMask, TMPBMPMask
2067                        wavestats/Q M_RGB2Gray
2068                        M_RGB2Gray/=V_max                               //normalize to be 1 or 0, seem to be 255
2069                        Rename M_RGB2Gray, M_ROIMask
2070                        UseMask = 1
2071                else
2072                        Wave M_ROIMask
2073                        KillWaves/Z M_ROIMask
2074                        UseMask = 0
2075                        print "No Mask Loaded, user needs to setup their own "
2076                endif
2077                //parse the parameter file
2078                if(stringmatch(LoadCalibration,"Yes"))
2079                        NI1_12IDBLoadTXTMetadata(MaskPathStr, SelectedCalibrationFile) 
2080                else
2081                        print "No calibration file loaded. You are on your own!!!"
2082                endif
2083        endif
2084
2085
2086        setDataFolder OldDFf   
2087        return APS12IDBProcMethod
2088end
2089//*******************************************************************************************************************************************
2090//*******************************************************************************************************************************************
2091//*******************************************************************************************************************************************
2092Function/S NI1_12IDBLoadTXTMetadata(PathStr, FileNameToLoad)           
2093        string PathStr, FileNameToLoad
2094       
2095        NewPath/O/Q/Z LogFilesPath, PathStr
2096        variable refNum, err
2097        string OneLineStr, MetadataString="", newWaveNOte=""
2098        open/R/T="????"/P=LogFilesPath/Z refNum as FileNameToLoad
2099        if(V_flag!=0)
2100                close refNum
2101                Abort "Metadata import failed"
2102        else            //open succesful
2103                Do
2104                        FreadLine refNum,OneLineStr
2105                        if(strlen(OneLineStr)<=0)
2106                                //break
2107                                err=1
2108                        endif
2109                        MetadataString+=OneLineStr+";"
2110                while(err==0)
2111                Close refNum
2112        endif
2113        MetadataString = ReplaceString("%", MetadataString, "")
2114        MetadataString = ReplaceString("\n", MetadataString, "")
2115        MetadataString = ReplaceString("\r", MetadataString, "")
2116        //MetadataString = ReplaceString(" ", MetadataString, "")
2117        string currentItemString
2118        variable i=0
2119        do
2120                currentItemString=StringFromList(i, MetadataString, ";")
2121                i+=1
2122                NI1_12IDBProcessTXTLine(currentItemString)
2123        while(strlen(currentItemString)>0)
2124end
2125
2126//*******************************************************************************************************************************************
2127//*******************************************************************************************************************************************
2128//*******************************************************************************************************************************************
2129Function NI1_12IDBProcessTXTLine(LineToProcess)
2130        string LineToProcess
2131       
2132        if(StringMatch(LineToProcess, "*[*]*" ))
2133                LineToProcess[strsearch(LineToProcess, " ", strsearch(LineToProcess, "[", 0))]=";"
2134                LineToProcess = ReplaceString("[", LineToProcess, "")
2135                LineToProcess = ReplaceString("]", LineToProcess, "")
2136        endif
2137       
2138        LineToProcess=ReplaceString(" ", LineToProcess, "")+";"
2139        if(StringMatch(LineToProcess, "*row*" ))
2140                variable/g APS12IDBtempRow = NumberByKey("row", LineToProcess, ":", ";")
2141        endif
2142        if(StringMatch(LineToProcess, "*col*" ))
2143                variable/g APS12IDBtempCol = NumberByKey("col", LineToProcess, ":", ";")
2144        endif
2145        if(StringMatch(LineToProcess, "*pSize*" ))
2146                NVAR PixelSizeX = root:Packages:Convert2Dto1D:PixelSizeX
2147                NVAR PixelSizeY = root:Packages:Convert2Dto1D:PixelSizeY
2148                PixelSizeX = NumberByKey("pSize", LineToProcess, ":", ";")
2149                PixelSizeY = NumberByKey("pSize", LineToProcess, ":", ";")
2150        endif
2151        if(StringMatch(LineToProcess, "*SDD*" )&& !StringMatch(LineToProcess, "*SDDrel*" ))
2152                NVAR SampleToCCDdistance = root:Packages:Convert2Dto1D:SampleToCCDdistance
2153                SampleToCCDdistance = NumberByKey("SDD", LineToProcess, ":", ";")
2154        endif
2155        if(StringMatch(LineToProcess, "*BeamXY*" ))
2156                NVAR BeamCenterX = root:Packages:Convert2Dto1D:BeamCenterX
2157                NVAR BeamCenterY = root:Packages:Convert2Dto1D:BeamCenterY
2158                NVAR APS12IDBtempRow
2159                //Again, THIS IS INVERTED...
2160                string TempStr=StringByKey("BeamXY", LineToProcess+"p", ":", "p")
2161                variable BCX, BCY
2162                BCX = str2num(StringFromList(0,TempStr,";"))
2163                BCY = str2num(StringFromList(1,TempStr,";"))
2164                BeamCenterY = APS12IDBtempRow - BCY             
2165                BeamCenterX = BCX
2166        endif
2167        if(StringMatch(LineToProcess, "*eng*" )&&!StringMatch(LineToProcess, "*wavelength*" )&&!StringMatch(LineToProcess, "*xeng*" ))
2168                NVAR XrayEnergy = root:Packages:Convert2Dto1D:XrayEnergy
2169                NVAR Wavelength = root:Packages:Convert2Dto1D:Wavelength
2170                XrayEnergy = NumberByKey("eng", LineToProcess, ":", ";")
2171                Wavelength = 12.39842/XrayEnergy
2172        endif
2173        if(StringMatch(LineToProcess, "*wavelength*" ))
2174                NVAR Wavelength = root:Packages:Convert2Dto1D:Wavelength
2175                Wavelength = NumberByKey("wavelength", LineToProcess, ":", ";")
2176        endif
2177        if(StringMatch(LineToProcess, "*yaw*" ))
2178                NVAR VerticalTilt = root:Packages:Convert2Dto1D:VerticalTilt
2179                //Again, THIS IS INVERTED...
2180                VerticalTilt = -1* NumberByKey("yaw", LineToProcess, ":", ";")         
2181        endif
2182        if(StringMatch(LineToProcess, "*absIntCoeff*" ))
2183                NVAR CorrectionFactor = root:Packages:Convert2Dto1D:CorrectionFactor
2184                //Again, THIS IS INVERTED...
2185                CorrectionFactor = 1e-6 * NumberByKey("absIntCoeff", LineToProcess, ":", ";")           
2186        endif
2187        if(StringMatch(LineToProcess, "*qNum*" ))
2188                NVAR QvectorNumberPoints = root:Packages:Convert2Dto1D:QvectorNumberPoints
2189                QvectorNumberPoints = NumberByKey("qNum", LineToProcess, ":", ";")             
2190        endif
2191        if(StringMatch(LineToProcess, "*qMin*" ))
2192                NVAR UserQMin = root:Packages:Convert2Dto1D:UserQMin
2193                UserQMin = NumberByKey("qMin", LineToProcess, ":", ";")         
2194        endif
2195        if(StringMatch(LineToProcess, "*qMax*" ))
2196                NVAR UserQMax = root:Packages:Convert2Dto1D:UserQMax
2197                UserQMax = NumberByKey("qMax", LineToProcess, ":", ";")         
2198        endif
2199
2200       
2201       
2202end
2203//*******************************************************************************************************************************************
2204//*******************************************************************************************************************************************
2205
2206//*******************************************************************************************************************************************
2207//*******************************************************************************************************************************************
2208Function NI1_12IDBGetTranmsission(fileName)
2209        string fileName
2210
2211        wave/Z CCDImageToConvert = root:Packages:Convert2Dto1D:CCDImageToConvert
2212        wave/Z EmptyData = root:Packages:Convert2Dto1D:EmptyData
2213        if(!WaveExists(CCDImageToConvert) || !WaveExists(EmptyData))
2214                abort "Needed Images do not exist. Load Sample and Emty data before going further"
2215        endif
2216        string sampleNote=note(CCDImageToConvert)
2217        sampleNote = ReplaceString(" ", sampleNote, "")
2218        string emptyNote=note(EmptyData)
2219        emptyNote = ReplaceString(" ", emptyNote, "")
2220        variable SampleBeamStopDiode=NumberByKey("Photodiode", sampleNote , ":" , ";")
2221        variable EmptyBeamStopDiode=NumberByKey("Photodiode", emptyNote , ":" , ";")
2222        variable SampleBeamStopI0=NumberByKey("I0", sampleNote , ":" , ";")
2223        variable EmptyBeamStopI0=NumberByKey("I0", emptyNote , ":" , ";")
2224        variable transmission = (SampleBeamStopDiode/SampleBeamStopI0)/(EmptyBeamStopDiode/EmptyBeamStopI0)
2225        print "Found transmission = "+num2str(transmission)
2226        return transmission
2227end
2228//*******************************************************************************************************************************************
2229
2230Function NI1_12IDBGetSampleBS(fileName)
2231        string fileName
2232        wave/Z CCDImageToConvert = root:Packages:Convert2Dto1D:CCDImageToConvert
2233        //wave/Z EmptyData = root:Packages:Convert2Dto1D:EmptyData
2234        if(!WaveExists(CCDImageToConvert))// || !WaveExists(EmptyData))
2235                abort "Needed Image do not exist. Load Sample data before going further"
2236        endif
2237        string sampleNote=note(CCDImageToConvert)
2238        sampleNote = ReplaceString(" ", sampleNote, "")
2239        //string emptyNote=note(EmptyData)
2240        //emptyNote = ReplaceString(" ", emptyNote, "")
2241        //variable SampleBeamStopDiode=NumberByKey("Photodiode", sampleNote , ":" , ";")
2242        //variable EmptyBeamStopDiode=NumberByKey("Photodiode", emptyNote , ":" , ";")
2243        variable SampleBeamStopBS=NumberByKey("BS", sampleNote , ":" , ";")
2244        //variable EmptyBeamStopI0=NumberByKey("I0", emptyNote , ":" , ";")
2245        //variable I0Normalized = (SampleBeamStopDiode/SampleBeamStopI0)//(EmptyBeamStopDiode/EmptyBeamStopI0)
2246        print "Found Sample BS = "+num2str(SampleBeamStopBS)
2247        return SampleBeamStopBS
2248end
2249//*******************************************************************************************************************************************
2250
2251Function NI1_12IDBGetSampleI0(fileName)
2252        string fileName
2253        wave/Z CCDImageToConvert = root:Packages:Convert2Dto1D:CCDImageToConvert
2254        //wave/Z EmptyData = root:Packages:Convert2Dto1D:EmptyData
2255        if(!WaveExists(CCDImageToConvert))// || !WaveExists(EmptyData))
2256                abort "Needed Image do not exist. Load Sample data before going further"
2257        endif
2258        string sampleNote=note(CCDImageToConvert)
2259        sampleNote = ReplaceString(" ", sampleNote, "")
2260        //string emptyNote=note(EmptyData)
2261        //emptyNote = ReplaceString(" ", emptyNote, "")
2262        //variable SampleBeamStopDiode=NumberByKey("Photodiode", sampleNote , ":" , ";")
2263        //variable EmptyBeamStopDiode=NumberByKey("Photodiode", emptyNote , ":" , ";")
2264        variable SampleBeamStopI0=NumberByKey("I0", sampleNote , ":" , ";")
2265        //variable EmptyBeamStopI0=NumberByKey("I0", emptyNote , ":" , ";")
2266        //variable I0Normalized = (SampleBeamStopDiode/SampleBeamStopI0)//(EmptyBeamStopDiode/EmptyBeamStopI0)
2267        print "Found Sample I0 = "+num2str(SampleBeamStopI0)
2268        return SampleBeamStopI0
2269end
2270//*******************************************************************************************************************************************
2271Function NI1_12IDBGetEmptyI0(fileName)
2272        string fileName
2273        //wave/Z CCDImageToConvert = root:Packages:Convert2Dto1D:CCDImageToConvert
2274        wave/Z EmptyData = root:Packages:Convert2Dto1D:EmptyData
2275        if(!WaveExists(EmptyData))// || !WaveExists(EmptyData))
2276                abort "Needed Image do not exist. Load Empty data before going further"
2277        endif
2278        //string sampleNote=note(CCDImageToConvert)
2279        //sampleNote = ReplaceString(" ", sampleNote, "")
2280        string emptyNote=note(EmptyData)
2281        emptyNote = ReplaceString(" ", emptyNote, "")
2282        //variable SampleBeamStopDiode=NumberByKey("Photodiode", sampleNote , ":" , ";")
2283        //variable EmptyBeamStopDiode=NumberByKey("Photodiode", emptyNote , ":" , ";")
2284        //variable SampleBeamStopI0=NumberByKey("I0", sampleNote , ":" , ";")
2285        variable EmptyBeamStopI0=NumberByKey("I0", emptyNote , ":" , ";")
2286        //variable I0Normalized = (EmptyBeamStopDiode/EmptyBeamStopI0)//(EmptyBeamStopDiode/EmptyBeamStopI0)
2287        print "Found Empty I0 = "+num2str(EmptyBeamStopI0)
2288        return EmptyBeamStopI0
2289end
2290
2291//*******************************************************************************************************************************************
2292//*******************************************************************************************************************************************
2293
2294//*******************************************************************************************************************************************
2295//*******************************************************************************************************************************************
2296Function/S NI1_12IDBLoadMetadata(FileNameToLoad, LoadedWvHere)         
2297        string FileNameToLoad
2298        wave LoadedWvHere
2299       
2300        //get the path to Slogs now, it is one level up and inside the log folder
2301        PathInfo Convert2Dto1DDataPath
2302        string DataFilePath=S_path
2303        string UsingWhat=StringFromList(ItemsInList(DataFilePath,":")-1, DataFilePath,":")
2304        string LogPathStr= RemoveFromList(UsingWhat, DataFilePath,":")+"log"
2305        NewPath/O/Q/Z LogFilesPath, LogPathStr
2306        string LogFileName="L"+FileNameToLoad[1,inf]
2307        LogFileName = ReplaceString("tif", LogFileName, "meta")
2308        if(StringMatch(FileNameToLoad[0], "S" ))
2309                usingWhat = "SAXS"
2310        elseif(StringMatch(FileNameToLoad[0], "W" ))
2311                usingWhat = "WAXS"
2312        elseif(StringMatch(FileNameToLoad[0], "P" ))
2313                usingWhat = "PE"
2314                abort "Do not know what to do with PE detectors yet. Fix me"
2315        else
2316                abort "Unknown type of data used, fix me first"
2317        endif
2318        variable refNum, err
2319        string OneLineStr, MetadataString="", newWaveNOte=""
2320        open/R/T="????"/P=LogFilesPath/Z refNum as LogFileName
2321        if(V_flag!=0)
2322                close refNum
2323                Abort "Metadata import failed"
2324        else            //open succesful
2325                Do
2326                        FreadLine refNum,OneLineStr
2327                        if(strlen(OneLineStr)<=0)
2328                                //break
2329                                err=1
2330                        endif
2331                        MetadataString+=OneLineStr+";"
2332                while(err==0)
2333                Close refNum
2334        endif
2335        MetadataString = ReplaceString("%", MetadataString, "")
2336        MetadataString = ReplaceString("\n", MetadataString, "")
2337        MetadataString = ReplaceString("\r", MetadataString, "")
2338        //MetadataString = ReplaceString(" ", MetadataString, "")
2339        newWaveNOte = NI1_12IDBProcessMetadata(usingWhat, MetadataString, LoadedWvHere)
2340        return newWaveNote
2341end
2342
2343//*******************************************************************************************************************************************
2344//*******************************************************************************************************************************************
2345
2346Function/S NI1_12IDBProcessMetadata(which, MetadataString, LoadedWvHere)
2347        string which, MetadataString
2348        wave LoadedWvHere
2349
2350        //parse this string and do what is needed...
2351        string NewWaveNote=""
2352        string currentItemString
2353        variable i, maxItems, includeMe
2354        maxItems=ItemsInList(MetadataString,";")
2355        includeMe = 1
2356        i = 0
2357        //check that needed metadata are actually there or bail out on users...
2358        if(StringMatch(which, "SAXS"))  //require SAXS data
2359                if(!stringmatch(MetadataString, "*SAXS Detector*"))
2360                        DoAlert 0, "Metadata do not contain SAXS part"
2361                        return ""
2362                endif
2363        endif
2364        if(StringMatch(which, "WAXS"))  //require SAXS data
2365                if(!stringmatch(MetadataString, "*WAXS Detector*"))
2366                        DoAlert 0,  "Metadata do not contain WAXS part"
2367                        return ""
2368                endif
2369        endif
2370       
2371        //read first part...
2372        do
2373                        currentItemString=StringFromList(i, MetadataString, ";")
2374                        i+=1
2375                        NewWaveNote+=currentItemString+";"
2376        while(!StringMatch(currentItemString, "SAXS Detector"))
2377        // now read SAXS part, if needed...
2378        do
2379                currentItemString=StringFromList(i, MetadataString, ";")
2380                i+=1
2381                if(StringMatch(which, "SAXS"))
2382                        //process the line as needed
2383                        NI1_12IDBProcessLine(currentItemString, LoadedWvHere)
2384                        NewWaveNote+=currentItemString+";"
2385                endif
2386        while(!StringMatch(currentItemString, "WAXS Detector"))
2387        do
2388                currentItemString=StringFromList(i, MetadataString, ";")
2389                i+=1
2390                if(StringMatch(which, "WAXS"))
2391                        //process the line as needed
2392                        NI1_12IDBProcessLine(currentItemString, LoadedWvHere)
2393                        NewWaveNote+=currentItemString+";"
2394                endif
2395        while(!StringMatch(currentItemString, "*Setup information*"))
2396        do
2397                currentItemString=StringFromList(i, MetadataString, ";")
2398                i+=1
2399                //process the line as needed
2400                NI1_12IDBProcessLine(currentItemString, LoadedWvHere)
2401                NewWaveNote+=currentItemString+";"
2402        while(i<maxItems)       
2403        print NewWaveNote
2404        return NewWaveNote
2405end
2406
2407//*******************************************************************************************************************************************
2408//*******************************************************************************************************************************************
2409Function NI1_12IDBProcessLine(LineToProcess, LoadedWvHere)
2410        string LineToProcess
2411        wave LoadedWvHere
2412       
2413        LineToProcess=ReplaceString(" ", LineToProcess, "")+";"
2414        NVAR APS12IDBReloadPars
2415        if(APS12IDBReloadPars)
2416                if(StringMatch(LineToProcess, "*PixelSize(mm)*" ))
2417                        NVAR PixelSizeX = root:Packages:Convert2Dto1D:PixelSizeX
2418                        NVAR PixelSizeY = root:Packages:Convert2Dto1D:PixelSizeY
2419                        PixelSizeX = NumberByKey("PixelSize(mm)", LineToProcess, ":", ";")
2420                        PixelSizeY = NumberByKey("PixelSize(mm)", LineToProcess, ":", ";")
2421                endif
2422                if(StringMatch(LineToProcess, "*Sample-to-detectorDistance(mm)*" ))
2423                        NVAR SampleToCCDdistance = root:Packages:Convert2Dto1D:SampleToCCDdistance
2424                        SampleToCCDdistance = NumberByKey("Sample-to-detectorDistance(mm)", LineToProcess, ":", ";")
2425                endif
2426                if(StringMatch(LineToProcess, "*BeamCenterX*" ))
2427                        NVAR BeamCenterX = root:Packages:Convert2Dto1D:BeamCenterX
2428                        BeamCenterX = NumberByKey("BeamCenterX", LineToProcess, ":", ";")
2429                endif
2430                if(StringMatch(LineToProcess, "*BeamCenterY*" ))
2431                        NVAR BeamCenterY = root:Packages:Convert2Dto1D:BeamCenterY
2432                        //Again, THIS IS INVERTED...
2433                        variable DimYSize=DimSize(LoadedWvHere, 1 )
2434                        BeamCenterY = DimYSize - NumberByKey("BeamCenterY", LineToProcess, ":", ";")           
2435                endif
2436                if(StringMatch(LineToProcess, "*X-rayEnergy(keV)*" ))
2437                        NVAR XrayEnergy = root:Packages:Convert2Dto1D:XrayEnergy
2438                        NVAR Wavelength = root:Packages:Convert2Dto1D:Wavelength
2439                        XrayEnergy = NumberByKey("X-rayEnergy(keV)", LineToProcess, ":", ";")
2440                        Wavelength = 12.39842/XrayEnergy
2441                endif
2442                if(StringMatch(LineToProcess, "*TiltAnglePitch(degree)*" ))
2443                        NVAR VerticalTilt = root:Packages:Convert2Dto1D:VerticalTilt
2444                        //Again, THIS IS INVERTED...
2445                        VerticalTilt = -1* NumberByKey("TiltAnglePitch(degree)", LineToProcess, ":", ";")               
2446                endif
2447        endif
2448end
2449//*******************************************************************************************************************************************
2450//*******************************************************************************************************************************************
2451//Function NI1_12IDBGetUserInput()                      //todo: some error handling...
2452//              //should be able to find mask in current working folder
2453//      string OldDFf=GetDataFolder(1)
2454//      NVAR UseMask = root:Packages:Convert2Dto1D:UseMask
2455//      variable ProcessingTypeVal=0            //Processing type is : 0 use beamline processing (just reduction) or 1 subtract empty/background and reduce.
2456//      string ProcessingTypeStr="No"
2457//      setDataFOlder root:Packages:Convert2Dto1D:
2458//      //get the path to SAXS_mask2M.bmp or WAXS_mask2M.bpm, it is one level up...
2459//      PathInfo Convert2Dto1DDataPath
2460//      string DataFilePath=S_path
2461//      string UsingWhat=StringFromList(ItemsInList(DataFilePath,":")-1, DataFilePath,":")
2462//      string MaskPathStr= RemoveFromList(UsingWhat, DataFilePath,":")
2463//      //mask may or may not exist, we need to get user to pick one or tell us it does not exist...
2464//      NewPath/O/Q TempMaskUserPath, MaskPathStr
2465//      string ListOfBMPFiles=IndexedFile(TempMaskUserPath, -1, ".bmp")
2466//      string SelectedMaskFile
2467//      if(strlen(ListOfBMPFiles)>0)
2468//              Prompt SelectedMaskFile, "Select BMP Mask file", popup, ListOfBMPFiles+"---;"
2469//              Prompt ProcessingTypeStr, "Subtract Empty/background", popup, "No;Yes;"
2470//              DoPrompt "Select Mask/Method", ProcessingTypeStr, SelectedMaskFile
2471//              if(V_Flag || stringmatch(SelectedMaskFile,"---"))
2472//                      print "User canceled mask file selection, continue without it"
2473//                      UseMask = 0
2474//                      if(stringMatch(ProcessingTypeStr,"Yes"))
2475//                              ProcessingTypeVal = 1
2476//                      endif
2477//                      return ProcessingTypeVal
2478//              endif
2479//              if(stringMatch(ProcessingTypeStr,"Yes"))
2480//                      ProcessingTypeVal = 1
2481//              endif
2482//              ImageLoad/T=bmp/Q/N=TMPBMPMask/Z/P=TempMaskUserPath SelectedMaskFile
2483//              if(V_Flag)
2484//                      print ":Loaded succesfully mask file from "+MaskPathStr+SelectedMaskFile
2485//              else
2486//                      DoALert/T="Could not load Mask file" 0, "Could not load selected file with mask, you need to create mask manually"
2487//                      UseMask = 0
2488//                      return ProcessingTypeVal
2489//              endif
2490//              Wave LoadedmaskImage = TMPBMPMask
2491//              ImageTransform rgb2gray LoadedmaskImage
2492//              Wave M_RGB2Gray
2493//              ImageTransform flipCols M_RGB2Gray                      //this is correct flip needed...
2494//              DoWIndow CCDImageToConvertFig
2495//              if(V_Flag)
2496//                      RemoveImage/W=CCDImageToConvertFig/Z  M_ROIMask
2497//              endif
2498//              KillWaves/Z M_ROIMask, TMPBMPMask
2499//              wavestats/Q M_RGB2Gray
2500//              M_RGB2Gray/=V_max                               //normalize to be 1 or 0, seem to be 255
2501//              Rename M_RGB2Gray, M_ROIMask
2502//              UseMask = 1
2503//      else            //no mask file found
2504//              print "No BMP mask file found, continue without it"
2505//              Prompt ProcessingTypeStr, "Subtract Empty/background", popup, "No;Yes;"
2506//              DoPrompt "Select Method", SelectedMaskFile, ProcessingTypeStr
2507//              if(stringMatch(ProcessingTypeStr,"Yes"))
2508//                      ProcessingTypeVal = 1
2509//              endif
2510//              UseMask = 0
2511//              return ProcessingTypeVal
2512//      endif
2513//
2514//
2515//
2516//
2517//      setDataFolder OldDFf   
2518//      return ProcessingTypeVal
2519//end
2520//*******************************************************************************************************************************************
2521//*******************************************************************************************************************************************
2522
2523Function NI1_12IDBHowTo()
2524       
2525        doWIndow APS12IDB_Instructions
2526        if(V_Flag)
2527                DoWIndow/F APS12IDB_Instructions
2528        else
2529        String nb = "APS12IDB_Instructions"
2530        NewNotebook/N=$nb/F=1/V=1/K=1/ENCG={1,1}/W=(930,427,1644,1205) as "APS12IDB_Instructions"
2531        Notebook $nb defaultTab=10, magnification=125
2532        Notebook $nb showRuler=1, rulerUnits=2, updating={1, 1}
2533        Notebook $nb newRuler=Normal, justification=0, margins={0,0,468}, spacing={0,0,0}, tabs={}, rulerDefaults={"Helvetica",11,0,(0,0,0)}
2534        Notebook $nb newRuler=Title, justification=0, margins={0,0,468}, spacing={0,0,0}, tabs={}, rulerDefaults={"Geneva",12,3,(0,0,0)}
2535        Notebook $nb ruler=Title, text="Instructions for use of APS 12IDC special configuration\r"
2536        Notebook $nb ruler=Normal, text="\r"
2537        Notebook $nb text="\r"
2538        Notebook $nb text="1. Find path to your tif images. Pick folder with raw tiff images, not the average folder. \r"
2539        Notebook $nb text="\r"
2540        Notebook $nb text="2. Code will find available masks and present dialog to select:\r"
2541        Notebook $nb text="\ta. Data reduction method (see below)\r"
2542        Notebook $nb text="\tb. Proper (SAXS/WAXS mask)\r"
2543        Notebook $nb text="\r"
2544        Notebook $nb text="3. Configuration and calibration should be read from meta files with metadata for each file automaticall"
2545        Notebook $nb text="y. \r"
2546        Notebook $nb text="\r"
2547        Notebook $nb text="\r"
2548        Notebook $nb text="*** Data reduction methods ***\r"
2549        Notebook $nb text="1. Subtract Empty/Background NO: reduces each image separately, normalized by transmitted counts (flux an"
2550        Notebook $nb text="d transmission normalization), masked. Solvent/background sutraction needs to be done later, for example"
2551        Notebook $nb text=" in BioSAXS Irena tools, but you can average many data sets together. This is default beamline and bioSAXS setting.\r"
2552        Notebook $nb text="\r"
2553        Notebook $nb text="2. Subtract Empty/Background : YES. This is typical Nika processing - solvent/background image is subtr"
2554        Notebook $nb text="acted in Nika directly, with flux normalization for sample and background, transmission calculation etc."
2555        Notebook $nb text=" In this case only ONE background image can be used at time, which may not be suitable if you have multiple images. \r"
2556        Notebook $nb text="\r"
2557        Notebook $nb text="\r"
2558        Notebook $nb text="Jan Ilavsky, 1/5/2021\r"
2559        Notebook $nb text="\r"
2560        Notebook $nb fStyle=2, text="Hint: watch history area for notes on what Nika has found and done. \r"
2561
2562        endif
2563end
2564
2565//*******************************************************************************************************************************************
2566//                      end of 12ID-B camera support.
Note: See TracBrowser for help on using the repository browser.