source: trunk/User Procedures/Indra 2/IN3_Calculations.ipf @ 870

Last change on this file since 870 was 870, checked in by ilavsky, 3 years ago

Moving forward with Multiu plotting tool

File size: 129.7 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.41
5
6//*************************************************************************\
7//* Copyright (c) 2005 - 2019, 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.41 added some fudge factor for Qmin search and MSAXS handling. And change the logic so one can understand, what is happening.
13//1.40 added automatci location of the Qmin where data start due to Int Sa/Bl ratio.
14//1.39 Fixed step scanning GUI issues.
15//1.38 Added ability to overwrite Flyscan amplifier dead times.
16//1.37 fix bug when debugger when no data and Desmearing was checked.
17//1.36 fix manual page called by help button
18//1.35 modify the sleep between multiple USAXS data reductions in IN3_InputPanelButtonProc to be more user friendly
19//1.34 fixed which resulting waves are plotted to include M_DSM, DSM, M_SMR, and SMR waves in this order.
20//1.33 modified graph size control to use IN2G_GetGraphWidthHeight and associated settings. Should work on various display sizes.
21//1.32 changed main graph name and size is dynamic now.
22//1.31 added Desmearing as data reduction step.
23//1.30 some fixes in Modified Gauss fitting. Modifed to remeber better Qmin for processign in batch.
24//1.29 added live processing
25//1.28 added OverRideSampleTransmission
26//1.27 Fixes to Mod Gauss fitting to avoid problems when NaNs from range changes are present.
27//1.26 GUI fixes for USAXS graphs and panels
28//1.25 added finding Qmin from FWHM of the sample peak
29//1.24 enable override of UPDsize, which did not work up to now...
30//1.23 fixed Bkg5 Overwrite which was not correctly read intot he system.
31//1.22 Added support for Import & process new FLyscan processing GUI.
32//1.21 added PUD size to step scan data and some otehr changes.
33//1.20 added read UPD size to handle flyscanned data. Need finish for step scanning!
34//1.19 minor fixes for panel scaling
35//1.18 Remove Dropout function
36//1.17 minor change in MOdified Gauss fit function which fixes sometime observed misfits. Coef wave MUST be double precision.
37//1.16 minor GUI chaneg to keep users advised abotu saving data
38//1.15 modified fitting of the peak height for Modified gauss
39//1.14 added save data to Load & process next button. Faster and easier.
40//1.13 extended Modified guass fitting range, speed up by avoiding display updates of teh top fittings (major speed increase).
41//1.12 increased Modified Guass fitting range slightly.
42//1.11 adds Overwrite for UPD dark current range 5
43//1.10 adds FlyScan support
44//1.09 controls for few more items displayed on Tab0 with pek-to-peak transmission and MSAXS/SAXS correction
45//1.08 added pin diode transmission
46//1.07 added (beta version now) measurement of transmission by using diode on front of the A stage
47//1.06 modified for weight calibration
48//1.05 FIxed bump to Compiler when no data selected in Data selection popup.
49//1.04 2/2013, JIL: modified to enable calibration per weight
50//1.03 2/2013 fixed Process next sample for changed control procedures.
51//1.02 4/2012 modified q shifts step to be 0.5e-6, 10x less than before.
52//1.01 2/2012 modified function Modified gauss to handle bad points appearing in this cycle in the data. Moved some button adn add option to fix PD range
53
54
55//***********************************************************************************************************************************
56//***********************************************************************************************************************************
57//***********************************************************************************************************************************
58//***********************************************************************************************************************************
59Function IN3_InputPanelButtonProc(B_Struct) : ButtonControl
60        STRUCT WMButtonAction &B_Struct
61
62        String ctrlName
63        ctrlName = B_Struct.ctrlName
64        string winNm=B_Struct.win
65
66        if(B_Struct.eventcode!=2)
67                return 1
68        endif
69        string oldDf=GetDataFolder(1)
70        setDataFolder root:Packages:Indra3
71        NVAR ListProcDisplayDelay = root:Packages:Indra3:ListProcDisplayDelay
72
73        if(cmpstr(ctrlName,"GetHelp")==0)
74                //Open www manual with the right page
75                IN2G_OpenWebManual("Indra/FlyscanDataReduction.html")
76        endif
77        if(cmpstr(ctrlName,"GetReadme")==0)
78                Dowindow USAXSQuickManual
79                if (V_flag)
80                        Dowindow/F USAXSQuickManual
81                else
82                        IN3_GenerateReadMe()   
83                endif
84        endif
85
86        if (cmpstr(ctrlName,"SelectNextSampleAndProcess")==0)
87                SVAR DataFolderName=root:Packages:Indra3:DataFolderName
88                SVAR LastSample=root:Packages:Indra3:LastSample
89                String AllFolders=IR2P_GenStringOfFolders(winNm=winNm)
90                string ShortOldSaName = StringFromList(ItemsInList(LastSample, ":")-1, LastSample , ":")
91                variable CurrentFolder=WhichListItem(ShortOldSaName,AllFolders)
92                string ShortNewSaName = StringFromList(CurrentFolder+1, AllFolders , ";")
93                if(CurrentFolder>=0)
94                        DataFolderName = ReplaceString(ShortOldSaName, DataFolderName,ShortNewSaName)
95                        PopupMenu SelectDataFolder,mode=1,win=USAXSDataReduction, popvalue=ShortNewSaName
96                endif
97                DoWIndow/F USAXSDataReduction
98        endif
99        if (cmpstr(ctrlName,"LiveProcessing")==0)
100                IN3_OnLineDataProcessing()     
101        endif
102        if (cmpstr(ctrlName,"ProcessData2")==0 || cmpstr(ctrlName,"SelectNextSampleAndProcess2")==0)
103                //import the data
104                variable howMany
105                if(cmpstr(ctrlName,"ProcessData2")==0)
106                        howMany=0
107                else
108                        howMany=1
109                endif
110                string LoadedDataList = IN3_FlyScanLoadHdf5File2(howMany)               //0 is for load 1, 1 is for load all selected.
111                variable Items, i
112                if(cmpstr(ctrlName,"ProcessData2")==0)
113                        Items=1
114                else
115                        Items=ItemsInList(LoadedDataList)
116                endif
117                //remember where the cursor of Qmin is... 
118                variable/g QminDefaultForProcessing
119                NVAR QminDefaultForProcessing
120                Wave/Z R_qvec
121                DoWIndow RcurvePlotGraph
122                if(WaveExists(R_qvec) && V_Flag && strlen(CsrInfo(A,"RcurvePlotGraph")))
123                        QminDefaultForProcessing = R_Qvec[pcsr(A, "RcurvePlotGraph")]
124                else
125                        QminDefaultForProcessing = 0
126                endif
127                //it should be recoded now.
128                For(i=0;i<Items;i+=1)
129                        SVAR DataFolderName=    root:Packages:Indra3:DataFolderName
130                        DataFolderName = stringFromList(i,LoadedDataList)
131                        if(stringMatch(DataFolderName,"---"))
132                                setDataFolder oldDf
133                                abort
134                        endif
135                        IN3_LoadData()          //load data in the tool.
136                        IN3_LoadBlank()
137                        IN3_SetPDParameters()
138                                //      hopefully not needed any more IN2A_CleanWavesForSPECtroubles()                          //clean the waves with USAXS data for Spec timing troubles, if needed
139                        IN3_GetMeasParam()     
140                        IN3_RecalculateData(0)
141                        IN3_GraphData()         //create graphs                 
142                        IN3_ReturnCursorBack(QminDefaultForProcessing)
143                        IN3_FitDefaultTop()
144                        IN3_RecalculateData(4)
145                        IN3_FitDefaultTop()
146                        IN3_GetDiodeTransmission(0)
147                        IN3_RecalculateData(1)
148                        TabControl DataTabs , value= 0, win=USAXSDataReduction
149                        NI3_TabPanelControl("",0)
150                        IN3_DesmearData()
151                        DoWIndow/F USAXSDataReduction
152                        ResumeUpdate
153                        DoUpdate /W=RcurvePlotGraph
154                        //DoUpdate /W=USAXSDataReduction
155                        if(howMany)
156                                IN3_SaveData() 
157                                NVAR UserSavedData=root:Packages:Indra3:UserSavedData
158                                UserSavedData=2
159                                IN3_FixSaveData()
160                                DoWIndow/F USAXSDataReduction
161                                UserSavedData=1
162                                IN3_FixSaveData()
163                                if(i<Items-1)   
164                                        sleep/S/B/Q/C=6/M="Delay "+num2str(ListProcDisplayDelay)+" seconds for user data review" ListProcDisplayDelay
165                                endif
166                        endif
167                endfor
168        endif
169
170
171
172        if (cmpstr(ctrlName,"ProcessData")==0 || cmpstr(ctrlName,"SelectNextSampleAndProcess")==0)
173                SVAR DataFolderName=    root:Packages:Indra3:DataFolderName
174                if(stringMatch(DataFolderName,"---"))
175                        setDataFolder oldDf
176                        abort
177                endif
178                IN3_LoadData()          //load data in the tool.
179                IN3_LoadBlank()
180                IN3_SetPDParameters()
181                        //      hopefully not needed any more IN2A_CleanWavesForSPECtroubles()                          //clean the waves with USAXS data for Spec timing troubles, if needed
182                IN3_GetMeasParam()     
183                IN3_RecalculateData(0)
184                IN3_GraphData()         //create graphs
185                IN3_ReturnCursorBack(0)
186                IN3_FitDefaultTop()
187                IN3_RecalculateData(4)
188                IN3_FitDefaultTop()
189                IN3_GetDiodeTransmission(0)
190                IN3_RecalculateData(1)
191                IN3_DesmearData()
192                TabControl DataTabs , value= 0, win=USAXSDataReduction
193                NI3_TabPanelControl("",0)
194                DoWIndow/F USAXSDataReduction
195                if (cmpstr(ctrlName,"SelectNextSampleAndProcess")==0)
196                        IN3_SaveData() 
197                        NVAR UserSavedData=root:Packages:Indra3:UserSavedData
198                        UserSavedData=1
199                        IN3_FixSaveData()
200                        DoWIndow/F USAXSDataReduction
201                endif
202        endif
203        if (cmpstr(ctrlName,"RemovePointsRange")==0)
204                RemovePointsWithMarquee()
205        endif
206        if (cmpstr(ctrlName,"Recalculate")==0)
207                IN3_RecalculateData(1) 
208                DoWIndow/F USAXSDataReduction
209                IN3_FixSaveData()
210                IN3_DesmearData()
211        endif
212
213        if (cmpstr(ctrlName,"SaveResults")==0)
214                IN3_SaveData() 
215                NVAR UserSavedData=root:Packages:Indra3:UserSavedData
216                UserSavedData=1
217                IN3_FixSaveData()
218                DoWIndow/F USAXSDataReduction
219        endif
220        if (cmpstr(ctrlName,"RecoverDefault")==0)
221                NVAR SampleThickness
222                NVAR SampleThicknessBckp
223                SampleThickness = SampleThicknessBckp
224                IN3_RecalculateData(2)
225                IN3_DesmearData()
226                DoWIndow/F USAXSDataReduction
227        endif
228        if (cmpstr(ctrlName,"RecoverDefaultBlnkVals")==0)
229                NVAR BlankWidthBckp
230                NVAR BlankWidth
231                BlankWidth = BlankWidthBckp
232                NVAR BlankFWHMBckp
233                NVAR BlankFWHM
234                BlankFWHM = BlankFWHMBckp
235                NVAR BlankMaximumBckp
236                NVAR BlankMaximum
237                BlankMaximum = BlankMaximumBckp
238                IN3_RecalculateData(2)
239                IN3_DesmearData()
240                DoWIndow/F USAXSDataReduction
241        endif
242
243
244        if (cmpstr(ctrlName,"RemovePoint")==0)
245                if (strlen(CsrWave(A))==0)
246                        Abort "cursor A is not in the graph...nothing to do..."
247                endif
248                variable pointNumberToBeRemoved=xcsr(A)
249                if (strlen(CsrWave(B))!=0)
250                        DoAlert 0, "Remove cursor B [square] before proceeding"
251                else
252                        //this part should be done always
253                        Wave FixMe=CsrWaveRef(A)
254                        FixMe[pointNumberToBeRemoved]=NaN
255                        //if we need to fix more waves, it can be done here
256                endif
257                cursor/P A, $CsrWave(A), pointNumberToBeRemoved+1               //set the cursor to the right so we do not scare user
258                DoWIndow/F USAXSDataReduction
259        endif
260       
261        setDataFolder OldDf
262end
263
264//***********************************************************************************************************************************
265//***********************************************************************************************************************************
266//***********************************************************************************************************************************
267//***********************************************************************************************************************************
268
269Function IN3_GetDiodeTransmission(SkipMessage)
270        variable SkipMessage
271
272        NVAR isBlank=   root:Packages:Indra3:isBlank
273        if(isBlank)
274                return 0
275        endif
276
277
278        SVAR MeasurementParameters = root:Packages:Indra3:MeasurementParameters
279        SVAR BlankName = root:Packages:Indra3:BlankName
280        SVAR/Z BLMeasurementParameters = $(BlankName+"MeasurementParameters")
281        NVAR SampleTransmissionPeakToPeak = root:Packages:Indra3:SampleTransmissionPeakToPeak
282        NVAR MSAXSCorrection = root:Packages:Indra3:MSAXSCorrection
283        NVAR SampleTransmission = root:Packages:Indra3:SampleTransmission
284        NVAR UsePinTransmission=        root:Packages:Indra3:UsePinTransmission
285       
286       
287        variable USAXSPinT_Measure      =NumberByKey("USAXSPinT_Measure", MeasurementParameters, "=", ";")
288        variable USAXSPinT_AyPosition   =NumberByKey("USAXSPinT_AyPosition", MeasurementParameters, "=", ";")
289        variable USAXSPinT_Time         =NumberByKey("USAXSPinT_Time", MeasurementParameters, "=", ";")
290        variable USAXSPinT_pinCounts    =NumberByKey("USAXSPinT_pinCounts", MeasurementParameters, "=", ";")
291        variable USAXSPinT_pinGain              =NumberByKey("USAXSPinT_pinGain", MeasurementParameters, "=", ";")
292        variable USAXSPinT_I0Counts     =NumberByKey("USAXSPinT_I0Counts", MeasurementParameters, "=", ";")
293        variable USAXSPinT_I0Gain               =NumberByKey("USAXSPinT_I0Gain", MeasurementParameters, "=", ";")
294
295        variable BLUSAXSPinT_Measure            =NumberByKey("USAXSPinT_Measure", BLMeasurementParameters, "=", ";")
296        variable BLUSAXSPinT_AyPosition =NumberByKey("USAXSPinT_AyPosition", BLMeasurementParameters, "=", ";")
297        variable BLUSAXSPinT_Time                       =NumberByKey("USAXSPinT_Time", BLMeasurementParameters, "=", ";")
298        variable BLUSAXSPinT_pinCounts          =NumberByKey("USAXSPinT_pinCounts", BLMeasurementParameters, "=", ";")
299        variable BLUSAXSPinT_pinGain            =NumberByKey("USAXSPinT_pinGain", BLMeasurementParameters, "=", ";")
300        variable BLUSAXSPinT_I0Counts           =NumberByKey("USAXSPinT_I0Counts", BLMeasurementParameters, "=", ";")
301        variable BLUSAXSPinT_I0Gain             =NumberByKey("USAXSPinT_I0Gain", BLMeasurementParameters, "=", ";")
302
303        NVAR/Z USAXSPinTvalue = root:Packages:Indra3:USAXSPinTvalue
304        if(!NVAR_Exists(USAXSPinTvalue))
305                variable/g root:Packages:Indra3:USAXSPinTvalue
306        endif
307        USAXSPinTvalue=0
308        if(USAXSPinT_Measure && BLUSAXSPinT_Measure)
309                USAXSPinTvalue = ((USAXSPinT_pinCounts/USAXSPinT_pinGain)/(USAXSPinT_I0Counts/USAXSPinT_I0Gain))/((BLUSAXSPinT_pinCounts/BLUSAXSPinT_pinGain)/(BLUSAXSPinT_I0Counts/BLUSAXSPinT_I0Gain))
310                if(!SkipMessage)
311                        print "Found pin Diode measured transmission for these measurements = "+num2str(USAXSPinTvalue)
312                endif
313                if(UsePinTransmission && USAXSPinTvalue>0)
314                        MSAXSCorrection = USAXSPinTvalue / SampleTransmissionPeakToPeak
315                endif
316        else
317                UsePinTransmission=0
318        endif
319       
320       
321end
322//***********************************************************************************************************************************
323//***********************************************************************************************************************************
324//***********************************************************************************************************************************
325//***********************************************************************************************************************************
326
327static Function IN3_ReturnCursorBack(QminDefaultForProcessing)
328        variable QminDefaultForProcessing
329       
330        string oldDf=GetDataFolder(1)
331        setDataFolder root:Packages:Indra3
332
333        Wave R_Int=root:Packages:Indra3:R_Int
334        Wave R_Qvec=root:Packages:Indra3:R_Qvec
335        Wave/Z BL_R_Int = root:Packages:Indra3:BL_R_Int
336        if(!WaveExists(BL_R_Int))               //reducing Blank, return and do nothing...
337                return 0
338        endif
339        Wave BL_R_Qvec = root:Packages:Indra3:BL_R_Qvec
340        NVAR PeakWidth = root:Packages:Indra3:PeakWidthArcSec
341        NVAR BlankWidth = root:Packages:Indra3:BlankWidth
342        NVAR Wavelength = root:Packages:Indra3:Wavelength
343
344
345        variable HaveMSAXSCOrrection=0
346        variable QminTheoreticalSample
347        variable QminTheoreticalBlank
348        variable Qmin
349        NVAR/Z FindMinQForData=root:Packages:Indra3:FindMinQForData             //added 2019-04 as convenience, find min Q when Int > IntBl*2
350        NVAR/Z MinQMinFindRatio=root:Packages:Indra3:MinQMinFindRatio
351        if(!NVAR_Exists(FindMinQForData))
352                variable/g FindMinQForData
353                FindMinQForData = 1
354                variable/g MinQMinFindRatio
355                MinQMinFindRatio = 1.3
356        endif
357
358        variable BlankFudgefactor       = 1.05  //this is fudge factor for Blank.
359        variable SampleFudgefactor = 0.95                       //this is for MSAXS dominated Sample width.
360        //this is real instrument Qmin under any conditions... Blank FWHM, 1.05 is fudge factor here...
361        QminTheoreticalBlank = BlankFudgefactor * 4 * pi * sin(BlankWidth*4.848e-6 /2) / Wavelength
362        //this is instrument resolution due to sample width, if we have MSAXS, this dominates.
363        //0.7 is fudge factor here... Seems to work for MSAXS calculations
364        QminTheoreticalSample = 4 * pi * sin(SampleFudgefactor * PeakWidth*4.848e-6 /2) / Wavelength
365        //now calculate Qmin based in intensity difference...
366        variable QminIntDifference=0
367        variable QminAUtoFOund=0
368        variable QminDifferenceInIntensities
369        //variable QminTheoreticalBlank = 1.05 * 4 * pi * sin(0.57 *BlankWidth*4.848e-6 /2) / Wavelength                //This is Qmin due to multiple scattering... scaled up a bit to make sure this makes sense...
370        //and of course, we have Qmin old which user used last time
371        NVAR/Z OldStartQValueForEvaluation
372        if(!NVAR_Exists(OldStartQValueForEvaluation))
373                variable/g OldStartQValueForEvaluation
374                OldStartQValueForEvaluation = QminDefaultForProcessing
375        endif
376
377        if(FindMinQForData)
378                        Duplicate/Free R_Int, IntRatio
379                        Duplicate/Free R_Qvec, QCorrection      //this is per point correction, we need bigger difference at low-q than high-q
380                        //need to find function which is q dependent and varies from Max correction to 1 over our range of Qs.
381                        variable MaxCorrection = 2
382                        variable PowerCorrection=4
383                        QCorrection =  1 + MaxCorrection*(abs(QminTheoreticalBlank/R_Qvec))^PowerCorrection
384                        QCorrection = (QCorrection<(MaxCorrection+1)) ? QCorrection : (MaxCorrection+1)
385                        //the above should peak at Q=0 with max correction of "MaxCorrection"+1 and drop off as function of q resolution.
386                        Duplicate/Free BL_R_Int, LogBlankInt
387                        LogBlankInt = log(BL_R_Int)
388                        IntRatio = interp(R_Qvec, BL_R_Qvec, LogBlankInt)               //this is interpolated log(BlankInt)
389                        IntRatio = 10^IntRatio                                                                                  //interpolated BlankInt
390                        IntRatio = R_Int / IntRatio                                                                             //this is R_int/BlankInt (interpolated to R_+Qvec)
391                        IntRatio = IntRatio / QCorrection
392                        wavestats/Q/R=[10,numpnts(IntRatio)/10] IntRatio
393                        FindLevel  /Q/EDGE=1/R=[V_minloc,numpnts(IntRatio)-1] IntRatio, MinQMinFindRatio
394                        if(V_Flag==0)   //found level
395                                QminDifferenceInIntensities = R_Qvec[ceil(V_LevelX)]
396                                QminAUtoFOund = 1
397                        else
398                                QminDifferenceInIntensities=0
399                                QminAUtoFOund = 0
400                        endif
401        endif                                                                                                                                   //so now, if user wants, we have qmin when data are 2*Background (first time).
402       
403        //now, pick the right Qmin and set some variable to know what message to post for user.
404        if(FindMinQForData)
405                //ignore old QMin
406                Qmin = max(QminTheoreticalBlank, QminTheoreticalSample, QminDifferenceInIntensities)
407                if(QminTheoreticalSample>QminTheoreticalBlank)
408                        HaveMSAXSCOrrection = 1
409                endif
410        else
411                //include old Qmin, but move right if needed.
412                Qmin = max(QminTheoreticalBlank, QminTheoreticalSample, OldStartQValueForEvaluation)
413                if(QminTheoreticalSample>QminTheoreticalBlank)
414                        HaveMSAXSCOrrection = 1
415                endif
416        endif
417        //now print soem messages which all users will simlpy ignore ;-)...
418        TextBox/C/W=RcurvePlotGraph/A=LB/X=0.2/Y=0.20/E=2/N=QminInformation/F=0 "\\Z10\\K(0,12800,52224)Theoretical Qmin of these data is = "+num2str(QminTheoreticalBlank)
419        //
420        if (QminAUtoFOund && !HaveMSAXSCOrrection)              //use autolocated value
421                OldStartQValueForEvaluation = Qmin
422                print "Warning - Qmin automatic search was requested. Located Qmin = "+num2str(Qmin)
423                TextBox/C/W=RcurvePlotGraph/N=QminReset/F=0/A=LT "\Zr050Located Qmin based on Int Sa/Bl ratio. Set to calculated Qmin = "+num2str(Qmin)
424                Cursor /P /W=RcurvePlotGraph  A  R_Int  round(BinarySearchInterp(R_Qvec, Qmin ))
425                Cursor /P /W=RcurvePlotGraph  B  R_Int  (numpnts(R_Qvec)-1)
426        elseif(HaveMSAXSCOrrection)                     //this is in case of multiple scattering...
427                OldStartQValueForEvaluation = Qmin
428                print "Warning - too small Qmin detected due to MSAXS. Reset to calculated Qmin = "+num2str(Qmin)
429                print "This can be due to multiple scattering in the sample. Note, you may need to return the Qmin back for other samples"
430                TextBox/C/W=RcurvePlotGraph/N=QminReset/F=0/A=LT "\Zr050Warning - small Qmin detected due to MSAXS. Reset to calculated Qmin = "+num2str(Qmin)
431                Cursor /P /W=RcurvePlotGraph  A  R_Int  round(BinarySearchInterp(R_Qvec, Qmin ))
432                Cursor /P /W=RcurvePlotGraph  B  R_Int  (numpnts(R_Qvec)-1)
433        else
434                Qmin = OldStartQValueForEvaluation                                                                                                                      //any other case...
435                Cursor /P /W=RcurvePlotGraph  A  R_Int  round(BinarySearchInterp(R_Qvec, Qmin ))
436                Cursor /P /W=RcurvePlotGraph  B  R_Int  (numpnts(R_Qvec)-1)
437        endif
438
439        setDataFolder OldDf
440
441end
442//***********************************************************************************************************************************
443//***********************************************************************************************************************************
444//***********************************************************************************************************************************
445//***********************************************************************************************************************************
446static Function IN3_FixSaveData()
447
448                //fix display in the panel to reflect saved data...
449                NVAR UserSavedData=root:Packages:Indra3:UserSavedData
450                if(UserSavedData==0)
451                        Button SaveResults fColor=(65280,0,0), win=USAXSDataReduction
452                        TitleBox SavedData  title="  Data   NOT   saved  ", fColor=(0,0,0), frame=1,labelBack=(65280,0,0), win=USAXSDataReduction
453                elseif(UserSavedData==1)
454                        Button SaveResults , win=USAXSDataReduction, fColor=(47872,47872,47872)
455                        TitleBox SavedData  title="  Data   are   saved  ", fColor=(0,0,0),labelBack=(47872,47872,47872),  frame=2, win=USAXSDataReduction
456                elseif(UserSavedData==2)
457                        Button SaveResults , win=USAXSDataReduction, fColor=(47872,47872,47872)
458                        TitleBox SavedData  title="Disp. results, will continue", fColor=(0,0,0),labelBack=(3,52428,1),  frame=2, win=USAXSDataReduction
459                else
460                        Button SaveResults , win=USAXSDataReduction, fColor=(47872,47872,47872)
461                        TitleBox SavedData  title="               ", fColor=(0,0,0),labelBack=(47872,47872,47872),  frame=2, win=USAXSDataReduction             
462                endif
463end
464//***********************************************************************************************************************************
465//***********************************************************************************************************************************
466//***********************************************************************************************************************************
467//***********************************************************************************************************************************
468
469static Function IN3_GetMeasParam()              //sets various spray parameters
470
471
472        string oldDf=GetDataFolder(1)
473        setDataFolder root:Packages:Indra3
474
475        SVAR SpecCommand
476        NVAR PhotoDiodeSize
477        NVAR Wavelength
478        NVAR SlitLength
479        NVAR NumberOfSteps
480        NVAR SDDistance
481        SVAR MeasurementParameters
482       
483        string specCommandSeparated= ReduceSpaceRunsInString(SpecCommand,1)
484        if (!cmpstr(SpecCommandSeparated[0,0]," "))
485                SpecCommandSeparated = SpecCommandSeparated[1,inf]                                              // remove any leading space
486        endif
487        SpecCommandSeparated = ChangePartsOfString(SpecCommandSeparated," ",";")                // one space is name separator
488
489        //      Following macro calls are know  to me
490        //      13 items: uascan motor start center finish minstep dy0 SDD_mm ay0 SAD_mm exponent intervals time.... new slit smeared macro with AY movement
491        //      14 items: sbuascan motor start center finish minstep dy0 asrp SDD_mm ay0 SAD_mm exponent intervals time.... old slit smeared macro before AY movement
492       
493        if (ItemsInList(SpecCommandSeparated)==13)
494                SDDistance=str2num(StringFromList(7,SpecCommandSeparated))
495        endif
496        if (ItemsInList(SpecCommandSeparated)==14)
497                SDDistance=str2num(StringFromList(8,SpecCommandSeparated))
498        endif
499        Variable ScanSteps=str2num(StringFromList(ItemsInList(SpecCommandSeparated)-2,SpecCommandSeparated))
500//fix for mono communication failure
501        if(numtype(NumberByKey("DCM_energy",MeasurementParameters,"="))!=0)
502                MeasurementParameters=ReplaceStringByKey("DCM_energy",MeasurementParameters,num2str(12),"=")
503                print "Warning>>>>  Nan found as energy for monochromator. Set to default 12keV. Change in IN3_GetMeasParam() in IN3_Calcualtions.ipf is needed"
504        endif
505
506
507        wavelength=12.398424437/NumberByKey("DCM_energy",MeasurementParameters,"=")
508        SlitLength=0.5*((4*pi)/wavelength)*sin(PhotoDiodeSize/(2*SDDistance))
509        NumberOfSteps=ScanSteps
510
511        MeasurementParameters=ReplaceStringByKey("Wavelength",MeasurementParameters,num2str(wavelength),"=")
512        MeasurementParameters=ReplaceStringByKey("SlitLength",MeasurementParameters,num2str(SlitLength),"=")
513        MeasurementParameters=ReplaceStringByKey("NumberOfSteps",MeasurementParameters,num2str(ScanSteps),"=")
514        MeasurementParameters=ReplaceStringByKey("SDDistance",MeasurementParameters,num2str(SDDistance),"=")
515       
516        IN2G_AppendNoteToAllWaves("Wavelength",num2str(wavelength))
517        IN2G_AppendNoteToAllWaves("SlitLength",num2str(SlitLength))
518        IN2G_AppendNoteToAllWaves("NumberOfSteps",num2str(ScanSteps))
519        IN2G_AppendNoteToAllWaves("SDDistance",num2str(SDDistance))
520
521        setDataFolder OldDf
522
523
524end
525//***********************************************************************************************************************************
526//***********************************************************************************************************************************
527//***********************************************************************************************************************************
528//***********************************************************************************************************************************
529
530static Function IN3_SetPDParameters()                           //setup PD parameters
531       
532        string oldDf=GetDataFolder(1)
533        setDataFolder root:Packages:Indra3
534       
535        SVAR UPD=UPDParameters                                          //define the global holding places
536        NVAR UPD_DK1=root:Packages:Indra3:UPD_DK1
537        NVAR UPD_DK2=root:Packages:Indra3:UPD_DK2
538        NVAR UPD_DK3=root:Packages:Indra3:UPD_DK3
539        NVAR UPD_DK4=root:Packages:Indra3:UPD_DK4
540        NVAR UPD_DK5=root:Packages:Indra3:UPD_DK5
541        NVAR UPD_G1=root:Packages:Indra3:UPD_G1
542        NVAR UPD_G2=root:Packages:Indra3:UPD_G2
543        NVAR UPD_G3=root:Packages:Indra3:UPD_G3
544        NVAR UPD_G4=root:Packages:Indra3:UPD_G4
545        NVAR UPD_G5=root:Packages:Indra3:UPD_G5
546        NVAR UPD_Vfc=root:Packages:Indra3:UPD_Vfc
547        NVAR UPD_DK1Err=root:packages:Indra3:UPD_DK1Err
548        NVAR UPD_DK2Err=root:packages:Indra3:UPD_DK2Err
549        NVAR UPD_DK3Err=root:packages:Indra3:UPD_DK3Err
550        NVAR UPD_DK4Err=root:packages:Indra3:UPD_DK4Err
551        NVAR UPD_DK5Err=root:packages:Indra3:UPD_DK5Err
552
553        UPD_Vfc =  NumberByKey("Vfc", UPD,"=")                                          //put the numbers in there
554        UPD_DK1=NumberByKey("Bkg1", UPD,"=")
555        UPD_G1=NumberByKey("Gain1", UPD,"=")
556        UPD_DK2=NumberByKey("Bkg2", UPD,"=")
557        UPD_G2=NumberByKey("Gain2", UPD,"=")
558        UPD_DK3=NumberByKey("Bkg3", UPD,"=")
559        UPD_G3=NumberByKey("Gain3", UPD,"=")
560        UPD_DK4=NumberByKey("Bkg4", UPD,"=")
561        UPD_G4=NumberByKey("Gain4", UPD,"=")
562        UPD_DK5=NumberByKey("Bkg5", UPD,"=")
563        UPD_G5=NumberByKey("Gain5", UPD,"=")
564        UPD_DK1Err=NumberByKey("Bkg1Err", UPD,"=")
565        UPD_DK2Err=NumberByKey("Bkg2Err", UPD,"=")
566        UPD_DK3Err=NumberByKey("Bkg3Err", UPD,"=")
567        UPD_DK4Err=NumberByKey("Bkg4Err", UPD,"=")
568        UPD_DK5Err=NumberByKey("Bkg5Err", UPD,"=")
569        if (UPD_DK1Err<=0)
570                UPD_DK1Err=1
571        endif
572        if (UPD_DK2Err<=0)
573                UPD_DK2Err=1
574        endif
575        if (UPD_DK3Err<=0)
576                UPD_DK3Err=1
577        endif
578        if (UPD_DK4Err<=0)
579                UPD_DK4Err=1
580        endif
581        if (UPD_DK5Err<=0)
582                UPD_DK5Err=1
583        endif
584        //read current size of UPD
585        NVAR PhotoDiodeSize=root:packages:Indra3:PhotoDiodeSize
586        PhotoDiodeSize=NumberByKey("UPDsize", UPD,"=")                                                                                                                          //Default PD size to 5.5mm at this time....
587        if(numtype(PhotoDiodeSize)!=0|| PhotoDiodeSize<=1)
588                PhotoDiodeSize = 5.5
589        endif
590
591        setDataFolder OldDf
592
593end
594//***********************************************************************************************************************************
595//***********************************************************************************************************************************
596//***********************************************************************************************************************************
597//***********************************************************************************************************************************
598static Function IN3_LoadData()
599
600        string oldDf=GetDataFolder(1)
601        setDataFolder root:Packages:Indra3
602       
603        //First Kill waves which may cause conflict.
604        KillWIndow/Z RcurvePlotGraph
605        String ListOfWaves  = DataFolderDir (2)[6,inf]
606        ListOfWaves = RemoveFromList("ListBoxDataSelWv", ListOfWaves,",")
607        ListOfWaves = RemoveFromList("ListBoxDataPositions", ListOfWaves,",")
608        ListOfWaves = RemoveFromList("ListBoxData", ListOfWaves,",")
609        variable i
610        For(i=0;i<ItemsInList(ListOfWaves,",");i+=1)
611                Wave/Z tempWv=$(StringFromList(i, ListOfWaves,","))
612                KillWaves/Z tempWv
613        endfor
614       
615                SVAR LastSample=root:Packages:Indra3:LastSample
616                SVAR DFloc=root:Packages:Indra3:DataFolderName
617                if (cmpstr(DFloc,"---")==0 ||strlen(DFloc)<1)
618                        abort
619                endif
620                LastSample = DFloc
621                Wave/Z OrigAR_encoder=$(DFloc+"AR_encoder")
622                if(!WaveExists(OrigAR_encoder))
623                        return 0
624                endif
625                Duplicate/O OrigAR_encoder, AR_encoder
626                Wave OrigPD_range=$(DFloc+"PD_range")
627                Duplicate/O OrigPD_range, PD_range
628                Wave OrigUSAXS_PD=$(DFloc+"USAXS_PD")
629                Duplicate/O OrigUSAXS_PD, USAXS_PD
630                Wave OrigMeasTime=$(DFloc+"MeasTime")
631                Duplicate/O OrigMeasTime, MeasTime
632                Wave OrigMonitor=$(DFloc+"Monitor")
633                Duplicate/O OrigMonitor, Monitor
634                Wave/Z OringI0_gain=$(DFloc+"I0_gain")
635                if(WaveExists(OringI0_gain))
636                        Duplicate/O OringI0_gain, I0_gain
637                endif
638
639                SVAR OrigSpecCommand =$(DFloc+"SpecCommand")
640                SVAR/Z OrigSpecMotors =$(DFloc+"SpecMotors")
641                SVAR OrigSpecSourceFileName =$(DFloc+"SpecSourceFileName")
642                SVAR OrigSpecComment =$(DFloc+"SpecComment")
643                SVAR OrigMeasurementParameters =$(DFloc+"MeasurementParameters")
644                SVAR OrigUPDParameters =$(DFloc+"UPDParameters")
645                SVAR OrigPathToRawData =$(DFloc+"PathToRawData")
646                string/g SpecCommand = OrigSpecCommand
647                string/g SpecSourceFileName = OrigSpecSourceFileName
648                string/g SpecComment = OrigSpecComment
649                string/g MeasurementParameters = OrigMeasurementParameters
650                string/g UPDParameters = OrigUPDParameters
651                string/g PathToRawData = OrigPathToRawData
652                SVAR userFriendlySamplename = root:Packages:Indra3:userFriendlySamplename
653                SVAR userFriendlySampleDFName = root:Packages:Indra3:userFriendlySampleDFName
654                userFriendlySamplename = OrigSpecComment
655                userFriendlySampleDFName = StringFromList(ItemsInList(DFloc, ":")-1, DFloc,":")
656                //fix BK5 is user specified its change...
657                NVAR OverwriteUPD_DK5 = root:Packages:Indra3:OverwriteUPD_DK5
658                if(OverwriteUPD_DK5>0)
659                        UPDParameters=ReplaceNumberByKey("Bkg5",UPDParameters, OverwriteUPD_DK5,"=")
660                endif
661
662               
663                SVAR Parameters=root:Packages:Indra3:ListOfASBParameters
664                Parameters=ReplaceStringByKey("Sample",Parameters,DFloc,"=")            //write results into ASBparameters
665
666                string IsItSBUSAXS=StringByKey("SPECCOMMAND", note(OrigAR_encoder), "=")[0,7]                   //find out if this is SBUSAXS
667                NVAR is2DCollimated=root:Packages:Indra3:is2DCollimated                                                                         //store this info for later...
668                is2DCollimated = 0
669                string Calibrate
670                if (stringmatch(IsItSBUSAXS,"sbuascan")||stringmatch(IsItSBUSAXS,"sbflysca"))                           //SBUSAXS, do not let user to select USAXS calibration
671                        Calibrate="SBUSAXS;"
672                        is2DCollimated = 1
673                else                                                                                                                                                   
674                        Calibrate="USAXS;"                              //and if it is USAXS data, do not let user select SBUSAXS calibration
675                        is2DCollimated = 0
676                endif
677                Parameters=ReplaceStringByKey("Calibrate",Parameters,Calibrate,"=")
678                NVAR SampleThickness
679                SampleThickness=NumberByKey("thickness", OrigMeasurementParameters,"=")
680                if(SVAR_Exists(OrigSpecMotors))
681                        string/g SpecMotors = OrigSpecMotors
682                        NVAR BeamExposureArea
683                        BeamExposureArea=NumberByKey("uslitverap", SpecMotors,":")* NumberByKey("uslithorap", SpecMotors,":")
684                endif
685                NVAR SampleThicknessBckp
686                SampleThicknessBckp = SampleThickness
687                //2017-01-18 add override Sample thickness
688                NVAR OverRideTh=root:Packages:Indra3:OverideSampleThickness
689                if(OverRideTh>0)
690                        SampleThickness = OverRideTh
691                endif
692               
693                //rezero some old stuff here...
694                NVAR SampleQOffset= root:Packages:Indra3:SampleQOffset
695                SampleQOffset=0
696                NVAR DisplayPeakCenter=root:Packages:Indra3:DisplayPeakCenter
697                DisplayPeakCenter=1
698                NVAR DisplayAlignSaAndBlank=root:Packages:Indra3:DisplayAlignSaAndBlank
699                DisplayAlignSaAndBlank=0
700                NVAR Qmin = root:Packages:Indra3:MSAXSStartPoint
701                NVAR Qmax=root:Packages:Indra3:MSAXSEndPoint
702//              Qmin=0
703//              Qmax=0
704                NVAR UserSavedData
705                UserSavedData=0
706                IN3_FixSaveData()
707        setDataFolder OldDf
708end
709
710//***********************************************************************************************************************************
711//***********************************************************************************************************************************
712//***********************************************************************************************************************************
713//***********************************************************************************************************************************
714//***********************************************************************************************************************************
715//***********************************************************************************************************************************
716static Function IN3_LoadBlank()
717        string oldDf=GetDataFolder(1)
718        setDataFolder root:Packages:Indra3
719       
720        NVAR IsBlank  = root:Packages:Indra3:IsBlank
721
722        if(!IsBlank)
723                SVAR BlankName = root:Packages:Indra3:BlankName
724                SVAR userFriendlyBlankName= root:Packages:Indra3:userFriendlyBlankName
725                userFriendlyBlankName = StringFromList(ItemsInList(BlankName,":")-1, BlankName, ":")
726                if(strlen(BlankName)<4)
727                        abort "Error, select first the Blank name - if none available, create one first"
728                endif
729                Wave BL_R_IntL = $(BlankName+"Blank_R_Int")
730                Wave BL_R_errorL = $(BlankName+"Blank_R_error")
731                Wave BL_R_QvecL = $(BlankName+"Blank_R_Qvec")
732                Duplicate/O BL_R_IntL, BL_R_Int
733                Duplicate/O BL_R_errorL, BL_R_error
734                Duplicate/O BL_R_QvecL, BL_R_Qvec
735                SVAR Parameters=ListOfASBParameters
736                Parameters=ReplaceStringByKey("Blank",Parameters,BlankName,"=")
737                NVAR BlankFWHM
738                NVAR BlankMaximum
739                NVAR BlankWidth
740                NVAR BlankWidthBckp
741                NVAR BlankFWHMBckp
742                NVAR BlankMaximumBckp
743                NVAR OrigBlankFWHM = $(BlankName+"PeakWidth")
744                NVAR OrigBlankMaximum = $(BlankName+"MaximumIntensity")
745                BlankFWHM= OrigBlankFWHM
746                BlankMaximum=OrigBlankMaximum
747                BlankWidth=OrigBlankFWHM*3600   //in arc seconds
748                BlankWidthBckp = BlankWidth
749                BlankFWHMBckp = BlankFWHM
750                BlankMaximumBckp = BlankMaximum
751        endif
752
753        setDataFolder OldDf     
754end
755//***********************************************************************************************************************************
756//***********************************************************************************************************************************
757//***********************************************************************************************************************************
758//***********************************************************************************************************************************
759//***********************************************************************************************************************************
760//***********************************************************************************************************************************
761
762//*****************************************************************************************************************
763//*****************************************************************************************************************
764//*****************************************************************************************************************
765//*****************************************************************************************************************
766//*****************************************************************************************************************
767
768
769
770static Function IN3_GraphData()
771
772        string oldDf=GetDataFolder(1)
773        setDataFolder root:Packages:Indra3
774        KillWIndow/Z RcurvePlotGraph
775        IN3_RcurvePlot()       
776        IN3_DisplayRightSubwindow()
777        IN3_FixDispControlsInRcurvePlot()
778
779       
780
781        setDataFolder OldDf
782
783end
784//***********************************************************************************************************************************
785//***********************************************************************************************************************************
786//***********************************************************************************************************************************
787//***********************************************************************************************************************************
788Function IN3_DisplayRightSubwindow()
789
790        NVAR DisplayPeakCenter =root:Packages:Indra3:DisplayPeakCenter
791        NVAR DisplayAlignSaAndBlank=root:Packages:Indra3:DisplayAlignSaAndBlank
792
793        String ExistingSubWindows=ChildWindowList("RcurvePlotGraph")
794        if(stringmatch(ExistingSubWindows,"*PeakCenter*"))
795                KillWindow RcurvePlotGraph#PeakCenter
796        endif
797        if(stringmatch(ExistingSubWindows,"*AlignSampleAndBlank*"))
798                KillWindow RcurvePlotGraph#AlignSampleAndBlank
799        endif
800       
801        if(DisplayPeakCenter)
802                IN3_PeakCenter()
803        elseif(DisplayAlignSaAndBlank)
804                IN3_AlignSampleAndBlank()
805        endif
806end
807
808//*****************************************************************************************************************
809//*****************************************************************************************************************
810//*****************************************************************************************************************
811//*****************************************************************************************************************
812//*****************************************************************************************************************
813
814
815//checbox control procedure
816Function IN3_MainPanelCheckBox(ctrlName,checked) : CheckBoxControl
817        String ctrlName
818        Variable checked
819
820        NVAR CalculateWeight=root:Packages:Indra3:CalculateWeight
821        NVAR CalculateThickness=root:Packages:Indra3:CalculateThickness
822        NVAR CalibrateToWeight=root:Packages:Indra3:CalibrateToWeight
823        NVAR CalibrateToVolume=root:Packages:Indra3:CalibrateToVolume
824        NVAR CalibrateArbitrary=root:Packages:Indra3:CalibrateArbitrary
825        NVAR UsePinTransmission=root:Packages:Indra3:UsePinTransmission
826        NVAR UseMSAXSCorrection=root:Packages:Indra3:UseMSAXSCorrection
827
828       
829        if (cmpstr("IsBlank",ctrlName)==0)
830                NVAR IsBlank=root:Packages:Indra3:IsBlank
831                NVAR SmoothRCurveData=root:Packages:Indra3:SmoothRCurveData
832                PopupMenu SelectBlankFolder, disable = IsBlank
833                //check if Blank name is correct
834                SVAR BlankName = root:Packages:Indra3:BlankName
835                if((stringMatch(BlankName,"")||stringMatch(BlankName,"---"))&&!IsBlank)
836                        BlankName = StringFromList(0,IN3_GenStringOfFolders(1))
837                        PopupMenu SelectBlankFolder win=USAXSDataReduction, mode=WhichListItem(BlankName, "---;"+IN3_GenStringOfFolders(1))+1, value="---;"+IN3_GenStringOfFolders(1)
838                        Print "No Blank was selected, we found Blank "+BlankName+"  , and used this one. Change if necessary."
839                        TitleBox SelectBlankFolderWarning win=USAXSDataReduction, disable=0
840                elseif(!stringMatch(BlankName,"")&&!IsBlank)
841                        TitleBox SelectBlankFolderWarning win=USAXSDataReduction, disable=1
842                        PopupMenu SelectBlankFolder win=USAXSDataReduction, mode=WhichListItem(BlankName, "---;"+IN3_GenStringOfFolders(1))+1, value="---;"+IN3_GenStringOfFolders(1)
843                endif
844                if(isBlank)
845                        TitleBox SelectBlankFolderWarning win=USAXSDataReduction, disable=1
846                        SmoothRCurveData=1
847                else
848                        SmoothRCurveData=0
849                endif
850        endif
851        if (cmpstr("RecalculateAutomatically",ctrlName)==0)
852
853        endif
854        if (cmpstr("SmoothRCurveData",ctrlName)==0)
855                        IN3_RecalculateData(2)
856                        IN3_DesmearData()
857        endif
858        NVAR CalculateWeight=root:Packages:Indra3:CalculateWeight
859        NVAR CalculateThickness=root:Packages:Indra3:CalculateThickness
860        if (cmpstr("CalculateThickness",ctrlName)==0)
861                NI3_TabPanelControl("",0)
862                IN3_CalcSampleWeightOrThickness()
863        endif
864        if (cmpstr("CalculateWeight",ctrlName)==0)
865                NI3_TabPanelControl("",0)
866                IN3_CalcSampleWeightOrThickness()
867        endif
868
869        if (stringmatch("CalibrateToVolume",ctrlName))
870                if(checked)
871                        CalibrateToWeight = 0
872                        CalibrateArbitrary = 0
873                else
874                        if((CalibrateToWeight+CalibrateArbitrary)!=1)
875                                CalibrateArbitrary = 1
876                                CalibrateToWeight = 0
877                        endif
878                endif
879                NI3_TabPanelControl("",0)
880        endif
881       
882        if(stringmatch("CalibrateToWeight",ctrlName) )
883                if(checked)
884                        CalibrateToVolume = 0
885                        CalibrateArbitrary = 0
886                else
887                        if((CalibrateToVolume+CalibrateArbitrary)!=1)
888                                CalibrateArbitrary = 0
889                                CalibrateToVolume = 1
890                        endif
891                endif
892                NI3_TabPanelControl("",0)
893        endif
894
895        if(stringmatch("CalibrateArbitrary",ctrlName) )
896                if(checked)
897                        CalibrateToVolume = 0
898                        CalibrateToWeight = 0
899                else
900                        if((CalibrateToVolume+CalibrateToWeight)!=1)
901                                CalibrateToWeight = 0
902                                CalibrateToVolume = 1
903                        endif
904                endif
905                NI3_TabPanelControl("",0)
906        endif
907       
908        if (cmpstr("UseMSAXSCorrection",ctrlName)==0)
909                IF(checked)
910                         UsePinTransmission=0
911                endif
912                NI3_TabPanelControl("",4)
913                IN3_RecalculateData(3)
914                IN3_DesmearData()
915        endif
916        if (cmpstr("UsePinTransmission",ctrlName)==0)
917                IF(checked)
918                         UseMSAXSCorrection=0
919                endif
920                NI3_TabPanelControl("",0)
921                IN3_RecalculateData(3)
922                IN3_DesmearData()
923        endif
924        if (cmpstr("RemoveDropouts",ctrlName)==0)
925                IN3_RecalculateData(1)
926                IN3_DesmearData()
927        endif
928       
929        if (cmpstr("DesmearData",ctrlName)==0)
930                NI3_TabPanelControl("",5)
931                IN3_RecalculateData(1)
932                IN3_DesmearData()
933        endif
934       
935       
936end
937//*****************************************************************************************************************
938//*****************************************************************************************************************
939//*****************************************************************************************************************
940Function IN3_COlorizeButton()
941        DOWINDOW RcurvePlotGraph
942        IF(V_FLag)
943                NVAR UseLorenz = root:Packages:Indra3:UseLorenz
944                NVAR UseModifiedGauss = root:Packages:Indra3:UseModifiedGauss
945                NVAR UseGauss = root:Packages:Indra3:UseGauss
946                if(UseModifiedGauss)
947                        Button FitModGauss,win=RcurvePlotGraph ,fColor=(16386,65535,16385)
948                else
949                        Button FitModGauss,win=RcurvePlotGraph ,fColor=(0,0,0)
950                endif
951                if(UseGauss)
952                        Button FitGauss,win=RcurvePlotGraph ,fColor=(16386,65535,16385)
953                else
954                        Button FitGauss,win=RcurvePlotGraph ,fColor=(0,0,0)
955                endif
956                if(UseLorenz)
957                        Button FitLorenz,win=RcurvePlotGraph ,fColor=(16386,65535,16385)
958                else
959                        Button FitLorenz,win=RcurvePlotGraph ,fColor=(0,0,0)
960                endif
961        endif
962end
963
964
965//*****************************************************************************************************************
966//*****************************************************************************************************************
967
968
969static Function IN3_RcurvePlot()
970        PauseUpdate; Silent 1           // building window...
971        String fldrSav0= GetDataFolder(1)
972        SetDataFolder root:Packages:Indra3:
973        Wave R_Int
974        Wave R_Qvec
975        NVAR IsBlank = root:Packages:Indra3:IsBlank
976
977//      Wave fit_PD_Intensity
978//      Wave fitX_PD_Intensity
979//      Wave R_error
980//      Wave AR_encoder
981        Wave/Z PeakFitWave
982        NVAR PeakCenterFitStartPoint=root:Packages:Indra3:PeakCenterFitStartPoint
983        NVAR PeakCenterFitEndPoint=root:Packages:Indra3:PeakCenterFitEndPoint
984       
985        //create main plot with R curve data
986        //variable NewWidth = 0.6*(IN2G_ScreenWidthHeight("width")*100) - 300
987        //variable NewHeight = 0.6*(IN2G_ScreenWidthHeight("height")*100)
988        //variable NewWidth = IN2G_GetGraphWidthHeight("width")
989        //variable NewHeight = IN2G_GetGraphWidthHeight("height")
990        //Display/K=1 /W=(300,36.5,900,500) R_Int vs R_Qvec as "USAXS data reduction plot"
991        Display/K=1 /W=(0,0,IN2G_GetGraphWidthHeight("width"),IN2G_GetGraphWidthHeight("height")) R_Int vs R_Qvec as "USAXS data reduction plot"
992        DoWindow/C RcurvePlotGraph
993        AutoPositionWindow/M=1/R=USAXSDataReduction  RcurvePlotGraph
994//      AppendToGraph fit_PD_Intensity vs fitX_PD_Intensity
995        //modify the displayed waves
996        ModifyGraph mode(R_Int)=4
997        ModifyGraph rgb(R_Int)=(65280,0,0)
998        ModifyGraph msize(R_Int)=2
999        ModifyGraph log=1
1000        ModifyGraph grid=2
1001        ModifyGraph axOffset(bottom)=0.888889
1002        ModifyGraph lblPos(left)=60,lblPos(bottom)=51
1003        ModifyGraph lblLatPos(left)=-4,lblLatPos(bottom)=-2
1004        Label left "Intensity"
1005        Label bottom "Q [A\\S-1\\M]"
1006        SetAxis bottom 1e-05, R_Qvec[numpnts(R_Qvec)-1]
1007        ShowInfo
1008        ControlBar 50
1009        SetVariable SampleTransmission,pos={200,5},size={300,22},title="Sample transmission (peak max)"
1010        SetVariable SampleTransmission,proc=IN3_ParametersChanged
1011        SetVariable SampleTransmission,limits={0,inf,0.005},variable= root:Packages:Indra3:SampleTransmissionPeakToPeak
1012
1013        SetVariable SampleAngleOffset,pos={200,25},size={300,22},title="Q offset              "
1014        SetVariable SampleAngleOffset,proc=IN3_ParametersChanged
1015        SetVariable SampleAngleOffset,limits={-inf,inf,0.5e-6},variable= root:Packages:Indra3:SampleQOffset
1016
1017        Button Recalculate,pos={170,25},size={100,20},proc=IN3_InputPanelButtonProc,title="\Zr090Recalculate", help={"Recalculate the data"}
1018        Button Recalculate fColor=(40969,65535,16385)
1019        Button RemovePointsRange,pos={280,3},size={100,20},proc=IN3_InputPanelButtonProc,title="\Zr090Rem pnts w/Marquee", help={"Remove point by selecting Range with Marquee"}
1020        Button RemovePoint,pos={280,25},size={100,20},proc=IN3_InputPanelButtonProc,title="\Zr090Remove pnt w/csr A", help={"Remove point with cursor A"}
1021        Button FixGain,pos={170,3},size={100,20}, proc=IN3_GraphButtonProc,title="\Zr090Fix Gain w/c A"
1022
1023        CheckBox UseModifiedGauss title="\Zr090Mod. Gauss",proc=IN3_RplotCheckProc
1024        CheckBox UseModifiedGauss variable=root:Packages:Indra3:UseModifiedGauss,mode=1,pos={385,1}
1025        CheckBox UseGauss title="\Zr090Gauss",proc=IN3_RplotCheckProc
1026        CheckBox UseGauss variable=root:Packages:Indra3:UseGauss,mode=1,pos={385,17}
1027        CheckBox UseLorenz title="\Zr090Lorenz",proc=IN3_RplotCheckProc
1028        CheckBox UseLorenz variable=root:Packages:Indra3:UseLorenz,mode=1,pos={385,34}
1029
1030        Button FitModGauss,pos={465,3},size={80,18}, proc=IN3_GraphButtonProc,title="\Zr090Fit Mod. Gauss"
1031        Button FitGauss,pos={555,3},size={80,18}, proc=IN3_GraphButtonProc,title="\Zr090Fit Gauss"
1032        Button FitLorenz,pos={555,25},size={80,18}, proc=IN3_GraphButtonProc,title="\Zr090Fit Lorenz"
1033
1034        CheckBox DisplayPeakCenter title="Display Peak Fit",proc=IN3_RplotCheckProc
1035        CheckBox DisplayPeakCenter variable=root:Packages:Indra3:DisplayPeakCenter,mode=1,pos={5,5}
1036        CheckBox DisplayAlignSaAndBlank title="Display Align Sa and Blank",proc=IN3_RplotCheckProc, disable=IsBlank
1037        CheckBox DisplayAlignSaAndBlank variable=root:Packages:Indra3:DisplayAlignSaAndBlank,mode=1,pos={5,25}
1038        //append sample and blank names...
1039        SVAR userFriendlySamplename = root:Packages:Indra3:userFriendlySamplename
1040        SVAR userFriendlyBlankName = root:Packages:Indra3:userFriendlyBlankName
1041        SVAR LastSample = root:Packages:Indra3:LastSample
1042        string LegendString="\\Zr130\\K(52224,0,0)Sample : "+userFriendlySamplename
1043        LegendString+="\r\\Zr090\\K(0,0,0)File : "+stringFromList(ItemsInList(LastSample,":")-1, LastSample, ":")
1044        SetDrawLayer UserFront
1045        IN3_COlorizeButton()
1046        NVAR IsBlank=root:Packages:Indra3:IsBlank
1047        if(!IsBlank)
1048                Wave/Z BL_R_Int=root:Packages:Indra3:BL_R_Int
1049                Wave/Z BL_R_error=root:Packages:Indra3:BL_R_error
1050                Wave/Z BL_R_Qvec= root:Packages:Indra3:BL_R_Qvec
1051                AppendToGraph BL_R_Int vs BL_R_Qvec
1052                ModifyGraph rgb(BL_R_Int)=(0,0,0), mode(BL_R_Int)=0
1053                NVAR TrimDataStart=root:Packages:Indra3:TrimDataStart
1054                NVAR TrimDataEnd=root:Packages:Indra3:TrimDataEnd
1055                if(TrimDataStart>0)
1056                        Cursor/P/W=RcurvePlotGraph A R_Int TrimDataStart       
1057                endif
1058                if(TrimDataEnd>0)
1059                        Cursor/P/W=RcurvePlotGraph B R_Int TrimDataEnd 
1060                endif
1061                LegendString+="\r\\K(0,0,0)Blank : "+userFriendlyBlankName
1062        endif
1063        TextBox/C/N=SampleAndBLank/A=LC/F=0/B=1/X=0.00/Y=-25.00 LegendString
1064       
1065
1066        SetDataFolder fldrSav0
1067End
1068//***********************************************************************************************************************************
1069//***********************************************************************************************************************************
1070Function IN3_FixDispControlsInRcurvePlot()
1071
1072
1073        NVAR DisplayPeakCenter = root:Packages:Indra3:DisplayPeakCenter
1074        NVAR DisplayAlignSaAndBlank = root:Packages:Indra3:DisplayAlignSaAndBlank
1075       
1076        SetVariable SampleTransmission,win=RcurvePlotGraph, disable =DisplayPeakCenter
1077        SetVariable SampleAngleOffset,win=RcurvePlotGraph, disable =DisplayPeakCenter
1078
1079        Button FitGauss,win=RcurvePlotGraph, disable =DisplayAlignSaAndBlank
1080        Button FitModGauss,win=RcurvePlotGraph, disable =DisplayAlignSaAndBlank
1081        Button FitLorenz,win=RcurvePlotGraph, disable =DisplayAlignSaAndBlank
1082
1083        Button Recalculate,win=RcurvePlotGraph, disable =DisplayAlignSaAndBlank
1084        Button RemovePoint,win=RcurvePlotGraph, disable =DisplayAlignSaAndBlank
1085        Button RemovePointsRange,win=RcurvePlotGraph, disable =DisplayAlignSaAndBlank
1086        Button FixGain,win=RcurvePlotGraph, disable =DisplayAlignSaAndBlank
1087
1088        Checkbox UseModifiedGauss,win=RcurvePlotGraph, disable =DisplayAlignSaAndBlank
1089        Checkbox UseGauss,win=RcurvePlotGraph, disable =DisplayAlignSaAndBlank
1090        Checkbox UseLorenz,win=RcurvePlotGraph, disable =DisplayAlignSaAndBlank
1091
1092end
1093
1094//*****************************************************************************************************************
1095//*****************************************************************************************************************
1096//*****************************************************************************************************************
1097
1098static Function IN3_PeakCenter()
1099        PauseUpdate; Silent 1           // building window...
1100        String fldrSav0= GetDataFolder(1)
1101        SetDataFolder root:Packages:Indra3:
1102        Wave R_Int
1103        Wave R_Qvec
1104        Wave fit_PD_Intensity
1105//      Wave fitX_PD_Intensity
1106//      Wave R_error
1107        Wave AR_encoder
1108        Wave/Z PeakFitWave
1109        Wave PD_Intensity
1110        Wave PD_Error
1111        NVAR PeakCenterFitStartPoint=root:Packages:Indra3:PeakCenterFitStartPoint
1112        NVAR PeakCenterFitEndPoint=root:Packages:Indra3:PeakCenterFitEndPoint
1113       
1114        //create main plot with R curve data
1115        //create the other graph
1116        Display/K=1/W=(0.431,0.03,0.8,0.399)/FG=(,GT,FR,)/PG=(,,PR,)/HOST=RcurvePlotGraph  PD_Intensity vs AR_encoder
1117        AppendToGraph fit_PD_Intensity,PeakFitWave
1118        //modify displayed waves
1119        ModifyGraph mode(PD_Intensity)=3
1120        ModifyGraph lSize(fit_PD_Intensity)=2
1121        ModifyGraph lStyle(PeakFitWave)=3
1122        ModifyGraph rgb(fit_PD_Intensity)=(0,0,52224),rgb(PeakFitWave)=(0,0,65280)
1123        ModifyGraph nticks(bottom)=2
1124        ModifyGraph lblMargin(left)=26,lblMargin(bottom)=1
1125        ModifyGraph lblLatPos=-1
1126        Label left "Intensity"
1127        Label bottom "AR angle [deg]"
1128        ErrorBars PD_Intensity Y,wave=(PD_Error,PD_Error)
1129        variable center = (PeakCenterFitEndPoint + PeakCenterFitStartPoint)/2
1130        variable start = max(center - 1.5 * (center - PeakCenterFitStartPoint),0)
1131        variable end1 = min(center + 1.8 * (PeakCenterFitEndPoint-center),numpnts(AR_encoder))
1132        SetAxis bottom AR_encoder[start],AR_encoder[end1]
1133        Cursor/P A PD_Intensity PeakCenterFitStartPoint
1134        Cursor/P B PD_Intensity PeakCenterFitEndPoint
1135        RenameWindow #,PeakCenter
1136        SetActiveSubwindow ##
1137
1138        SetDataFolder fldrSav0
1139End
1140//***********************************************************************************************************************************
1141//***********************************************************************************************************************************
1142//***********************************************************************************************************************************
1143//***********************************************************************************************************************************
1144//***********************************************************************************************************************************
1145//***********************************************************************************************************************************
1146//*****************************************************************************************************************
1147//*****************************************************************************************************************
1148//*****************************************************************************************************************
1149
1150static Function IN3_AlignSampleAndBlank()
1151        PauseUpdate; Silent 1           // building window...
1152        String fldrSav0= GetDataFolder(1)
1153        SetDataFolder root:Packages:Indra3:
1154       
1155        NVAR IsBlank = root:Packages:Indra3:IsBlank
1156        if(IsBlank)
1157                return 0
1158        endif
1159        Wave R_Int
1160        Wave R_Qvec
1161        Wave R_Error
1162//      Wave fit_PD_Intensity
1163//      Wave fitX_PD_Intensity
1164        Wave R_error
1165        Wave AR_encoder
1166        Wave PeakFitWave
1167        NVAR PeakCenterFitStartPoint=root:Packages:Indra3:PeakCenterFitStartPoint
1168        NVAR PeakCenterFitEndPoint=root:Packages:Indra3:PeakCenterFitEndPoint
1169        Wave BL_R_Int
1170        Wave BL_R_Qvec
1171       
1172        //create main plot with R curve data
1173        //create the other graph
1174        Display/K=1/W=(0.431,0.03,0.8,0.399)/FG=(,GT,FR,)/PG=(,,PR,)/HOST=RcurvePlotGraph  R_Int vs R_Qvec
1175        AppendToGraph BL_R_Int vs BL_R_Qvec
1176        //modify displayed waves
1177        ModifyGraph mode(R_Int)=3
1178        ModifyGraph rgb(BL_R_Int)=(0,0,0)
1179        ModifyGraph lstyle(BL_R_Int)=3,lsize(BL_R_Int)=2
1180        ModifyGraph nticks(bottom)=2
1181        ModifyGraph lblMargin(left)=26,lblMargin(bottom)=1
1182        ModifyGraph lblLatPos=-1
1183        Label left "Intensity"
1184        Label bottom "Q [A\S-1\M]"
1185        ErrorBars R_Int Y,wave=(R_Error,R_Error)
1186        variable center = (PeakCenterFitEndPoint + PeakCenterFitStartPoint)/2
1187        variable start = max(center - 1.5 * abs(center - PeakCenterFitStartPoint),0)
1188        variable end1 = min(center + 2.1 * abs(center - PeakCenterFitEndPoint),numpnts(AR_encoder))
1189        SetAxis bottom R_Qvec[start],R_Qvec[end1]
1190//      Cursor/P A R_Int PeakCenterFitStartPoint
1191//      Cursor/P B R_Int PeakCenterFitEndPoint
1192        RenameWindow #,AlignSampleAndBlank
1193        SetActiveSubwindow ##
1194
1195        SetDataFolder fldrSav0
1196End
1197//***********************************************************************************************************************************
1198//***********************************************************************************************************************************
1199//***********************************************************************************************************************************
1200//***********************************************************************************************************************************
1201//***********************************************************************************************************************************
1202//***********************************************************************************************************************************
1203static Function IN3_AppendBlankToRPlot()
1204        string oldDf=GetDataFolder(1)
1205        setDataFolder root:Packages:Indra3
1206       
1207        NVAR IsBlank
1208        if(!IsBlank)
1209                Wave BL_R_Int
1210                Wave BL_R_Qvec
1211//              Wave BL_AR_encoder
1212               
1213                AppendToGraph/W=RcurvePlotGraph BL_R_Int vs BL_R_Qvec
1214                ModifyGraph/W=RcurvePlotGraph rgb(BL_R_Int)=(0,0,0)
1215
1216//              AppendToGraph/W=RcurvePlotGraph#PeakCenter BL_R_Int vs BL_AR_encoder
1217//              ModifyGraph/W=RcurvePlotGraph#PeakCenter rgb(BL_R_Int)=(0,0,0)
1218               
1219       
1220        endif
1221
1222
1223        setDataFolder OldDf     
1224end
1225//***********************************************************************************************************************************
1226//***********************************************************************************************************************************
1227//***********************************************************************************************************************************
1228//***********************************************************************************************************************************
1229//***********************************************************************************************************************************
1230//***********************************************************************************************************************************
1231
1232//***************************************************************************************************************************************
1233//***************************************************************************************************************************************
1234//***************************************************************************************************************************************
1235//***************************************************************************************************************************************
1236//***************************************************************************************************************************************
1237//***************************************************************************************************************************************
1238
1239Function IN3_GraphButtonProc(ctrlName) : ButtonControl
1240        String ctrlName
1241       
1242        NVAR PeakCenterFitStartPoint=root:Packages:Indra3:PeakCenterFitStartPoint
1243        NVAR PeakCenterFitEndPoint=root:Packages:Indra3:PeakCenterFitEndPoint
1244        Wave AR_encoder=root:Packages:Indra3:AR_encoder
1245        String AcsrWaveName = StringByKey("TNAME", CsrInfo(A , "RcurvePlotGraph#PeakCenter")  , ":" , ";")
1246        String BcsrWaveName = StringByKey("TNAME", CsrInfo(B , "RcurvePlotGraph#PeakCenter")  , ":" , ";")
1247        variable curX
1248        if (!stringMatch(AcsrWaveName,"PD_Intensity"))
1249                curX = xcsr(A , "RcurvePlotGraph#PeakCenter")
1250                Cursor /W=RcurvePlotGraph#PeakCenter A, PD_Intensity, (BinarySearch(AR_encoder, curX ))
1251        endif
1252        if (!stringMatch(BcsrWaveName,"PD_Intensity"))
1253                curX = xcsr(B, "RcurvePlotGraph#PeakCenter")
1254                Cursor /W=RcurvePlotGraph#PeakCenter B, PD_Intensity, (BinarySearch(AR_encoder, curX )+1)
1255        endif
1256
1257        if(stringMatch(ctrlName,"FixGain"))
1258                if((strlen(csrInfo(A,"RcurvePlotGraph"))<1)||(!stringMatch(stringByKey("TNAME",csrinfo(A,"RcurvePlotGraph")),"R_Int")))
1259                        DoAlert 0, "Cursor A not set or set on incorrect wave, should be on R_Int"
1260                else
1261                        Wave PD_range = root:Packages:Indra3:PD_range
1262                        variable CurPDRange, curPntNum
1263                        curPntNum=pcsr(A,"RcurvePlotGraph")
1264                        CurPDRange=PD_range[curPntNum]
1265                        Prompt CurPDRange, "Change the PD range for selected point"
1266                        DoPrompt "Fix the PD range here", CurPDRange
1267                        if(V_Flag)
1268                                abort
1269                        endif
1270                        CurPDRange = round(CurPDRange)
1271                        if(CurPDRange<1||CurPDRange>5)
1272                                DoAlert 0, "PD range input is wrong, 1-5 and intergers possible only)"
1273                        else
1274                                PD_range[curPntNum]=CurPDRange
1275                                IN3_RecalculateData(1) 
1276                                IN3_DesmearData()
1277                                DoWIndow/F USAXSDataReduction
1278                        endif                   
1279                endif
1280               
1281               
1282        endif
1283        if(stringMatch(ctrlName,"FitGauss"))
1284                //get position of cursors from the right window and run fitting rouitne with gaussien
1285                PeakCenterFitStartPoint=min(pcsr(A, "RcurvePlotGraph#PeakCenter"),pcsr(B, "RcurvePlotGraph#PeakCenter"))
1286                PeakCenterFitEndPoint=max(pcsr(A, "RcurvePlotGraph#PeakCenter"),pcsr(B, "RcurvePlotGraph#PeakCenter"))
1287                IN3_FitGaussTop("")
1288                IN3_RecalculateData(1) 
1289                IN3_DesmearData()
1290        endif
1291        if(stringMatch(ctrlName,"FitModGauss"))
1292                //get position of cursors from the right window and run fitting rouitne with gaussien
1293                PeakCenterFitStartPoint=min(pcsr(A, "RcurvePlotGraph#PeakCenter"),pcsr(B, "RcurvePlotGraph#PeakCenter"))
1294                PeakCenterFitEndPoint=max(pcsr(A, "RcurvePlotGraph#PeakCenter"),pcsr(B, "RcurvePlotGraph#PeakCenter"))
1295                IN3_FitModGaussTop("", 1)
1296                IN3_RecalculateData(1) 
1297                IN3_DesmearData()
1298        endif
1299        if(stringMatch(ctrlName,"FitLorenz"))
1300                //get position of cursors from the right window and run fitting rouitne with lorenzian
1301                PeakCenterFitStartPoint=min(pcsr(A, "RcurvePlotGraph#PeakCenter"),pcsr(B, "RcurvePlotGraph#PeakCenter"))
1302                PeakCenterFitEndPoint=max(pcsr(A, "RcurvePlotGraph#PeakCenter"),pcsr(B, "RcurvePlotGraph#PeakCenter"))
1303                IN3_FitLorenzianTop("")
1304                IN3_RecalculateData(1) 
1305                IN3_DesmearData()
1306        endif
1307End
1308
1309///**********************************************************************************************************
1310//**********************************************************************************************************
1311//**********************************************************************************************************
1312
1313Function IN3_FitGaussTop(ctrlname) : Buttoncontrol                      // calls the Gaussien fit
1314        string ctrlname
1315       
1316        string oldDf=GetDataFolder(1)
1317        setDataFolder root:Packages:Indra3
1318
1319        NVAR PeakCenterFitStartPoint
1320        NVAR PeakCenterFitEndPoint
1321
1322        Wave PD_error
1323        Wave Ar_encoder
1324        Wave PD_Intensity
1325        Make/O/N=200 PeakFitWave
1326        DoWIndow RcurvePlotGraph
1327        String ExistingSubWindows
1328        if(V_Flag)
1329                ExistingSubWindows=ChildWindowList("RcurvePlotGraph")
1330        else
1331                ExistingSubWindows=""
1332        endif
1333        if(stringmatch(ExistingSubWindows,"*PeakCenter*"))
1334                getAxis/W=RcurvePlotGraph#PeakCenter /Q bottom
1335                SetScale/I x V_min, V_max,"", PeakFitWave
1336        else
1337                variable center = (PeakCenterFitStartPoint + PeakCenterFitEndPoint)/2
1338                variable start = max(0,center - (center -PeakCenterFitStartPoint) *3 )
1339                variable end1 = min(center + (PeakCenterFitEndPoint-center) *3, numpnts(Ar_encoder) )
1340                SetScale/I x Ar_encoder[start], Ar_encoder[end1],"", PeakFitWave
1341        endif
1342        K0=0
1343        //      if(strlen(CsrInfo(A, "RcurvePlot")) <1  || strlen(CsrInfo(B, "RcurvePlot"))<1)
1344        //              return 0
1345        //      endif
1346        //Duplicate /R=[PeakCenterFitStartPoint,PeakCenterFitEndPoint]/Free PD_Intensity, PDIntFit
1347        //Duplicate /R=[PeakCenterFitStartPoint,PeakCenterFitEndPoint]/Free Ar_encoder, ArEncFit
1348        //Duplicate /R=[PeakCenterFitStartPoint,PeakCenterFitEndPoint]/Free PD_error, PDErrFit
1349        //IN2G_RemoveNaNsFrom3Waves(PDIntFit,ArEncFit,PDErrFit)
1350        //CurveFit/Q/N/H="1000" /L=50  gauss PDIntFit  /X=ArEncFit/D /W=PDErrFit /I=1   //Gauss
1351        CurveFit/Q/N/H="1000" /L=50  gauss PD_Intensity [PeakCenterFitStartPoint,PeakCenterFitEndPoint]  /X=Ar_encoder/D /W=PD_error /I=1       //Gauss
1352                //      print "Fitted Gaussian between points  "+num2str(PeakCenterFitStartPoint)+"   and    "+num2str(PeakCenterFitEndPoint)+"    reached Chi-squared/numpoints    " +num2str(V_chisq/(PeakCenterFitEndPoint-PeakCenterFitStartPoint))
1353                //      string ModifyWave
1354                //      ModifyWave="fit_"+WaveName("",0,1)                                              //new wave with the lorenzian fit
1355                //      ModifyGraph /W=RcurvePlot lsize(fit_PD_Intensity)=3, rgb(fit_PD_intensity)=(0,15872,65280)
1356                NVAR BeamCenter
1357        NVAR MaximumIntensity
1358        NVAR PeakWidth         
1359        NVAR PeakWidthArcSec           
1360        Variable BeamCenterError, MaximumIntensityError, PeakWidthError
1361        Wave W_coef
1362        Wave W_sigma
1363                //      Wave FitResiduals
1364                //      FitResiduals= ((W_coef[0]+W_coef[1]*exp(-((Ar_encoder[p]-W_coef[2])/W_coef[3])^2)) - PD_Intensity[p])/PD_error[p]
1365                //      FitResiduals[0,PeakCenterFitStartPoint-1]=NaN
1366                //      FitResiduals[PeakCenterFitEndPoint+1,inf]=NaN
1367        PeakFitWave= W_coef[0]+W_coef[1]*exp(-((x-W_coef[2])/W_coef[3])^2)
1368        BeamCenter=W_coef[2]
1369        BeamCenterError=W_sigma[2]
1370        MaximumIntensity=W_coef[1]
1371        MaximumIntensityError=W_sigma[1]
1372        PeakWidth = 2*(sqrt(ln(2)))*abs(W_coef[3])
1373        PeakWidthArcSec = PeakWidth*3600
1374        PeakWidthError=2*(sqrt(ln(2)))*abs(W_sigma[3])
1375        Variable GaussPeakWidth=2*(sqrt(ln(2)))*abs(W_coef[3])                  // properly fixed by now.
1376        Variable GaussPeakWidthError=2*(sqrt(ln(2)))*abs(W_sigma[3])
1377        string BmCnterStr
1378        Sprintf BmCnterStr, "%8.5f", BeamCenter
1379        String Width="\Z12FWHM   "+num2str(3600*GaussPeakWidth)+" +/- "+num2str(3600*GaussPeakWidthError)+"  arc-sec"
1380        Width+="\rMax       "+num2str(MaximumIntensity)+"   +/-  "+num2str(MaximumIntensityError)
1381        Width+="\rBm Cntr  "+BmCnterStr+"  +/-  "+num2str(BeamCenterError)+"  deg."
1382        DoWindow RcurvePlotGraph
1383        if(V_Flag)
1384                Textbox/W=RcurvePlotGraph/K/N=text1
1385                TextBox/W=RcurvePlotGraph/N=text1/F=0/B=2/X=63.96/Y=89.45 Width
1386        endif
1387//      ModifyGraph rgb($ModifyWave)=(0,15872,65280)
1388//      KillWaves W_WaveList
1389        Wave/Z R_Qvec
1390        if(WaveExists(R_Qvec))
1391                string ListOfWaveNames = "R_Qvec;R_Int;R_Error;Qvec;"
1392                IN2G_AppendNoteToListOfWaves(ListOfWaveNames,"PeakFitFunction","Gauss")
1393                IN2G_AppendNoteToListOfWaves(ListOfWaveNames,"BeamCenter",num2str(BeamCenter))
1394                IN2G_AppendNoteToListOfWaves(ListOfWaveNames,"MaximumIntensity",num2str(MaximumIntensity))
1395                IN2G_AppendNoteToListOfWaves(ListOfWaveNames,"FWHM",num2str(PeakWidth*3600))
1396                IN2G_AppendNoteToListOfWaves(ListOfWaveNames,"BeamCenterError",num2str(BeamCenterError))
1397                IN2G_AppendNoteToListOfWaves(ListOfWaveNames,"MaximumIntensityError",num2str(MaximumIntensityError))
1398                IN2G_AppendNoteToListOfWaves(ListOfWaveNames,"FWHM_Error",num2str(PeakWidthError*3600))
1399        endif
1400        setDataFolder OldDf
1401
1402End
1403///**********************************************************************************************************
1404///**********************************************************************************************************
1405///**********************************************************************************************************
1406///**********************************************************************************************************
1407///**********************************************************************************************************
1408
1409Function IN3_FitDefaultTop()
1410        NVAR UseModifiedGauss
1411        NVAR UseGauss
1412        NVAR UseLorenz
1413
1414        if(UseModifiedGauss)
1415                IN3_FitModGaussTop("",0)       
1416        elseif(UseGauss)
1417                IN3_FitGaussTop("")
1418        elseif(UseLorenz)
1419                IN3_FitLorenzianTop("")
1420        else
1421                Abort "No default fiting method selected, please restart the tool"
1422       
1423        endif
1424end
1425//**********************************************************************************************************
1426//**********************************************************************************************************
1427///**********************************************************************************************************
1428///**********************************************************************************************************
1429
1430Function IN3_FitModGaussTop(ctrlname, DoNOtChangeLimits) : Buttoncontrol                        // calls the Gaussien fit
1431        string ctrlname
1432        variable DoNOtChangeLimits                      //added 6-2017 to prevent some crashes in fitting...   
1433       
1434        string oldDf=GetDataFolder(1)
1435        setDataFolder root:Packages:Indra3
1436
1437        NVAR PeakCenterFitStartPoint
1438        NVAR PeakCenterFitEndPoint
1439
1440        Wave PD_error
1441        Wave Ar_encoder
1442        Wave PD_Intensity
1443        Make/O/N=200 PeakFitWave
1444        DoWIndow RcurvePlotGraph
1445        String ExistingSubWindows
1446        if(V_Flag)
1447                ExistingSubWindows=ChildWindowList("RcurvePlotGraph")
1448        else
1449                ExistingSubWindows=""
1450        endif
1451        if(stringmatch(ExistingSubWindows,"*PeakCenter*"))
1452                getAxis/W=RcurvePlotGraph#PeakCenter /Q bottom
1453                SetScale/I x V_min, V_max,"", PeakFitWave
1454        else
1455                variable center = (PeakCenterFitStartPoint + PeakCenterFitEndPoint)/2
1456                variable start = max(0,center - (center -PeakCenterFitStartPoint) *3 )
1457                variable end1 = min(center + (PeakCenterFitEndPoint-center) *3, numpnts(Ar_encoder) )
1458                SetScale/I x Ar_encoder[start], Ar_encoder[end1],"", PeakFitWave
1459        endif
1460//      K0=0
1461        MAKE/O/D/N=4 W_coef             //fix 2015-06 Coefficient wave MUST be double precision or weird things happen with fits.
1462        wavestats/Q PD_Intensity
1463        //workaround problems 2012/01, one large point appears ...
1464        Duplicate/Free PD_Intensity, tempPDInt
1465        //this tempPDInt needs nan's removed. need to interpolate values?
1466        wavestats/Q tempPDInt
1467        tempPDInt[V_maxloc]=Nan
1468        W_Coef[0]=V_max
1469        W_coef[1]=Ar_encoder[V_maxloc]
1470        FindLevels /N=5/P/Q  tempPDInt, V_max/2
1471        wave W_FindLevels
1472        variable startPointL, endPointL
1473        if(DoNOtChangeLimits)
1474                startPointL=PeakCenterFitStartPoint
1475                endPointL=PeakCenterFitEndPoint
1476        else
1477                if(Numpnts(W_FindLevels)==2)
1478                        startPointL=W_FindLevels[0]
1479                        endPointL=W_FindLevels[1]
1480                elseif(Numpnts(W_FindLevels)>2)
1481                        FindLevel /P/Q W_FindLevels, V_maxloc
1482                        startPointL = W_FindLevels[floor(V_LevelX)]
1483                        endPointL = W_FindLevels[ceil(V_LevelX)]
1484                elseif(Numpnts(W_FindLevels)<2)         //only one or no crossing found? this happens when NaNs are in the waves
1485                        startPointL =  IN3_FindlevelsWithNaNs(tempPDInt, V_max/2, V_maxloc, 0)
1486                        endPointL = IN3_FindlevelsWithNaNs(tempPDInt, V_max/2, V_maxloc, 1)
1487                endif
1488        endif
1489//      Cursor/P /W=RcurvePlotGraph#PeakCenter A  PD_Intensity  startPointL
1490//      Cursor/P /W=RcurvePlotGraph#PeakCenter B  PD_Intensity  endPointL
1491        W_coef[2] = abs(Ar_encoder[startPointL] - Ar_encoder[endPointL])/(2*(2*ln(2))^0.5)
1492        W_coef[3]=2
1493        //W[3]>1                //modified 7/6/2010 per request from Fan. K3 coefficient needs to be large enough to avoid weird Peak shapes.
1494        //more cahnges 6-2017 to fix failures in fitting.
1495        Make/O/T/N=3 T_Constraints
1496        T_Constraints[0] = {"K3>1.3"}
1497        T_Constraints[1] = {"K3<3"}
1498        T_Constraints[2] = {"K2<0.0006"}
1499        variable V_FitError=0
1500        FuncFit/NTHR=0/Q/N  IN3_ModifiedGauss W_coef PD_Intensity [PeakCenterFitStartPoint,PeakCenterFitEndPoint]  /X=Ar_encoder /D /W=PD_error /I=1 /C=T_Constraints   //Gauss
1501        //FuncFit/Q/NTHR=0/L=50  IN3_ModifiedGauss W_coef PD_Intensity [startPointL,endPointL]  /X=Ar_encoder /D /W=PD_error /I=1 /C=T_Constraints      //Gauss
1502        if(V_FitError>0)
1503                abort "Peak profile fitting function error. Please select wider range of data or change fitting function (Gauss is good choice)"
1504        endif
1505        NVAR BeamCenter
1506        NVAR MaximumIntensity
1507        NVAR PeakWidth         
1508        NVAR PeakWidthArcSec           
1509        Variable BeamCenterError, MaximumIntensityError, PeakWidthError
1510        Wave W_coef
1511        Wave W_sigma
1512        PeakFitWave= W_coef[0]*exp(-0.5*(abs(x-W_coef[1])/W_coef[2])^W_coef[3])
1513        BeamCenter=W_coef[1]
1514        BeamCenterError=W_sigma[1]
1515        MaximumIntensity=W_coef[0]
1516        MaximumIntensityError=W_sigma[0]
1517        PeakWidth = 2*W_coef[2]*(2*ln(2))^(1/W_coef[3])
1518        PeakWidthArcSec = PeakWidth*3600
1519        PeakWidthError= 0//2*W_sigma[2]*(2*ln(2))^(1/W_sigma[3])...........need to calcualte approximate value in the future...
1520        Variable GaussPeakWidth=PeakWidth                               //2*(sqrt(ln(2)))*abs(W_coef[3])                        // properly fixed by now.
1521        Variable GaussPeakWidthError=   PeakWidthError                                  //2*(sqrt(ln(2)))*abs(W_sigma[3])
1522        string BmCnterStr
1523        Sprintf BmCnterStr, "%8.5f", BeamCenter
1524        String Width="\Z12FWHM   "+num2str(3600*GaussPeakWidth)+" +/- "+num2str(3600*GaussPeakWidthError)+"  arc-sec"
1525        Width+="\rMax       "+num2str(MaximumIntensity)+"   +/-  "+num2str(MaximumIntensityError)
1526        Width+="\rBm Cntr  "+BmCnterStr+"  +/-  "+num2str(BeamCenterError)+"  deg."
1527        DoWindow RcurvePlotGraph
1528        if(V_Flag)
1529                Textbox/W=RcurvePlotGraph/K/N=text1
1530                TextBox/W=RcurvePlotGraph/N=text1/F=0/B=2/X=63.96/Y=89.45 Width
1531        endif
1532//      ModifyGraph rgb($ModifyWave)=(0,15872,65280)
1533//      KillWaves W_WaveList
1534        Wave/Z R_Qvec
1535        if(WaveExists(R_Qvec))
1536                string ListOfWaveNames = "R_Qvec;R_Int;R_Error;Qvec;"
1537                IN2G_AppendNoteToListOfWaves(ListOfWaveNames,"PeakFitFunction","Modified Gauss")
1538                IN2G_AppendNoteToListOfWaves(ListOfWaveNames,"BeamCenter",num2str(BeamCenter))
1539                IN2G_AppendNoteToListOfWaves(ListOfWaveNames,"MaximumIntensity",num2str(MaximumIntensity))
1540                IN2G_AppendNoteToListOfWaves(ListOfWaveNames,"FWHM",num2str(PeakWidth*3600))
1541                IN2G_AppendNoteToListOfWaves(ListOfWaveNames,"BeamCenterError",num2str(BeamCenterError))
1542                IN2G_AppendNoteToListOfWaves(ListOfWaveNames,"MaximumIntensityError",num2str(MaximumIntensityError))
1543                IN2G_AppendNoteToListOfWaves(ListOfWaveNames,"FWHM_Error",num2str(PeakWidthError*3600))
1544        endif
1545        doupdate
1546        setDataFolder OldDf
1547
1548End
1549
1550//******************** name **************************************
1551Function IN3_FindlevelsWithNaNs(waveIn, LevelSearched, MaxLocation, LeftRight)
1552        wave waveIn
1553        variable LevelSearched, MaxLocation, LeftRight
1554        //set LeftRight to 0 for left and 1 for right of the MaxLocation
1555        variable LevelPoint = 0
1556        variable counter = MaxLocation
1557        variable Done=0
1558        Do
1559                if(LeftRight)
1560                        counter+=1
1561                else
1562                        counter-=1
1563                endif
1564                if(numtype(waveIn[counter])==0)
1565                        LevelPoint = counter
1566                        if(waveIn[counter]>LevelSearched && counter>0 && Counter<numpnts(WaveIn)) //fix when cannot reach 50% or less value...
1567                                LevelPoint = counter
1568                        else
1569                           if(abs(MaxLocation-LevelPoint)>3)
1570                                        Done=1
1571                                endif
1572                        endif
1573                endif   
1574        while (Done<1) 
1575        return LevelPoint       
1576end
1577       
1578//******************** name **************************************
1579///**********************************************************************************************************
1580//******************** FitLorenzianOnTopMacro **************************************
1581
1582Function IN3_ModifiedGauss(w,xvar) : FitFunc
1583        Wave w
1584        Variable xvar
1585
1586        //CurveFitDialog/ These comments were created by the Curve Fitting dialog. Altering them will
1587        //CurveFitDialog/ make the function less convenient to work with in the Curve Fitting dialog.
1588        //CurveFitDialog/ Equation:
1589        //CurveFitDialog/ f(xvar) = Amplitude*exp(-0.5*(abs(xvar-center)/cparameter)^dparameter)
1590        //CurveFitDialog/ End of Equation
1591        //CurveFitDialog/ Independent Variables 1
1592        //CurveFitDialog/ xvar
1593        //CurveFitDialog/ Coefficients 4
1594        //CurveFitDialog/ w[0] = Amplitude
1595        //CurveFitDialog/ w[1] = center
1596        //CurveFitDialog/ w[2] = cparameter
1597        //CurveFitDialog/ w[3] = dparameter
1598       
1599        return w[0]*exp(-0.5*(abs(xvar-w[1])/w[2])^w[3])
1600End
1601
1602//******************** name **************************************
1603///**********************************************************************************************************
1604//******************** FitLorenzianOnTopMacro **************************************
1605Function IN3_FitLorenzianTop(ctrlname) : Buttoncontrol                  // calls the Lorenzian fit
1606        string ctrlname
1607 
1608        string oldDf=GetDataFolder(1)
1609        setDataFolder root:Packages:Indra3
1610
1611        NVAR PeakCenterFitStartPoint
1612        NVAR PeakCenterFitEndPoint
1613        Wave PD_Intensity
1614        Wave Ar_encoder
1615        Wave PD_error
1616        Make/O/N=200 PeakFitWave
1617        DoWIndow RcurvePlotGraph
1618        String ExistingSubWindows
1619        if(V_Flag)
1620                ExistingSubWindows=ChildWindowList("RcurvePlotGraph")
1621        else
1622                ExistingSubWindows=""
1623        endif
1624        if(stringmatch(ExistingSubWindows,"*PeakCenter*"))
1625                getAxis/W=RcurvePlotGraph#PeakCenter /Q bottom
1626                SetScale/I x V_min, V_max,"", PeakFitWave
1627        else
1628                variable center = (PeakCenterFitStartPoint + PeakCenterFitEndPoint)/2
1629                variable start = max(0,center - (center -PeakCenterFitStartPoint) *3 )
1630                variable end1 = min(center + (PeakCenterFitEndPoint-center) *3, numpnts(Ar_encoder) )
1631                SetScale/I x Ar_encoder[start], Ar_encoder[end1],"", PeakFitWave
1632        endif
1633
1634        K0=0
1635        CurveFit/Q/N/H="1000" /L=50  lor PD_Intensity [PeakCenterFitStartPoint,PeakCenterFitEndPoint]  /X=Ar_encoder/D /W=PD_error /I=1 //Lorenzian
1636//      print "Fitted Lorenzian between points  "+num2str(PeakCenterFitStartPoint)+"   and    "+num2str(PeakCenterFitEndPoint)+"    reached Chi-squared/numpoints     " +num2str(V_chisq/(PeakCenterFitEndPoint-PeakCenterFitStartPoint))
1637//      string ModifyWave
1638//      ModifyWave="fit_"+WaveName("",0,1)                                              //new wave with the lorenzian fit
1639        NVAR BeamCenter
1640        NVAR MaximumIntensity
1641        NVAR PeakWidth 
1642        NVAR PeakWidthArcSec   
1643        Variable BeamCenterError, MaximumIntensityError, PeakWidthError
1644        Wave W_coef
1645        Wave W_sigma
1646        Wave PeakFitWave
1647//      Wave FitResiduals
1648//      FitResiduals= ((W_coef[0]+W_coef[1]/((Ar_encoder[p]-W_coef[2])^2+W_coef[3]))-PD_Intensity[p])/PD_error[p]
1649//      FitResiduals[0,xcsr(A)-1]=NaN
1650//      FitResiduals[xcsr(B)+1,inf]=NaN
1651        PeakFitWave= W_coef[0]+W_coef[1]/((x-W_coef[2])^2+W_coef[3])
1652        BeamCenterError=W_sigma[2]
1653        BeamCenter=W_coef[2]
1654        MaximumIntensity=W_coef[1]/W_coef[3]
1655        MaximumIntensityError=IN2G_ErrorsForDivision(W_coef[1],W_sigma[1],W_coef[3],W_sigma[3])
1656        PeakWidth = 2*sqrt(W_coef[3])
1657        PeakWidthArcSec = PeakWidth*3600
1658        //according to Andrew, the error here needs to be propagated through fractional error
1659        //that is, error of sqrt(x), sigma(sx)=X*(sigma(X)/2*X)
1660        PeakWidthError=PeakWidth*(W_sigma[3]/(2*W_coef[3]))
1661        string BmCenterStr, BmCenterErrStr
1662        Sprintf BmCenterStr, "%8.5f", BeamCenter
1663        Sprintf BmCenterErrStr, "%8.5f", BeamCenterError
1664        String Width="\Z12FWHM   "+num2str(PeakWidth*3600)+ " +/- "+num2str(PeakWidthError*3600)+"  arc-sec"
1665        Width+="\rMax     "+num2str(MaximumIntensity)+" +/-  "+num2str(MaximumIntensityError)
1666        Width+="\rBm Cntr   : "+BmCenterStr+" +/- "+ num2str(BeamCenterError)+"  deg."
1667        DoWindow RcurvePlotGraph
1668        if(V_Flag)
1669                Textbox/W=RcurvePlotGraph/K/N=text1
1670                TextBox/W=RcurvePlotGraph/N=text1/F=0/B=2/X=63.96/Y=89.45 Width
1671        endif
1672//      ModifyGraph rgb($ModifyWave)=(0,15872,65280)
1673//      KillWaves W_WaveList
1674        string ListOfWaveNames = "R_Qvec;R_Int;R_Error;Qvec;"
1675//      IN2G_AppendNoteToListOfWaves(ListOfWaveNames, Key,notetext
1676        IN2G_AppendNoteToListOfWaves(ListOfWaveNames,"PeakFitFunction","Lorenzian")
1677        IN2G_AppendNoteToListOfWaves(ListOfWaveNames,"BeamCenter",num2str(BeamCenter))
1678        IN2G_AppendNoteToListOfWaves(ListOfWaveNames,"MaximumIntensity",num2str(MaximumIntensity))
1679        IN2G_AppendNoteToListOfWaves(ListOfWaveNames,"FWHM",num2str(sqrt(W_coef[3])*3600*2))
1680        IN2G_AppendNoteToListOfWaves(ListOfWaveNames,"BeamCenterError",num2str(BeamCenterError))
1681        IN2G_AppendNoteToListOfWaves(ListOfWaveNames,"MaximumIntensityError",num2str(MaximumIntensityError))
1682        IN2G_AppendNoteToListOfWaves(ListOfWaveNames,"FWHM_Error",num2str(sqrt(W_sigma[3])*3600*2))
1683End
1684//**********************************************************************************************************
1685//**********************************************************************************************************
1686
1687//***************************************************************************************************************************************
1688//***************************************************************************************************************************************
1689//***************************************************************************************************************************************
1690//***************************************************************************************************************************************
1691//***************************************************************************************************************************************
1692//***************************************************************************************************************************************
1693Function IN3_ParametersChanged(ctrlName,varNum,varStr,varName) : SetVariableControl
1694        String ctrlName
1695        Variable varNum
1696        String varStr
1697        String varName
1698
1699        string oldDf=GetDataFolder(1)
1700        setDataFolder root:Packages:Indra3
1701        DoWIndow RcurvePlotGraph                                //only of the graph exists, or we get error...
1702        if(V_Flag)
1703                //need to sync blanks widths, if changed by user...
1704                NVAR WidthDeg=root:Packages:Indra3:BlankFWHM
1705                NVAR WidthArcSec=root:Packages:Indra3:BlankWidth
1706                if(stringmatch(ctrlName,"BlankWidth"))
1707                        WidthArcSec = WidthDeg * 3600
1708                endif
1709                if(stringmatch(ctrlName,"BlankWidthArcSec"))
1710                        WidthDeg =  WidthArcSec/3600
1711                endif
1712                if(stringmatch(ctrlName,"SubtractFlatBackground"))
1713                        NVAR SubtractFlatBackground= root:Packages:Indra3:SubtractFlatBackground
1714                        SetVariable SubtractFlatBackground,win=USAXSDataReduction,limits={0,Inf,0.05*SubtractFlatBackground}
1715                endif
1716                if(stringmatch(ctrlName,"PhotoDiodeSize"))
1717                        SVAR UPDParameters= root:Packages:Indra3:UPDParameters
1718                        UPDParameters =  ReplaceNumberByKey("UPDsize", UPDParameters, varNum, "=")
1719                endif
1720                if(stringmatch(ctrlName,"OverideSampleThickness"))
1721                        NVAR OverideSampleThickness=root:Packages:Indra3:OverideSampleThickness
1722                        NVAR SampleThickness=root:Packages:Indra3:SampleThickness
1723                        NVAR SampleThicknessBckp=root:Packages:Indra3:SampleThicknessBckp
1724                        if(OverideSampleThickness>0)
1725                                SampleThickness = OverideSampleThickness
1726                        else
1727                                SampleThickness = SampleThicknessBckp
1728                        endif
1729                        IN3_RecalculateData(2)
1730                        IN3_DesmearData()
1731                        DoWIndow/F USAXSDataReduction
1732                        //SVAR UPDParameters= root:Packages:Indra3:UPDParameters
1733                        //UPDParameters =  ReplaceNumberByKey("UPDsize", UPDParameters, varNum, "=")
1734                endif
1735       
1736                if(stringmatch(ctrlName,"BckgStartQ"))
1737                        IN3_DesmearData()
1738                endif
1739                NVAR RemoveDropouts = root:Packages:Indra3:RemoveDropouts
1740                //recalculate what needs to be done...
1741                if((stringmatch(ctrlName,"RemoveDropoutsTime")) || (stringmatch(ctrlName,"RemoveDropoutsFraction")) || (stringmatch(ctrlName,"RemoveDropoutsAvePnts")))
1742                        if(RemoveDropouts)
1743                                IN3_RecalculateData(1)
1744                                IN3_DesmearData()
1745                        endif
1746                else
1747                        IN3_RecalculateData(2)
1748                        IN3_DesmearData()
1749                endif
1750        endif
1751        setDataFolder OldDf
1752End
1753///*****************************************************************************************************************
1754//*****************************************************************************************************************
1755//*****************************************************************************************************************
1756//*****************************************************************************************************************
1757//*****************************************************************************************************************
1758Function IN3_UPDParametersChanged(ctrlName,varNum,varStr,varName) : SetVariableControl
1759        String ctrlName
1760        Variable varNum
1761        String varStr
1762        String varName
1763
1764        string oldDf=GetDataFolder(1)
1765        setDataFolder root:Packages:Indra3
1766        SVAR UPDList=UPDParameters
1767       
1768        if (!cmpstr(ctrlName,"VtoF"))                                           //Changing V to F
1769                UPDList=ReplaceNumberByKey("Vtof",UPDList, varNum,"=")
1770                UPDList=ReplaceNumberByKey("Vfc",UPDList, varNum,"=")
1771        endif
1772        if (!cmpstr(ctrlName,"Gain1"))                                          //Changing Gain1
1773                UPDList=ReplaceNumberByKey("Gain1",UPDList, varNum,"=")
1774        endif
1775        if (!cmpstr(ctrlName,"Gain2"))                                          //Changing Gain2
1776                UPDList=ReplaceNumberByKey("Gain2",UPDList, varNum,"=")
1777        endif
1778        if (!cmpstr(ctrlName,"Gain3"))                                          //Changing gain3
1779                UPDList=ReplaceNumberByKey("Gain3",UPDList, varNum,"=")
1780        endif
1781        if (!cmpstr(ctrlName,"Gain4"))                                          //Changing Gain4
1782                UPDList=ReplaceNumberByKey("Gain4",UPDList, varNum,"=")
1783        endif
1784        if (!cmpstr(ctrlName,"Gain5"))                                          //Changing Gain5
1785                UPDList=ReplaceNumberByKey("Gain5",UPDList, varNum,"=")
1786        endif
1787        if (!cmpstr(ctrlName,"Bkg1"))                                           //Changing Bkg 1
1788                UPDList=ReplaceNumberByKey("Bkg1",UPDList, varNum,"=")
1789        endif
1790        if (!cmpstr(ctrlName,"Bkg2"))                                           //Changing Bkg 2
1791                UPDList=ReplaceNumberByKey("Bkg2",UPDList, varNum,"=")
1792        endif
1793        if (!cmpstr(ctrlName,"Bkg3"))                                           //Changing Bkg 3
1794                UPDList=ReplaceNumberByKey("Bkg3",UPDList, varNum,"=")
1795        endif
1796        if (!cmpstr(ctrlName,"Bkg4"))                                           //Changing Bkg 4
1797                UPDList=ReplaceNumberByKey("Bkg4",UPDList, varNum,"=")
1798        endif
1799        if (!cmpstr(ctrlName,"Bkg5"))                                           //Changing Bkg 5
1800                UPDList=ReplaceNumberByKey("Bkg5",UPDList, varNum,"=")
1801        endif
1802        if (!cmpstr(ctrlName,"Bkg5Overwrite"))                                          //Changing Bkg 5
1803                NVAR UPD_DK5=root:Packages:Indra3:UPD_DK5
1804                if(varNum!=0)
1805                        UPD_DK5 = varNum
1806                        UPDList=ReplaceNumberByKey("Bkg5",UPDList, UPD_DK5,"=")
1807                else
1808                        SVAR MeasurementParameters = root:Packages:Indra3:MeasurementParameters
1809                        UPD_DK5 = NumberByKey("Bkg5", MeasurementParameters, "=", ";")
1810                        UPDList=ReplaceNumberByKey("Bkg5",UPDList, UPD_DK5,"=")
1811                endif
1812        endif
1813
1814
1815        IN3_RecalculateData(1)                  //and here we recalcualte the R wave
1816        IN3_DesmearData()
1817        setDataFolder OldDf
1818End
1819//*****************************************************************************************************************
1820//*****************************************************************************************************************
1821//*****************************************************************************************************************
1822//*****************************************************************************************************************
1823//*****************************************************************************************************************
1824
1825Function NI3_TabPanelControl(name,tab)
1826        String name
1827        Variable tab
1828
1829        string oldDf=GetDataFolder(1)
1830        setDataFolder root:Packages:Indra3
1831        NVAR IsBlank=root:Packages:Indra3:IsBlank
1832
1833
1834
1835        NVAR CalculateWeight=root:Packages:Indra3:CalculateWeight
1836        NVAR CalculateThickness=root:Packages:Indra3:CalculateThickness
1837        NVAR CalibrateToWeight=root:Packages:Indra3:CalibrateToWeight
1838        NVAR CalibrateToVolume=root:Packages:Indra3:CalibrateToVolume
1839        NVAR CalibrateArbitrary=root:Packages:Indra3:CalibrateArbitrary
1840        NVAR UsePinTransmission=root:Packages:Indra3:UsePinTransmission
1841        NVAR UseMSAXSCorrection=root:Packages:Indra3:UseMSAXSCorrection
1842        NVAR DesmearData = root:Packages:Indra3:DesmearData
1843
1844        Button RecoverDefault,win=USAXSDataReduction, disable=(tab!=0 || IsBlank)
1845        CheckBox CalibrateToVolume,win=USAXSDataReduction, disable=(tab!=0 || IsBlank)
1846        CheckBox CalibrateToWeight,win=USAXSDataReduction, disable=(tab!=0 || IsBlank)
1847        CheckBox CalibrateArbitrary,win=USAXSDataReduction, disable=(tab!=0 || IsBlank)
1848
1849        SetVariable USAXSPinTvalue, win=USAXSDataReduction, disable=(tab!=0 || IsBlank)
1850        CheckBox UsePinTransmission, win=USAXSDataReduction, disable=(tab!=0 || IsBlank)
1851        SetVariable MSAXSCorrectionT0, win=USAXSDataReduction, disable=(tab!=0 || IsBlank || (!UsePinTransmission && !UseMSAXSCorrection) )
1852        SetVariable PeakToPeakTransmission, win=USAXSDataReduction, disable=(tab!=0 || IsBlank)
1853       
1854        CheckBox CalculateThickness,win=USAXSDataReduction, disable=(tab!=0 || IsBlank)
1855        CheckBox CalculateWeight,win=USAXSDataReduction, disable=(tab!=0 || IsBlank || !CalibrateToWeight )
1856        SetVariable SampleThickness,win=USAXSDataReduction, disable=(tab!=0 || IsBlank || CalibrateArbitrary), noedit=(CalculateThickness), frame=!CalculateThickness
1857        SetVariable OverideSampleThickness,win=USAXSDataReduction, disable=(tab!=0 || IsBlank || CalibrateArbitrary), noedit=(CalculateThickness), frame=!CalculateThickness
1858        SetVariable SampleWeightInBeam,win=USAXSDataReduction, disable=(tab!=0 || IsBlank || !CalibrateToWeight || CalibrateArbitrary), noedit=CalculateWeight, frame=!CalculateWeight
1859        SetVariable SampleTransmission,win=USAXSDataReduction, disable=(tab!=0 || IsBlank)
1860        SetVariable SampleLinAbsorption,win=USAXSDataReduction, disable=(tab!=0 || IsBlank || CalibrateArbitrary), noedit=!CalculateThickness, frame=CalculateThickness
1861        SetVariable SampleDensity,win=USAXSDataReduction, disable=(tab!=0 || IsBlank || !CalibrateToWeight || CalibrateArbitrary), frame=CalculateWeight, noedit=!CalculateWeight
1862        SetVariable SampleFilledFraction,win=USAXSDataReduction, disable=(tab!=0 || IsBlank || !CalibrateToVolume || CalibrateArbitrary),noedit=!CalculateThickness, frame=CalculateThickness
1863        SetVariable FlyScanRebinToPoints,win=USAXSDataReduction, disable=(tab!=0 || IsBlank)
1864        //SetVariable BeamExposureArea, win=USAXSDataReduction, disable=(tab!=0 || IsBlank || CalibrateArbitrary), noedit=!(CalculateWeight&&CalibrateToWeight), frame=!CalculateWeight
1865
1866
1867        TitleBox Info3,win=USAXSDataReduction, disable=(tab!=1)
1868        TitleBox Info4,win=USAXSDataReduction, disable=(tab!=1)
1869        SetVariable VtoF,win=USAXSDataReduction, disable=(tab!=1)
1870        SetVariable Gain1,win=USAXSDataReduction, disable=(tab!=1)
1871        SetVariable Gain2,win=USAXSDataReduction, disable=(tab!=1)
1872        SetVariable Gain3,win=USAXSDataReduction, disable=(tab!=1)
1873        SetVariable Gain4,win=USAXSDataReduction, disable=(tab!=1)
1874        SetVariable Gain5,win=USAXSDataReduction, disable=(tab!=1)
1875        SetVariable Bkg1,win=USAXSDataReduction, disable=(tab!=1)
1876        SetVariable Bkg2,win=USAXSDataReduction, disable=(tab!=1)
1877        SetVariable Bkg3,win=USAXSDataReduction, disable=(tab!=1)
1878        SetVariable Bkg4,win=USAXSDataReduction, disable=(tab!=1)
1879        SetVariable Bkg5,win=USAXSDataReduction, disable=(tab!=1)
1880        SetVariable Bkg1Err,win=USAXSDataReduction, disable=(tab!=1)
1881        SetVariable Bkg2Err,win=USAXSDataReduction, disable=(tab!=1)
1882        SetVariable Bkg3Err,win=USAXSDataReduction, disable=(tab!=1)
1883        SetVariable Bkg4Err,win=USAXSDataReduction, disable=(tab!=1)
1884        SetVariable Bkg5Err,win=USAXSDataReduction, disable=(tab!=1)
1885        SetVariable Bkg5Overwrite,win=USAXSDataReduction, disable=(tab!=1)
1886       
1887        ControlInfo/W=USAXSDataReduction FSOverWriteRage1DeadTime
1888        if(V_Flag!=0)
1889                SetVariable FSOverWriteRage1DeadTime,win=USAXSDataReduction, disable=(tab!=1)
1890                SetVariable FSOverWriteRage2DeadTime,win=USAXSDataReduction, disable=(tab!=1)
1891                SetVariable FSOverWriteRage3DeadTime,win=USAXSDataReduction, disable=(tab!=1)
1892                SetVariable FSOverWriteRage4DeadTime,win=USAXSDataReduction, disable=(tab!=1)
1893                SetVariable FSOverWriteRage5DeadTime,win=USAXSDataReduction, disable=(tab!=1)
1894                SetVariable FSRage1DeadTime,win=USAXSDataReduction, disable=(tab!=1)
1895                SetVariable FSRage2DeadTime,win=USAXSDataReduction, disable=(tab!=1)
1896                SetVariable FSRage3DeadTime,win=USAXSDataReduction, disable=(tab!=1)
1897                SetVariable FSRage4DeadTime,win=USAXSDataReduction, disable=(tab!=1)
1898                SetVariable FSRage5DeadTime,win=USAXSDataReduction, disable=(tab!=1)
1899                TitleBox Info5,win=USAXSDataReduction, disable=(tab!=1 || IsBlank)
1900        endif
1901
1902        SetVariable SubtractFlatBackground,win=USAXSDataReduction, disable=(tab!=1 || IsBlank)
1903        SetVariable SpecCommand,win=USAXSDataReduction, disable=(tab!=2)
1904        SetVariable PhotoDiodeSize,win=USAXSDataReduction, disable=(tab!=2)
1905        SetVariable Wavelength,win=USAXSDataReduction, disable=(tab!=2)
1906        SetVariable SDDistance,win=USAXSDataReduction, disable=(tab!=2)
1907        SetVariable SlitLength,win=USAXSDataReduction, disable=(tab!=2)
1908        SetVariable NumberOfSteps,win=USAXSDataReduction, disable=(tab!=2)
1909
1910        SetVariable MaximumIntensity,win=USAXSDataReduction, disable=(tab!=3)
1911        SetVariable PeakWidth,win=USAXSDataReduction, disable=(tab!=3)
1912        SetVariable PeakWidthArcSec,win=USAXSDataReduction, disable=(tab!=3)
1913        SetVariable BlankMaximum,win=USAXSDataReduction, disable=(tab!=3 || IsBlank)
1914        SetVariable BlankWidth,win=USAXSDataReduction, disable=(tab!=3 || IsBlank)
1915        SetVariable BlankWidthArcSec,win=USAXSDataReduction, disable=(tab!=3 || IsBlank)
1916        CheckBox CalibrateUseSampleFWHM,win=USAXSDataReduction, disable=(tab!=3 || IsBlank)
1917        Button RecoverDefaultBlnkVals,win=USAXSDataReduction, disable=(tab!=3 || IsBlank)
1918
1919        CheckBox DesmearData, win=USAXSDataReduction, disable=(tab!=5)
1920        SetVariable BckgStartQ, win=USAXSDataReduction, disable=(tab!=5 || !DesmearData)
1921        PopupMenu BackgroundFnct, win=USAXSDataReduction, disable=(tab!=5 || !DesmearData)
1922
1923        CheckBox UseMSAXSCorrection,win=USAXSDataReduction, disable=(tab!=4 || IsBlank)
1924        //UseMSAXSCorrection
1925        SetVariable MSAXSCorrection,win=USAXSDataReduction, disable=(tab!=4 || !(UseMSAXSCorrection ||UsePinTransmission) || IsBlank)
1926        SetVariable MSAXSStartPoint,win=USAXSDataReduction, disable=(tab!=4 || !UseMSAXSCorrection || IsBlank)
1927        SetVariable MSAXSEndPoint,win=USAXSDataReduction, disable=(tab!=4 || !UseMSAXSCorrection || IsBlank)
1928        String ExistingSubWindows=ChildWindowList("USAXSDataReduction")
1929        if(stringmatch(ExistingSubWindows,"*MSAXSGraph*") && IsBlank)
1930                KillWindow  USAXSDataReduction#MSAXSGraph
1931                ExistingSubWindows=ChildWindowList("USAXSDataReduction")
1932        endif
1933        if(tab!=4 || !UseMSAXSCorrection)
1934                IN3_HideMSAXSGraph()
1935        else
1936                IN3_ShowMSAXSGraph()
1937        endif
1938        //color wave in main graph as appropriate
1939        if(tab==1)
1940                IN3_ColorMainGraph(1)
1941        else
1942                IN3_ColorMainGraph(0)
1943        endif
1944        IN3_DisplayDesExtAndError()
1945        setDataFolder OldDf
1946end
1947
1948//*****************************************************************************************************************
1949//*****************************************************************************************************************
1950//*****************************************************************************************************************
1951
1952Function/T IN3_GenStringOfFolders(useBlankData)
1953        variable useBlankData
1954       
1955        string ListOfQFolders
1956        string result
1957        if (useBlankData)
1958                        result=IN2G_FindFolderWithWaveTypes("root:USAXS:", 10, "Blank_*", 1)
1959        endif
1960       
1961        return result
1962end
1963
1964
1965//*****************************************************************************************************************
1966//*****************************************************************************************************************
1967//*****************************************************************************************************************
1968//*****************************************************************************************************************
1969//*****************************************************************************************************************
1970
1971//*************************************************************************************************
1972//*************************************************************************************************
1973//*************************************************************************************************
1974//*********     Live data collection part
1975//*************************************************************************************************
1976//*************************************************************************************************
1977//*************************************************************************************************
1978
1979Function IN3_OnLineDataProcessing()     
1980        //create global variables
1981        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
1982        String OldDf=GetDataFolder(1)
1983        SetDataFOlder root:Packages:Indra3
1984        NewDataFolder/O/S BckgMonitorParams
1985        String ListOfVariables, ListOfStrings
1986        ListOfVariables = "BckgUpdateInterval;BckgDisplayOnly;BckgConvertData;"
1987        ListOfStrings = "BckgStatus;"
1988        variable i
1989        for(i=0;i<itemsInList(ListOfVariables);i+=1)   
1990                IN2G_CreateItem("variable",StringFromList(i,ListOfVariables))
1991        endfor         
1992        for(i=0;i<itemsInList(ListOfStrings);i+=1)     
1993                IN2G_CreateItem("string",StringFromList(i,ListOfStrings))
1994        endfor         
1995        NVAR BckgUpdateInterval
1996        if(BckgUpdateInterval<5)
1997                BckgUpdateInterval=30
1998        endif
1999
2000        NVAR BckgDisplayOnly
2001        NVAR BckgConvertData
2002        if(BckgConvertData+BckgDisplayOnly!=1)
2003                BckgDisplayOnly=1
2004                BckgConvertData=0
2005        endif
2006        SVAR BckgStatus
2007        setDataFolder OldDf
2008        DoWindow IN3_LiveDataProcessing
2009        if(V_Flag==0)
2010                NewPanel /FLT/K=1/W=(573,44,1000,210) as "USAXS Background processing"
2011                DoWindow/C IN3_LiveDataProcessing
2012                SetDrawLayer UserBack
2013                SetDrawEnv fsize= 14,fstyle= 3,textrgb= (0,0,65535)
2014                DrawText 6,25,"USAXS \"Live\" data proc."
2015                SetDrawEnv fsize= 10
2016                DrawText 178,18,"This tool controls background process which"
2017                SetDrawEnv fsize= 10
2018                DrawText 178,33,"watches current data folder and when new files(s)"
2019                SetDrawEnv fsize= 10
2020                DrawText 178,48,"is found, Converts the data set"
2021                SetDrawEnv fsize= 10
2022                DrawText 178,63,"Use sort and Match options to control behavior"
2023                SetDrawEnv fsize= 10
2024                DrawText 178,78,"When multiple files are found, arbitrary is selected "
2025                TitleBox Status pos={5,35},variable=root:Packages:Indra3:BckgMonitorParams:BckgStatus,fColor=(65535,0,0),labelBack=(32792,65535,1)
2026                TitleBox Status fColor=(0,0,0),labelBack=(65535,65535,65535)
2027                Button StartBackgrTask,pos={200,100},size={140,23},proc=IN3_BackgrTaskButtonProc,title="Start folder watch"
2028                Button StartBackgrTask,help={"Start Background task here"}
2029                Button StopBackgrTask,pos={200,130},size={140,23},proc=IN3_BackgrTaskButtonProc,title="Stop folder watch"
2030                Button StopBackgrTask,help={"Start Background task here"}
2031                PopupMenu UpdateTimeSelection pos={10, 74}, title="Update Time [sec] :"
2032                PopupMenu UpdateTimeSelection proc=IN3_BacgroundUpdatesPopMenuProc
2033                PopupMenu UpdateTimeSelection value="5;10;15;30;45;60;120;360;600;", mode=WhichListItem(num2str(BckgUpdateInterval),"5;10;15;30;45;60;120;360;600;")+1
2034                CheckBox BackgroundDisplayOnly pos={10,110},title="Convert and Display only"
2035                CheckBox BackgroundDisplayOnly proc=IN3_BakcgroundCheckProc
2036                CheckBox BackgroundDisplayOnly variable=root:Packages:Indra3:BckgMonitorParams:BckgDisplayOnly
2037                CheckBox BackgroundConvert pos={10,130},title="Convert and Save"
2038                CheckBox BackgroundConvert proc=IN3_BakcgroundCheckProc
2039                CheckBox BackgroundConvert variable=root:Packages:Indra3:BckgMonitorParams:BckgConvertData
2040                SetActiveSubwindow _endfloat_
2041        endif
2042        CtrlNamedBackground IN3_MonitorDataFolder, status
2043        if(NumberByKey("RUN", S_Info))          //running, restart witrh new parameters
2044                BckgStatus = "   Running background job   "
2045                TitleBox Status win=IN3_LiveDataProcessing,fColor=(65535,0,0),labelBack=(32792,65535,1)
2046        else
2047                BckgStatus = "   Background job not running   "
2048                TitleBox Status win=IN3_LiveDataProcessing,fColor=(0,0,0),labelBack=(65535,65535,65535)
2049        endif
2050
2051end
2052
2053//*************************************************************************************************
2054//*************************************************************************************************
2055//*************************************************************************************************
2056
2057
2058
2059Function IN3_BackgrTaskButtonProc(ba) : ButtonControl
2060        STRUCT WMButtonAction &ba
2061
2062        switch( ba.eventCode )
2063                case 2: // mouse up
2064                        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
2065                        // click code here
2066                        if(stringmatch("StartBackgrTask",ba.ctrlName))
2067                                IN3_StartFolderWatchTask()
2068                        endif
2069                        if(stringmatch("StopBackgrTask",ba.ctrlName))
2070                                IN3_StopFolderWatchTask()
2071                        endif
2072                        break
2073                case -1: // control being killed
2074                        break
2075        endswitch
2076
2077        return 0
2078End
2079//*************************************************************************************************
2080//*************************************************************************************************
2081//*************************************************************************************************
2082//*************************************************************************************************
2083//*************************************************************************************************
2084//*************************************************************************************************
2085
2086
2087Function IN3_StartFolderWatchTask()
2088        //Variable numTicks = 5 * 60 // Run every two seconds (120 ticks)
2089        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
2090        NVAR BckgUpdateInterval= root:Packages:Indra3:BckgMonitorParams:BckgUpdateInterval
2091                CtrlNamedBackground IN3_MonitorDataFolder, period=BckgUpdateInterval*60, proc=IN3_MonitorFldrBackground
2092                CtrlNamedBackground IN3_MonitorDataFolder, start
2093                Printf "USAXS FolderWatch background task (\"IN3_MonitorDataFolder\") started with %d [s] update interval\r", BckgUpdateInterval
2094                SVAR BckgStatus = root:Packages:Indra3:BckgMonitorParams:BckgStatus
2095                BckgStatus = "   Running background job   "
2096                TitleBox Status win=IN3_LiveDataProcessing,fColor=(65535,0,0),labelBack=(32792,65535,1)
2097                Button LiveProcessing win=USAXSDataReduction, fColor=(65535,0,0)
2098End
2099//*************************************************************************************************
2100//*************************************************************************************************
2101//*************************************************************************************************
2102
2103Function IN3_StopFolderWatchTask()
2104        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
2105   CtrlNamedBackground IN3_MonitorDataFolder, stop
2106        Printf "FolderWatch background task (\"IN3_MonitorDataFolder\") stopped\r"
2107                SVAR BckgStatus = root:Packages:Indra3:BckgMonitorParams:BckgStatus
2108                BckgStatus = "   Background job not running   "
2109                TitleBox Status win=IN3_LiveDataProcessing,fColor=(0,0,0),labelBack=(65535,65535,65535)
2110                Button LiveProcessing win=USAXSDataReduction, fColor=(65535,65535,65535)
2111End
2112//*************************************************************************************************
2113//*************************************************************************************************
2114//*************************************************************************************************
2115
2116
2117Function IN3_BacgroundUpdatesPopMenuProc(pa) : PopupMenuControl
2118        STRUCT WMPopupAction &pa
2119
2120        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
2121        switch( pa.eventCode )
2122                case 2: // mouse up
2123                        Variable popNum = pa.popNum
2124                        String popStr = pa.popStr
2125                        if(stringMatch("UpdateTimeSelection",pa.ctrlName))
2126                                NVAR BckgUpdateInterval= root:Packages:Indra3:BckgMonitorParams:BckgUpdateInterval
2127                                BckgUpdateInterval = str2num(pa.popStr)
2128                                CtrlNamedBackground IN3_MonitorDataFolder, status
2129                                if(NumberByKey("RUN", S_Info))          //running, restart with new parameters
2130                                        IN3_StopFolderWatchTask()
2131                                        IN3_StartFolderWatchTask()
2132                                endif
2133                        endif
2134                        break
2135                case -1: // control being killed
2136                        break
2137        endswitch
2138
2139        return 0
2140End
2141
2142//*************************************************************************************************
2143//*************************************************************************************************
2144//*************************************************************************************************
2145Function IN3_BakcgroundCheckProc(cba) : CheckBoxControl
2146        STRUCT WMCheckboxAction &cba
2147
2148        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
2149        switch( cba.eventCode )
2150                case 2: // mouse up
2151                        Variable checked = cba.checked
2152                        NVAR BckgConvertData=root:Packages:Indra3:BckgMonitorParams:BckgConvertData
2153                        NVAR BckgDisplayOnly=root:Packages:Indra3:BckgMonitorParams:BckgDisplayOnly
2154                        if(stringMatch(cba.CtrlName,"BackgroundDisplayOnly"))
2155                                if(cba.checked)
2156                                        BckgDisplayOnly=1
2157                                        BckgConvertData=0
2158                                endif
2159                        endif
2160                        if(stringMatch(cba.CtrlName,"BackgroundConvert"))
2161                                if(cba.checked)
2162                                        BckgDisplayOnly=0
2163                                        BckgConvertData=1
2164                                endif
2165                        endif
2166                       
2167                        break
2168                case -1: // control being killed
2169                        break
2170        endswitch
2171
2172        return 0
2173End
2174
2175//*************************************************************************************************
2176//*************************************************************************************************
2177//*************************************************************************************************
2178
2179Function IN3_MonitorFldrBackground(s) // This is the function that will be called periodically
2180        STRUCT WMBackgroundStruct &s
2181       
2182        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
2183        //this should monitor result of Refresh on the folder and grab the new data set and process it.
2184        Wave/T ListOf2DSampleData=root:Packages:USAXS_FlyScanImport:WaveOfFiles
2185        Wave ListOf2DSampleDataNumbers=root:Packages:USAXS_FlyScanImport:WaveOfSelections
2186        NVAR BckgConvertData=root:Packages:Indra3:BckgMonitorParams:BckgConvertData
2187        NVAR BckgDisplayOnly=root:Packages:Indra3:BckgMonitorParams:BckgDisplayOnly
2188        //problem, USAXS writes part of the file before end of scan, sop we actually need to display file before last.
2189        SVAR/Z LiveProcPriorSampleName=root:Packages:Indra3:BckgMonitorParams:LiveProcPriorSampleName
2190        if(!Svar_Exists(LiveProcPriorSampleName))
2191                string/g root:Packages:Indra3:BckgMonitorParams:LiveProcPriorSampleName
2192                SVAR LiveProcPriorSampleName=root:Packages:Indra3:BckgMonitorParams:LiveProcPriorSampleName
2193                LiveProcPriorSampleName=""
2194        endif
2195        string LiveProcPriorSampleNameLoc=LiveProcPriorSampleName
2196        Duplicate/Free/T ListOf2DSampleData, ListOf2DSampleDataOld
2197        //update the lists
2198        IR3C_UpdateListOfFilesInWvs("USAXSDataReduction")
2199        IR3C_SortListOfFilesInWvs("USAXSDataReduction")
2200        variable NumberOfNewImages
2201
2202        Printf "%s : task %s called, found %d data images in current folder\r", time(), s.name, numpnts(ListOf2DSampleData)
2203
2204        if(numpnts(ListOf2DSampleData)>numpnts(ListOf2DSampleDataOld))  //new data set appeared
2205                NumberOfNewImages=numpnts(ListOf2DSampleData)-numpnts(ListOf2DSampleDataOld)
2206                //here we need to select the new file. Only when files are not ordered, or it should be clear.
2207                Printf "%s : found %g new data image(s), will pick one to display \r", time(), NumberOfNewImages
2208                Make/Free/T ResWave
2209                IN2G_FindNewTextElements(ListOf2DSampleData,ListOf2DSampleDataOld,reswave)
2210                Printf "%s : Found new file %s, but this is likely now being collected \r", time(), reswave[0]
2211                LiveProcPriorSampleName = reswave[0]
2212                if(strlen(LiveProcPriorSampleNameLoc)>1)
2213                        Printf "%s : Selected prior existing file %s, calling user routine using this file name \r", time(), LiveProcPriorSampleNameLoc
2214                        //need to find it in the original wave and select it in the control
2215                        variable i
2216                        For(i=0;i<numpnts(ListOf2DSampleData);i+=1)
2217                                if(stringmatch(ListOf2DSampleData[i],LiveProcPriorSampleNameLoc))
2218                                        ListOf2DSampleDataNumbers[i]=1
2219                                        break
2220                                endif
2221                        endfor
2222                        //Printf "%s : found %g new data image(s), since sorting is selected, using the last one \r", time(), NumberOfNewImages
2223                                STRUCT WMButtonAction B_Struct
2224                                B_Struct.ctrlName = "ProcessData2"
2225                                B_Struct.win = "USAXSDataReduction"
2226                                B_Struct.eventcode=2
2227                        if(BckgDisplayOnly || BckgConvertData)
2228                                Print "Calling \"Load/process one\" routine \r"
2229                                IN3_InputPanelButtonProc(B_Struct)
2230                        endif
2231                        if(BckgConvertData)
2232                                Print "Calling \"Save data\" routine \r"
2233                                B_Struct.ctrlName = "SaveResults"
2234                                B_Struct.win = "USAXSDataReduction"
2235                                B_Struct.eventcode=2
2236                                IN3_InputPanelButtonProc(B_Struct)
2237                        endif
2238                        //IN3_PlotProcessedData()               //this is now done automatically by saving the data.
2239                endif
2240        endif
2241       
2242   return 0             // Continue background task
2243End
2244
2245//*************************************************************************************************
2246//*************************************************************************************************
2247//*************************************************************************************************
2248
2249Function IN3_PlotProcessedData()
2250
2251        //last data name
2252        SVAR LastSample = root:Packages:Indra3:LastSample
2253        NVAR IsBlank = root:Packages:Indra3:IsBlank
2254       
2255        //new data should be here:
2256        if(IsBlank)                     //look for
2257                        Wave/Z Ywave=$(LastSample+"Blank_R_Int")
2258                        Wave/Z Xwave=$(LastSample+"Blank_R_Qvec")
2259                        Wave/Z Ewave=$(LastSample+"Blank_R_error")
2260        else
2261                        Wave/Z Ywave=$(LastSample+"M_DSM_Int")
2262                        Wave/Z Xwave=$(LastSample+"M_DSM_Qvec")
2263                        Wave/Z Ewave=$(LastSample+"M_DSM_Error")                       
2264                        if(!WaveExists(Ywave))
2265                                Wave/Z Ywave=$(LastSample+"DSM_Int")
2266                                Wave/Z Xwave=$(LastSample+"DSM_Qvec")
2267                                Wave/Z Ewave=$(LastSample+"DSM_Error")
2268                                if(!WaveExists(Ywave))
2269                                        Wave/Z Ywave=$(LastSample+"M_SMR_Int")
2270                                        Wave/Z Xwave=$(LastSample+"M_SMR_Qvec")
2271                                        Wave/Z Ewave=$(LastSample+"M_SMR_Error")
2272                                        if(!WaveExists(Ywave))
2273                                                Wave/Z Ywave=$(LastSample+"SMR_Int")
2274                                                Wave/Z Xwave=$(LastSample+"SMR_Qvec")
2275                                                Wave/Z Ewave=$(LastSample+"SMR_Error")
2276                                        endif
2277                                endif
2278                        endif
2279        endif
2280        if(WaveExists(Ywave)&&WaveExists(Xwave)&&(!IsBlank))
2281                DoWIndow/Z USAXSProcessedDataGraph
2282                if(V_Flag==0)
2283                        Display /K=1/W=(500,300,500+0.5*IN2G_GetGraphWidthHeight("width"),300+0.5*IN2G_GetGraphWidthHeight("height")) Ywave vs Xwave as "USAXS Processed data"
2284                        DoWindow/C USAXSProcessedDataGraph
2285                        ModifyGraph mode=3
2286                        ModifyGraph log=1
2287                        ModifyGraph mirror=1
2288                        Label left "Intensity"
2289                        Label bottom "Q [A\\S-1\\M]"
2290                        SetAxis bottom 1e-4,*
2291                elseif(V_Flag>0)
2292                        DoWIndow/F USAXSProcessedDataGraph
2293                        CheckDisplayed /W=USAXSProcessedDataGraph $(NameOfWave(Ywave))
2294                        if(!V_Flag)
2295                                AppendToGraph Ywave vs Xwave
2296                                ModifyGraph mode=3
2297                        endif
2298                endif
2299                IN2G_ColorTopGrphRainbow()
2300                //IN2G_ColorTraces( )
2301                IN2G_LegendTopGrphFldr(str2num(IN2G_LkUpDfltVar("LegendSize")),12,1,0)
2302                //      IN2G_GenerateLegendForGraph(10,0,1)
2303                DoUpdate /W=USAXSProcessedDataGraph
2304        endif
2305       
2306end
2307
2308
2309//*************************************************************************************************
2310//*************************************************************************************************
2311//*************************************************************************************************
2312
2313Function IN3_DesmearData()
2314       
2315        String fldrSav0= GetDataFolder(1)
2316        SetDataFolder root:Packages:Indra3:
2317        NVAR DesmearData = root:Packages:Indra3:DesmearData
2318        NVAR IsBlank = root:Packages:Indra3:IsBlank                                             //cannot desmear Blank
2319        NVAR is2DCollimated=root:Packages:Indra3:is2DCollimated         //cannot desmear pinhole data
2320        if(IsBlank)
2321                return 0
2322        endif   
2323        if(DesmearData && !is2DCollimated)
2324                NVAR SlitLength = root:Packages:Indra3:SlitLength
2325                NVAR DesmearNumberOfInterations=root:Packages:Indra3:DesmearNumberOfInterations
2326                WAVE/Z SMR_Int = root:Packages:Indra3:SMR_Int
2327                if(!WaveExists(SMR_Int))                //wave does n to exist, stop here...   
2328                        setDataFolder fldrSav0
2329                        return 0
2330                endif
2331                WAVE SMR_Error = root:Packages:Indra3:SMR_Error
2332                WAVE SMR_Qvec = root:Packages:Indra3:SMR_Qvec
2333                WAVE SMR_dQ = root:Packages:Indra3:SMR_dQ
2334                Killwaves/Z DSM_Int, DSM_Qvec, DSM_Error, DSM_dQ
2335                Duplicate/Free SMR_Int, tmpWork_Int
2336                Duplicate/Free SMR_Error, tmpWork_Error
2337                Duplicate/Free SMR_Qvec, tmpWork_Qvec
2338                Duplicate/Free SMR_dQ, tmpWork_dQ
2339
2340                Duplicate/O SMR_Int, DesmNormalizedError
2341                Duplicate/Free SMR_Int, absNormalizedError
2342                variable numOfPoints = numpnts(SMR_Int)
2343                variable endme=0, oldendme = 0, DesmearAutoTargChisq, difff
2344                DesmearAutoTargChisq = 0.5
2345                variable ExtensionFailed
2346                variable NumIterations=0
2347                Do
2348                        ExtensionFailed = IN3_OneDesmearIteration(tmpWork_Int,tmpWork_Qvec,tmpWork_Error, SMR_Int, SMR_Error, DesmNormalizedError)
2349                        if(ExtensionFailed)
2350                                setDataFolder fldrSav0
2351                                return 0
2352                        endif
2353                        absNormalizedError=abs(DesmNormalizedError)
2354                        Duplicate/Free/O absNormalizedError, tmpabsNormalizedError
2355                        IN2G_RemNaNsFromAWave(tmpabsNormalizedError)
2356                        endme = sum(tmpabsNormalizedError)/numpnts(absNormalizedError)
2357                        difff=1 - oldendme/endme
2358                        oldendme=endme
2359                        NumIterations+=1
2360                while (endme>DesmearAutoTargChisq && abs(difff)>0.01 && NumIterations<50)       
2361
2362                Duplicate/O tmpWork_Int, DSM_Int
2363                Duplicate/O tmpWork_Qvec, DSM_Qvec
2364                Duplicate/O tmpWork_Error, DSM_Error
2365                Duplicate/O tmpWork_dQ, DSM_dQ
2366                DoWindow RcurvePlotGraph
2367                if(V_Flag)
2368                        CheckDisplayed /W=RcurvePlotGraph DSM_Int
2369                                if(V_Flag<1)
2370                                        AppendToGraph/R/W=RcurvePlotGraph DSM_Int vs DSM_Qvec
2371                                endif
2372                        ModifyGraph/W=RcurvePlotGraph mode(DSM_Int)=3,rgb(DSM_Int)=(1,39321,19939)             
2373                        ModifyGraph/W=RcurvePlotGraph mode(DSM_Int)=4
2374                        //Label/W=RcurvePlotGraph right "DSM & SMR Intensity"   
2375                        Label/W=RcurvePlotGraph right "\\K(3,52428,1)DSM & \\K(1,16019,65535)SMR \\K(0,0,0)Intensity"
2376                        DoUpdate /W=RcurvePlotGraph
2377                        IN3_DisplayDesExtAndError()
2378                endif
2379        elseif(is2DCollimated)          //2DUSAXS, keep desmeared data, remove slit smeared data if present
2380                DoWindow RcurvePlotGraph
2381                if(V_Flag)
2382                        CheckDisplayed /W=RcurvePlotGraph  SMR_Int
2383                        if(V_Flag)
2384                                removefromgraph /W=RcurvePlotGraph/Z SMR_Int
2385                                Label/W=RcurvePlotGraph right "\\K(0,0,0)DSM Intensity"
2386                                DoUpdate /W=RcurvePlotGraph
2387                        endif   
2388                endif
2389        else            //remove desmeared data if present
2390                DoWindow RcurvePlotGraph
2391                if(V_Flag)
2392                        CheckDisplayed /W=RcurvePlotGraph  DSM_Int
2393                        if(V_Flag)
2394                                removefromgraph /W=RcurvePlotGraph/Z DSM_Int
2395                                removefromgraph /W=RcurvePlotGraph/Z fit_ExtrapIntWave
2396                                removefromgraph /W=RcurvePlotGraph/Z DesmNormalizedError
2397                                Label/W=RcurvePlotGraph right "\\K(0,0,0)SMR Intensity"
2398                                DoUpdate /W=RcurvePlotGraph
2399                        endif   
2400                endif
2401                WAVE/Z DSM_Int = root:Packages:Indra3:DSM_Int
2402                WAVE/Z DSM_Error = root:Packages:Indra3:DSM_Error
2403                WAVE/Z DSM_Qvec = root:Packages:Indra3:DSM_Qvec
2404                WAVE/Z DSM_dQ = root:Packages:Indra3:DSM_dQ
2405                Wave/Z fit_ExtrapIntwave = root:Packages:Indra3:fit_ExtrapIntwave
2406                Wave/Z DesmNormalizedError = root:Packages:Indra3:DesmNormalizedError
2407                KillWaves/Z DSM_Int, DSM_Qvec, DSM_Error, DSM_dQ, fit_ExtrapIntwave, DesmNormalizedError
2408               
2409        endif
2410        setDataFolder fldrSav0
2411       
2412end
2413
2414
2415//***********************************************************************************************************************************
2416//***********************************************************************************************************************************
2417
2418Function IN3_OneDesmearIteration(DesmearIntWave,DesmearQWave,DesmearEWave, origSmearedInt, origSmearedErr, NormalizedError)
2419        Wave DesmearIntWave, DesmearQWave, DesmearEWave, origSmearedInt, origSmearedErr, NormalizedError
2420               
2421        string OldDf=GetDataFolder(1)
2422        setDataFolder root:Packages:Indra3:
2423
2424        SVAR BackgroundFunction    = root:Packages:Indra3:DsmBackgroundFunction
2425        NVAR SlitLength                         =       root:Packages:Indra3:SlitLength
2426        NVAR NumberOfIterations =       root:Packages:Indra3:DesmearNumberOfInterations
2427        NVAR numOfPoints               = root:Packages:Indra3:DesmearNumPoints
2428        NVAR BckgStartQ                 = root:Packages:Indra3:DesmearBckgStart
2429        numOfPoints = numpnts(DesmearIntWave)
2430        if(BckgStartQ>DesmearQWave[numOfPoints-1]/1.5)
2431                BckgStartQ = DesmearQWave[numOfPoints-1]/1.5
2432        endif
2433        Duplicate/Free DesmearIntWave, SmFitIntensity
2434        Duplicate/Free origSmearedInt, OrigIntToSmear
2435        Duplicate/Free origSmearedErr, SmErrors
2436        variable ExtensionFailed=0
2437       
2438        ExtensionFailed = IN3_ExtendData(DesmearIntWave, DesmearQWave, SmErrors, slitLength, BckgStartQ, BackgroundFunction)                    //extend data to 2xnumOfPoints to Qmax+2.1xSlitLength
2439        if(ExtensionFailed)
2440                return 1
2441        endif
2442        if(slitlength>0)
2443                IN3_SmearData(DesmearIntWave, DesmearQWave, slitLength, SmFitIntensity)                                         //smear the data, output is SmFitIntensity
2444        endif
2445        Redimension/N=(numOfPoints) SmFitIntensity, DesmearIntWave, DesmearQWave, NormalizedError               //cut the data back to original length (Qmax, numOfPoints)
2446       
2447        NormalizedError=(origSmearedInt-SmFitIntensity)/SmErrors                        //NormalizedError (input-my Smeared data)/input errors
2448        duplicate/O/Free DesmearIntWave, FastFitIntensity, SlowFitIntensity
2449        //fast convergence
2450        FastFitIntensity=DesmearIntWave*(OrigIntToSmear/SmFitIntensity)                                                         
2451        //slow convergence
2452        SlowFitIntensity=DesmearIntWave+(OrigIntToSmear-SmFitIntensity)                                                         
2453       
2454        variable i
2455//      if(DesmearFastOnly)
2456//              DesmearedIntWave = FastFitIntensity
2457//      elseif(DesmearSlowOnly)
2458//              DesmearedIntWave = SlowFitIntensity
2459//      elseif(DesmearDampen)
2460                For(i=0;i<(numpnts(DesmearIntWave));i+=1)
2461                        if (abs(NormalizedError[i])>0.5)
2462                                DesmearIntWave[i]=FastFitIntensity[i]
2463                        else
2464                                DesmearIntWave[i]=DesmearIntWave[i]
2465                        endif   
2466                endfor
2467//      else
2468//              For(i=0;i<(numpnts(FitIntensity));i+=1)
2469//                      if (abs(NormalizedError[i])>DesmearSwitchOverVal)
2470//                              DesmearedIntWave[i]=FastFitIntensity[i]
2471//                      else
2472//                              DesmearedIntWave[i]=SlowFitIntensity[i]
2473//                      endif   
2474//              endfor
2475//      endif   
2476        NumberOfIterations+=1
2477        //remove the normalized error extremes
2478        wavestats/Q NormalizedError
2479        NormalizedError[x2pnt(NormalizedError,V_minLoc)] = Nan
2480        NormalizedError[x2pnt(NormalizedError,V_maxLoc)] = Nan
2481        //Duplicate/O DesmearIntWave, DesmearEWave
2482        DesmearEWave=0
2483        IN3_GetErrors(origSmearedErr, origSmearedInt, DesmearIntWave, DesmearEWave, DesmearQWave)                       //this routine gets the errors
2484        setDataFolder OldDf
2485        return 0
2486End
2487
2488//***********************************************************************************************************************************
2489//***********************************************************************************************************************************
2490//***********************************************************************************************************************************
2491//*************************************Extends the data using user specified parameters***************
2492Function IN3_ExtendData(Int_wave, Q_vct, Err_wave, slitLength, Qstart, SelectedFunction)
2493        wave Int_wave, Q_vct, Err_wave
2494        variable slitLength, Qstart             //RecordFitParam=1 when we should record fit parameters in logbook
2495        string SelectedFunction
2496       
2497        if (numtype(slitLength)!=0)
2498                abort "Slit length error"
2499        endif
2500        if (slitLength<0.0001 || slitLength>1)
2501                DoALert 0, "Weird value for Slit length, please check"
2502        endif
2503       
2504        string oldDf=GetDataFolder(1)
2505        setDataFolder root:Packages:Indra3
2506
2507        WAVE/Z W_coef=W_coef
2508        if (WaveExists(W_coef)!=1)                                     
2509                make/N=2 W_coef
2510        endif
2511        W_coef=0                //reset for recording purposes...
2512        //check if this makes any sense, sometimes we have issues with data and need to break here.
2513        Wavestats/Q Int_wave
2514        if(V_numNans>0 || V_numINFs>0)
2515                abort
2516        endif
2517       
2518        string ProblemsWithQ=""
2519        string ProblemWithFit=""
2520        string ProblemsWithInt=""
2521        variable DataLengths=numpnts(Q_vct)-1                                                   //get number of original data points
2522        variable Qstep=((Q_vct(DataLengths)/Q_vct(DataLengths-1))-1)*Q_vct(DataLengths)
2523        variable ExtendByQ=sqrt(Q_vct(DataLengths)^2 + (1.5*slitLength)^2) - Q_vct(DataLengths)
2524        if (ExtendByQ<2.1*Qstep)
2525                ExtendByQ=2.1*Qstep
2526        endif
2527        variable NumNewPoints=floor(ExtendByQ/Qstep)   
2528        if (NumNewPoints<1)
2529                NumNewPoints=1
2530        endif   
2531        variable OriginalNumPnts=numpnts(Int_wave)
2532        if (NumNewPoints>OriginalNumPnts)
2533                NumNewPoints=OriginalNumPnts
2534        endif   
2535        variable newLength=numpnts(Q_vct)+NumNewPoints                          //New length of waves
2536        variable FitFrom=binarySearch(Q_vct, Qstart)                                    //get at which point of Q start fitting for extension
2537        if (FitFrom<=0)                                                                                         //error in selection of Q fitting range
2538                FitFrom=DataLengths-10
2539                ProblemsWithQ="I did reset Fitting Q range for you..."
2540        endif
2541        //There seems to be bug, which prevents me from using /D in FuncFit and cursor control
2542        //therefore we will have to now handle this ourselves...
2543        //FIrst check if the wave exists
2544        Wave/Z fit_ExtrapIntwave
2545        if (!WaveExists(fit_ExtrapIntwave))
2546                Make/O/N=300 fit_ExtrapIntwave
2547        endif
2548        //Now we need to set it's x scaling to the range of Q values we need to study
2549        SetScale/I x Q_vct[FitFrom],Q_vct[DataLengths-1],"", fit_ExtrapIntwave
2550        //reset the fit wave to constant value
2551        fit_ExtrapIntwave=Int_wave[DataLengths-1]
2552               
2553        Redimension /N=(newLength) Int_wave, Q_vct, Err_wave                    //increase length of the two waves
2554       
2555        variable i=0, ii=0     
2556        variable/g V_FitError=0                                 //this is way to avoid bombing due to numerical problems
2557        variable/g V_FitOptions=4                               //this should suppress the window showing progress (4) & force robust fitting (6)
2558                                                                                //using robust fitting caused problems, do not use...
2559//      variable/g V_FitTol=0.00001                             //and this should force better fit
2560        variable/g V_FitMaxIters=50
2561//      variable/g V_FitNumIters
2562       
2563//      DoWindow CheckTheBackgroundExtns
2564//      if (V_flag)
2565//              RemoveFromGraph /W=CheckTheBackgroundExtns /Z Fit_ExtrapIntwave
2566//      endif
2567        //***********here start different ways to extend the data
2568
2569        if (cmpstr(SelectedFunction,"flat")==0)                         //flat background, for some reason only way this works is
2570        //lets setup parameters for FuncFit
2571                if (exists("W_coef")!=1)                                        //using my own function to fit. Crazy!!
2572                        make/N=2 W_coef
2573                endif
2574                Redimension/D/N=1 W_coef
2575                Make/O/N=1 E_wave
2576                E_wave[0]=1e-6
2577                W_coef[0]=Int_wave[((FitFrom+DataLengths)/2)]                   //here is starting guesses
2578                K0=W_coef[0]                                                                            //another way to get starting guess in
2579                V_FitError=0                                                                                    //this is way to avoid bombing due to numerical problems
2580                //now lets do the fitting
2581                FuncFit/N/Q IN3_FlatFnct W_coef Int_wave [FitFrom, DataLengths-1] /I=1 /W=Err_Wave /E=E_Wave /X=Q_vct   //Here we get the fit to the Int_wave in
2582                //now check for the convergence
2583                if (V_FitError!=0)
2584                        //we had error during fitting
2585                        ProblemWithFit="Linear fit function did not converge properly,\r change function or Q range"
2586                else            //the fit converged properly
2587                        For(i=1;i<=NumNewPoints;i+=1)                                                                   
2588                                Q_vct[DataLengths+i]=Q_vct[DataLengths]+(ExtendByQ)*(i/NumNewPoints)            //extend Q
2589                                Int_wave[DataLengths+i]= W_coef[0]                                                              //extend Int
2590                        EndFor
2591                        fit_ExtrapIntwave=W_coef[0]
2592                endif
2593        endif
2594
2595
2596        if (cmpstr(SelectedFunction,"power law")==0)                    //power law background
2597                V_FitError=0                                    //this is way to avoid bombing due to numerical problems
2598                //now lets do the fitting       
2599                K0 = 0
2600                CurveFit/N/Q/H="100" Power Int_wave[FitFrom, DataLengths-1] /X=Q_vct /W=Err_Wave /I=1
2601                if (V_FitError!=0)
2602                        //we had error during fitting
2603                        ProblemWithFit="Power law fit function did not converge properly,\r change function or Q range"
2604                else            //the fit converged properly
2605                        For(i=1;i<=NumNewPoints;i+=1)                                                                   
2606                                Q_vct[DataLengths+i]=Q_vct[DataLengths]+(ExtendByQ)*(i/NumNewPoints)            //extend Q
2607                                Int_wave[DataLengths+i]= W_coef[0]+W_coef[1]*(Q_vct[DataLengths+i])^W_coef[2]                   //extend Int
2608                        endfor
2609                        fit_ExtrapIntwave=W_coef[0]+W_coef[1]*(x)^W_coef[2]
2610                endif
2611        endif
2612
2613
2614        if (cmpstr(SelectedFunction,"Porod")==0)                                //Porod background
2615                if (exists("W_coef")!=1)
2616                        make/N=2 W_coef
2617                endif
2618                Redimension/D/N=2 W_coef
2619                variable estimate1_w0=Int_wave[(DataLengths-1)]
2620                variable estimate1_w1=Q_vct[(FitFrom)]^4*Int_wave[(FitFrom)]
2621                W_coef={estimate1_w0,estimate1_w1}                                                      //here are starting guesses, may need to be fixed.
2622                K0=estimate1_w0
2623                K1=estimate1_w1
2624                V_FitError=0                                    //this is way to avoid bombing due to numerical problems
2625                //now lets do the fitting       
2626                Make/O/T CTextWave={"K0 > "+num2str(estimate1_w0/100)}
2627                FuncFit/N/Q IN3_Porod W_coef Int_wave [FitFrom, DataLengths-1] /I=1 /C=CTextWave/W=Err_Wave /X=Q_vct                    //Porod function here
2628                if (V_FitError!=0)
2629                        //we had error during fitting
2630                        ProblemWithFit="Porod fit function did not converge properly,\r change function or Q range"
2631                else            //the fit converged properly
2632                        For(i=1;i<=NumNewPoints;i+=1)                                                                   
2633                                Q_vct[DataLengths+i]=Q_vct[DataLengths]+(ExtendByQ)*(i/NumNewPoints)            //extend Q
2634                                Int_wave[DataLengths+i]=W_coef[0]+W_coef[1]/(Q_vct[DataLengths+i])^4            //extend Int
2635                        endfor
2636                        fit_ExtrapIntwave=W_coef[0]+W_coef[1]/(x)^4
2637                endif
2638        endif
2639
2640
2641        if (cmpstr(SelectedFunction,"PowerLaw w flat")==0)                              //fit polynom 3rd degree
2642                if (exists("W_coef")!=1)
2643                        make/N=3 W_coef
2644                endif
2645        //      variable estimate1_w0=Int_wave[(DataLengths-1)]
2646        //      variable estimate1_w1=Q_vct[(FitFrom)]^4*Int_wave[(FitFrom)]
2647                K0=Int_wave[(DataLengths-1)]
2648                K1=(Int_wave[(FitFrom)] - K0) * (Q_vct[(FitFrom)]^3)
2649                K2=-3
2650                W_coef={K0,K1, K2}                                                      //here are starting guesses, may need to be fixed.
2651
2652                Make/O/T CTextWave={"K1 > 0","K2 < 0","K0 > 0", "K2 > -6"}
2653                Redimension/D/N=3 W_coef
2654                V_FitError=0                                    //this is way to avoid bombing due to numerical problems
2655                        Curvefit/N/G/Q power Int_wave [FitFrom, DataLengths-1] /I=1 /C=CTextWave/X=Q_vct /W=Err_Wave           
2656                if (V_FitError!=0)
2657                        //we had error during fitting
2658                        ProblemWithFit="Power Law with flat fit function did not converge properly,\r change function or Q range"
2659                else            //the fit converged properly
2660                        For(i=1;i<=NumNewPoints;i+=1)                                                                   
2661                                Q_vct[DataLengths+i]=Q_vct[DataLengths]+(ExtendByQ)*(i/NumNewPoints)            //extend Q
2662                                Int_wave[DataLengths+i]= W_coef[0]+W_coef[1]*(Q_vct[DataLengths+i]^W_coef[2])
2663                        endfor
2664                        fit_ExtrapIntwave=W_coef[0]+W_coef[1]*(x^W_coef[2])
2665                        endif
2666                endif
2667
2668//              wavestats/Q/R=[DataLengths+1,] Int_wave
2669//      //      print DataLengths
2670//              if (V_min<0)
2671//                      ProblemsWithInt="Extrapolated Intensity <0, select different function"
2672//              endif
2673        variable ExtensionFailed=0
2674        string ErrorMessages=""
2675        if (strlen(ProblemsWithQ)!=0)
2676                ErrorMessages=ProblemsWithQ+"\r"
2677        endif
2678        if (strlen(ProblemsWithInt)!=0)
2679                ErrorMessages=ProblemsWithInt+"\r"
2680        endif
2681        if (strlen(ProblemWithFit)!=0)
2682                ErrorMessages+=ProblemWithFit
2683        endif
2684        if (strlen(ErrorMessages)!=0)
2685                ExtensionFailed=1
2686                DoAlert /T="Desmearing failed" 0, ErrorMessages
2687        endif
2688        setDataFolder OldDf
2689        return ExtensionFailed
2690end
2691
2692//***********************************************************************************************************************************
2693//***********************************************************************************************************************************
2694//*****************************This function smears data***********************
2695Function IN3_SmearData(Int_to_smear, Q_vec_sm, slitLength, Smeared_int)
2696        wave Int_to_smear, Q_vec_sm, Smeared_int
2697        variable slitLength
2698       
2699        string OldDf=GetDataFolder(1)
2700        setDataFolder root:Packages:Indra3
2701        variable oldNumPnts=numpnts(Q_vec_sm)
2702        //modified 2/28/2017 - with Fly scans and merged data having lot more points, this is getting to be slow. Keep max number of new points to 300
2703        variable newNumPoints
2704        if(oldNumPnts<300)
2705                newNumPoints = 2*oldNumPnts
2706        else
2707                newNumPoints = oldNumPnts+300
2708        endif
2709        Duplicate/O/Free Int_to_smear, tempInt_to_smear
2710        Redimension /N=(newNumPoints) tempInt_to_smear          //increase the points here.
2711        Duplicate/O/Free Q_vec_sm, tempQ_vec_sm
2712        Redimension/N=(newNumPoints) tempQ_vec_sm
2713        tempQ_vec_sm[oldNumPnts, ] =tempQ_vec_sm[oldNumPnts-1] +20* tempQ_vec_sm[p-oldNumPnts]                  //creates extension of number of points up to 20*original length
2714        tempInt_to_smear[oldNumPnts, ]  = tempInt_to_smear[oldNumPnts-1] * (1-(tempQ_vec_sm[p]  - tempQ_vec_sm[oldNumPnts])/(20*tempQ_vec_sm[oldNumPnts-1]))//extend the data by simple fixed value...
2715       
2716        Make/D/Free/N=(oldNumPnts) Smear_Q, Smear_Int                                                   
2717        //Q's in L spacing and intensitites in the l's will go to Smear_Int (intensity distribution in the slit, changes for each point)
2718
2719        variable DataLengths=numpnts(Q_vec_sm)
2720
2721        Smear_Q=2*slitLength*(Q_vec_sm[p]-Q_vec_sm[0])/(Q_vec_sm[DataLengths-1]-Q_vec_sm[0])            //create distribution of points in the l's which mimics the original distribution of points
2722        //the 2* added later, because without it I did not  cover the whole slit length range...
2723        variable i=0
2724        DataLengths=numpnts(Smeared_int)
2725        MatrixOp/FREE Q_vec_sm2=powR(Q_vec_sm,2)
2726        MatrixOp/FREE Smear_Q2=powR(Smear_Q,2)
2727        MultiThread Smeared_int = IN3_SmearDataFastFunc(Q_vec_sm2[p], Smear_Q,Smear_Q2, tempQ_vec_sm, tempInt_to_smear, SlitLength)
2728
2729        Smeared_int*= 1 / slitLength                                                                                                                    //normalize
2730       
2731        setDataFolder OldDf
2732end
2733//***********************************************************************************************************************************//***********************************************************************************************************************************
2734//***********************************************************************************************************************************
2735//***********************************************************************************************************************************
2736//***********************************************************************************************************************************
2737
2738Function IN3_FlatFnct(w,x) : FitFunc
2739        wave w
2740        variable x
2741       
2742        return w[0]
2743end
2744//***********************************************************************************************************************************
2745//***********************************************************************************************************************************
2746
2747Function IN3_Porod(w,x) : FitFunc
2748        Wave w
2749        Variable x
2750
2751        //CurveFitDialog/ These comments were created by the Curve Fitting dialog. Altering them will
2752        //CurveFitDialog/ make the function less convenient to work with in the Curve Fitting dialog.
2753        //CurveFitDialog/ Equation:
2754        //CurveFitDialog/ f(x) = c1+c2*(x^(-4))
2755        //CurveFitDialog/ End of Equation
2756        //CurveFitDialog/ Independent Variables 1
2757        //CurveFitDialog/ x
2758        //CurveFitDialog/ Coefficients 2
2759        //CurveFitDialog/ w[0] = c1
2760        //CurveFitDialog/ w[1] = c2
2761
2762        return w[0]+w[1]*(x^(-4))
2763End
2764//***********************************************************************************************************************************
2765//***********************************************************************************************************************************
2766//***********************************************************************************************************************************
2767//***********************************************************************************************************************************
2768Threadsafe function IN3_SmearDataFastFunc(Q_vec_sm2, Smear_Q,Smear_Q2, tempQ_vec_sm, tempInt_to_smear, SlitLength)
2769                        variable Q_vec_sm2, SlitLength
2770                        wave Smear_Q, Smear_Q2, tempQ_vec_sm, tempInt_to_smear 
2771                        Duplicate/Free Smear_Q, Smear_Int
2772                        //Smear_Int=interp(sqrt( Q_vec_sm2 +(Smear_Q2[p])), tempQ_vec_sm, tempInt_to_smear)             //put the distribution of intensities in the slit for each point
2773                        //this is using Interpolate2, seems slightly faster than above line alone...
2774                        Duplicate/Free Smear_Q, InterSmear_Q
2775                        InterSmear_Q = sqrt( Q_vec_sm2 +(Smear_Q2[p]))
2776                        //surprisingly, below code is tiny bit slower that the two lines above...
2777                        //MatrixOp/FREE InterSmear_Q=sqrt(Smear_Q2 + Q_vec_sm2)
2778                        Interpolate2/I=3/T=1/X=InterSmear_Q /Y=Smear_Int tempQ_vec_sm, tempInt_to_smear
2779                        return areaXY(Smear_Q, Smear_Int, 0, slitLength)                                                        //integrate the intensity over the slit
2780end
2781//***********************************************************************************************************************************
2782//***********************************************************************************************************************************
2783Function IN3_GetErrors(SmErrors, SmIntensity, FitIntensity, DsmErrors, Qvector)         //calculates errors using Petes formulas
2784        wave SmErrors, SmIntensity, FitIntensity, DsmErrors, Qvector
2785       
2786        Silent 1       
2787       
2788        DsmErrors=FitIntensity*(SmErrors/SmIntensity)                                           //error proportional to input data
2789        WAVE W_coef=W_coef
2790        variable i=1, imax=numpnts(FitIntensity)
2791        Redimension/N=(numpnts(FitIntensity)) DsmErrors
2792        Do
2793                if( (numtype(FitIntensity[i-1])==0) && (numtype(FitIntensity[i])==0) && (numtype(FitIntensity[i+1])==0) )
2794                        CurveFit/Q line, FitIntensity (i-1, i+1) /X=Qvector                             //linear function here
2795                        DsmErrors[i]+=abs(W_coef[0]+W_coef[1]*Qvector[i] - FitIntensity[i])     //error due to scatter of data
2796                endif
2797        i+=1
2798        while (i<imax-1)
2799
2800        DsmErrors[0]=DsmErrors[1]                                                                       //some error needed for 1st point
2801        DsmErrors[imax-1]=DsmErrors[imax-2]                                                             //and error for last point     
2802
2803        Smooth /E=2 3, DsmErrors
2804       
2805end
2806
2807//***********************************************************************************************************************************
2808//***********************************************************************************************************************************
2809
2810Function IN3_DisplayDesExtAndError()
2811               
2812                DoWindow RcurvePlotGraph
2813                if(V_Flag)
2814                        ControlInfo /W=USAXSDataReduction DataTabs
2815                        if(V_Value==5)
2816                                Wave/Z fit_ExtrapIntwave = root:Packages:Indra3:fit_ExtrapIntwave
2817                                if(WaveExists(fit_ExtrapIntwave))
2818                                        CheckDisplayed /W=RcurvePlotGraph fit_ExtrapIntwave
2819                                        if(V_Flag<1)
2820                                                AppendToGraph/R/W=RcurvePlotGraph fit_ExtrapIntwave     
2821                                                ModifyGraph /W=RcurvePlotGraph mode(fit_ExtrapIntwave)=0,lstyle(fit_ExtrapIntwave)=3,rgb(fit_ExtrapIntwave)=(65535,0,0)
2822                                                ModifyGraph /W=RcurvePlotGraph lsize(fit_ExtrapIntwave)=4
2823                                        endif
2824                                endif   
2825                                Wave/Z DesmNormalizedError = root:Packages:Indra3:DesmNormalizedError
2826                                Wave/Z DSM_Qvec=root:Packages:Indra3:DSM_Qvec
2827                                if(WaveExists(DesmNormalizedError)&&WaveExists(DSM_Qvec))
2828                                        CheckDisplayed /W=RcurvePlotGraph DesmNormalizedError
2829                                        if(V_Flag<1)
2830                                                AppendToGraph/L=VertCrossing/W=RcurvePlotGraph DesmNormalizedError vs DSM_Qvec
2831                                                ModifyGraph/W=RcurvePlotGraph mode(DesmNormalizedError)=2,rgb(DesmNormalizedError)=(0,0,0)
2832                                                SetAxis/A/E=2/W=RcurvePlotGraph VertCrossing
2833                                                ModifyGraph/W=RcurvePlotGraph lblPos(VertCrossing)=45
2834                                                Label/W=RcurvePlotGraph VertCrossing "Normalized residual"
2835                                        endif
2836                                endif   
2837                        else
2838                                Wave/Z DSM_Int
2839                                CheckDisplayed /W=RcurvePlotGraph DSM_Int
2840                                        if(V_Flag)
2841                                                ModifyGraph/W=RcurvePlotGraph mode(DSM_Int)=3,rgb(DSM_Int)=(1,39321,19939)             
2842                                                ModifyGraph/W=RcurvePlotGraph mode(DSM_Int)=4
2843                                                //Label/W=RcurvePlotGraph right "DSM & SMR Intensity"   
2844                                                Label/W=RcurvePlotGraph right "\\K(3,52428,1)DSM & \\K(1,16019,65535)SMR \\K(0,0,0)Intensity"
2845                                        else
2846                                       
2847                                        endif
2848                                RemoveFromGraph /W=RcurvePlotGraph/Z fit_ExtrapIntwave
2849                                RemoveFromGraph /W=RcurvePlotGraph/Z DesmNormalizedError
2850                        endif
2851                endif
2852end
2853//***********************************************************************************************************************************
2854//***********************************************************************************************************************************
Note: See TracBrowser for help on using the repository browser.