source: trunk/User Procedures/Irena/IRB1_bioSAXS.ipf @ 922

Last change on this file since 922 was 922, checked in by ilavsky, 2 years ago

Bug fixes, close to version 1beta for PDDF

  • Property svn:eol-style set to native
File size: 183.5 KB
Line 
1#pragma TextEncoding = "UTF-8"
2#pragma rtGlobals=3             // Use modern global access method and strict wave access.
3#pragma version=0.1
4#pragma IgorVersion = 8.03
5
6
7//*************************************************************************\
8//* Copyright (c) 2005 - 2020, Argonne National Laboratory
9//* This file is distributed subject to a Software License Agreement found
10//* in the file LICENSE that is included with this distribution.
11//*************************************************************************/
12constant IRB1_ImportBioSAXSASCIIDataVersion = 0.1                       //IRB1_ImportBioSAXSASCIIData tool version number.
13constant IRB1_DataManipulation = 0.1                                                    //IRB1_DataManipulation tool version number.
14constant IRB1_SetVariableStepScaling = 0.01                                     //this is fraction of the value to which the step in SetVariable is set. 
15constant IRB1_PDDFInterfaceVersion = 0.1                                        //IRB1_PDDFInterfaceFunction version number
16//functions for bioSAXS community
17//
18//version summary
19//0.1 early beta version
20
21//Contains these main parts:
22//Import ASCII data:    IRB1_ImportASCII()
23//Avergae data and other data manipulations : IRB1_DataManipulation()
24//ATSAS support IRB1_PDDFInterfaceFunction()
25
26
27
28//************************************************************************************************************
29//************************************************************************************************************
30//************************************************************************************************************
31//                              This is customized BioSAXS Import ASCII
32//************************************************************************************************************
33//************************************************************************************************************
34//************************************************************************************************************
35//todo:
36//add scaling controls
37//check capcilities and add any needed fixes on data
38//fix manual link (aka: vrite manual)
39//fix version control and restarting, add to kill function
40//fix any bugs and functionality...
41Function IRB1_ImportASCII()
42
43        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
44        IN2G_CheckScreenSize("height",720)
45        DoWindow IR1I_ImportBioSAXSASCIIData
46        if(V_Flag)
47                DoWindow/F IR1I_ImportBioSAXSASCIIData
48        else
49                //intit first
50                //need to create panel
51                IRB1_InitializeImportData()
52                IRB1_ImportBioSAXSASCIIDataFnct()
53                ING2_AddScrollControl()
54                IR1_UpdatePanelVersionNumber("IRB1_ImportBioSAXSASCIIData", IRB1_ImportBioSAXSASCIIDataVersion,1)
55        endif
56end
57//************************************************************************************************************
58Function IRB1_ImportASCIIMainCheckVersion()     
59        DoWindow IR1I_ImportBioSAXSASCIIData
60        if(V_Flag)
61                if(!IR1_CheckPanelVersionNumber("IR1I_ImportBioSAXSASCIIData", IRB1_ImportBioSAXSASCIIDataVersion))
62                        DoAlert /T="The Import ASCII panel was created by incorrect version of Irena " 1, "Import ASCII tool needa to be restarted to work properly. Restart now?"
63                        if(V_flag==1)
64                                KillWIndow/Z IR1I_ImportBioSAXSASCIIData
65                                IRB1_ImportASCII()
66                        else            //at least reinitialize the variables so we avoid major crashes...
67                                IRB1_InitializeImportData()
68                        endif
69                endif
70        endif
71end
72//************************************************************************************************************
73//************************************************************************************************************
74//************************************************************************************************************
75//                              This is customized BioSAXS Data manipulation package
76//************************************************************************************************************
77//************************************************************************************************************
78//************************************************************************************************************
79//todo:
80//add options to use different error propagation, per request uses Standard deviation
81//      UseStdDev = 0
82//      UseSEM = 0
83//      PropagateErrors = 1
84
85Function IRB1_DataManipulation()
86        IN2G_CheckScreenSize("width",1200)
87        DoWIndow IRB1_DataManipulationPanel
88        if(V_Flag)
89                DoWindow/F IRB1_DataManipulationPanel
90        else
91                IRB1_DataManInitBioSAXS()
92                IRB1_DataManPanelFnct()
93                IR3C_MultiUpdateListOfAvailFiles("Irena:BioSAXSDataMan")
94                ING2_AddScrollControl()
95                IR1_UpdatePanelVersionNumber("IRB1_DataManipulationPanel", IRB1_DataManipulation,1)
96        endif
97end
98//************************************************************************************************************
99//************************************************************************************************************
100Function IRB1_DataManMainCheckVersion()
101        DoWindow IRB1_DataManipulationPanel
102        if(V_Flag)
103                if(!IR1_CheckPanelVersionNumber("IRB1_DataManipulationPanel", IRB1_DataManipulation))
104                        DoAlert /T="The Data Manipulation panel was created by incorrect version of Irena " 1, "Data Manipulation tool needa to be restarted to work properly. Restart now?"
105                        if(V_flag==1)
106                                KillWIndow/Z IRB1_DataManipulationPanel
107                                IRB1_DataManipulation()
108                        else            //at least reinitialize the variables so we avoid major crashes...
109                                IRB1_DataManInitBioSAXS()
110                        endif
111                endif
112        endif
113end
114//************************************************************************************************************
115//************************************************************************************************************
116//************************************************************************************************************
117//                              This is BioSAXS Data package to run PDDF and some ATSAS functions
118//************************************************************************************************************
119//************************************************************************************************************
120//************************************************************************************************************
121//NOTE: you need ATSAS
122
123Function IRB1_PDDFInterfaceFunction()
124        IN2G_CheckScreenSize("width",1200)
125        DoWIndow IRB1_PDDFInterfacePanel
126        if(V_Flag)
127                DoWindow/F IRB1_PDDFInterfacePanel
128        else
129                IRB1_PDDFInitialize()
130                IRB1_PDDFPanelFnct()
131                SetWindow IRB1_PDDFInterfacePanel, hook(ATSASCursorMoved) = IRB1_PDDFGraphWindowHook
132                IR3C_MultiUpdateListOfAvailFiles("Irena:PDDFInterface")
133                ING2_AddScrollControl()
134                IR1_UpdatePanelVersionNumber("IRB1_PDDFInterfacePanel", IRB1_PDDFInterfaceVersion,1)
135                IRB1_PDDFResetValuesToPreventStale()
136        endif
137end
138//************************************************************************************************************
139//************************************************************************************************************
140Function IRB1_PDDFMainCheckVersion()   
141        DoWindow IRB1_PDDFInterfacePanel
142        if(V_Flag)
143                if(!IR1_CheckPanelVersionNumber("IRB1_PDDFInterfacePanel", IRB1_PDDFInterfaceVersion))
144                        DoAlert /T="The ATSAS panel was created by incorrect version of Irena " 1, "ATSAS tool needa to be restarted to work properly. Restart now?"
145                        if(V_flag==1)
146                                KillWIndow/Z IRB1_PDDFInterfacePanel
147                                IRB1_PDDFInterfaceFunction()
148                        else            //at least reinitialize the variables so we avoid major crashes...
149                                IRB1_PDDFInitialize()
150                        endif
151                endif
152        endif
153end
154//************************************************************************************************************
155//************************************************************************************************************
156//************************************************************************************************************
157//************************************************************************************************************
158//                              This is customized Merge multiple data sets for BioSAXS Data
159//************************************************************************************************************
160//************************************************************************************************************
161//************************************************************************************************************
162
163Function IRB1_MergeMultipleData()
164                IR3D_DataMerging()
165                //tweak values for users
166                NVAR UseQRSdata1 = root:Packages:Irena:SASDataMerging:UseQRSdata1
167                UseQRSdata1 = 1
168                NVAR UseQRSdata2 = root:Packages:Irena:SASDataMerging:UseQRSdata2
169                UseQRSdata1 = 2
170                SVAR MatchStr1 = root:Packages:Irena:SASDataMerging:Data1MatchString
171                SVAR MatchStr2 = root:Packages:Irena:SASDataMerging:Data2MatchString
172                MatchStr1 = "sub"
173                MatchStr2 = "sub"
174                IR3D_UpdateListOfAvailFiles(1)
175                IR3D_UpdateListOfAvailFiles(2)
176                IR3D_RebuildListboxTables()     
177end
178//************************************************************************************************************
179//************************************************************************************************************
180//************************************************************************************************************
181//                              This is customized ASCII export for BioSAXS Data
182//************************************************************************************************************
183//************************************************************************************************************
184//************************************************************************************************************
185
186Function IRB1_ASCIIExport()
187                IR2E_UniversalDataExport()
188                //tweak values for users
189                NVAR useQRS=root:Packages:IR2_UniversalDataExport:UseQRSdata
190                NVAR useResults=root:Packages:IR2_UniversalDataExport:UseResults
191                NVAR useUSAXS=root:Packages:IR2_UniversalDataExport:UseIndra2data
192                useQRS=1
193                useUSAXS = 0
194                useResults = 0
195                SVAR FolderMatchStr = root:Packages:IrenaControlProcs:UnivDataExportPanel:FolderMatchStr
196                FolderMatchStr = "sub"
197end
198//************************************************************************************************************
199//************************************************************************************************************
200//************************************************************************************************************
201//                              Part of customized BioSAXS Import ASCII
202//************************************************************************************************************
203
204Function IRB1_ImportBioSAXSASCIIDataFnct()
205        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
206        PauseUpdate; Silent 1           // building window...
207        NewPanel /K=1 /W=(3,40,430,760)/N=IRB1_ImportBioSAXSASCIIData as "Import Bio SAXS data"
208        TitleBox MainTitle title="\Zr200Import bioSAXS ASCII Data in Igor",pos={20,5},frame=0,fstyle=3, fixedSize=1,font= "Times New Roman", size={400,24},anchor=MC,fColor=(0,0,52224)
209        TitleBox FakeLine1 title=" ",fixedSize=1,size={330,3},pos={16,40},frame=0,fColor=(0,0,52224), labelBack=(0,0,52224)
210        IR3C_AddDataControls("ImportDataPath", "Irena:ImportBioSAXSData", "IRB1_ImportBioSAXSASCIIData","dat", "","","IRB1_PreviewDataFnct")
211        ListBox ListOfAvailableData,size={220,477}, pos={5,113}
212        Button SelectAll,pos={5,595}
213        Button DeSelectAll, pos={120,595}
214        PopupMenu SortOptionString pos={250,120}
215
216        CheckBox SAXSData,pos={250,160},size={16,14},proc=IRB1_CheckProc,title="SAXS data?",variable= root:Packages:Irena:ImportBioSAXSData:SAXSData,mode=1, help={"Check if these are SAXS data..."}
217        CheckBox WAXSdata,pos={250,180},size={16,14},proc=IRB1_CheckProc,title="WAXS data data?",variable= root:Packages:Irena:ImportBioSAXSData:WAXSdata,mode=1, help={"Check if these are WAXS data..."}
218
219        CheckBox GroupSamplesTogether,pos={240,220},size={16,14},proc=IRB1_CheckProc,title="Group by Samples?",variable= root:Packages:Irena:ImportBioSAXSData:GroupSamplesTogether,mode=0, help={"Check if you want multipel sample measurements grouped together"}
220
221        CheckBox QvectorInnm,pos={240,250},size={16,14},proc=IRB1_CheckProc,title="Convert Q from [1/nm]?",variable= root:Packages:Irena:ImportBioSAXSData:QvectorInnm,mode=0, help={"Irena uses Angstroms, if data Q vector is in 1/nm, check here."}
222
223
224
225//      SetVariable SkipNumberOfLines,pos={300,133},size={70,19},proc=IR1I_SetVarProc,title=" "
226//      SetVariable SkipNumberOfLines,help={"Insert number of lines to skip"}
227//      NVAR DisableSkipLines=root:Packages:ImportData:SkipLines
228//      SetVariable SkipNumberOfLines,variable= root:Packages:ImportData:SkipNumberOfLines, disable=(!DisableSkipLines)
229//
230        Button Preview,pos={280,370},size={80,20}, proc=IRB1_ButtonProc,title="Preview"
231        Button Preview,help={"Preview selected file."}
232        Button ImportSelectedData,pos={230,400},size={180,20}, proc=IRB1_ButtonProc,title="Import Selected Data"
233        Button ImportSelectedData,help={"Test how if import can be succesful and how many waves are found"}
234        Button GetHelp,pos={335,50},size={80,15},fColor=(65535,32768,32768), proc=IRB1_ButtonProc,title="Get Help", help={"Open www manual page for this tool"}
235
236end
237//**********************************************************************************************************
238//**********************************************************************************************************
239//**********************************************************************************************************
240//************************************************************************************************************
241//************************************************************************************************************
242//                              Part of customized BioSAXS Import ASCII
243//************************************************************************************************************
244
245
246Function IRB1_CheckProc(cba) : CheckBoxControl
247        STRUCT WMCheckboxAction &cba
248
249        switch( cba.eventCode )
250                case 2: // mouse up
251                        Variable checked = cba.checked
252                        NVAR SAXSdata= root:Packages:Irena:ImportBioSAXSData:SAXSData
253                        NVAR WAXSData= root:Packages:Irena:ImportBioSAXSData:WAXSData
254                        if(stringmatch(cba.ctrlname,"SAXSData"))
255                                SAXSdata = checked
256                                WAXSData = !checked
257                        endif
258                        if(stringmatch(cba.ctrlname,"WAXSData"))
259                                SAXSdata = !checked
260                                WAXSData = checked
261                        endif
262                        if(stringmatch(cba.ctrlname,"DisplayErrorBars"))
263                                pauseUpdate
264                                NVAR DisplayErrorBars = root:Packages:Irena:BioSAXSDataMan:DisplayErrorBars
265                                IN2G_ShowHideErrorBars(DisplayErrorBars, topGraphStr="IRB1_DataManipulationPanel#LogLogDataDisplay")
266                                DoUpdate
267                        endif
268                       
269                        break
270                case -1: // control being killed
271                        break
272        endswitch
273
274        return 0
275End
276//**********************************************************************************************************
277//**********************************************************************************************************
278//**********************************************************************************************************
279//************************************************************************************************************
280//************************************************************************************************************
281//                              Part of customized BioSAXS Import ASCII
282//************************************************************************************************************
283
284
285Function IRB1_ButtonProc(ba) : ButtonControl
286        STRUCT WMButtonAction &ba
287
288        switch( ba.eventCode )
289                case 2: // mouse up
290                        // click code here
291                        if(stringmatch(ba.ctrlName,"ImportSelectedData"))
292                                IRB1_ImportDataFnct()           
293                        endif
294                        if(stringmatch(ba.ctrlName,"Preview"))
295                                IRB1_PreviewDataFnct()
296                        endif
297                        if(stringmatch(ba.ctrlName,"GetHelp"))
298                                        IN2G_OpenWebManual("Irena/ImportDataBio.html")                          //fix me!!                     
299                        endif
300                       
301                        break
302                case -1: // control being killed
303                        break
304        endswitch
305
306        return 0
307End
308//**********************************************************************************************************
309//**********************************************************************************************************
310//**********************************************************************************************************
311//************************************************************************************************************
312//************************************************************************************************************
313//                              Part of customized BioSAXS Import ASCII
314//************************************************************************************************************
315static Function IRB1_ImportDataFnct()
316        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
317
318        string TopPanel=WinName(0, 64)
319        DfRef OldDf=GetDataFolderDFR()
320       
321        Wave/T WaveOfFiles    = root:Packages:Irena:ImportBioSAXSData:WaveOfFiles
322        Wave WaveOfSelections = root:Packages:Irena:ImportBioSAXSData:WaveOfSelections
323        NVAR SAXSdata= root:Packages:Irena:ImportBioSAXSData:SAXSData
324        NVAR WAXSData= root:Packages:Irena:ImportBioSAXSData:WAXSData
325        NVAR GroupSamplesTogether       =       root:Packages:Irena:ImportBioSAXSData:GroupSamplesTogether
326        KillWindow/Z TestImportGraph
327        PathInfo ImportDataPath
328        string DataSelPathString=S_path
329        if(SAXSdata)
330                NewDataFolder/O/S root:SAXS
331        elseif(WAXSdata)
332                NewDataFolder/O/S root:WAXS
333        else
334                NewDataFolder/O/S root:ImportedData
335        endif
336        string BaseFolder = getDataFolder(1)
337        variable i, imax, icount
338        string SelectedFile
339        string SelectedFileName
340        string SelectedSampleName
341        string NewNote
342        NVAR QvectorInnm = root:Packages:Irena:ImportBioSAXSData:QvectorInnm
343        imax = numpnts(WaveOfSelections)
344        icount = 0
345        for(i=0;i<imax;i+=1)
346                if (WaveOfSelections[i])
347                        NewNote=""
348                        setDataFolder BaseFolder
349                        selectedfile = WaveOfFiles[i]
350                        SelectedFileName = RemoveEnding(RemoveListItem(ItemsInList(selectedfile,".")-1, selectedfile,"."),".")
351                        //now make assumption about sample name, we can group samples together.
352                        if(GroupSamplesTogether)
353                                SelectedSampleName = RemoveEnding(RemoveListItem(ItemsInList(selectedfile,"_")-1, selectedfile,"_"),"_")
354                                SelectedSampleName = CleanupName(SelectedSampleName,1)
355                                SelectedFileName = CleanupName(SelectedFileName, 1)
356                                //create and move into the SampleFolder
357                                if(strlen(SelectedSampleName)>1)                //cases, when name cannot be deduced in above level.
358                                        NewDataFolder/O/S $((SelectedSampleName))
359                                endif
360                        endif
361                        //now folder for the specific imported ASCII file
362                        NewDataFolder/O/S $((SelectedFileName))
363                        KillWaves/Z wave0, wave1, wave2
364                        LoadWave/Q/A/D/G/P=ImportDataPath  selectedfile
365                        Wave wave0
366                        Wave wave1
367                        Wave/Z wave2
368                        KillWaves/Z $(PossiblyQuoteName("q_"+SelectedFileName)), $(PossiblyQuoteName("r_"+SelectedFileName)), $(PossiblyQuoteName("s_"+SelectedFileName))
369                        Rename wave0, $(PossiblyQuoteName("q_"+SelectedFileName))
370                        Rename wave1, $(PossiblyQuoteName("r_"+SelectedFileName))
371                        if(WaveExists(wave2))   //this should be error data, but if they do not exist, we need to fake them. ATSAS assume 4% intensity...
372                                Rename wave2, $(PossiblyQuoteName("s_"+SelectedFileName))
373                        else
374                                Duplicate/O wave1, $(PossiblyQuoteName("s_"+SelectedFileName))
375                                Wave NewErrWv=$(PossiblyQuoteName("s_"+SelectedFileName))
376                                NewErrWv *=0.04
377                        endif
378                        //need to clean upimported waves, if Intensity is 0, point shoudl be removed...
379                        Wave Intensity = $(PossiblyQuoteName("r_"+SelectedFileName))
380                        Wave Qvec = $(PossiblyQuoteName("q_"+SelectedFileName))
381                        Wave Error = $(PossiblyQuoteName("s_"+SelectedFileName))
382                        Intensity = Intensity[p]>0 ? Intensity[p] : nan
383                        IN2G_RemoveNaNsFrom3Waves(Qvec,Intensity,Error)
384                        if(QvectorInnm)
385                                Qvec/=10
386                        endif
387                        NewNote="Imported data;"+date()+";"+time()+";Original File Name="+selectedfile+";Original file location="+DataSelPathString+";"
388                        Note /K/NOCR Intensity, NewNote
389                        Note /K/NOCR Qvec, NewNote
390                        Note /K/NOCR Error, NewNote
391                        icount+=1
392                endif
393        endfor
394        print "Imported "+num2str(icount)+" data file(s) in total"
395        setDataFolder OldDf
396end
397
398//************************************************************************************************************
399//************************************************************************************************************
400//                              Part of customized BioSAXS Import ASCII
401//************************************************************************************************************
402static Function IRB1_InitializeImportData()
403       
404        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
405        DfRef OldDf=GetDataFolderDFR()
406       
407        NewDataFolder/O/S root:Packages
408        NewDataFolder/O/S root:Packages:Irena
409        NewDataFolder/O/S root:Packages:Irena:ImportBioSAXSData
410       
411        string ListOfStrings
412        string ListOfVariables
413        variable i
414       
415        ListOfStrings = "DataPathName;DataExtension;IntName;QvecName;ErrorName;NewDataFolderName;NewIntensityWaveName;DataTypeToImport;"
416        ListOfStrings+="NewQWaveName;NewErrorWaveName;NewQErrorWavename;NameMatchString;TooManyPointsWarning;RemoveStringFromName;"
417        ListOfVariables = "UseFileNameAsFolder;UseIndra2Names;UseQRSNames;DataContainErrors;UseQISNames;"
418        ListOfVariables += "SAXSData;WAXSdata;GroupSamplesTogether;QvectorInnm;"       
419//      ListOfVariables += "CreateSQRTErrors;Col1Int;Col1Qvec;Col1Err;Col1QErr;FoundNWaves;"   
420//      ListOfVariables += "QvectInA;QvectInNM;QvectInDegrees;CreateSQRTErrors;CreatePercentErrors;PercentErrorsToUse;"
421//      ListOfVariables += "ScaleImportedData;ScaleImportedDataBy;ImportSMRdata;SkipLines;SkipNumberOfLines;"   
422//      ListOfVariables += "IncludeExtensionInName;RemoveNegativeIntensities;AutomaticallyOverwrite;"   
423//      ListOfVariables += "TrimData;TrimDataQMin;TrimDataQMax;ReduceNumPnts;TargetNumberOfPoints;ReducePntsParam;"     
424//      ListOfVariables += "NumOfPointsFound;TrunkateStart;TrunkateEnd;Wavelength;"     
425//      ListOfVariables += "DataCalibratedArbitrary;DataCalibratedVolume;DataCalibratedWeight;"
426
427
428                //and here we create them
429        for(i=0;i<itemsInList(ListOfVariables);i+=1)   
430                IN2G_CreateItem("variable",StringFromList(i,ListOfVariables))
431        endfor         
432                                                               
433        for(i=0;i<itemsInList(ListOfStrings);i+=1)     
434                IN2G_CreateItem("string",StringFromList(i,ListOfStrings))
435        endfor 
436
437        SVAR TooManyPointsWarning
438        TooManyPointsWarning=" "
439       
440        Make/O/T/N=0 WaveOfFiles
441        Make/O/N=0 WaveOfSelections
442
443        NVAR SAXSData
444        NVAR WAXSdata
445        if(SAXSData+WAXSdata!=1)
446                SAXSData=1
447                WAXSdata=0
448        endif
449        NVAR GroupSamplesTogether
450        GroupSamplesTogether = 1
451end
452
453//**********************************************************************************************************
454//**********************************************************************************************************
455//**********************************************************************************************************
456//**********************************************************************************************************
457
458Function IRB1_PreviewDataFnct()
459        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
460        DfRef OldDf=GetDataFolderDFR()
461       
462        Wave/T WaveOfFiles    = root:Packages:Irena:ImportBioSAXSData:WaveOfFiles
463        Wave WaveOfSelections = root:Packages:Irena:ImportBioSAXSData:WaveOfSelections
464        NVAR QvectorInnm = root:Packages:Irena:ImportBioSAXSData:QvectorInnm
465
466        if(sum(WaveOfSelections)<1)
467                WaveOfSelections[0]=1
468        endif
469        variable i, imax, icount
470        string SelectedFileName, selectedfile
471        SelectedFileName = "TestImport"
472        imax = numpnts(WaveOfSelections)       
473        newDataFOlder/O/S root:Packages:Irena:Temp
474        KillWindow/Z TestImportGraph
475        KillWaves/Z q_TestImport, r_TestImport, s_TestImport, wave0, wave1, wave2
476        for(i=0;i<imax;i+=1)
477                if (WaveOfSelections[i])
478                        selectedfile = WaveOfFiles[i]
479                        LoadWave/Q/A/D/G/P=ImportDataPath  selectedfile
480                        Wave wave0
481                        Wave wave1
482                        Wave wave2
483                        Rename wave0, $(PossiblyQuoteName("q_"+SelectedFileName))
484                        Rename wave1, $(PossiblyQuoteName("r_"+SelectedFileName))
485                        Rename wave2, $(PossiblyQuoteName("s_"+SelectedFileName))
486                        Wave Intensity = $(PossiblyQuoteName("r_"+SelectedFileName))
487                        Wave Qvec = $(PossiblyQuoteName("q_"+SelectedFileName))
488                        Wave Error = $(PossiblyQuoteName("S_"+SelectedFileName))
489                        if(QvectorInnm)
490                                Qvec/=10
491                        endif
492                        Display/K=1 /N=TestImportGraph/W=(50, 50, 550,400 ) Intensity vs Qvec as "Test import of "+selectedfile
493                        ModifyGraph log=1,mirror=1
494                        Label left "Intensity [arbitrary]"
495                        Label bottom "Q [1/A]"
496                        ModifyGraph mode=3
497                        AutoPositionWindow/R=IRB1_ImportBioSAXSASCIIData TestImportGraph
498                        setDataFolder OldDf
499                        return 1
500                        icount+=1
501                endif
502        endfor
503        setDataFolder OldDf
504end
505//************************************************************************************************************
506//************************************************************************************************************
507//                              End of customized BioSAXS Import ASCII
508//************************************************************************************************************
509//************************************************************************************************************
510//************************************************************************************************************
511//************************************************************************************************************
512//                              Part of customized BioSAXS Data Manipulation package
513//************************************************************************************************************
514//************************************************************************************************************
515//************************************************************************************************************
516//************************************************************************************************************
517//************************************************************************************************************
518static Function IRB1_DataManPanelFnct()
519        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
520        PauseUpdate; Silent 1           // building window...
521        NewPanel /K=1 /W=(2.25,43.25,1195,800) as "BioSAXS data manipulation"
522        DoWIndow/C IRB1_DataManipulationPanel
523        TitleBox MainTitle title="BioSAXS data manipulation",pos={140,2},frame=0,fstyle=3, fixedSize=1,font= "Times New Roman", size={360,30},fSize=22,fColor=(0,0,52224)
524        string UserDataTypes=""
525        string UserNameString=""
526        string XUserLookup=""
527        string EUserLookup=""
528        IR2C_AddDataControls("Irena:BioSAXSDataMan","IRB1_DataManipulationPanel","DSM_Int;M_DSM_Int;SMR_Int;M_SMR_Int;","AllCurrentlyAllowedTypes",UserDataTypes,UserNameString,XUserLookup,EUserLookup, 0,1, DoNotAddControls=1)
529        IR3C_MultiAppendControls("Irena:BioSAXSDataMan","IRB1_DataManipulationPanel", "IRB1_DataManAppendOneDataSet","",1,0)
530        TitleBox Dataselection pos={10,25}
531        ListBox DataFolderSelection pos={4,135},size={250,540}
532        CheckBox UseIndra2Data disable=3
533        CheckBox UseResults disable=3
534        CheckBox UseQRSData disable=1
535        NVAR UseQRSData = root:Packages:Irena:BioSAXSDataMan:UseQRSData
536        NVAR UseResults = root:Packages:Irena:BioSAXSDataMan:UseResults
537        NVAR UseIndra2Data = root:Packages:Irena:BioSAXSDataMan:UseIndra2Data
538        UseResults = 0
539        UseIndra2Data = 0
540        UseQRSData = 1
541        Button GetHelp,pos={335,50},size={80,15},fColor=(65535,32768,32768), proc=IRB1_DataManButtonProc,title="Get Help", help={"Open www manual page for this tool"}
542
543
544
545        TabControl ProcessingTabs,pos={262,135},size={250,500}
546        TabControl ProcessingTabs,tabLabel(0)="Average",tabLabel(1)="Subtract"
547        TabControl ProcessingTabs,tabLabel(2)="Scale"
548        TabControl ProcessingTabs proc=IRB1_DataManTabProc
549
550        //tab 1 controls
551        Button SelectAllData,pos={280,170},size={190,20}, proc=IRB1_DataManButtonProc,title="1. Select All Data", help={"Select all data in the Listbox"}
552        Button PlotSelectedData,pos={280,200},size={190,20}, proc=IRB1_DataManButtonProc,title="2. Plot Selected Data", help={"Plot selected data in the graph"}
553        TitleBox AverageInstructions title="\Zr1203. Remove data by right click",size={330,15},pos={275,237},frame=0,fColor=(0,0,65535),labelBack=0
554        Button AverageData,pos={280,270},size={190,20}, proc=IRB1_DataManButtonProc,title="4. Average & save Data", help={"Average data in the Graph and save with _avg in name"}
555        Button ClearGraph,pos={280,300},size={190,20}, proc=IRB1_DataManButtonProc,title="5. Clear graph", help={"Clear the graph Graph"}
556
557        TitleBox AverageInstructions2 title="\Zr120Name for ave folder : ",size={330,15},pos={270,350},frame=0,fColor=(0,0,65535),labelBack=0
558        SetVariable AverageOutputFolderString,pos={265,370},size={245,15}, noproc,title=" ", noedit=1, frame=0
559        Setvariable AverageOutputFolderString, variable=root:Packages:Irena:BioSAXSDataMan:AverageOutputFolderString
560
561       
562        //tab 2 controls
563        TitleBox AverageInstructions3 title="\Zr1201. Pick Buffer folder (ave) : ",size={330,15},pos={270,175},frame=0,fColor=(0,0,65535),labelBack=0
564        PopupMenu SelectBufferData,pos={262,200},size={180,20},fStyle=2,proc=IRB1_PopMenuProc,title=" "
565        SVAR SelectedBufferFolder = root:Packages:Irena:BioSAXSDataMan:SelectedBufferFolder
566        PopupMenu SelectBufferData,mode=1,popvalue=SelectedBufferFolder,value= IRB1_ListBufferScans()
567        TitleBox AverageInstructions7 title="\Zr1202. Add data (double click) ",size={330,15},pos={270,225},frame=0,fColor=(0,0,65535),labelBack=0
568        TitleBox AverageInstructions8 title="\Zr1203. Tweak scaling ",size={330,15},pos={270,250},frame=0,fColor=(0,0,65535),labelBack=0
569
570        SetVariable BufferScalingFraction,pos={270,275},size={220,15}, proc=IRB1_SetVarProc,title="Scale buffer =", noedit=0, frame=1, limits={0,10,0.002}
571        Setvariable BufferScalingFraction, variable=root:Packages:Irena:BioSAXSDataMan:BufferScalingFraction, bodyWidth=100
572
573        Button SubtractBuffer,pos={280,300},size={190,20}, proc=IRB1_DataManButtonProc,title="4. Subtract Buffer & Save", help={"Subtract Buffer from data and save with _sub in name"}
574        TitleBox AverageInstructions9 title="\Zr120Or, select many and process all ",size={330,15},pos={270,350},frame=0,fColor=(0,0,65535),labelBack=0
575        Button SubtractBufferMany,pos={280,375},size={190,20}, proc=IRB1_DataManButtonProc,title="Sub. Buffer On Selected", help={"Subtract Buffer from all selected data and save with _sub in name"}
576
577        TitleBox AverageInstructions4 title="\Zr120Input Data Name : ",size={245,15},pos={270,410},frame=0,fColor=(0,0,65535),labelBack=0
578        SetVariable UserSourceDataFolderName,pos={280,430},size={245,15}, noproc,variable=root:Packages:Irena:BioSAXSDataMan:UserSourceDataFolderName
579        SetVariable UserSourceDataFolderName, title=" ", limits={0,0,0}, noedit=1, frame=0
580        TitleBox AverageInstructions5 title="\Zr120Buffer Data Name : ",size={245,15},pos={270,460},frame=0,fColor=(0,0,65535),labelBack=0
581        SetVariable UserBufferDataFolderName,pos={280,480},size={245,15}, noproc,variable=root:Packages:Irena:BioSAXSDataMan:UserBufferDataFolderName
582        SetVariable UserBufferDataFolderName, title=" ", limits={0,0,0}, noedit=1, frame=0
583        TitleBox AverageInstructions6 title="\Zr120Output Data Name : ",size={245,15},pos={270,510},frame=0,fColor=(0,0,65535),labelBack=0
584        SetVariable SubtractedOutputFldrName,pos={280,530},size={245,15}, noproc,variable=root:Packages:Irena:BioSAXSDataMan:SubtractedOutputFldrName
585        SetVariable SubtractedOutputFldrName, title=" ", limits={0,0,0}, noedit=1, frame=0
586
587        //tab 3 - scaling data
588        TitleBox ScaleInstructions1 title="\Zr1201. Add data (double click)",size={330,15},pos={270,175},frame=0,fColor=(0,0,65535),labelBack=0
589        TitleBox ScaleInstructions2 title="\Zr1202. Tweak Scaling/background",size={330,15},pos={270,200},frame=0,fColor=(0,0,65535),labelBack=0
590        TitleBox ScaleInstructions3 title="\Zr1203. Data are saved automatically",size={330,15},pos={270,225},frame=0,fColor=(0,0,65535),labelBack=0
591
592        Button ScaleRangeOfData,pos={280,260},size={190,20}, proc=IRB1_DataManButtonProc,title="4. Scale & Save Selected Data", help={"Load and save selected data and save with _scaled in name"}
593
594        SetVariable DataScalingConstant,pos={280,340},size={220,15}, proc=IRB1_DataManSetVarProc,variable=root:Packages:Irena:BioSAXSDataMan:DataScalingConstant
595        NVAR TmpVal = root:Packages:Irena:BioSAXSDataMan:DataScalingConstant
596        SetVariable DataScalingConstant, title="Data Scaling :                  ", limits={0,inf,IRB1_SetVariableStepScaling*TmpVal}
597
598        SetVariable ErrorScalingConstant,pos={280,370},size={220,15}, proc=IRB1_DataManSetVarProc,variable=root:Packages:Irena:BioSAXSDataMan:ErrorScalingConstant
599        NVAR TmpVal = root:Packages:Irena:BioSAXSDataMan:ErrorScalingConstant
600        SetVariable ErrorScalingConstant, title="Error Scaling :                 ", limits={0,inf,IRB1_SetVariableStepScaling*TmpVal}
601
602        SetVariable FlatBackgroundSubtract,pos={280,400},size={220,15}, proc=IRB1_DataManSetVarProc,variable=root:Packages:Irena:BioSAXSDataMan:FlatBackgroundSubtract
603        NVAR TmpVal = root:Packages:Irena:BioSAXSDataMan:FlatBackgroundSubtract
604        SetVariable FlatBackgroundSubtract, title="Flat background subtract :   ", limits={-inf,inf,IRB1_SetVariableStepScaling*TmpVal}
605
606
607        ///*** end of tabs...
608        Display /W=(521,10,1183,750) /HOST=# /N=LogLogDataDisplay
609        SetActiveSubwindow ##
610                        //      Display /W=(521,350,1183,410) /HOST=# /N=ResidualDataDisplay
611                        //      SetActiveSubwindow ##
612                        //      Display /W=(521,420,1183,750) /HOST=# /N=LinearizedDataDisplay
613                        //      SetActiveSubwindow ##
614
615
616        SetVariable SleepBetweenDataProcesses,pos={275,640},size={220,15}, noproc,variable=root:Packages:Irena:BioSAXSDataMan:SleepBetweenDataProcesses
617        SetVariable SleepBetweenDataProcesses, title="Sleep between data sets", limits={0.0,30,1}
618
619        Checkbox OverwriteExistingData, pos={320,670},size={76,14},title="Overwrite Ouput?", noproc, variable=root:Packages:Irena:BioSAXSDataMan:OverwriteExistingData
620        Checkbox DisplayErrorBars, pos={320,695},size={76,14},title="Display Error Bars", proc=IRB1_CheckProc, variable=root:Packages:Irena:BioSAXSDataMan:DisplayErrorBars
621        Button AutoScaleGraph,pos={280,720},size={190,20}, proc=IRB1_DataManButtonProc,title="Autoscale Graph", help={"Autoscale the graph axes"}
622
623        TitleBox Instructions1 title="\Zr100Double click to add data to graph",size={330,15},pos={4,680},frame=0,fColor=(0,0,65535),labelBack=0
624        TitleBox Instructions2 title="\Zr100Shift-click to select range of data",size={330,15},pos={4,695},frame=0,fColor=(0,0,65535),labelBack=0
625        TitleBox Instructions3 title="\Zr100Ctrl/Cmd-click to select one data set",size={330,15},pos={4,710},frame=0,fColor=(0,0,65535),labelBack=0
626        TitleBox Instructions4 title="\Zr100Regex for not contain: ^((?!string).)*$",size={330,15},pos={4,725},frame=0,fColor=(0,0,65535),labelBack=0
627        TitleBox Instructions5 title="\Zr100Regex for contain:  string, two: str2.*str1",size={330,15},pos={4,740},frame=0,fColor=(0,0,65535),labelBack=0
628        TitleBox Instructions6 title="\Zr100Regex for case independent:  (?i)string",size={330,15},pos={4,755},frame=0,fColor=(0,0,65535),labelBack=0
629       
630        //and set the tab control to tab=0
631        STRUCT WMTabControlAction TempTCA
632        TempTCA.eventcode=2
633        TempTCA.tab=0
634        IRB1_DataManTabProc(TempTCA)
635end
636//**********************************************************************************************************
637//**********************************************************************************************************
638//**********************************************************************************************************
639
640Function IRB1_DataManTabProc(tca) : TabControl
641        STRUCT WMTabControlAction &tca
642
643        switch( tca.eventCode )
644                case 2: // mouse up
645                        IN2G_PrintDebugStatement(IrenaDebugLevel, 3,"Calling Tabcontrol procedure")
646                        SVAR DataMatchString = root:Packages:Irena:BioSAXSDataMan:DataMatchString
647                        NVAR InvertGrepSearch = root:Packages:Irena:BioSAXSDataMan:InvertGrepSearch
648                        Variable tab = tca.tab
649                        //tab 0
650                                Button SelectAllData,win=IRB1_DataManipulationPanel, disable=(tab!=0)
651                                Button PlotSelectedData,win=IRB1_DataManipulationPanel, disable=(tab!=0)
652                                TitleBox AverageInstructions,win=IRB1_DataManipulationPanel, disable=(tab!=0)
653                                Button AverageData,win=IRB1_DataManipulationPanel, disable=(tab!=0)
654                                Button ClearGraph,win=IRB1_DataManipulationPanel, disable=(tab!=0 && tab!=2)
655                                TitleBox AverageInstructions2,win=IRB1_DataManipulationPanel, disable=(tab!=0)
656                                SetVariable AverageOutputFolderString,win=IRB1_DataManipulationPanel, disable=(tab!=0)
657                        //tab 1
658                                TitleBox AverageInstructions3,win=IRB1_DataManipulationPanel, disable=(tab!=1)
659                                PopupMenu SelectBufferData,win=IRB1_DataManipulationPanel, disable=(tab!=1)
660                                SetVariable BufferScalingFraction,win=IRB1_DataManipulationPanel, disable=(tab!=1)
661                                Button SubtractBuffer,win=IRB1_DataManipulationPanel, disable=(tab!=1)
662                                Button SubtractBufferMany,win=IRB1_DataManipulationPanel, disable=(tab!=1)
663                                TitleBox AverageInstructions4 ,win=IRB1_DataManipulationPanel, disable=(tab!=1)
664                                TitleBox AverageInstructions5 ,win=IRB1_DataManipulationPanel, disable=(tab!=1)
665                                TitleBox AverageInstructions6 ,win=IRB1_DataManipulationPanel, disable=(tab!=1)
666                                TitleBox AverageInstructions7 ,win=IRB1_DataManipulationPanel, disable=(tab!=1)
667                                TitleBox AverageInstructions8 ,win=IRB1_DataManipulationPanel, disable=(tab!=1)
668                                TitleBox AverageInstructions9 ,win=IRB1_DataManipulationPanel, disable=(tab!=1)
669                                SetVariable SubtractedOutputFldrName,win=IRB1_DataManipulationPanel, disable=(tab!=1)
670                                SetVariable UserBufferDataFolderName,win=IRB1_DataManipulationPanel, disable=(tab!=1)
671                                SetVariable UserSourceDataFolderName,win=IRB1_DataManipulationPanel, disable=(tab!=1)
672                        //tab 2
673                                TitleBox ScaleInstructions1,win=IRB1_DataManipulationPanel, disable=(tab!=2)
674                                TitleBox ScaleInstructions2,win=IRB1_DataManipulationPanel, disable=(tab!=2)
675                                TitleBox ScaleInstructions3,win=IRB1_DataManipulationPanel, disable=(tab!=2)
676                                SetVariable DataScalingConstant,win=IRB1_DataManipulationPanel, disable=(tab!=2)
677                                SetVariable ErrorScalingConstant,win=IRB1_DataManipulationPanel, disable=(tab!=2)
678                                Button ScaleRangeOfData,win=IRB1_DataManipulationPanel, disable=(tab!=2)
679                                SetVariable FlatBackgroundSubtract,win=IRB1_DataManipulationPanel, disable=(tab!=2)
680                               
681                        //other stuff, clear teh graph
682                                //IRB1_DataManRemoveAllDataSets()
683                                IN2G_RemoveDataFromGraph(topGraphStr = "IRB1_DataManipulationPanel#LogLogDataDisplay")
684                        //set controls for names
685                        if(tab==1)
686                                InvertGrepSearch = 0
687                                DataMatchString="ave"
688                        elseif(tab==0)
689                                InvertGrepSearch = 1
690                                DataMatchString="ave|sub"
691                        elseif(tab==2)
692                                InvertGrepSearch = 0
693                                DataMatchString=""
694                        endif
695                       
696                                IR3C_MultiUpdateListOfAvailFiles("Irena:BioSAXSDataMan")
697                        break
698                case -1: // control being killed
699                        break
700        endswitch
701
702        return 0
703End
704//**********************************************************************************************************
705//**********************************************************************************************************
706//**********************************************************************************************************
707
708Function IRB1_DataManButtonProc(ba) : ButtonControl
709        STRUCT WMButtonAction &ba
710
711        switch( ba.eventCode )
712                case 2: // mouse up
713                        // click code here
714                        if(stringMatch(ba.ctrlName,"PlotSelectedData"))
715                                IRB1_DataManAppendSelectedDataSets()
716                        endif
717                        if(stringMatch(ba.ctrlName,"AverageData"))
718                                IRB1_DataManAverageDataSetsts()
719                        endif//
720
721                        if(stringMatch(ba.ctrlName,"SelectAllData"))
722                                Wave SelectionOfAvailableData = root:Packages:Irena:BioSAXSDataMan:SelectionOfAvailableData     
723                                SelectionOfAvailableData = 1
724                        endif
725                        if(stringMatch(ba.ctrlName,"ClearGraph"))
726                                IN2G_RemoveDataFromGraph(topGraphStr = "IRB1_DataManipulationPanel#LogLogDataDisplay")
727                        endif
728                        if(stringMatch(ba.ctrlName,"AutoScaleGraph"))
729                                SetAxis/W=IRB1_DataManipulationPanel#LogLogDataDisplay /A
730                        endif
731                        if(stringMatch(ba.ctrlName,"SubtractBuffer"))
732                                IRB1_DataManSubtractBufferOne()
733                        endif
734                        if(stringMatch(ba.ctrlName,"SubtractBufferMany"))
735                                IRB1_DataManSubtractBufferMany()
736                        endif
737                        if(stringMatch(ba.ctrlName,"ScaleRangeOfData"))
738                                IRB1_DataManScaleMany()
739                        endif
740                        if(stringmatch(ba.ctrlName,"GetHelp"))
741                                IN2G_OpenWebManual("Irena/ImportData.html")                             //fix me!!                     
742                        endif
743
744                        break
745                case -1: // control being killed
746                        break
747        endswitch
748
749        return 0
750End
751//**********************************************************************************************************
752//**********************************************************************************************************
753//**********************************************************************************************************
754
755Function IRB1_DataManSetVarProc(sva) : SetVariableControl
756        STRUCT WMSetVariableAction &sva
757
758        switch( sva.eventCode )
759                case 1: // mouse up
760                case 2: // Enter key
761                case 3: // Live update
762                        Variable dval = sva.dval
763                        String sval = sva.sval
764                        if(StringMatch(sva.CtrlName, "DataScalingConstant"))
765                                NVAR TmpVal = root:Packages:Irena:BioSAXSDataMan:DataScalingConstant
766                                SetVariable DataScalingConstant,win=IRB1_DataManipulationPanel, limits={0,inf,IRB1_SetVariableStepScaling*TmpVal}
767                                //and here call recalculate the curves....
768                                IRB1_DataManScaleDataOne()
769                        endif
770                        if(StringMatch(sva.CtrlName, "ErrorScalingConstant"))
771                                NVAR TmpVal = root:Packages:Irena:BioSAXSDataMan:ErrorScalingConstant
772                                SetVariable ErrorScalingConstant,win=IRB1_DataManipulationPanel, limits={0,inf,IRB1_SetVariableStepScaling*TmpVal}
773                                //and here call recalculate the curves....
774                                IRB1_DataManScaleDataOne()
775                        endif
776                        if(StringMatch(sva.CtrlName, "FlatBackgroundSubtract"))
777                                NVAR TmpVal = root:Packages:Irena:BioSAXSDataMan:FlatBackgroundSubtract
778                                SetVariable FlatBackgroundSubtract,win=IRB1_DataManipulationPanel, limits={0,inf,IRB1_SetVariableStepScaling*TmpVal}
779                                //and here call recalculate the curves....
780                                IRB1_DataManScaleDataOne()
781                        endif
782                       
783                       
784                        break
785                case -1: // control being killed
786                        break
787        endswitch
788
789        return 0
790End
791//**********************************************************************************************************
792//**********************************************************************************************************
793//**********************************************************************************************************
794//
795//static Function IRB1_DataManRemoveAllDataSets()
796//
797//      IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
798//      DfRef OldDf=GetDataFolderDFR()
799//      setDataFolder root:Packages:Irena:BioSAXSDataMan
800//      variable i, numTraces
801//      string TraceNames
802//     
803//      TraceNames= TraceNameList("IRB1_DataManipulationPanel#LogLogDataDisplay",";",3)
804//      numTraces = ItemsInList(TraceNames)
805//      //remove all traces...
806//      For(i=0;i<numTraces;i+=1)
807//              RemoveFromGraph/W=IRB1_DataManipulationPanel#LogLogDataDisplay /Z $(StringFromList(i,TraceNames))
808//      endfor
809//
810//end
811//**********************************************************************************************************
812//**********************************************************************************************************
813//**********************************************************************************************************
814
815static Function IRB1_DataManAverageDataSetsts()
816
817        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
818        DfRef OldDf=GetDataFolderDFR()
819        setDataFolder root:Packages:Irena:BioSAXSDataMan
820        variable i, numTraces
821        string TraceNames, NewNote
822       
823        TraceNames= TraceNameList("IRB1_DataManipulationPanel#LogLogDataDisplay",";",3)
824        TraceNames=GrepList(TraceNames, "_ave",1 , ";" )                                                                                        //this removes any _ave waves which user may have generated by multiple push of the button.
825        NewNote = "Averaged Data;"+date()+";"+time()+";List of Data waves="+TraceNames
826        numTraces = ItemsInList(TraceNames)
827        //create needed lists first...
828        make/Free/T/N=(numTraces) FldrNamesTWv
829        make/Free/N=(numTraces) SelFldrs
830        SelFldrs = 1
831        string TempStrName
832        string Xtmplt,Ytmplt,Etmplt,OutFldrNm,OutXWvNm, OutYWvNm,OutEWvNm
833        variable UseStdDev,UseSEM, UseMinMax, PropagateErrors
834
835        //build the lists of folders...
836        make/WAVE/N=(numTraces)/Free  wr
837        For(i=0;i<numTraces;i+=1)
838                wr[i] = TraceNameToWaveRef("IRB1_DataManipulationPanel#LogLogDataDisplay", StringFromList(i,TraceNames))
839        endfor
840        FldrNamesTWv = GetWavesDataFolder(wr[p], 1)
841        //take first folder name, append the user appendix and create new strings here...
842        string FirstFolderShortName=StringFromList(ItemsInList(FldrNamesTWv[0], ":")-1, FldrNamesTWv[0], ":")
843        string OutputWaveNameMain = RemoveListItem(ItemsInList(FirstFolderShortName,"_")-1, FirstFolderShortName, "_") +"ave"
844        OutYWvNm = "r_"+OutputWaveNameMain
845        OutEWvNm = "s_"+OutputWaveNameMain
846        OutXWvNm = "q_"+OutputWaveNameMain
847        string FullPathToFirstFolder = FldrNamesTWv[numpnts(FldrNamesTWv)-1]
848        string OldFolderName = StringFromList(ItemsInList(FullPathToFirstFolder,":")-1, FullPathToFirstFolder, ":")
849        FullPathToFirstFolder  = ReplaceString(OldFOlderName, FullPathToFirstFolder, OutputWaveNameMain)
850        OutFldrNm = FullPathToFirstFolder       
851        Xtmplt = "(?i)q_"
852        Ytmplt = "(?i)r_"
853        Etmplt = "(?i)s_"
854        UseStdDev = 1
855        UseSEM = 0
856        PropagateErrors = 0
857        UseMinMax = 0
858        IR3M_AverageMultipleWaves(FldrNamesTWv,SelFldrs,Xtmplt,Ytmplt,Etmplt,UseStdDev,UseSEM, UseMinMax, PropagateErrors)     
859        Wave AveragedDataXwave = root:Packages:DataManipulationII:AveragedDataXwave
860        Wave AveragedDataYwave = root:Packages:DataManipulationII:AveragedDataYwave
861        Wave AveragedDataEwave = root:Packages:DataManipulationII:AveragedDataEwave
862        NVAR Overwrite=root:Packages:Irena:BioSAXSDataMan:OverwriteExistingData
863
864        //and now I need to save the data
865        if(DataFolderExists(OutFldrNm)&&!Overwrite)
866                DoAlert /T="Folder for Average data exists" 1, "Folder "+OutFldrNm+" exists, do you want to overwrite?"
867                if(V_Flag!=1)
868                        abort
869                endif
870        endif
871        NewDataFolder/O/S $(RemoveEnding(OutFldrNm , ":") )
872        Duplicate/O AveragedDataXwave, $(OutXWvNm)
873        Duplicate/O AveragedDataYwave, $(OutYWvNm)
874        Duplicate/O AveragedDataEwave, $(OutEWvNm)
875        Wave NewAveXWave = $(OutXWvNm)
876        Wave NewAveYWave = $(OutYWvNm)
877        Wave NewAveEWave = $(OutEWvNm)
878        Note /K/NOCR NewAveXWave, NewNote
879        Note /K/NOCR NewAveYWave, NewNote
880        Note /K/NOCR NewAveEWave, NewNote
881        Print "Created averaged data set in:"+OutFldrNm +"\r       Averaged following data sets:"+TraceNames
882        CheckDisplayed /W=IRB1_DataManipulationPanel#LogLogDataDisplay $(nameOfWave(NewAveYWave))
883        if(V_Flag!=1)
884                AppendToGraph /W=IRB1_DataManipulationPanel#LogLogDataDisplay  NewAveYWave  vs NewAveXWave
885                ErrorBars/T=2/L=2 /W=IRB1_DataManipulationPanel#LogLogDataDisplay $(NameOfWave(NewAveYWave)) Y,wave=(NewAveEWave,NewAveEWave)
886                ModifyGraph /W=IRB1_DataManipulationPanel#LogLogDataDisplay lstyle($(NameOfWave(NewAveYWave)))=3,lsize($(NameOfWave(NewAveYWave)))=3,rgb($(NameOfWave(NewAveYWave)))=(0,0,0)
887        endif
888        //IN2G_ColorTopGrphRainbow(topGraphStr="IRB1_DataManipulationPanel#LogLogDataDisplay")
889        IN2G_LegendTopGrphFldr(12, 20, 1, 0, topGraphStr="IRB1_DataManipulationPanel#LogLogDataDisplay")
890        //NVAR DisplayErrorBars = root:Packages:Irena:BioSAXSDataMan:DisplayErrorBars
891        //IN2G_ShowHideErrorBars(DisplayErrorBars, topGraphStr="IRB1_DataManipulationPanel#LogLogDataDisplay")
892        DoUpdate
893        setDataFOlder oldDf
894end
895//**********************************************************************************************************
896//**********************************************************************************************************
897//**********************************************************************************************************
898//**********************************************************************************************************
899Function IRB1_DataManAppendSelectedDataSets()
900
901        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
902        variable i
903        string FoldernameStr
904        PauseUpdate
905        IN2G_RemoveDataFromGraph(topGraphStr = "IRB1_DataManipulationPanel#LogLogDataDisplay")
906        Wave/T ListOfAvailableData = root:Packages:Irena:BioSAXSDataMan:ListOfAvailableData
907        Wave SelectionOfAvailableData = root:Packages:Irena:BioSAXSDataMan:SelectionOfAvailableData     
908        for(i=0;i<numpnts(ListOfAvailableData);i+=1)
909                if(SelectionOfAvailableData[i]>0.5)
910                        IRB1_DataManAppendOneDataSet(ListOfAvailableData[i])
911                endif
912        endfor
913        IN2G_ColorTopGrphRainbow(topGraphStr="IRB1_DataManipulationPanel#LogLogDataDisplay")
914        IN2G_LegendTopGrphFldr(12, 20, 1, 0, topGraphStr="IRB1_DataManipulationPanel#LogLogDataDisplay")
915        NVAR DisplayErrorBars = root:Packages:Irena:BioSAXSDataMan:DisplayErrorBars
916        IN2G_ShowHideErrorBars(DisplayErrorBars, topGraphStr="IRB1_DataManipulationPanel#LogLogDataDisplay")
917        DoUpdate
918
919end
920
921//**********************************************************************************************************
922//**********************************************************************************************************
923//**************************************************************************************
924Function IRB1_DataManAppendOneDataSet(FolderNameStr)
925        string FolderNameStr
926       
927        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
928        DfRef OldDf=GetDataFolderDFR()
929        SetDataFolder root:Packages:Irena:BioSAXSDataMan                                        //go into the folder
930        //IR3D_SetSavedNotSavedMessage(0)
931        //figure out if we are doing averaging or buffer subtraction
932        ControlInfo /W=IRB1_DataManipulationPanel ProcessingTabs
933        variable UsingAveraging=0
934        variable Subtracting=0
935        variable Scaling=0
936        if(V_Value==0)
937                UsingAveraging=1
938        elseif(V_Value==1)
939                Subtracting=1                   //buffer subtraction
940        elseif(V_Value==2)
941                Scaling=1                                       //scaling data         
942        endif
943        SVAR DataStartFolder=root:Packages:Irena:BioSAXSDataMan:DataStartFolder
944        SVAR DataFolderName=root:Packages:Irena:BioSAXSDataMan:DataFolderName
945        SVAR IntensityWaveName=root:Packages:Irena:BioSAXSDataMan:IntensityWaveName
946        SVAR QWavename=root:Packages:Irena:BioSAXSDataMan:QWavename
947        SVAR ErrorWaveName=root:Packages:Irena:BioSAXSDataMan:ErrorWaveName
948        SVAR dQWavename=root:Packages:Irena:BioSAXSDataMan:dQWavename
949        NVAR UseIndra2Data=root:Packages:Irena:BioSAXSDataMan:UseIndra2Data
950        NVAR UseQRSdata=root:Packages:Irena:BioSAXSDataMan:UseQRSdata
951        //these are variables used by the control procedure
952        NVAR UseResults=  root:Packages:Irena:BioSAXSDataMan:UseResults
953        NVAR UseUserDefinedData=  root:Packages:Irena:BioSAXSDataMan:UseUserDefinedData
954        NVAR UseModelData = root:Packages:Irena:BioSAXSDataMan:UseModelData
955
956        SVAR AverageOutputFolderString = root:Packages:Irena:BioSAXSDataMan:AverageOutputFolderString
957        SVAR SubtractedOutputFldrName=root:Packages:Irena:BioSAXSDataMan:SubtractedOutputFldrName
958        SVAR UserSourceDataFolderName=root:Packages:Irena:BioSAXSDataMan:UserSourceDataFolderName
959        UseResults = 0
960        UseUserDefinedData = 0
961        UseModelData = 0
962        //get the names of waves, assume this tool actually works. May not under some conditions. In that case this tool will not work.
963        string tempStr
964        if(ItemsInList(FolderNameStr, ":")>1)
965                tempStr=StringFromList(ItemsInList(FolderNameStr, ":")-1, FolderNameStr, ":")
966        else
967                tempStr = FolderNameStr
968        endif
969        AverageOutputFolderString = RemoveListItem(ItemsInList(tempStr,"_")-1, tempStr, "_") +"ave"
970        IR3C_SelectWaveNamesData("Irena:BioSAXSDataMan", FolderNameStr)                 //this routine will preset names in strings as needed,
971//      DataFolderName = DataStartFolder+FolderNameStr
972//      QWavename = stringFromList(0,IR2P_ListOfWaves("Xaxis","", "IRB1_DataManipulationPanel"))
973//      IntensityWaveName = stringFromList(0,IR2P_ListOfWaves("Yaxis","*", "IRB1_DataManipulationPanel"))
974//      ErrorWaveName = stringFromList(0,IR2P_ListOfWaves("Error","*", "IRB1_DataManipulationPanel"))
975//      if(UseIndra2Data)
976//              dQWavename = ReplaceString("Qvec", QWavename, "dQ")
977//      elseif(UseQRSdata)
978//              dQWavename = "w"+QWavename[1,31]
979//      else
980//              dQWavename = ""
981//      endif
982        Wave/Z SourceIntWv=$(DataFolderName+IntensityWaveName)
983        Wave/Z SourceQWv=$(DataFolderName+QWavename)
984        Wave/Z SourceErrorWv=$(DataFolderName+ErrorWaveName)
985        Wave/Z SourcedQWv=$(DataFolderName+dQWavename)
986        if(!WaveExists(SourceIntWv)||   !WaveExists(SourceQWv)||!WaveExists(SourceErrorWv))
987                Abort "Data selection failed for Data"
988        endif
989        if(Subtracting)         //subtracting buffer from ave data or scaling data, in each case, must remove the existing files.
990                //preset for user output name for merged data
991                UserSourceDataFolderName = StringFromList(ItemsInList(FolderNameStr, ":")-1, FolderNameStr, ":")
992                SubtractedOutputFldrName = ReplaceString("_ave", UserSourceDataFolderName, "_sub")
993                //remove, if needed, all data from graph
994                IN2G_RemoveDataFromGraph(topGraphStr = "IRB1_DataManipulationPanel#LogLogDataDisplay")
995                //append Buffer data if exist...
996                Wave/Z q_BufferData = q_BufferData
997                Wave/Z r_BufferData = r_BufferData
998                Wave/Z s_BufferData = s_BufferData
999                if(WaveExists(r_BufferData) || WaveExists(q_BufferData) || WaveExists(s_BufferData))
1000                        //and check the data are in the graph, else it willconfuse user.
1001                        CheckDisplayed /W=IRB1_DataManipulationPanel#LogLogDataDisplay r_BufferData
1002                        if(V_Flag!=1)
1003                                AppendToGraph /W=IRB1_DataManipulationPanel#LogLogDataDisplay  r_BufferData  vs q_BufferData
1004                                ErrorBars/T=2/L=2 /W=IRB1_DataManipulationPanel#LogLogDataDisplay r_BufferData Y,wave=(s_BufferData,s_BufferData)
1005                                ModifyGraph /W=IRB1_DataManipulationPanel#LogLogDataDisplay lstyle(r_BufferData)=3,lsize(r_BufferData)=3,rgb(r_BufferData)=(0,0,0)     
1006                        endif
1007                endif
1008        endif
1009        if(Scaling)
1010                //remove, if needed, all data from graph
1011                IN2G_RemoveDataFromGraph(topGraphStr = "IRB1_DataManipulationPanel#LogLogDataDisplay")
1012        endif
1013        CheckDisplayed /W=IRB1_DataManipulationPanel#LogLogDataDisplay SourceIntWv
1014        if(!V_flag)
1015                AppendToGraph /W=IRB1_DataManipulationPanel#LogLogDataDisplay  SourceIntWv  vs SourceQWv
1016                ModifyGraph /W=IRB1_DataManipulationPanel#LogLogDataDisplay log=1, mirror=1
1017                Label /W=IRB1_DataManipulationPanel#LogLogDataDisplay left "Intensity 1"
1018                Label /W=IRB1_DataManipulationPanel#LogLogDataDisplay bottom "Q [A\\S-1\\M]"
1019                ErrorBars /W=IRB1_DataManipulationPanel#LogLogDataDisplay $(NameOfWave(SourceIntWv)) Y,wave=(SourceErrorWv,SourceErrorWv)
1020        endif
1021        if(Scaling)             //in this case we can safely process data or user looks at graph with no change.
1022                IRB1_DataManScaleDataOne()
1023        endif
1024       
1025        IN2G_ColorTopGrphRainbow(topGraphStr="IRB1_DataManipulationPanel#LogLogDataDisplay")
1026        IN2G_LegendTopGrphFldr(12, 20, 1, 0, topGraphStr="IRB1_DataManipulationPanel#LogLogDataDisplay")
1027        NVAR DisplayErrorBars = root:Packages:Irena:BioSAXSDataMan:DisplayErrorBars
1028        IN2G_ShowHideErrorBars(DisplayErrorBars, topGraphStr="IRB1_DataManipulationPanel#LogLogDataDisplay")
1029        SetDataFolder oldDf
1030end
1031//**********************************************************************************************************
1032//**********************************************************************************************************
1033//**********************************************************************************************************
1034
1035static Function IRB1_DataManInitBioSAXS()       
1036
1037        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
1038        DfRef OldDf=GetDataFolderDFR()
1039        string ListOfVariables
1040        string ListOfStrings
1041        variable i
1042               
1043        if (!DataFolderExists("root:Packages:Irena:BioSAXSDataMan"))            //create folder
1044                NewDataFolder/O root:Packages
1045                NewDataFolder/O root:Packages:Irena
1046                NewDataFolder/O root:Packages:Irena:BioSAXSDataMan
1047        endif
1048        SetDataFolder root:Packages:Irena:BioSAXSDataMan                                        //go into the folder
1049
1050        //here define the lists of variables and strings needed, separate names by ;...
1051        ListOfStrings="DataFolderName;IntensityWaveName;QWavename;ErrorWaveName;dQWavename;DataUnits;"
1052        ListOfStrings+="DataStartFolder;DataMatchString;FolderSortString;FolderSortStringAll;"
1053        ListOfStrings+="UserMessageString;SavedDataMessage;UserSourceDataFolderName;UserBufferDataFolderName;"
1054        ListOfStrings+="AverageOutputFolderString;SelectedBufferFolder;SubtractedOutputFldrName;"
1055
1056        ListOfVariables="UseIndra2Data1;UseQRSdata1;DisplayErrorBars;"
1057        ListOfVariables+="OverwriteExistingData;SleepBetweenDataProcesses;"
1058        ListOfVariables+="BufferScalingFraction;DataQEnd;DataQstart;"
1059        ListOfVariables+="DataScalingConstant;ErrorScalingConstant;FlatBackgroundSubtract;"
1060
1061        //and here we create them
1062        for(i=0;i<itemsInList(ListOfVariables);i+=1)   
1063                IN2G_CreateItem("variable",StringFromList(i,ListOfVariables))
1064        endfor         
1065                                                               
1066        for(i=0;i<itemsInList(ListOfStrings);i+=1)     
1067                IN2G_CreateItem("string",StringFromList(i,ListOfStrings))
1068        endfor 
1069
1070        ListOfStrings="DataFolderName;IntensityWaveName;QWavename;ErrorWaveName;dQWavename;"
1071//      ListOfStrings+="NewDataFolderName;NewIntensityWaveName;NewQWavename;NewErrorWaveName;"
1072        for(i=0;i<itemsInList(ListOfStrings);i+=1)     
1073                SVAR teststr=$(StringFromList(i,ListOfStrings))
1074                teststr =""
1075        endfor         
1076        ListOfStrings="DataMatchString;FolderSortString;FolderSortStringAll;"
1077        for(i=0;i<itemsInList(ListOfStrings);i+=1)     
1078                SVAR teststr=$(StringFromList(i,ListOfStrings))
1079                if(strlen(teststr)<1)
1080                        teststr =""
1081                endif
1082        endfor         
1083        ListOfStrings="DataStartFolder;"
1084        for(i=0;i<itemsInList(ListOfStrings);i+=1)     
1085                SVAR teststr=$(StringFromList(i,ListOfStrings))
1086                if(strlen(teststr)<1)
1087                        teststr ="root:"
1088                endif
1089        endfor         
1090        SVAR SelectedBufferFolder
1091        if(strlen(SelectedBufferFolder)<2)
1092                SelectedBufferFolder = "---"
1093        endif
1094        NVAR BufferScalingFraction
1095        if(BufferScalingFraction<0.001)
1096                BufferScalingFraction = 1
1097        endif
1098        NVAR DataScalingConstant
1099        NVAR ErrorScalingConstant
1100        if(DataScalingConstant<1e-30)
1101                DataScalingConstant=1
1102        endif
1103        if(ErrorScalingConstant<1e-30)
1104                ErrorScalingConstant=1
1105        endif
1106        NVAR SleepBetweenDataProcesses
1107        if(SleepBetweenDataProcesses<0.1)
1108                SleepBetweenDataProcesses = 2
1109        endif
1110       
1111        Make/O/T/N=(0) ListOfAvailableData
1112        Make/O/N=(0) SelectionOfAvailableData
1113        SetDataFolder oldDf
1114
1115end
1116//**************************************************************************************
1117//**************************************************************************************
1118//**************************************************************************************
1119//cannot be static, called from panel.
1120Function/T IRB1_ListBufferScans()
1121
1122        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
1123        String AllDataFolders
1124        AllDataFolders=IR3C_MultiGenStringOfFolders("Irena:BioSAXSDataMan", "root:",0, 1,0, 0,1)
1125        //seelct only AVeraged data.
1126        AllDataFolders = GrepList(AllDataFolders, "ave", 0)
1127       
1128        return AllDataFolders
1129end
1130//**********************************************************************************************************
1131//**********************************************************************************************************
1132//**********************************************************************************************************
1133
1134Function IRB1_SetVarProc(sva) : SetVariableControl
1135        STRUCT WMSetVariableAction &sva
1136
1137        switch( sva.eventCode )
1138                case 1: // mouse up
1139                case 2: // Enter key
1140                case 3: // Live update
1141                        Variable dval = sva.dval
1142                        String sval = sva.sval
1143                        if(stringmatch(sva.ctrlName,"BufferScalingFraction"))
1144                                NVAR BufferScalingFraction = root:Packages:Irena:BioSAXSDataMan:BufferScalingFraction
1145                                IRB1_DataManCopyAndScaleBuffer()
1146                        endif
1147                       
1148                        break
1149                case -1: // control being killed
1150                        break
1151        endswitch
1152
1153        return 0
1154End
1155//**********************************************************************************************************
1156//**********************************************************************************************************
1157//**********************************************************************************************************
1158
1159Function IRB1_PopMenuProc(pa) : PopupMenuControl
1160        STRUCT WMPopupAction &pa
1161
1162        switch( pa.eventCode )
1163                case 2: // mouse up
1164                        Variable popNum = pa.popNum
1165                        String popStr = pa.popStr
1166                        if(stringmatch(pa.ctrlName,"SelectBufferData"))
1167                                SVAR SelectedBufferFolder = root:Packages:Irena:BioSAXSDataMan:SelectedBufferFolder
1168                                SelectedBufferFolder = popStr
1169                                IRB1_DataManCopyAndScaleBuffer()
1170                        endif
1171                       
1172                        break
1173                case -1: // control being killed
1174                        break
1175        endswitch
1176
1177        return 0
1178End
1179///******************************************************************************************
1180///******************************************************************************************
1181///******************************************************************************************
1182
1183static Function IRB1_DataManCopyAndScaleBuffer()
1184
1185        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
1186        DfRef OldDf=GetDataFolderDFR()
1187        SetDataFolder root:Packages:Irena:BioSAXSDataMan:
1188        SVAR SelectedBufferFolder = root:Packages:Irena:BioSAXSDataMan:SelectedBufferFolder
1189        NVAR BufferScalingFraction = root:Packages:Irena:BioSAXSDataMan:BufferScalingFraction
1190        SVAR UserBufferDataFolderName = root:Packages:Irena:BioSAXSDataMan:UserBufferDataFolderName
1191       
1192        string XwaveNameStr = SelectedBufferFolder+"q_"+StringFromList(ItemsInList(SelectedBufferFolder,":")-1, SelectedBufferFolder, ":")
1193        string YwaveNameStr = SelectedBufferFolder+"r_"+StringFromList(ItemsInList(SelectedBufferFolder,":")-1, SelectedBufferFolder, ":")
1194        string EwaveNameStr = SelectedBufferFolder+"s_"+StringFromList(ItemsInList(SelectedBufferFolder,":")-1, SelectedBufferFolder, ":")
1195       
1196        Wave/Z Xwave = $(XwaveNameStr)
1197        Wave/Z Ywave = $(YwaveNameStr)
1198        Wave/Z Ewave = $(EwaveNameStr)
1199        if(!WaveExists(XWave) || !WaveExists(YWave) || !WaveExists(EWave))
1200                ABort "Buffer wave selection failed"
1201        endif
1202       
1203        Duplicate/O Xwave, q_BufferData
1204        Duplicate/O Ywave, r_BufferData
1205        Duplicate/O Ewave, s_BufferData
1206       
1207        Wave q_BufferData = q_BufferData
1208        Wave r_BufferData = r_BufferData
1209        Wave s_BufferData = s_BufferData
1210       
1211        r_BufferData*=BufferScalingFraction
1212        s_BufferData*=BufferScalingFraction
1213
1214        CheckDisplayed /W=IRB1_DataManipulationPanel#LogLogDataDisplay r_BufferData
1215        if(V_Flag!=1)
1216                AppendToGraph /W=IRB1_DataManipulationPanel#LogLogDataDisplay  r_BufferData  vs q_BufferData
1217                ErrorBars/T=2/L=2 /W=IRB1_DataManipulationPanel#LogLogDataDisplay r_BufferData Y,wave=(s_BufferData,s_BufferData)
1218                ModifyGraph /W=IRB1_DataManipulationPanel#LogLogDataDisplay lstyle(r_BufferData)=3,lsize(r_BufferData)=3,rgb(r_BufferData)=(0,0,0)     
1219                ModifyGraph /W=IRB1_DataManipulationPanel#LogLogDataDisplay log=1, mirror=1
1220        endif
1221        UserBufferDataFolderName = StringFromList(ItemsInList(SelectedBufferFolder, ":")-1, SelectedBufferFolder, ":")
1222        NVAR DisplayErrorBars = root:Packages:Irena:BioSAXSDataMan:DisplayErrorBars
1223        IN2G_ShowHideErrorBars(DisplayErrorBars, topGraphStr="IRB1_DataManipulationPanel#LogLogDataDisplay")
1224
1225        SetDataFolder OldDf
1226end
1227///******************************************************************************************
1228///******************************************************************************************
1229///******************************************************************************************
1230static Function IRB1_DataManSubtractBufferMany()
1231
1232        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
1233        DfRef OldDf=GetDataFolderDFR()
1234        SetDataFolder root:Packages:Irena:BioSAXSDataMan:
1235        IN2G_RemoveDataFromGraph(topGraphStr = "IRB1_DataManipulationPanel#LogLogDataDisplay")
1236        variable i
1237        Wave/T ListOfAvailableData = root:Packages:Irena:BioSAXSDataMan:ListOfAvailableData
1238        Wave SelectionOfAvailableData = root:Packages:Irena:BioSAXSDataMan:SelectionOfAvailableData     
1239        NVAR SleepBetweenDataProcesses = root:Packages:Irena:BioSAXSDataMan:SleepBetweenDataProcesses
1240        for(i=0;i<numpnts(ListOfAvailableData);i+=1)
1241                if(SelectionOfAvailableData[i]>0.5)
1242                        IRB1_DataManAppendOneDataSet(ListOfAvailableData[i])
1243                        IRB1_DataManSubtractBufferOne()
1244                        DoUpdate
1245                        sleep/S/C=6/M="Subtracted buffer for "+ListOfAvailableData[i] SleepBetweenDataProcesses
1246                endif
1247        endfor
1248        Print "Done subtracting buffer"
1249        SetDataFolder OldDf
1250end
1251//**********************************************************************************************************
1252//**********************************************************************************************************
1253//**********************************************************************************************************
1254
1255static Function IRB1_DataManScaleMany()
1256
1257        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
1258        DfRef OldDf=GetDataFolderDFR()
1259        SetDataFolder root:Packages:Irena:BioSAXSDataMan:
1260        IN2G_RemoveDataFromGraph(topGraphStr = "IRB1_DataManipulationPanel#LogLogDataDisplay")
1261        variable i
1262        Wave/T ListOfAvailableData = root:Packages:Irena:BioSAXSDataMan:ListOfAvailableData
1263        Wave SelectionOfAvailableData = root:Packages:Irena:BioSAXSDataMan:SelectionOfAvailableData     
1264        NVAR SleepBetweenDataProcesses = root:Packages:Irena:BioSAXSDataMan:SleepBetweenDataProcesses
1265        for(i=0;i<numpnts(ListOfAvailableData);i+=1)
1266                if(SelectionOfAvailableData[i]>0.5)
1267                        IRB1_DataManAppendOneDataSet(ListOfAvailableData[i])
1268                        IRB1_DataManScaleDataOne()
1269                        DoUpdate
1270                        sleep/S/C=6/M="Subtracted buffer for "+ListOfAvailableData[i] SleepBetweenDataProcesses
1271                endif
1272        endfor
1273        Print "Done subtracting buffer"
1274        SetDataFolder OldDf
1275end
1276///******************************************************************************************
1277///******************************************************************************************
1278///******************************************************************************************
1279
1280
1281static Function IRB1_DataManSubtractBufferOne()
1282
1283        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
1284        DfRef OldDf=GetDataFolderDFR()
1285        SetDataFolder root:Packages:Irena:BioSAXSDataMan:
1286        variable i, numTraces
1287        string TraceNames
1288        string OriginalDataNote, BufferDataNote
1289       
1290        SVAR SourceFolderName = root:Packages:Irena:BioSAXSDataMan:DataFolderName
1291        NVAR Overwrite=root:Packages:Irena:BioSAXSDataMan:OverwriteExistingData
1292
1293        string XwaveNameStr = SourceFolderName+"q_"+StringFromList(ItemsInList(SourceFolderName,":")-1, SourceFolderName, ":")
1294        string YwaveNameStr = SourceFolderName+"r_"+StringFromList(ItemsInList(SourceFolderName,":")-1, SourceFolderName, ":")
1295        string EwaveNameStr = SourceFolderName+"s_"+StringFromList(ItemsInList(SourceFolderName,":")-1, SourceFolderName, ":")
1296
1297        Wave/Z Xwave = $(XwaveNameStr)
1298        Wave/Z Ywave = $(YwaveNameStr)
1299        Wave/Z Ewave = $(EwaveNameStr)
1300        if(!WaveExists(XWave) || !WaveExists(YWave) || !WaveExists(EWave))
1301                ABort "Source wave selection failed"
1302        endif
1303
1304        Duplicate/O Xwave, q_SampleData
1305        Duplicate/O Ywave, r_SampleData
1306        Duplicate/O Ewave, s_SampleData
1307
1308        Wave q_SampleData = q_SampleData
1309        Wave r_SampleData = r_SampleData
1310        Wave s_SampleData = s_SampleData
1311        OriginalDataNote=note(r_SampleData)
1312        Wave/Z q_BufferData = q_BufferData
1313        Wave/Z r_BufferData = r_BufferData
1314        Wave/Z s_BufferData = s_BufferData
1315        if(!WaveExists(r_BufferData) || !WaveExists(q_BufferData) || !WaveExists(s_BufferData))
1316                ABort "Buffer waves Do not exist, seelct buffer first, then run again"
1317        endif
1318        BufferDataNote=note(r_BufferData)
1319        //and check the data are in the graph, else it willconfuse user.
1320        CheckDisplayed /W=IRB1_DataManipulationPanel#LogLogDataDisplay r_BufferData
1321        if(V_Flag!=1)
1322                AppendToGraph /W=IRB1_DataManipulationPanel#LogLogDataDisplay  r_BufferData  vs q_BufferData
1323                ErrorBars/T=2/L=2 /W=IRB1_DataManipulationPanel#LogLogDataDisplay r_BufferData Y,wave=(s_BufferData,s_BufferData)
1324                ModifyGraph /W=IRB1_DataManipulationPanel#LogLogDataDisplay lstyle(r_BufferData)=3,lsize(r_BufferData)=3,rgb(r_BufferData)=(0,0,0)     
1325        endif
1326       
1327        //do subtraction, thhere is not general procedrue in the Data manipulation...
1328        Duplicate/Free r_SampleData, ResultsInt, TempBufIntInterp2
1329        Duplicate/Free q_SampleData, ResultsQ, TempBuffEInterp2
1330        Duplicate/Free s_SampleData, ResultsE
1331        Duplicate/Free r_BufferData, TempIntLog2
1332        Duplicate/Free s_BufferData, TempELog2
1333        TempIntLog2=log(r_BufferData)
1334        TempELog2=log(s_BufferData)
1335        TempBufIntInterp2 = 10^(interp(q_SampleData, q_BufferData, TempIntLog2))
1336        TempBuffEInterp2 = 10^(interp(q_SampleData, q_BufferData, TempELog2))
1337        if (BinarySearch(ResultsQ, q_BufferData[0] )>0)
1338                TempBufIntInterp2[0,BinarySearch(ResultsQ, q_BufferData[0] )]=NaN
1339                TempBuffEInterp2[0,BinarySearch(ResultsQ, q_BufferData[0] )]=NaN
1340        endif
1341        if ((BinarySearch(ResultsQ, q_BufferData[numpnts(q_BufferData)-1] )!=numpnts(ResultsQ)-1)&&(BinarySearch(ResultsQ, q_BufferData[numpnts(q_BufferData)-1] )!=-2))
1342                TempBufIntInterp2[BinarySearch(ResultsQ, q_BufferData[numpnts(q_BufferData)-1])+1,inf]=Nan
1343                TempBuffEInterp2[BinarySearch(ResultsQ, q_BufferData[numpnts(q_BufferData)-1])+1,inf]=Nan
1344        endif
1345        ResultsInt = r_SampleData - TempBufIntInterp2
1346        ResultsE = sqrt(s_SampleData^2 + TempBuffEInterp2^2)
1347        IN2G_ReplaceNegValsByNaNWaves(ResultsInt,ResultsQ,ResultsE)
1348        IN2G_RemoveNaNsFrom3Waves(ResultsInt,ResultsQ,ResultsE)
1349
1350        String OutFldrNm, OutXWvNm, OutYWvNm,OutEWvNm
1351        OutFldrNm = ReplaceString("_ave", SourceFolderName, "_sub")
1352        string FirstFolderShortName=StringFromList(ItemsInList(OutFldrNm, ":")-1, OutFldrNm, ":")
1353        string OutputWaveNameMain = RemoveListItem(ItemsInList(FirstFolderShortName,"_")-1, FirstFolderShortName, "_") +"sub"
1354        OutYWvNm = "r_"+OutputWaveNameMain
1355        OutEWvNm = "s_"+OutputWaveNameMain
1356        OutXWvNm = "q_"+OutputWaveNameMain
1357        //and now I need to save the data
1358        if(DataFolderExists(OutFldrNm)&&!Overwrite)
1359                DoAlert /T="Folder for Subtracted data exists" 1, "Folder "+OutFldrNm+" exists, do you want to overwrite?"
1360                if(V_Flag!=1)
1361                        abort
1362                endif
1363        endif
1364        NewDataFolder/O/S $(RemoveEnding(OutFldrNm , ":") )
1365        Duplicate/O ResultsQ, $(OutXWvNm)
1366        Duplicate/O ResultsInt, $(OutYWvNm)
1367        Duplicate/O ResultsE, $(OutEWvNm)
1368        Wave NewSubtractedXWave = $(OutXWvNm)
1369        Wave NewSubtractedYWave = $(OutYWvNm)
1370        Wave NewSubtractedEWave = $(OutEWvNm)
1371        print "Subtracted buffer from "+SourceFolderName
1372        string NewNote
1373        SVAR BufferName=root:Packages:Irena:BioSAXSDataMan:UserBufferDataFolderName
1374        NewNote="Subtracted Buffer;"+date()+";"+time()+";Data Folder="+SourceFolderName+";Buffer Folder="+BufferName+";"
1375        NewNote+="DataNote:"+OriginalDataNote+";"
1376        NewNote+="BufferNote:"+BufferDataNote+";"
1377        Note /K/NOCR NewSubtractedYWave, NewNote
1378        Note /K/NOCR NewSubtractedXWave, NewNote
1379        Note /K/NOCR NewSubtractedEWave, NewNote
1380        CheckDisplayed /W=IRB1_DataManipulationPanel#LogLogDataDisplay $(NameOfWave(NewSubtractedYWave))
1381        if(V_Flag!=1)
1382                AppendToGraph /W=IRB1_DataManipulationPanel#LogLogDataDisplay  NewSubtractedYWave  vs NewSubtractedXWave
1383                ErrorBars/T=2/L=2 /W=IRB1_DataManipulationPanel#LogLogDataDisplay $(NameOfWave(NewSubtractedYWave)) Y,wave=(NewSubtractedEWave,NewSubtractedEWave)
1384                ModifyGraph /W=IRB1_DataManipulationPanel#LogLogDataDisplay lstyle($(NameOfWave(NewSubtractedYWave)))=3,lsize($(NameOfWave(NewSubtractedYWave)))=3,rgb($(NameOfWave(NewSubtractedYWave)))=(0,0,0)
1385                ModifyGraph /W=IRB1_DataManipulationPanel#LogLogDataDisplay rgb($(NameOfWave(NewSubtractedYWave)))=(0,0,65535)
1386        endif
1387        IN2G_ColorTopGrphRainbow(topGraphStr="IRB1_DataManipulationPanel#LogLogDataDisplay")
1388        IN2G_LegendTopGrphFldr(12, 20, 1, 0, topGraphStr="IRB1_DataManipulationPanel#LogLogDataDisplay")
1389        NVAR DisplayErrorBars = root:Packages:Irena:BioSAXSDataMan:DisplayErrorBars
1390        IN2G_ShowHideErrorBars(DisplayErrorBars, topGraphStr="IRB1_DataManipulationPanel#LogLogDataDisplay")
1391
1392        setDataFOlder oldDf
1393end
1394//**********************************************************************************************************
1395//**********************************************************************************************************
1396//**********************************************************************************************************
1397
1398static Function IRB1_DataManScaleDataOne()
1399
1400        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
1401        DfRef OldDf=GetDataFolderDFR()
1402        SetDataFolder root:Packages:Irena:BioSAXSDataMan:
1403        variable i, numTraces
1404        string TraceNames
1405        string OriginalDataNote, BufferDataNote
1406       
1407        SVAR SourceFolderName = root:Packages:Irena:BioSAXSDataMan:DataFolderName
1408        NVAR Overwrite=root:Packages:Irena:BioSAXSDataMan:OverwriteExistingData
1409        NVAR DataScalingConstant=root:Packages:Irena:BioSAXSDataMan:DataScalingConstant
1410        NVAR ErrorScalingConstant=root:Packages:Irena:BioSAXSDataMan:ErrorScalingConstant
1411        NVAR FlatBackgroundSubtract=root:Packages:Irena:BioSAXSDataMan:FlatBackgroundSubtract
1412
1413        string XwaveNameStr = SourceFolderName+"q_"+StringFromList(ItemsInList(SourceFolderName,":")-1, SourceFolderName, ":")
1414        string YwaveNameStr = SourceFolderName+"r_"+StringFromList(ItemsInList(SourceFolderName,":")-1, SourceFolderName, ":")
1415        string EwaveNameStr = SourceFolderName+"s_"+StringFromList(ItemsInList(SourceFolderName,":")-1, SourceFolderName, ":")
1416
1417        Wave/Z Xwave = $(XwaveNameStr)
1418        Wave/Z Ywave = $(YwaveNameStr)
1419        Wave/Z Ewave = $(EwaveNameStr)
1420        if(!WaveExists(XWave) || !WaveExists(YWave) || !WaveExists(EWave))
1421                ABort "Source wave selection failed"
1422        endif
1423
1424        Duplicate/O Xwave, q_SampleData
1425        Duplicate/O Ywave, r_SampleData
1426        Duplicate/O Ewave, s_SampleData
1427
1428        Wave q_SampleData = q_SampleData
1429        Wave r_SampleData = r_SampleData
1430        Wave s_SampleData = s_SampleData
1431        OriginalDataNote=note(r_SampleData)
1432        Duplicate/Free r_SampleData, ResultsInt
1433        Duplicate/Free q_SampleData, ResultsQ
1434        Duplicate/Free s_SampleData, ResultsE
1435        //process the data
1436        ResultsInt = DataScalingConstant * (r_SampleData -FlatBackgroundSubtract)
1437        ResultsE = ErrorScalingConstant * s_SampleData
1438       
1439        IN2G_ReplaceNegValsByNaNWaves(ResultsInt,ResultsQ,ResultsE)
1440        IN2G_RemoveNaNsFrom3Waves(ResultsInt,ResultsQ,ResultsE)
1441
1442        String OutFldrNm, OutXWvNm, OutYWvNm,OutEWvNm
1443        OutFldrNm = removeEnding(SourceFolderName,":") + "_scaled"
1444        string FirstFolderShortName=StringFromList(ItemsInList(OutFldrNm, ":")-1, OutFldrNm, ":")
1445        string OutputWaveNameMain = RemoveListItem(ItemsInList(FirstFolderShortName,"_")-1, FirstFolderShortName, "_") +"scaled"
1446        OutYWvNm = "r_"+OutputWaveNameMain
1447        OutEWvNm = "s_"+OutputWaveNameMain
1448        OutXWvNm = "q_"+OutputWaveNameMain
1449        //and now I need to save the data
1450        if(DataFolderExists(OutFldrNm)&&!Overwrite)
1451                DoAlert /T="Folder for Scaled data exists" 1, "Folder "+OutFldrNm+" exists, do you want to overwrite?"
1452                if(V_Flag!=1)
1453                        abort
1454                endif
1455        endif
1456        NewDataFolder/O/S $(RemoveEnding(OutFldrNm , ":") )
1457        Duplicate/O ResultsQ, $(OutXWvNm)
1458        Duplicate/O ResultsInt, $(OutYWvNm)
1459        Duplicate/O ResultsE, $(OutEWvNm)
1460        Wave NewScaledXWave = $(OutXWvNm)
1461        Wave NewScaledYWave = $(OutYWvNm)
1462        Wave NewScaledEWave = $(OutEWvNm)
1463        print "Scaled data from "+SourceFolderName+"   and saved into new folder :    "+OutFldrNm
1464        string NewNote
1465        NewNote="Data scaled;"+date()+";"+time()+";Data Folder="+SourceFolderName+";"
1466        NewNote+="Intensity values scaled by:"+num2str(DataScalingConstant)+";"+"After subtracting flat background:"+num2str(FlatBackgroundSubtract)+";"
1467        NewNote+="Error values scaled by:"+num2str(ErrorScalingConstant)+";"
1468        NewNote+="Prior data note:"+OriginalDataNote+";"
1469        Note /K/NOCR NewScaledYWave, NewNote
1470        Note /K/NOCR NewScaledXWave, NewNote
1471        Note /K/NOCR NewScaledEWave, NewNote
1472        CheckDisplayed /W=IRB1_DataManipulationPanel#LogLogDataDisplay $(NameOfWave(NewScaledYWave))
1473        if(V_Flag!=1)
1474                AppendToGraph /W=IRB1_DataManipulationPanel#LogLogDataDisplay  NewScaledYWave  vs NewScaledXWave
1475                ErrorBars/T=2/L=2 /W=IRB1_DataManipulationPanel#LogLogDataDisplay $(NameOfWave(NewScaledYWave)) Y,wave=(NewScaledEWave,NewScaledEWave)
1476                ModifyGraph /W=IRB1_DataManipulationPanel#LogLogDataDisplay lstyle($(NameOfWave(NewScaledYWave)))=3,lsize($(NameOfWave(NewScaledYWave)))=3,rgb($(NameOfWave(NewScaledYWave)))=(0,0,0)
1477                ModifyGraph /W=IRB1_DataManipulationPanel#LogLogDataDisplay rgb($(NameOfWave(NewScaledYWave)))=(0,0,65535)
1478        endif
1479        IN2G_ColorTopGrphRainbow(topGraphStr="IRB1_DataManipulationPanel#LogLogDataDisplay")
1480        IN2G_LegendTopGrphFldr(12, 20, 1, 0, topGraphStr="IRB1_DataManipulationPanel#LogLogDataDisplay")
1481        NVAR DisplayErrorBars = root:Packages:Irena:BioSAXSDataMan:DisplayErrorBars
1482        IN2G_ShowHideErrorBars(DisplayErrorBars, topGraphStr="IRB1_DataManipulationPanel#LogLogDataDisplay")
1483
1484        setDataFOlder oldDf
1485end
1486//**********************************************************************************************************
1487//**********************************************************************************************************
1488//**********************************************************************************************************
1489
1490
1491//************************************************************************************************************
1492//                                                      ATSAS PDDF and MW weight calculation support in Irena Tool
1493//************************************************************************************************************
1494//************************************************************************************************************
1495Function IRB1_PDDFPanelFnct()
1496        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
1497        PauseUpdate; Silent 1           // building window...
1498        NewPanel /K=1 /W=(2.25,43.25,1210,800) as "PDDF-MW-Rg"
1499        DoWIndow/C IRB1_PDDFInterfacePanel
1500        TitleBox MainTitle title="PDDF using Irena or ATSAS",pos={140,2},frame=0,fstyle=3, fixedSize=1,font= "Times New Roman", size={360,30},fSize=22,fColor=(0,0,52224)
1501        string UserDataTypes=""
1502        string UserNameString=""
1503        string XUserLookup=""
1504        string EUserLookup=""
1505        IR2C_AddDataControls("Irena:PDDFInterface","IRB1_PDDFInterfacePanel","DSM_Int;M_DSM_Int;SMR_Int;M_SMR_Int;","AllCurrentlyAllowedTypes",UserDataTypes,UserNameString,XUserLookup,EUserLookup, 0,1, DoNotAddControls=1)
1506        IR3C_MultiAppendControls("Irena:PDDFInterface","IRB1_PDDFInterfacePanel", "IRB1_PDDFAppendOneDataSet","",1,0)
1507        TitleBox Dataselection pos={10,25}
1508        ListBox DataFolderSelection pos={4,135},size={250,540}
1509        CheckBox UseIndra2Data disable=3
1510        CheckBox UseResults disable=3
1511        CheckBox UseQRSData disable=1
1512        NVAR UseQRSData = root:Packages:Irena:PDDFInterface:UseQRSData
1513        NVAR UseResults = root:Packages:Irena:PDDFInterface:UseResults
1514        NVAR UseIndra2Data = root:Packages:Irena:PDDFInterface:UseIndra2Data
1515        UseResults = 0
1516        UseIndra2Data = 0
1517        UseQRSData = 1
1518        Button GetHelp,pos={500,10},size={80,15},fColor=(65535,32768,32768), proc=IRB1_DataManButtonProc,title="Get Help", help={"Open www manual page for this tool"}
1519
1520        TitleBox PDDFInstructions6 title="\Zr100Q range for analysis, use cursors to set",size={330,15},pos={340,62},frame=0,fColor=(0,0,65535),labelBack=0
1521        SetVariable DataQstart,pos={340,80},size={170,15}, proc=IRB1_PDDFSetVarProc,title="Q min for fitting     "
1522        Setvariable DataQstart, variable=root:Packages:Irena:PDDFInterface:DataQstart, limits={-inf,inf,0}
1523        SetVariable DataQEnd,pos={340,100},size={170,15}, proc=IRB1_PDDFSetVarProc,title="Q max for fitting    "
1524        Setvariable DataQEnd, variable=root:Packages:Irena:PDDFInterface:DataQEnd, limits={-inf,inf,0}
1525
1526
1527        //Dist Tabs definition
1528        TabControl PDDFTabs,pos={260,130},size={330,330}, proc=IRB1_PDDFTabProc
1529        TabControl PDDFTabs,tabLabel(0)="PDDF",tabLabel(1)="Mol. Weight", value=0
1530
1531        //TAB 0
1532        //PDDF Gnom specifics
1533        TitleBox PDDFInstructions5 title="\Zr120PDDF controls - method & parameters : ",size={430,15},pos={270,156},frame=0,fColor=(0,0,65535),labelBack=0
1534        //PDDFUseGNOM;PDDFuseMoore;PDDFuseregularization
1535        checkbox PDDFUseGNOM, pos={270,180}, title="GNOM", size={80,14},proc=IRB1_PDDFCheckProc, variable=root:Packages:Irena:PDDFInterface:PDDFUseGNOM, mode=1, help={"Run PDDF using ATSAS gnom"}
1536        checkbox PDDFUseAutoGNOM, pos={340,180}, title="autoGNOM", size={76,14},proc=IRB1_PDDFCheckProc, variable=root:Packages:Irena:PDDFInterface:PDDFUseAutoGNOM, mode=1, help={"Run PDDF using ATSAS datgnom"}
1537        checkbox PDDFuseregularization, pos={430,180}, title="Irena Reg.", size={76,14},proc=IRB1_PDDFCheckProc, variable=root:Packages:Irena:PDDFInterface:PDDFuseregularization,mode=1 , help={"Run PDDF using Irena regularization method"}
1538        checkbox PDDFuseMoore, pos={530,180}, title="Moore", size={76,14},proc=IRB1_PDDFCheckProc, variable=root:Packages:Irena:PDDFInterface:PDDFuseMoore,mode=1,  help={"Run PDDF using Irena Moore method"}
1539
1540        TitleBox PDDFInstructions8 title="\Zr100Optional PDDF input parameters : ",size={500,15},pos={270,210},frame=0,fColor=(0,0,65535),labelBack=0
1541        checkbox GnomForceRmin0, pos={300,235}, title="Rmin==0?", size={76,14},proc=IRB1_PDDFCheckProc, variable=root:Packages:Irena:PDDFInterface:GnomForceRmin0, help={"Force Rmin=0 for Gnom"}
1542        checkbox GnomForceRmax0, pos={440,235}, title="Rmax==0?", size={76,14},proc=IRB1_PDDFCheckProc, variable=root:Packages:Irena:PDDFInterface:GnomForceRmax0, help={"Force Dmax=0 for Gnom"}
1543        SetVariable GnomAlfaValue,pos={270,260},size={140,15}, noproc,title="Alfa in = ",variable=root:Packages:Irena:PDDFInterface:GnomAlfaValue, limits={0,5,0.1}, help={"Alfa value estimate for Gnom, if you know. ) for automatic"}
1544        //common settings
1545        SetVariable NumBinsInR,pos={440,260},size={140,15}, noproc,title="R pnts in =",variable=root:Packages:Irena:PDDFInterface:NumBinsInR, limits={0,1000,20}, help={"Set to specific number (100) or leave to 0 for automatic"}
1546        //Dmax
1547        SetVariable DmaxEstimate,pos={270,290},size={160,15}, noproc,title="Dmax Est = ", variable=root:Packages:Irena:PDDFInterface:DmaxEstimate, limits={1,3000,5}, format="%1.4g", help={"Estimate, change as needed"}
1548        //Moore settings
1549        SetVariable MooreNumFunctions,pos={440,290},size={140,15}, noproc,title="Num Func =",variable=root:Packages:Irena:PDDFInterface:MooreNumFunctions, limits={10,300,10}
1550        checkbox MooreDetNumFunctions, pos={265,320}, title="Det Num Functions?", size={76,14},proc=IRB1_PDDFCheckProc, variable=root:Packages:Irena:PDDFInterface:MooreDetNumFunctions, help={"Determine number of functions"}
1551        checkbox MooreFitMaxSize, pos={445,320}, title="Fit max size?", size={76,14},proc=IRB1_PDDFCheckProc, variable=root:Packages:Irena:PDDFInterface:MooreFitMaxSize, help={"Fit max size"}
1552        //run the fit
1553        Button RunPDDFonData,pos={300,350},size={200,20}, proc=IRB1_PDDFButtonProc,title="Run PDDF on current data", help={"Run PDDF method of yoru choice on these data"}
1554        Button RunSequenceofPDDF,pos={300,375},size={200,20}, proc=IRB1_PDDFButtonProc,title="Run PDDF on all selected", help={"Run GNOM on these data"}
1555        //here we need some output values from GNOM, need space at leats for Alfa
1556        SetVariable GNOMAlfaResult,pos={270,400},size={160,15}, noproc,title="GNOM Alfa out =",variable=root:Packages:Irena:PDDFInterface:GNOMAlfaResult,disable=0, noedit=1,limits={0,inf,0},frame=0
1557
1558        //TAB 1
1559        //MW controls
1560        checkbox PDDFUseProtein, pos={300,155}, title="\Zr120Protein", size={120,14},proc=IRB1_PDDFCheckProc, variable=root:Packages:Irena:PDDFInterface:PDDFUseProtein, fColor=(65535,0,0), mode=1, help={"Run PDDF with setting for Proteins. Changes density and SLD"}
1561        checkbox PDDFUseNucleicAcid, pos={450,155}, title="\Zr120Nucleic Acid", size={120,14},proc=IRB1_PDDFCheckProc, variable=root:Packages:Irena:PDDFInterface:PDDFUseNucleicAcid, fColor=(65535,0,0), mode=1, help={"Run PDDF with settings from Nucleai acid. Changes density and SLD"}
1562        Button PDDFCalcRgAndMolecularWeight,pos={310,180},size={170,20}, proc=IRB1_PDDFButtonProc,title="Fit Rg and calculate MW", help={"Calculate Dmax on these data"}
1563        TitleBox PDDFInstructions1 title="\Zr120SAXSMoW2 & Rambo-Tainer Qmax : ",size={230,15},pos={270,220},frame=0,fColor=(0,0,65535),labelBack=0
1564        checkbox InvariantCalcQmax8overRg, pos={270,250}, title="Qmax 8/Rg?", size={76,14},proc=IRB1_PDDFCheckProc, variable=root:Packages:Irena:PDDFInterface:InvariantCalcQmax8overRg, mode=0, help={"Set Qmax to 8/Rg automatically"}
1565        checkbox InvariantCalcQmaxLog225, pos={400,250}, title="Qmax I(0)/200?", size={76,14},proc=IRB1_PDDFCheckProc, variable=root:Packages:Irena:PDDFInterface:InvariantCalcQmaxLog225, mode=0, help={"Set Qmax to Q when I(0)/200"}
1566        SetVariable InvariantCalcQmax,pos={270,275},size={250,18}, bodyWidth=90, proc=IRB1_PDDFSetVarProc,title="Qmax = ", variable=root:Packages:Irena:PDDFInterface:InvariantCalcQmax, limits={0.01,1,0.01},frame=1,bodyWidth=90, help={"Qmax to use"}, format="%4.2f"
1567
1568        TitleBox PDDFInstructions11 title="\Zr120Rambo-Tainer Background : ",size={230,15},pos={270,310},frame=0,fColor=(0,0,65535),labelBack=0
1569        checkbox RamboTainerAutoSetBckg, pos={270,330}, title="Auto Find Backg.?", size={76,14},proc=IRB1_PDDFCheckProc, variable=root:Packages:Irena:PDDFInterface:RamboTainerAutoSetBckg, mode=0, help={"Find Background AUtomatically background from I(Q)"}
1570        checkbox RamboTainerSubtractFlatBackground, pos={420,330}, title="Subtract Background?", size={76,14},proc=IRB1_PDDFCheckProc, variable=root:Packages:Irena:PDDFInterface:RamboTainerSubtractFlatBackground, mode=0, help={"Subtract background from I(Q)"}
1571        NVAR RamboTainerFlatBackground=root:Packages:Irena:PDDFInterface:RamboTainerFlatBackground
1572        SetVariable RamboTainerFlatBackground,pos={270,355},size={250,18}, bodyWidth=90, proc=IRB1_PDDFSetVarProc,title="Flat Background = ", variable=root:Packages:Irena:PDDFInterface:RamboTainerFlatBackground, limits={0.00,inf,RamboTainerFlatBackground*0.01},frame=1, help={"Flat Background"}, format="%4.2f"
1573
1574        TitleBox PDDFInstructions12 title="\Zr120Real Space/PDDF (GNOM) Mol. Weight Conc.",size={330,15},pos={270,390},frame=0,fColor=(0,0,65535),labelBack=0
1575        SetVariable ConcentrationForCals,pos={270,410},size={250,18}, proc=IRB1_PDDFSetVarProc,title="c [mg/ml] = ", bodyWidth=90,variable=root:Packages:Irena:PDDFInterface:ConcentrationForCals,limits={0,inf,0.1}, help={"Concentration for MW calculations"}
1576        TitleBox PDDFInstructions2 title="\Zr100Remember - this Estimate requires Absolute Intensity!",size={330,15},pos={270,435},frame=0,fColor=(0,0,65535),labelBack=0
1577
1578        //Below, at the end...
1579        TitleBox PDDFInstructions21 title="\Zr140Mol Weight results:",size={250,15},pos={350,460},frame=0,fColor=(0,0,65535),labelBack=0
1580        TitleBox PDDFInstructions23 title="\Zr110Reciprocal space (Guinier fit):",size={330,15},pos={270,480},frame=0,fColor=(0,0,65535),labelBack=0
1581        SetVariable ReciprocalPorodVolumeA3,pos={290,500},size={100,15}, format="%4.0f",bodyWidth=50, noproc,title="Vol [A^3] = ", variable=root:Packages:Irena:PDDFInterface:ReciprocalPorodVolumeA3, noedit=1,limits={0,inf,0},frame=0, help={"True Volume of protein in [cm3] "}
1582        SetVariable ReciprocalSpaceI0,pos={350,500},size={120,15},bodyWidth=50, noproc,title="I0 = ", variable=root:Packages:Irena:PDDFInterface:ReciprocalSpaceI0, noedit=1,limits={0,inf,0},frame=0,size={180,17}, bodyWidth=70, help={"Porod Invariant calcualtion result"}, format="%4.2f"
1583        SetVariable ReciprocalSpaceRg,pos={480,500},size={120,17},bodyWidth=50, noproc,title="Rg [A] = ", variable=root:Packages:Irena:PDDFInterface:ReciprocalSpaceRg, noedit=1,limits={0,inf,0},frame=0, help={"Density of protein, user changeable, in g/cm3"}, format="%4.2f"
1584        SetVariable SAXSMoW2MWRecSpacekDa,pos={300,520},size={250,15},bodyWidth=70, noproc,title="SAXSMoW2 MW [kDa]  = ", variable=root:Packages:Irena:PDDFInterface:SAXSMoW2MWRecSpacekDa, noedit=1,fstyle=1, fsize=13, limits={0,inf,0},frame=0, help={"Molecular weight calculated from SAXSMoW2 method in kDa"}, fColor=(52428,1,1), format="%8.2f"
1585        SetVariable RamboTainerMWRecSpacekDa,pos={300,540},size={250,15},bodyWidth=70, noproc,title="Rambo-Tainer MW [kDa]  = ",variable=root:Packages:Irena:PDDFInterface:RamboTainerMWRecSpacekDa, disable=0, noedit=1,limits={0,inf,0},frame=0,fstyle=1, fsize=13, fColor=(52428,1,1), help={"Molecular weight calculated from Rambo-Tainer method in kDa"}, format="%8.2f"
1586       
1587        TitleBox PDDFInstructions22 title="\Zr110Real space (GNOM+abs. Int.+conc.):",size={330,15},pos={270,570},frame=0,fColor=(0,0,65535),labelBack=0
1588        SetVariable RealSpacePorodVolumeA3,pos={290,590},size={100,15},bodyWidth=50, format="%4.0f", noproc,title="Vol [A^3] = ", variable=root:Packages:Irena:PDDFInterface:RealSpacePorodVolumeA3, noedit=1,limits={0,inf,0},frame=0, help={"True Volume of protein in [A^3] "}
1589        SetVariable RealSpaceI0,pos={350,590},size={120,15},bodyWidth=50, noproc,title="I0 = ",variable=root:Packages:Irena:PDDFInterface:RealSpaceI0, disable=0, noedit=1,limits={0,inf,0},frame=0, size={180,17}, bodyWidth=70, help={"Porod Invariant calcualtion result"}, format="%4.2f"
1590        SetVariable RealSpaceRg,pos={480,590},size={120,17},bodyWidth=50, noproc,title="Rg [A] = ",variable=root:Packages:Irena:PDDFInterface:RealSpaceRg,  disable=0, noedit=1,limits={0,inf,0},frame=0, format="%4.2f"
1591        SetVariable SAXSMoW2MWRealSpacekDa,pos={300,612},size={250,15},bodyWidth=70, noproc,title="SAXSMoW2 MW [kDa]  = ", variable=root:Packages:Irena:PDDFInterface:SAXSMoW2MWRealSpacekDa, noedit=1,fstyle=1, fsize=13, limits={0,inf,0},frame=0, help={"Molecular weight calculated from SAXSMoW2 method in kDa"}, fColor=(52428,1,1), format="%8.2f"
1592        SetVariable PDDFCalculatedMW,pos={300,635},size={250,15},bodyWidth=70, noproc,title="Abs. Int. Est. MW [kDa]  = ",variable=root:Packages:Irena:PDDFInterface:PDDFCalculatedMW, disable=0, noedit=1,limits={0,inf,0},frame=0,fstyle=1, fsize=13, fColor=(52428,1,1), help={"Molecular weight calculated from PDDF method in kDa"}, format="%8.2f"
1593
1594//
1595        //Controls for results 
1596        TitleBox PDDFInstructions3 title="\Zr110Save results controls : ",size={200,15},pos={300,660},frame=0,fColor=(0,0,65535),labelBack=0
1597        TitleBox PDDFInstructions4 title="\Zr100Where? : ",size={120,15},pos={485,660},frame=0,fColor=(0,0,65535),labelBack=0
1598        checkbox SaveToFolder, pos={495,679}, title="Folder", size={76,14},noproc, variable=root:Packages:Irena:PDDFInterface:SaveToFolder, mode=0, help={"Save to folder"}
1599        checkbox SaveToNotebook, pos={495,697}, title="Notebook", size={76,14},noproc, variable=root:Packages:Irena:PDDFInterface:SaveToNotebook, mode=0, help={"Save to notebook"}
1600        checkbox SaveToWaves, pos={495,715}, title="Waves", size={76,14},noproc, variable=root:Packages:Irena:PDDFInterface:SaveToWaves, mode=0, help={"Save to notebook"}
1601        checkbox SaveToGNOMOut, pos={495,733}, title="Gnom out", size={76,14},noproc, variable=root:Packages:Irena:PDDFInterface:SaveToGNOMOut, mode=0, help={"Export GNOM Out file outside"}
1602
1603        //results presentation for all methods...
1604        Button SavePDDFresults,pos={300,685},size={180,20}, proc=IRB1_PDDFButtonProc,title="Save PDDF results", help={"Save PDDF results to folder"}
1605        Button OpenResultsAndTable,pos={300,710},size={180,15}, proc=IRB1_PDDFButtonProc,title="Open Table and Notebook", help={"Open Table and Notebook with results"}
1606        Button DeleteResultsAndTable,pos={230,735},size={130,15}, proc=IRB1_PDDFButtonProc,title="Delete results waves", help={"Delete waves with results, this will clean the records!"}
1607        Checkbox OverwriteExistingData, pos={370,735},size={76,14},title="Overwrite Ouput?", noproc, variable=root:Packages:Irena:PDDFInterface:OverwriteExistingData
1608
1609        //create graphs for Data and PDDF
1610        Display /W=(600,5,1192,365) /HOST=# /N=DataDisplay
1611        SetActiveSubwindow ##
1612
1613        Display /W=(600,370,1192,730) /HOST=# /N=PDFDisplay
1614        SetActiveSubwindow ##
1615
1616        Button SelectAllData,pos={190,680},size={80,20}, proc=IRB1_PDDFButtonProc,title="Select All", help={"Select all data in the Listbox"}
1617
1618        SetVariable SleepBetweenDataProcesses,pos={600,735},size={220,15}, noproc,variable=root:Packages:Irena:PDDFInterface:SleepBetweenDataProcesses
1619        SetVariable SleepBetweenDataProcesses, title="Sleep between data sets", limits={0.0,30,1}
1620        Checkbox DisplayErrorBars, pos={860,735},size={76,14},title="Display Error Bars", proc=IRB1_PDDFCheckProc, variable=root:Packages:Irena:PDDFInterface:DisplayErrorBars
1621        Button AutoScaleGraph,pos={1020,735},size={140,15}, proc=IRB1_PDDFButtonProc,title="Autoscale Graph", help={"Autoscale the graph axes"}
1622
1623
1624
1625        TitleBox Instructions1 title="\Zr100Double click to add data to graph",size={330,15},pos={4,680},frame=0,fColor=(0,0,65535),labelBack=0
1626        TitleBox Instructions2 title="\Zr100Shift-click to select range of data",size={330,15},pos={4,695},frame=0,fColor=(0,0,65535),labelBack=0
1627        TitleBox Instructions3 title="\Zr100Ctrl/Cmd-click to select one data set",size={330,15},pos={4,710},frame=0,fColor=(0,0,65535),labelBack=0
1628        TitleBox Instructions4 title="\Zr100Regex for not contain: ^((?!string).)*$",size={330,15},pos={4,725},frame=0,fColor=(0,0,65535),labelBack=0
1629        TitleBox Instructions5 title="\Zr100Regex for contain:  string, two: str2.*str1",size={330,15},pos={4,740},frame=0,fColor=(0,0,65535),labelBack=0
1630        TitleBox Instructions6 title="\Zr100Regex for case independent:  (?i)string",size={330,15},pos={4,755},frame=0,fColor=(0,0,65535),labelBack=0   
1631
1632       
1633        IRB1_PDDFFixTabControls(0)
1634end
1635//**********************************************************************************************************
1636//**********************************************************************************************************
1637
1638Function IRB1_PDDFRecalculareQmax()
1639
1640                        NVAR InvariantCalcQmax8overRg = root:Packages:Irena:PDDFInterface:InvariantCalcQmax8overRg
1641                        NVAR InvariantCalcQmaxLog225 = root:Packages:Irena:PDDFInterface:InvariantCalcQmaxLog225
1642                       
1643                        NVAR InvariantCalcQmax = root:Packages:Irena:PDDFInterface:InvariantCalcQmax
1644                        NVAR ReciprocalSpaceRg = root:Packages:Irena:PDDFInterface:ReciprocalSpaceRg
1645                        NVAR ReciprocalSpaceI0=root:Packages:Irena:PDDFInterface:ReciprocalSpaceI0
1646                        Wave Intensity=root:Packages:Irena:PDDFInterface:Intensity
1647                        Wave Qvector=root:Packages:Irena:PDDFInterface:Q_vec
1648                       
1649                        if(InvariantCalcQmax8overRg && ReciprocalSpaceRg>0)     
1650                                InvariantCalcQmax = 8/ReciprocalSpaceRg
1651                        elseif(InvariantCalcQmaxLog225 && ReciprocalSpaceI0>0)
1652                                variable IntToFind = ReciprocalSpaceI0/200
1653                                FindLevel/P/Q Intensity, IntToFind
1654                                if(V_Flag==0)   //level found...
1655                                        InvariantCalcQmax = Qvector[V_LevelX]
1656                                else    //now found...
1657                                        InvariantCalcQmax = Qvector[numpnts(Qvector)-2]
1658                                endif
1659                        else
1660                                if(InvariantCalcQmax<0.05)
1661                                        InvariantCalcQmax = 0.3
1662                                endif
1663                        endif                   
1664end
1665
1666//**********************************************************************************************************
1667//**********************************************************************************************************
1668Function IRB1_PDDFSetVarProc(sva) : SetVariableControl
1669        STRUCT WMSetVariableAction &sva
1670
1671        variable tempP
1672        switch( sva.eventCode )
1673                case 1: // mouse up
1674                case 2: // Enter key
1675                        if(StringMatch(sva.ctrlName, "ConcentrationForCals" )||StringMatch(sva.ctrlName, "ScattLengthDensDifference" ))
1676                                IRB1_PDDFCalculateRgI0()
1677                        endif
1678                        NVAR DataQstart=root:Packages:Irena:PDDFInterface:DataQstart
1679                        NVAR DataQEnd=root:Packages:Irena:PDDFInterface:DataQEnd
1680                        NVAR DataQEndPoint = root:Packages:Irena:PDDFInterface:DataQEndPoint
1681                        NVAR DataQstartPoint = root:Packages:Irena:PDDFInterface:DataQstartPoint
1682                        if(stringmatch(sva.ctrlName,"DataQEnd"))
1683                                WAVE OriginalDataQWave = root:Packages:Irena:PDDFInterface:OriginalDataQWave
1684                                tempP = BinarySearch(OriginalDataQWave, DataQEnd )
1685                                if(tempP<1)
1686                                        print "Wrong Q value set, Data Q max must be at most 1 point before the end of Data"
1687                                        tempP = numpnts(OriginalDataQWave)-2
1688                                        DataQEnd = OriginalDataQWave[tempP]
1689                                endif
1690                                DataQEndPoint = tempP                   
1691                        endif
1692                        if(stringmatch(sva.ctrlName,"DataQstart"))
1693                                WAVE OriginalDataQWave = root:Packages:Irena:PDDFInterface:OriginalDataQWave
1694                                tempP = BinarySearch(OriginalDataQWave, DataQstart )
1695                                if(tempP<1)
1696                                        print "Wrong Q value set, Data Q min must be at least 1 point from the start of Data"
1697                                        tempP = 1
1698                                        DataQstart = OriginalDataQWave[tempP]
1699                                endif
1700                                DataQstartPoint=tempP
1701                        endif
1702                       
1703                        if(stringmatch(sva.ctrlName,"InvariantCalcQmax"))
1704                                NVAR InvariantCalcQmax8overRg = root:Packages:Irena:PDDFInterface:InvariantCalcQmax8overRg
1705                                NVAR InvariantCalcQmaxLog225 = root:Packages:Irena:PDDFInterface:InvariantCalcQmaxLog225
1706                                InvariantCalcQmax8overRg = 0
1707                                InvariantCalcQmaxLog225 = 0
1708                        endif
1709                        if(stringmatch(sva.ctrlName,"RamboTainerFlatBackground"))
1710                                NVAR RamboTainerAutoSetBckg = root:Packages:Irena:PDDFInterface:RamboTainerAutoSetBckg
1711                                RamboTainerAutoSetBckg = 0
1712                                NVAR Backg=root:Packages:Irena:PDDFInterface:RamboTainerFlatBackground
1713                                SetVariable RamboTainerFlatBackground, limits={0.00,inf,Backg*0.05}
1714
1715                                //IRB1_PDDFFitRgAndG()
1716                                IRB1_PDDFCalcRamboTainer()
1717                        endif
1718                        if(stringmatch(sva.ctrlName,"InvariantCalcQmax"))
1719                                //IRB1_PDDFFitRgAndG()
1720                                IRB1_PDDFCalcSAXSMoW2()
1721                                IRB1_PDDFCalcRamboTainer()
1722                        endif
1723
1724
1725                        break
1726                case 3: // Live update
1727                        Variable dval = sva.dval
1728                        String sval = sva.sval
1729                        break
1730                case -1: // control being killed
1731                        break
1732        endswitch
1733
1734        return 0
1735End
1736
1737
1738//**************************************************************************************
1739//**************************************************************************************
1740//**************************************************************************************
1741//**************************************************************************************
1742Function IRB1_PDDFTabProc(tca) : TabControl
1743        STRUCT WMTabControlAction &tca
1744
1745        switch( tca.eventCode )
1746                case 2: // mouse up
1747                        Variable tab = tca.tab
1748                        //do something here
1749                        IRB1_PDDFFixTabControls(tab)
1750                        IN2G_RemoveDataFromGraph(topGraphStr = "IRB1_PDDFInterfacePanel#PDFDisplay")
1751                        RemoveFromGraph/W=IRB1_PDDFInterfacePanel#DataDisplay /Z FitScatteringProfileBckg
1752                        RemoveFromGraph/W=IRB1_PDDFInterfacePanel#DataDisplay /Z FitScatteringProfile
1753                        RemoveFromGraph/W=IRB1_PDDFInterfacePanel#DataDisplay /Z PDDFModelIntensity
1754
1755                        break
1756                case -1: // control being killed
1757                        break
1758        endswitch
1759
1760        return 0
1761End
1762//**************************************************************************************
1763//**************************************************************************************
1764//**************************************************************************************
1765
1766
1767static Function IRB1_PDDFFixTabControls(whichTab)
1768                variable whichTab
1769                //whichTab=0 for PDDF, whichTab=1 for MW methods.
1770               
1771        NVAR PDDFUseGNOM                                        =root:Packages:Irena:PDDFInterface:PDDFUseGNOM
1772        NVAR PDDFuseMoore                                       =root:Packages:Irena:PDDFInterface:PDDFuseMoore
1773        NVAR PDDFuseregularization              =root:Packages:Irena:PDDFInterface:PDDFuseregularization
1774        NVAR PDDFUseAutoGNOM                            =root:Packages:Irena:PDDFInterface:PDDFUseAutoGNOM
1775
1776        //MW controls
1777        checkbox PDDFUseProtein, win=IRB1_PDDFInterfacePanel, disable = (whichTab!=1)
1778        checkbox PDDFUseNucleicAcid, win=IRB1_PDDFInterfacePanel,  disable = (whichTab!=1)
1779        TitleBox PDDFInstructions1, win=IRB1_PDDFInterfacePanel,  disable = (whichTab!=1)
1780        Button PDDFCalcRgAndMolecularWeight, win=IRB1_PDDFInterfacePanel,  disable = (whichTab!=1)
1781        //SetVariable ReciprocalPorodVolumeA3, win=IRB1_PDDFInterfacePanel,  disable = (whichTab!=1)
1782        checkbox RamboTainerAutoSetBckg,  disable = (whichTab!=1)
1783        checkbox InvariantCalcQmax8overRg,  disable = (whichTab!=1)
1784        checkbox InvariantCalcQmaxLog225,  disable = (whichTab!=1)
1785        SetVariable InvariantCalcQmax,  disable = (whichTab!=1)
1786        checkbox RamboTainerSubtractFlatBackground,  disable = (whichTab!=1)
1787        SetVariable RamboTainerFlatBackground,  disable = (whichTab!=1)
1788        SetVariable ConcentrationForCals, win=IRB1_PDDFInterfacePanel,  disable = (whichTab!=1)
1789        TitleBox PDDFInstructions2, win=IRB1_PDDFInterfacePanel,  disable = (whichTab!=1)
1790        TitleBox PDDFInstructions11, win=IRB1_PDDFInterfacePanel,  disable = (whichTab!=1)
1791        TitleBox PDDFInstructions12, win=IRB1_PDDFInterfacePanel,  disable = (whichTab!=1)
1792        //PDDF Gnom specifics
1793        TitleBox PDDFInstructions5, win=IRB1_PDDFInterfacePanel,   disable = (whichTab!=0)
1794//      //PDDFUseGNOM;PDDFuseMoore;PDDFuseregularization
1795        checkbox PDDFUseGNOM, win=IRB1_PDDFInterfacePanel,  disable = (whichTab!=0)
1796        checkbox PDDFUseAutoGNOM, win=IRB1_PDDFInterfacePanel,   disable = (whichTab!=0)
1797        checkbox PDDFuseregularization, win=IRB1_PDDFInterfacePanel,   disable = (whichTab!=0)
1798        checkbox PDDFuseMoore, win=IRB1_PDDFInterfacePanel,  disable = (whichTab!=0)
1799        TitleBox PDDFInstructions8, win=IRB1_PDDFInterfacePanel,   disable = (whichTab!=0)
1800
1801        checkbox GnomForceRmin0, win=IRB1_PDDFInterfacePanel, disable=(whichTab!=0 || !PDDFUseGNOM)
1802        checkbox GnomForceRmax0, win=IRB1_PDDFInterfacePanel, disable=(whichTab!=0 ||!PDDFUseGNOM)
1803        SetVariable GnomAlfaValue, win=IRB1_PDDFInterfacePanel, disable=(whichTab!=0 ||!PDDFUseGNOM)
1804        //common settings
1805        SetVariable NumBinsInR, win=IRB1_PDDFInterfacePanel, disable=(whichTab!=0 || PDDFUseAutoGNOM)
1806        //Moore settings
1807        SetVariable MooreNumFunctions, win=IRB1_PDDFInterfacePanel, disable=(whichTab!=0 ||!PDDFuseMoore)
1808        checkbox MooreDetNumFunctions, win=IRB1_PDDFInterfacePanel, disable=(whichTab!=0 ||!PDDFuseMoore)
1809        checkbox MooreFitMaxSize, win=IRB1_PDDFInterfacePanel, disable=(whichTab!=0 ||!PDDFuseMoore)
1810        SetVariable DmaxEstimate, win=IRB1_PDDFInterfacePanel,  disable = (whichTab!=0)
1811        Button RunPDDFonData, win=IRB1_PDDFInterfacePanel,  disable = (whichTab!=0)
1812        Button RunSequenceofPDDF, win=IRB1_PDDFInterfacePanel,  disable = (whichTab!=0)
1813        SetVariable GNOMAlfaResult, win=IRB1_PDDFInterfacePanel,  disable = (whichTab!=0)
1814end
1815//**********************************************************************************************************
1816//**********************************************************************************************************
1817Function IRB1_PDDFCheckProc(cba) : CheckBoxControl
1818        STRUCT WMCheckboxAction &cba
1819
1820        switch( cba.eventCode )
1821                case 2: // mouse up
1822                        Variable checked = cba.checked
1823                        if(stringmatch(cba.ctrlname,"DisplayErrorBars"))
1824                                pauseUpdate
1825                                NVAR DisplayErrorBars = root:Packages:Irena:PDDFInterface:DisplayErrorBars
1826                                IN2G_ShowHideErrorBars(DisplayErrorBars, topGraphStr="IRB1_PDDFInterfacePanel#DataDisplay")
1827                                DoUpdate
1828                        endif
1829                        NVAR PDDFUseGNOM = root:Packages:Irena:PDDFInterface:PDDFUseGNOM
1830                        NVAR PDDFuseMoore = root:Packages:Irena:PDDFInterface:PDDFuseMoore
1831                        NVAR PDDFuseregularization = root:Packages:Irena:PDDFInterface:PDDFuseregularization
1832                        NVAR PDDFUseAutoGNOM = root:Packages:Irena:PDDFInterface:PDDFUseAutoGNOM
1833                        NVAR PDDFUseProtein = root:Packages:Irena:PDDFInterface:PDDFUseProtein
1834                        NVAR PDDFUseNucleicAcid = root:Packages:Irena:PDDFInterface:PDDFUseNucleicAcid
1835                        NVAR InvariantCalcQmax8overRg = root:Packages:Irena:PDDFInterface:InvariantCalcQmax8overRg
1836                        NVAR InvariantCalcQmaxLog225 = root:Packages:Irena:PDDFInterface:InvariantCalcQmaxLog225
1837
1838                        if(stringmatch(cba.ctrlname,"RamboTainerAutoSetBckg"))
1839                                //IRB1_PDDFFitRgAndG()
1840                                //IRB1_PDDFCalcSAXSMoW2()
1841                                IRB1_PDDFCalcRamboTainer()
1842                        endif
1843                        if(stringmatch(cba.ctrlname,"RamboTainerSubtractFlatBackground"))
1844                                //IRB1_PDDFFitRgAndG()
1845                                //IRB1_PDDFCalcSAXSMoW2()
1846                                IRB1_PDDFCalcRamboTainer()
1847                        endif
1848                        if(stringmatch(cba.ctrlname,"InvariantCalcQmax8overRg"))
1849                                if(checked)
1850                                        //InvariantCalcQmax8overRg = 0
1851                                        InvariantCalcQmaxLog225 = 0
1852                                endif
1853                                //IRB1_PDDFRecalculareQmax()
1854                                //IRB1_PDDFFitRgAndG()
1855                                IRB1_PDDFCalcSAXSMoW2()
1856                                IRB1_PDDFCalcRamboTainer()
1857                        endif
1858                        if(stringmatch(cba.ctrlname,"InvariantCalcQmaxLog225"))
1859                                if(checked)
1860                                        InvariantCalcQmax8overRg = 0
1861                                        //InvariantCalcQmaxLog225 = 0
1862                                endif
1863                                //IRB1_PDDFRecalculareQmax()
1864                                //IRB1_PDDFFitRgAndG()
1865                                IRB1_PDDFCalcSAXSMoW2()
1866                                IRB1_PDDFCalcRamboTainer()
1867                        endif
1868
1869
1870                        if(stringmatch(cba.ctrlname,"PDDFUseGNOM"))
1871                                if(checked)
1872                                        //PDDFUseGNOM = 0
1873                                        PDDFuseMoore = 0
1874                                        PDDFuseregularization = 0
1875                                        PDDFUseAutoGNOM = 0
1876                                endif
1877                                IRB1_PDDFFixTabControls(0)
1878                        endif
1879                        if(stringmatch(cba.ctrlname,"PDDFUseAutoGNOM"))
1880                                if(checked)
1881                                        PDDFUseGNOM = 0
1882                                        PDDFuseMoore = 0
1883                                        PDDFuseregularization = 0
1884                                        PDDFUseAutoGNOM = 1
1885                                endif
1886                                IRB1_PDDFFixTabControls(0)
1887                        endif
1888                        if(stringmatch(cba.ctrlname,"PDDFuseMoore"))
1889                                if(checked)
1890                                        PDDFUseGNOM = 0
1891                                        //PDDFuseMoore = 0
1892                                        PDDFuseregularization = 0
1893                                        PDDFUseAutoGNOM = 0
1894                                endif
1895                                IRB1_PDDFFixTabControls(0)
1896                        endif
1897                        if(stringmatch(cba.ctrlname,"PDDFuseregularization"))
1898                                if(checked)
1899                                        PDDFUseGNOM = 0
1900                                        PDDFuseMoore = 0
1901                                        //PDDFuseregularization = 0
1902                                        PDDFUseAutoGNOM = 0
1903                                endif
1904                                IRB1_PDDFFixTabControls(0)
1905                        endif
1906                        if(stringmatch(cba.ctrlname,"PDDFUseProtein"))
1907                                PDDFUseNucleicAcid=!PDDFUseProtein
1908                                IRB1_PDDFSetDensitySLD()       
1909                                IRB1_PDDFResetValuesToPreventStale()
1910                        endif                   
1911                        if(stringmatch(cba.ctrlname,"PDDFUseNucleicAcid"))
1912                                PDDFUseProtein=!PDDFUseNucleicAcid
1913                                IRB1_PDDFSetDensitySLD()       
1914                                IRB1_PDDFResetValuesToPreventStale()
1915                        endif
1916                        break
1917                case -1: // control being killed
1918                        break
1919        endswitch
1920
1921        return 0
1922End
1923//**********************************************************************************************************
1924//**********************************************************************************************************
1925
1926Function IRB1_PDDFButtonProc(ba) : ButtonControl
1927        STRUCT WMButtonAction &ba
1928
1929        switch( ba.eventCode )
1930                case 2: // mouse up
1931                        // click code here
1932                        if(stringMatch(ba.ctrlName,"RunPDDFonData"))
1933                                NVAR PDDFUseGNOM = root:Packages:Irena:PDDFInterface:PDDFUseGNOM
1934                                NVAR PDDFuseMoore = root:Packages:Irena:PDDFInterface:PDDFuseMoore
1935                                NVAR PDDFuseregularization = root:Packages:Irena:PDDFInterface:PDDFuseregularization
1936                                if(PDDFuseregularization)
1937                                        IRB1_PDDFRunIrenaPDDF()
1938                                        IRB1_PDDFMakeResChi2()
1939                                        IRB1_PDDFAppendPDDFModel()
1940                                        //update calculations...
1941                                        IRB1_PDDFCalculateRgI0()
1942                                elseif(PDDFuseMoore)
1943                                        IRB1_PDDFRunIrenaPDDF()
1944                                        IRB1_PDDFMakeResChi2()
1945                                        IRB1_PDDFAppendPDDFModel()
1946                                        //update calculations...
1947                                        IRB1_PDDFCalculateRgI0()
1948                                else //this is autognom or gnom, handled by one function
1949                                        IRB1_PDDFRunGNOM()
1950                                        //update calculations...
1951                                        IRB1_PDDFCalcSAXSMoW2()
1952                                        IRB1_PDDFMakeResChi2()
1953                                        IRB1_PDDFAppendPDDFModel()                             
1954                                endif
1955                        endif
1956                        if(stringMatch(ba.ctrlName,"SavePDDFresults"))
1957                                IRB1_PDDFSaveResultsToNotebook()
1958                                IRB1_PDDFSaveResultsToFldr()
1959                                IRB1_PDDFSaveToWaves()
1960                                IRB1_SaveToGnomOutFile()
1961                        endif
1962                        if(stringMatch(ba.ctrlName,"RunSequenceofPDDF"))
1963                                IRB1_PDDFFitSequenceOfData()
1964                        endif
1965                        if(stringMatch(ba.ctrlName,"SelectAllData"))
1966                                Wave SelectionOfAvailableData = root:Packages:Irena:PDDFInterface:SelectionOfAvailableData     
1967                                SelectionOfAvailableData = 1
1968                        endif
1969                        if(stringMatch(ba.ctrlName,"ClearGraph"))
1970                                IN2G_RemoveDataFromGraph(topGraphStr = "IRB1_PDDFInterfacePanel#DataDisplay")
1971                        endif
1972                        if(stringMatch(ba.ctrlName,"AutoScaleGraph"))
1973                                SetAxis/W=IRB1_PDDFInterfacePanel#DataDisplay /A
1974                                SetAxis/W=IRB1_PDDFInterfacePanel#PDFDisplay /A
1975                        endif
1976                        if(stringmatch(ba.ctrlName,"GetHelp"))
1977                                IN2G_OpenWebManual("Irena/ImportData.html")                             //fix me!!                     
1978                        endif
1979                        if(stringMatch(ba.ctrlName,"PDDFCalcRgAndMolecularWeight"))
1980                                IRB1_PDDFFitRgAndG()
1981                                IRB1_PDDFCalcSAXSMoW2()
1982                                IRB1_PDDFCalcRamboTainer()
1983                        endif
1984                        if(stringMatch(ba.ctrlName,"OpenResultsAndTable"))
1985                                IR1_CreateResultsNbk()
1986                                DoWindow IRB1_PDDFFitResultsTable
1987                                if(V_Flag)
1988                                        DoWIndow/F IRB1_PDDFFitResultsTable
1989                                else
1990                                        IRB1_PDDFFitResultsTableFnct()
1991                                endif           
1992                        endif
1993                        if(stringMatch(ba.ctrlName,"DeleteResultsAndTable"))
1994                                KillWIndow/Z IRB1_PDDFFitResultsTable
1995                                KillDataFOlder/Z root:PDDFFitResults:
1996                        endif
1997
1998
1999                        break
2000                case -1: // control being killed
2001                        break
2002        endswitch
2003
2004        return 0
2005End
2006//**********************************************************************************************************
2007//**********************************************************************************************************
2008
2009static Function IRB1_PDDFFitSequenceOfData()
2010
2011        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
2012                Wave SelectionOfAvailableData = root:Packages:Irena:PDDFInterface:SelectionOfAvailableData
2013                Wave/T ListOfAvailableData = root:Packages:Irena:PDDFInterface:ListOfAvailableData
2014                NVAR SleepBetweenDataProcesses=root:Packages:Irena:PDDFInterface:SleepBetweenDataProcesses
2015                variable i, imax
2016                imax = numpnts(ListOfAvailableData)
2017                For(i=0;i<imax;i+=1)
2018                        if(SelectionOfAvailableData[i]>0.5)             //data set selected
2019                                IRB1_PDDFAppendOneDataSet(ListOfAvailableData[i])
2020                                NVAR PDDFUseGNOM = root:Packages:Irena:PDDFInterface:PDDFUseGNOM
2021                                NVAR PDDFuseMoore = root:Packages:Irena:PDDFInterface:PDDFuseMoore
2022                                NVAR PDDFuseregularization = root:Packages:Irena:PDDFInterface:PDDFuseregularization
2023                                if(PDDFuseregularization)
2024                                        IRB1_PDDFRunIrenaPDDF()
2025                                        IRB1_PDDFMakeResChi2()
2026                                        IRB1_PDDFAppendPDDFModel()
2027                                        IRB1_PDDFCalculateRgI0()
2028                                elseif(PDDFuseMoore)
2029                                        IRB1_PDDFRunIrenaPDDF()
2030                                        IRB1_PDDFMakeResChi2()
2031                                        IRB1_PDDFAppendPDDFModel()
2032                                        IRB1_PDDFCalculateRgI0()
2033                                else
2034                                        IRB1_PDDFRunGNOM()
2035                                        IRB1_PDDFMakeResChi2()
2036                                        IRB1_PDDFAppendPDDFModel()     
2037                                        IRB1_PDDFCalcSAXSMoW2()                 
2038                                endif
2039                                IRB1_PDDFSaveResultsToNotebook()
2040                                IRB1_PDDFSaveResultsToFldr()
2041                                IRB1_PDDFSaveToWaves()
2042                                IRB1_SaveToGnomOutFile()
2043                                DoUpdate
2044                                if(SleepBetweenDataProcesses>0.5)
2045                                        sleep/S/C=6/M="Fitted data for "+ListOfAvailableData[i] SleepBetweenDataProcesses
2046                                endif
2047                        endif
2048                endfor
2049                print "all selected data processed"
2050end
2051//**********************************************************************************************************
2052//
2053Function IRB1_PDDFCalculateRgI0()
2054
2055        NVAR PDDFCalcRg=root:Packages:Irena:PDDFInterface:RealSpaceRg
2056        NVAR PDDFCalcI0=root:Packages:Irena:PDDFInterface:RealSpaceI0
2057        Wave Radius = root:Packages:Irena:PDDFInterface:pddfRadius
2058        Wave Pr = root:Packages:Irena:PDDFInterface:pddfPr
2059        NVAR ConcentrationForCals=root:Packages:Irena:PDDFInterface:ConcentrationForCals
2060        NVAR ScattLengthDensDifference=root:Packages:Irena:PDDFInterface:ScattLengthDensDifference
2061        NVAR PDDFCalculatedMW=root:Packages:Irena:PDDFInterface:PDDFCalculatedMW
2062       
2063        Duplicate/Free Pr, R2Pr
2064        R2Pr = Radius^2 * Pr
2065       
2066        PDDFCalcI0 = 4*pi*areaXY(Radius, Pr )
2067       
2068        PDDFCalcRg = sqrt(areaXY(Radius, R2Pr )/areaXY(Radius, Pr ))
2069       
2070        PDDFCalculatedMW = 6.023e23*PDDFCalcI0/(ConcentrationForCals*(ScattLengthDensDifference*1e10)^2)
2071
2072end
2073//**********************************************************************************************************
2074//**********************************************************************************************************
2075//**********************************************************************************************************
2076//**********************************************************************************************************
2077
2078
2079Function IRB1_PDDFCalcSAXSMoW2()
2080
2081        Wave OriginalIntensity=root:Packages:Irena:PDDFInterface:Intensity
2082        Wave OriginalQvector=root:Packages:Irena:PDDFInterface:Q_vec
2083        Wave OriginalError=root:Packages:Irena:PDDFInterface:Errors
2084        //now method 1 how to calcualet MW:     
2085        //calculate Molecular weight using SAXSMol2 method...
2086        //now, calculate invariant.
2087        //In this case we follow manuscript for SAXSMoW 2.0, DOI: 10.1002/pro.3528
2088        //Vassili Piadov, Evandro Ares de Araújo, Mario Oliveira Neto,  Aldo Felix Craievich, and Igor Polikarpov
2089        //PROTEIN SCIENCE 2019 | VOL 28:454–463
2090        //use Model data below ~ 0.6*pi/Rg and real data above this as needed...
2091        NVAR MWPorodInvariant=root:Packages:Irena:PDDFInterface:MWPorodInvariant
2092        NVAR ReciprocalPorodVolumeA3=root:Packages:Irena:PDDFInterface:ReciprocalPorodVolumeA3
2093        NVAR RealSpacePorodVolumeA3=root:Packages:Irena:PDDFInterface:RealSpacePorodVolumeA3
2094        NVAR MWMassDensityProtein=root:Packages:Irena:PDDFInterface:MWMassDensityProtein                        //g/cm3, see line after formula 11
2095        NVAR SAXSMoW2MWRecSpacekDa=root:Packages:Irena:PDDFInterface:SAXSMoW2MWRecSpacekDa
2096        NVAR SAXSMoW2MWRealSpacekDa=root:Packages:Irena:PDDFInterface:SAXSMoW2MWRealSpacekDa   
2097        NVAR InvariantCalcQmax8overRg = root:Packages:Irena:PDDFInterface:InvariantCalcQmax8overRg
2098        NVAR InvariantCalcQmaxLog225 = root:Packages:Irena:PDDFInterface:InvariantCalcQmaxLog225       
2099        NVAR InvariantCalcQmax = root:Packages:Irena:PDDFInterface:InvariantCalcQmax
2100        IRB1_PDDFRecalculareQmax()                              //this will set Qmax as needed... //formula 7 or 8 or user choice
2101        //alternative is to pick InvariantCalcQmax based on Formula 8, so log(I(o)/I(gmax) ~ 2.25
2102        NVAR ReciprocalSpaceI0=root:Packages:Irena:PDDFInterface:ReciprocalSpaceI0
2103        NVAR ReciprocalSpaceRg=root:Packages:Irena:PDDFInterface:ReciprocalSpaceRg
2104        NVAR ReciprocalSpaceB=root:Packages:Irena:PDDFInterface:ReciprocalSpaceB
2105        NVAR ReciprocalSpacePorodSlope=root:Packages:Irena:PDDFInterface:ReciprocalSpacePorodSlope
2106        variable TempNumPoints=2000
2107        Make/Free/N=(TempNumPoints) InvariantIntWv, InvariantQWv, InvarQstar, InvarIntQ2
2108        variable Bval, Aval
2109        variable Vprime
2110        variable ChangeToRealIntP, QValueToChange       
2111        if(ReciprocalSpaceI0>0 && ReciprocalSpaceRg>1)                                                                                                                  //prevent crash when user did not run the Guinier fit...
2112                InvariantQWv            =       p*(InvariantCalcQmax/(numpnts(InvariantQWv)-1))+0.00002                                 //this creates Q wave between 0.00002 and qmax
2113                InvarQstar                      =       InvariantQWv / (erf(InvariantQWv*ReciprocalSpaceRg/sqrt(6)))^3                                                  //Q* for Unified level
2114                InvariantIntWv          =       ReciprocalSpaceI0*exp(-InvariantQWv^2*ReciprocalSpaceRg^2/3)+(ReciprocalSpaceB/InvarQstar^ReciprocalSpacePorodSlope)                    //no background Unified intensity
2115                //now we need to replace intensity from somethign around 0.6*pi/Rg with experimental intensity
2116                QValueToChange  =       0.4*pi/ReciprocalSpaceRg
2117                ChangeToRealIntP        =       BinarySearch(InvariantQWv,QValueToChange )
2118                InvariantIntWv[ChangeToRealIntP, ] = OriginalIntensity[BinarySearchInterp(OriginalQvector, InvariantQWv[p])]
2119                //done, this shoudl now have attached tail of real data...
2120                InvarIntQ2 = InvariantIntWv * InvariantQWv^2                                                                                                                    //I * Q^2
2121                MWPorodInvariant = areaXY(InvariantQWv, InvarIntQ2)                                                                                                     //this is from Q=0 to Q=InvariantCalcQmax
2122                Vprime = 2*pi^2*ReciprocalSpaceI0/MWPorodInvariant                                                                                      //this is formula 5
2123                //setup the weird approximation of missing tail correction for invariant...
2124                //this is formula 10
2125                Aval = -2.114e6 * InvariantCalcQmax^4 + 2.920e6 * InvariantCalcQmax^3 - 1.472e6*InvariantCalcQmax^2 + 3.349e5*InvariantCalcQmax - 3.577e4
2126                Bval = 12.09*InvariantCalcQmax^3 - 9.39*InvariantCalcQmax^2 + 3.03*InvariantCalcQmax + 0.29
2127                ReciprocalPorodVolumeA3  = Aval + Bval*Vprime                                                                                                           //this is in A^3
2128                //formula 11
2129                SAXSMoW2MWRecSpacekDa = MWMassDensityProtein*ReciprocalPorodVolumeA3* 1e-24     /1.662e-21     
2130        else
2131                SAXSMoW2MWRecSpacekDa = 0
2132                ReciprocalPorodVolumeA3 = 0             
2133        endif   
2134        // and if we have Intensity from GNOM, here is real space SAXSMoW2 calculation:
2135        NVAR RealSpaceRg = root:Packages:Irena:PDDFInterface:RealSpaceRg
2136        NVAR RealSpaceI0 = root:Packages:Irena:PDDFInterface:RealSpaceI0
2137        NVAR PDDFCalculatedMW=root:Packages:Irena:PDDFInterface:PDDFCalculatedMW
2138        NVAR ConcentrationForCals=root:Packages:Irena:PDDFInterface:ConcentrationForCals
2139        NVAR ScattLengthDensDifference=root:Packages:Irena:PDDFInterface:ScattLengthDensDifference
2140        Wave/Z pddfModelIntExtrap = root:Packages:Irena:PDDFInterface:pddfModelIntExtrap
2141        Wave/Z pddfQvecExtrap = root:Packages:Irena:PDDFInterface:pddfQvecExtrap
2142        if(RealSpaceI0>0 && WaveExists(pddfModelIntExtrap) && WaveExists(pddfQvecExtrap))       //GNOM generated data exist...
2143                Duplicate/Free pddfModelIntExtrap, InvarIntQ2GNOM
2144                InvarIntQ2GNOM = pddfModelIntExtrap * pddfQvecExtrap^2
2145                MWPorodInvariant = areaXY(pddfQvecExtrap, InvarIntQ2GNOM)
2146                Vprime = 2*pi^2*RealSpaceI0/MWPorodInvariant                                                                                            //this is formula 5
2147                variable GNOMQmax=pddfQvecExtrap[numpnts(pddfQvecExtrap)-1]
2148                Aval = -2.114e6 * GNOMQmax^4 + 2.920e6 * GNOMQmax^3 - 1.472e6*GNOMQmax^2 + 3.349e5*GNOMQmax - 3.577e4
2149                Bval = 12.09*GNOMQmax^3 - 9.39*GNOMQmax^2 + 3.03*GNOMQmax + 0.29
2150                RealSpacePorodVolumeA3  = Aval + Bval*Vprime
2151                SAXSMoW2MWRealSpacekDa = MWMassDensityProtein*RealSpacePorodVolumeA3* 1e-24     /1.662e-21     
2152                //and this is calculation from absolute intensity
2153                PDDFCalculatedMW = 6.023e23*RealSpaceI0/(ConcentrationForCals*(ScattLengthDensDifference*1e10)^2)
2154        else
2155                SAXSMoW2MWRealSpacekDa = 0
2156                PDDFCalculatedMW = 0
2157                RealSpacePorodVolumeA3 = 0
2158        endif
2159        //this ends calculations for SAXSMoW2 ...
2160        Wave/Z FitScatteringProfile=root:Packages:Irena:PDDFInterface:FitScatteringProfile
2161        if(WaveExists(FitScatteringProfile))
2162                CheckDisplayed /W=IRB1_PDDFInterfacePanel#DataDisplay FitScatteringProfile
2163                if(V_Flag)
2164                        string Tagtext="\\F"+IN2G_LkUpDfltStr("FontType")+"\\Z"+IN2G_LkUpDfltVar("TagSize")+"SAXSMoW2 Rg [A] = "+num2str(ReciprocalSpaceRg)+"\r"
2165                        Tagtext+="\\F"+IN2G_LkUpDfltStr("FontType")+"\\Z"+IN2G_LkUpDfltVar("TagSize")+"I0 = "+num2str(ReciprocalSpaceI0)
2166                        //Tagtext+="\\F"+IN2G_LkUpDfltStr("FontType")+"\\Z"+IN2G_LkUpDfltVar("TagSize")+"Protein Vol [cm3] = "+num2str(ReciprocalPorodVolumeA3)+"\r"
2167                        Tagtext+="\\F"+IN2G_LkUpDfltStr("FontType")+"\\Z"+IN2G_LkUpDfltVar("TagSize")+"     MW [kDa] = "+num2str(SAXSMoW2MWRecSpacekDa)
2168                        Tag/C/N=GuessRg/A=LT/L=0/TL=0/W=IRB1_PDDFInterfacePanel#DataDisplay FitScatteringProfile, numpnts(FitScatteringProfile)/10,Tagtext
2169                endif
2170        endif
2171
2172        //***
2173
2174end
2175//**********************************************************************************************************
2176//**********************************************************************************************************
2177//**********************************************************************************************************
2178//**********************************************************************************************************
2179//**********************************************************************************************************
2180
2181
2182Function IRB1_PDDFCalcRamboTainer()
2183
2184        Wave OriginalIntensity=root:Packages:Irena:PDDFInterface:Intensity
2185        Wave OriginalQvector=root:Packages:Irena:PDDFInterface:Q_vec
2186        Wave OriginalError=root:Packages:Irena:PDDFInterface:Errors
2187
2188///
2189
2190        //now method from Rambo-Tainer, doi:10.1038/nature12070, Nature 2013, vol. 496, pg 477
2191        //Accurate assessment of mass, models and resolution by small-angle scattering
2192        //here is what this does:
2193        //1. Calculate Vc = I(0)/2*pi*Lc= I(0)/IntgQ*I(Q)dQ
2194        //calculate Qr (really, do we really have to use Q in some many meanings???) Qr=Vc^2/Rg         [A^3]
2195        //and now they plotted for Proteins and Nucelic acis separate dependnecies... Got approximately linar depency
2196        // ln(Q) = a* ln(MW) + b
2197        // protein MW= (Qr/0.1231)^1.0
2198        //Nucelic acid MW= (Qr/0.00934)^0.808
2199        //but first , we need to fit data with background also:
2200        NVAR InvariantCalcQmax8overRg = root:Packages:Irena:PDDFInterface:InvariantCalcQmax8overRg
2201        NVAR InvariantCalcQmaxLog225 = root:Packages:Irena:PDDFInterface:InvariantCalcQmaxLog225       
2202        NVAR InvariantCalcQmax = root:Packages:Irena:PDDFInterface:InvariantCalcQmax
2203        NVAR RamboTainerSubtractFlatBackground = root:Packages:Irena:PDDFInterface:RamboTainerSubtractFlatBackground
2204        NVAR RamboTainerFlatBackground = root:Packages:Irena:PDDFInterface:RamboTainerFlatBackground
2205        NVAR RamboTainerAutoSetBckg = root:Packages:Irena:PDDFInterface:RamboTainerAutoSetBckg
2206        IRB1_PDDFRecalculareQmax()                              //this will set Qmax as needed...
2207        //QstarVector = OriginalQvector / (erf(OriginalQvector*w_coef[1]/sqrt(6)))^3
2208        //FitScatteringProfile =  w_coef[0]*exp(-OriginalQvector^2*w_coef[1]^2/3)+(w_coef[2]/QstarVector^w_coef[3]) + w_coef[4]
2209        variable TempNumPoints=2000
2210        NVAR RamboTainerMWRecSpacekDa=root:Packages:Irena:PDDFInterface:RamboTainerMWRecSpacekDa
2211        NVAR PDDFUseNucleicAcid=root:Packages:Irena:PDDFInterface:PDDFUseNucleicAcid
2212        NVAR PDDFUseProtein=root:Packages:Irena:PDDFInterface:PDDFUseProtein
2213        NVAR ReciprocalSpaceI0=root:Packages:Irena:PDDFInterface:ReciprocalSpaceI0
2214        NVAR ReciprocalSpaceRg=root:Packages:Irena:PDDFInterface:ReciprocalSpaceRg
2215        NVAR ReciprocalSpaceB=root:Packages:Irena:PDDFInterface:ReciprocalSpaceB
2216        NVAR ReciprocalSpacePorodSlope=root:Packages:Irena:PDDFInterface:ReciprocalSpacePorodSlope
2217        if(ReciprocalSpaceRg<1 || ReciprocalSpacePorodSlope<1)
2218                return 0
2219        endif
2220
2221        Make/Free/N=(TempNumPoints) RamboTainerIntQ, RamboTainerQ, RamboTainerInt, RamboTainerQstar
2222        variable Qmaxmeasured=OriginalQvector[numpnts(OriginalQvector)-3]
2223        RamboTainerQ = p*(Qmaxmeasured/(numpnts(RamboTainerQ)-1))+0.00002                               //this creates Q wave between 0.00002 and qmax measured
2224        RamboTainerQstar = RamboTainerQ / (erf(RamboTainerQ*ReciprocalSpaceRg/sqrt(6)))^3       
2225        RamboTainerInt = ReciprocalSpaceI0*exp(-RamboTainerQ^2*ReciprocalSpaceRg^2/3)+(ReciprocalSpaceB/RamboTainerQstar^ReciprocalSpacePorodSlope)
2226        variable QValueToChange         =       0.4*pi/ReciprocalSpaceRg
2227        variable ChangeToRealIntP=BinarySearch(RamboTainerQ,QValueToChange)
2228        RamboTainerInt[ChangeToRealIntP, ] = OriginalIntensity[BinarySearchInterp(OriginalQvector, RamboTainerQ[p])]
2229        if(RamboTainerSubtractFlatBackground)
2230                RamboTainerInt -= RamboTainerFlatBackground                                             //this subtract approximate background from the data.
2231        endif
2232        RamboTainerIntQ = RamboTainerInt*RamboTainerQ
2233        //***                   Qmax for integration of Q*I(Q) is challenge...
2234        variable IntgQIQ=areaXY(RamboTainerQ, RamboTainerIntQ, 0, InvariantCalcQmax )
2235        //    now calculate I*Q vs Q to display in DataDisplay plot...
2236        Duplicate/O RamboTainerInt, TotalScatteredInt, IntgQIntensity
2237        Duplicate/O RamboTainerQ, TotalScatteredQ
2238        TotalScatteredInt = RamboTainerInt*RamboTainerQ
2239        multithread IntgQIntensity = areaXY(TotalScatteredQ, TotalScatteredInt, 0, TotalScatteredQ[p] )
2240        IN2G_RemoveDataFromGraph(topGraphStr = "IRB1_PDDFInterfacePanel#PDFDisplay")
2241        AppendToGraph /W=IRB1_PDDFInterfacePanel#PDFDisplay  TotalScatteredInt  vs TotalScatteredQ
2242        AppendToGraph /W=IRB1_PDDFInterfacePanel#PDFDisplay/R  IntgQIntensity  vs TotalScatteredQ
2243        ModifyGraph/W=IRB1_PDDFInterfacePanel#PDFDisplay  mirror(bottom)=1
2244        ModifyGraph/W=IRB1_PDDFInterfacePanel#PDFDisplay lstyle(IntgQIntensity)=3,rgb(IntgQIntensity)=(0,0,65535)
2245        //              SetAxis/W=IRB1_PDDFInterfacePanel#PDFDisplay/A/E=1 left
2246
2247        Label/W=IRB1_PDDFInterfacePanel#PDFDisplay left "Q * I(Q)"
2248        Label/W=IRB1_PDDFInterfacePanel#PDFDisplay right "sum(Q * I(Q)) to Qmax"
2249        Label/W=IRB1_PDDFInterfacePanel#PDFDisplay bottom "Q [1/A]"
2250        variable RTVc           =       ReciprocalSpaceI0/IntgQIQ
2251        variable RTQr           =       (RTVc)^2 / ReciprocalSpaceRg
2252        if(PDDFUseProtein)
2253                RamboTainerMWRecSpacekDa        =       (RTQr/0.1231)^1.0
2254                RamboTainerMWRecSpacekDa        /=      1000                                            //convert to kDA from DA               
2255        elseif(PDDFUseNucleicAcid)
2256        //Update tag result...
2257                RamboTainerMWRecSpacekDa        =       (RTQr/0.00934)^0.808
2258                RamboTainerMWRecSpacekDa        /=      1000                                            //convert to kDA from DA               
2259        endif
2260
2261end
2262//**********************************************************************************************************
2263//**********************************************************************************************************
2264//**********************************************************************************************************
2265//**********************************************************************************************************
2266
2267Function IRB1_PDDFFitRgAndG()
2268
2269        DFref oldDf= GetDataFolderDFR()
2270        setDataFolder root:Packages:Irena:PDDFInterface
2271
2272        Wave OriginalIntensity=root:Packages:Irena:PDDFInterface:Intensity
2273        Wave OriginalQvector=root:Packages:Irena:PDDFInterface:Q_vec
2274        Wave OriginalError=root:Packages:Irena:PDDFInterface:Errors
2275        variable AcsrPnt=pcsr(A, "IRB1_PDDFInterfacePanel#DataDisplay")
2276        variable BcsrPnt=pcsr(B, "IRB1_PDDFInterfacePanel#DataDisplay")
2277        if(AcsrPnt>BcsrPnt)             //somehow user got this confused here...
2278                variable tempV=BcsrPnt
2279                BcsrPnt = AcsrPnt
2280                AcsrPnt = tempV
2281        endif
2282        //Fit Data to I(0) and Rg
2283        //First fit is between cursors and without bacground, this is equivalent to linearization fit
2284        variable Rg
2285        Variable G
2286        Variable B
2287        G = OriginalIntensity[0]
2288        FindLevel /P/Q OriginalIntensity, OriginalIntensity[0]*0.3
2289        variable GetQAtRg=OriginalQvector[V_levelX]
2290        Rg = 2/GetQAtRg
2291        B = OriginalIntensity[V_levelX]*OriginalQvector[V_levelX]^4
2292        Make /N=4/O W_coef, LocalEwave
2293        Make/N=4/T/O T_Constraints
2294        T_Constraints[0] = {"K1 > 0"}
2295        T_Constraints[1] = {"K0 > 0"}
2296        T_Constraints[2] = {"K2 > 0"}
2297        T_Constraints[3] = {"K3 > 2"}
2298        //T_Constraints[4] = {"K4 >=0 "}
2299        Variable V_FitError=0                   //This should prevent errors from being generated
2300        W_coef[0]=G     //G
2301        W_coef[1]=Rg    //Rg
2302        W_coef[2]=B     //B
2303        W_coef[3]=3.2   //Porod slope
2304        //W_coef[4]=OriginalIntensity[numpnts(OriginalIntensity)-20]    //background
2305        FuncFit/Q IRB1_PDDFIntensityFit W_coef OriginalIntensity[AcsrPnt,BcsrPnt]  /X=OriginalQvector /C=T_Constraints /W=OriginalError /I=1//E=LocalEwave
2306        if (V_FitError!=0)      //there was error in fitting
2307                beep
2308                Abort "Fitting error, Cannot fit Rg or otehr parameters"
2309        endif
2310        //Store Unified fit results.
2311        G = w_coef[0]
2312        Rg = w_coef[1]
2313        B = w_coef[2]
2314        variable PorodSLope=w_coef[3]
2315        //variable Background = w_coef[4]
2316        //these are globasl for them
2317        NVAR ReciprocalSpaceI0=root:Packages:Irena:PDDFInterface:ReciprocalSpaceI0
2318        NVAR ReciprocalSpaceRg=root:Packages:Irena:PDDFInterface:ReciprocalSpaceRg
2319        NVAR ReciprocalSpaceB=root:Packages:Irena:PDDFInterface:ReciprocalSpaceB
2320        NVAR ReciprocalSpacePorodSlope=root:Packages:Irena:PDDFInterface:ReciprocalSpacePorodSlope
2321       
2322        ReciprocalSpaceI0 = G
2323        ReciprocalSpaceRg = Rg
2324        ReciprocalSpaceB = B
2325        ReciprocalSpacePorodSlope = PorodSLope
2326        //calculate Intensity to display
2327        Duplicate/O OriginalIntensity, QstarVector, FitScatteringProfile
2328        QstarVector = OriginalQvector / (erf(OriginalQvector*w_coef[1]/sqrt(6)))^3
2329        FitScatteringProfile =  w_coef[0]*exp(-OriginalQvector^2*w_coef[1]^2/3)+(w_coef[2]/QstarVector^w_coef[3])// + w_coef[4]
2330        CheckDisplayed /W=IRB1_PDDFInterfacePanel#DataDisplay  FitScatteringProfile 
2331        if(!V_flag)
2332                GetAxis /W=IRB1_PDDFInterfacePanel#DataDisplay /Q left
2333                AppendToGraph  /W=IRB1_PDDFInterfacePanel#DataDisplay  FitScatteringProfile  vs OriginalQvector
2334                ModifyGraph /W=IRB1_PDDFInterfacePanel#DataDisplay lstyle(FitScatteringProfile)=2,lsize(FitScatteringProfile)=1
2335                ModifyGraph /W=IRB1_PDDFInterfacePanel#DataDisplay rgb(FitScatteringProfile)=(1,3,39321)
2336        endif
2337        SetAxis/W=IRB1_PDDFInterfacePanel#DataDisplay/A left
2338
2339        //Second fit is from A cursor tomax Q and with bacground, this is For Rambo-Tainer to have background, if needed... 
2340        Make /N=5/O W_coef, LocalEwave
2341        Make/N=5/T/O T_Constraints
2342        T_Constraints[0] = {"K1 > 0"}
2343        T_Constraints[1] = {"K0 > 0"}
2344        T_Constraints[2] = {"K2 > 0"}
2345        T_Constraints[3] = {"K3 > 2"}
2346        T_Constraints[4] = {"K4 >=0 "}
2347        V_FitError=0                    //This should prevent errors from being generated
2348        W_coef[0]=G     //G
2349        W_coef[1]=Rg    //Rg
2350        W_coef[2]=B     //B
2351        W_coef[3]=3.2   //Porod slope
2352        W_coef[4]=OriginalIntensity[numpnts(OriginalIntensity)-20]      //background
2353        FuncFit/Q IRB1_PDDFIntensityFitBckg W_coef OriginalIntensity[AcsrPnt, ]  /X=OriginalQvector /C=T_Constraints /W=OriginalError /I=1//E=LocalEwave
2354        if (V_FitError!=0)      //there was error in fitting
2355                beep
2356                Abort "Fitting error in Rambo-Tainer method, Cannot fit Rg or other parameters"
2357        endif
2358        //Store Unified fit results.
2359        variable RTB, RTG, RTRg, RTP, RTBackground
2360        RTG = w_coef[0]
2361        RTRg = w_coef[1]
2362        RTB = w_coef[2]
2363        RTP =   w_coef[3]
2364        RTBackground =  w_coef[4]
2365        //calculate Intensity to display
2366        Duplicate/O OriginalIntensity, QstarVector, FitScatteringProfileBckg
2367        QstarVector = OriginalQvector / (erf(OriginalQvector*w_coef[1]/sqrt(6)))^3
2368        FitScatteringProfileBckg =  w_coef[0]*exp(-OriginalQvector^2*w_coef[1]^2/3)+(w_coef[2]/QstarVector^w_coef[3]) + w_coef[4]
2369        CheckDisplayed /W=IRB1_PDDFInterfacePanel#DataDisplay  FitScatteringProfileBckg 
2370        if(!V_flag)
2371                GetAxis /W=IRB1_PDDFInterfacePanel#DataDisplay /Q left
2372                AppendToGraph  /W=IRB1_PDDFInterfacePanel#DataDisplay  FitScatteringProfileBckg  vs OriginalQvector
2373                ModifyGraph /W=IRB1_PDDFInterfacePanel#DataDisplay lstyle(FitScatteringProfileBckg)=9,lsize(FitScatteringProfileBckg)=1
2374                ModifyGraph /W=IRB1_PDDFInterfacePanel#DataDisplay rgb(FitScatteringProfileBckg)=(3,52428,1)
2375        endif
2376        NVAR RamboTainerAutoSetBckg=root:Packages:Irena:PDDFInterface:RamboTainerAutoSetBckg
2377        NVAR RamboTainerFlatBackground=root:Packages:Irena:PDDFInterface:RamboTainerFlatBackground
2378        if(RamboTainerAutoSetBckg)
2379                RamboTainerFlatBackground = RTBackground
2380        endif
2381
2382
2383       
2384        KillWaves/Z LocalEwave, W_coef, T_constraints, QstarVector
2385        SetDataFolder oldDf
2386end
2387//*****************************************************************************************************************
2388//*****************************************************************************************************************
2389
2390Function IRB1_PDDFIntensityFit(w,q) : FitFunc
2391        Wave w
2392        Variable q
2393
2394        //CurveFitDialog/ These comments were created by the Curve Fitting dialog. Altering them will
2395        //CurveFitDialog/ make the function less convenient to work with in the Curve Fitting dialog.
2396        //CurveFitDialog/ Equation:
2397        //CurveFitDialog/ Prefactor=abs(Prefactor)
2398        //CurveFitDialog/ Rg=abs(Rg)
2399        //CurveFitDialog/ f(q) = Prefactor*exp(-q^2*Rg^2/3))
2400        //CurveFitDialog/ End of Equation
2401        //CurveFitDialog/ Independent Variables 1
2402        //CurveFitDialog/ q
2403        //CurveFitDialog/ Coefficients 2
2404        //CurveFitDialog/ w[0] = Prefactor
2405        //CurveFitDialog/ w[1] = Rg
2406        //CurveFitDialog/ w[2] = Porod prefactor
2407        //CurvefitDialog/ w[3] = PorodSlope
2408
2409        w[0]=abs(w[0])
2410        w[1]=abs(w[1])
2411        w[2]=abs(w[2])
2412        w[3]=abs(W[3])
2413        variable qstar=q/(erf(q*w[1]/sqrt(6)))^3
2414        return w[0]*exp(-q^2*w[1]^2/3)+(w[2]/qstar^w[3])
2415        //       QstarVector=QvectorWave/(erf(QvectorWave*Rg/sqrt(6)))^3
2416        //  G*exp(-QvectorWave^2*Rg^2/3)+(B/QstarVector^P)
2417
2418End
2419//*****************************************************************************************************************
2420//*****************************************************************************************************************
2421
2422Function IRB1_PDDFIntensityFitBckg(w,q) : FitFunc
2423        Wave w
2424        Variable q
2425
2426        //CurveFitDialog/ These comments were created by the Curve Fitting dialog. Altering them will
2427        //CurveFitDialog/ make the function less convenient to work with in the Curve Fitting dialog.
2428        //CurveFitDialog/ Equation:
2429        //CurveFitDialog/ Prefactor=abs(Prefactor)
2430        //CurveFitDialog/ Rg=abs(Rg)
2431        //CurveFitDialog/ f(q) = Prefactor*exp(-q^2*Rg^2/3))
2432        //CurveFitDialog/ End of Equation
2433        //CurveFitDialog/ Independent Variables 1
2434        //CurveFitDialog/ q
2435        //CurveFitDialog/ Coefficients 2
2436        //CurveFitDialog/ w[0] = Prefactor
2437        //CurveFitDialog/ w[1] = Rg
2438        //CurveFitDialog/ w[2] = Porod prefactor
2439        //CurvefitDialog/ w[3] = PorodSlope
2440        //CurvefitDialog/ w[4] = Background
2441
2442        //       QstarVector=QvectorWave/(erf(QvectorWave*Rg/sqrt(6)))^3
2443        //  G*exp(-QvectorWave^2*Rg^2/3)+(B/QstarVector^P) + background
2444
2445        w[0]=abs(w[0])
2446        w[1]=abs(w[1])
2447        w[2]=abs(w[2])
2448        w[3]=abs(W[3])
2449        variable qstar=q/(erf(q*w[1]/sqrt(6)))^3
2450        return w[0]*exp(-q^2*w[1]^2/3)+(w[2]/qstar^w[3])+w[4]
2451End
2452
2453//*****************************************************************************************************************
2454//*****************************************************************************************************************
2455
2456//*****************************************************************************************************************
2457//*****************************************************************************************************************
2458
2459//*****************************************************************************************************************
2460//**********************************************************************************************************
2461static Function IRB1_PDDFMakeResChi2()
2462
2463        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
2464        DfRef OldDf=GetDataFolderDFR()
2465        setDataFolder root:Packages:Irena:PDDFInterface
2466        wave/Z pddfInputIntensity = root:Packages:Irena:PDDFInterface:pddfInputIntensity
2467        Wave/Z pddfInputError = root:Packages:Irena:PDDFInterface:pddfInputError
2468        Wave/Z PDDFModelIntensity = root:Packages:Irena:PDDFInterface:PDDFModelIntensity
2469        Wave/Z pddfRadius                               =root:Packages:Irena:PDDFInterface:pddfRadius
2470        Wave/Z pddfPr                                   =root:Packages:Irena:PDDFInterface:pddfPr
2471        if(!WaveExists(pddfInputIntensity)||!WaveExists(pddfPr)||!WaveExists(PDDFModelIntensity))
2472                return 0
2473        endif
2474        Duplicate/O pddfInputIntensity, NormalizedResidual, ChisquaredWave      //waves for data
2475        IN2G_AppendorReplaceWaveNote("NormalizedResidual","Units"," ")
2476        IN2G_AppendorReplaceWaveNote("ChisquaredWave","Units"," ")
2477        NormalizedResidual=(pddfInputIntensity-PDDFModelIntensity)/pddfInputError               //we need this for graph
2478        ChisquaredWave=NormalizedResidual^2                                                                                     //and this is wave with Chisquared
2479        Duplicate/O pddfPr, CurrentResultsGamma
2480        CurrentResultsGamma = pddfPr/(4*pi*pddfPr^2)
2481
2482        setDataFolder oldDF
2483end
2484//**********************************************************************************************************
2485//**********************************************************************************************************
2486
2487Function IRB1_PDDFRunGNOM()
2488
2489        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
2490        DfRef OldDf=GetDataFolderDFR()
2491        SetDataFolder root:Packages:Irena:PDDFInterface
2492        //OK, these are existing data user wants to run ATSAS DATGNOM (formerly known as AUTOGNOM)
2493        //https://www.embl-hamburg.de/biosaxs/manuals/datpddf.html
2494        //process:
2495        //1. write out ASCII file q,r,s
2496        //2. run script for DATGNOM
2497        //3. load final result back in and display for users.
2498        SVAR DataFolderName=root:Packages:Irena:PDDFInterface:DataFolderName
2499        SVAR IntensityWaveName=root:Packages:Irena:PDDFInterface:IntensityWaveName
2500        SVAR QWavename=root:Packages:Irena:PDDFInterface:QWavename
2501        SVAR ErrorWaveName=root:Packages:Irena:PDDFInterface:ErrorWaveName
2502        NVAR DataQEnd = root:Packages:Irena:PDDFInterface:DataQEnd
2503        NVAR DataQstart = root:Packages:Irena:PDDFInterface:DataQstart
2504        NVAR DataQEndPoint = root:Packages:Irena:PDDFInterface:DataQEndPoint
2505        NVAR DataQstartPoint = root:Packages:Irena:PDDFInterface:DataQstartPoint
2506
2507        SVAR DATGNOMLocation=root:Packages:Irena:PDDFInterface:DATGNOMLocation
2508        SVAR FittingResults=root:Packages:Irena:PDDFInterface:FittingResults
2509        //parameters to use...
2510        NVAR DmaxEstimate=root:Packages:Irena:PDDFInterface:DmaxEstimate
2511        NVAR NumBinsInR=root:Packages:Irena:PDDFInterface:NumBinsInR
2512        NVAR GnomForceRmin0=root:Packages:Irena:PDDFInterface:GnomForceRmin0
2513        NVAR GnomForceRmax0=root:Packages:Irena:PDDFInterface:GnomForceRmax0
2514        NVAR GnomAlfaValue=root:Packages:Irena:PDDFInterface:GnomAlfaValue
2515        NVAR PDDFUseGNOM                                        =root:Packages:Irena:PDDFInterface:PDDFUseGNOM
2516        NVAR PDDFUseAutoGNOM                            =root:Packages:Irena:PDDFInterface:PDDFUseAutoGNOM
2517
2518
2519        //locate system tempPath
2520        newPath/O/Q/C ATSASWorkPath, (SpecialDirPath("Temporary", 0, 0, 0)+"IrenaATSAStmp:")            //this is Igor formated path
2521        PathInfo ATSASWorkPath
2522        String PathToATSASWorkPath = ParseFilePath(5, S_Path, "*", 0, 0)                                                        //this is system formated path
2523        ////   PRG2 HD:Users:ilavsky:tmp:IrenaATSAStmp:
2524        //locate DATGNOM
2525        PathInfo DATGNOMPath
2526        if(V_Flag<0.5)  //does not exist
2527                newPath/O/Q/Z DATGNOMPath, DATGNOMLocation              //this is Igor formated path
2528                if(V_Flag!=0)
2529                        string PathToApps = SpecialDirPath("Igor Application", 0, 0, 0)
2530                        PathToApps = RemoveListItem(ItemsInList(PathToApps, ":")-1, PathToApps, ":")            //remove Igor Pro X Folder
2531                        PathToApps = RemoveFromList("Wavemetrics", PathToApps, ":", 0)          //Remove Wavemetrics folder
2532                        newPath/O/Q/Z DATGNOMPath, PathToApps
2533                endif
2534        endif
2535        //now, find if the DATGNOM
2536        //are we on Windows or mac?
2537        string datgnomName=""
2538        string datgnomNameTemp
2539        if(PDDFUseGNOM)
2540                datgnomName="gnom"
2541        elseif(PDDFUseAutoGNOM)
2542                datgnomName="datgnom"
2543        else
2544                Abort "Unknown gnom executable selected"
2545        endif
2546        //On WIndows, to test for gnom, need gnom.exe, but to run, no extension. Make life difficutl... 
2547        if(stringmatch(IgorInfo(2),"Windows"))
2548                datgnomNameTemp=datgnomName+".exe"
2549        else
2550                datgnomNameTemp=datgnomName
2551        endif
2552        GetFileFolderInfo /Q/Z/P=DATGNOMPath datgnomNameTemp
2553        if(V_Flag!=0)
2554                DoAlert /T="GNOM/datGNOM executable not found" 0, "In next dialog locate FOLDER, where executable gnom (gnom.exe) and datgnom (datgnom.exe) files are located, please. Typically Windows: Program Files (x86)\ATSAS 3.01\bin and MacOS: Applications:ATSAS:bin"
2555                GetFileFolderInfo/D/P=DATGNOMPath datgnomNameTemp
2556                newPath/O/Q/Z DATGNOMPath, S_Path
2557                DATGNOMLocation = S_Path
2558        endif
2559        //At this moment we should have DATGNOMLocation be string with Igor path to datpddf and datpddfeName be name of executable.
2560        GetFileFolderInfo /Q/Z/P=DATGNOMPath datgnomNameTemp
2561        if(V_Flag!=0)
2562                Abort "Cannot find properly datgnom executable, something is worng here. Report as bug to author, please" 
2563        endif   
2564        //now export the data file.
2565        Wave/Z SourceIntWv=$(DataFolderName+IntensityWaveName)
2566        Wave/Z SourceQWv=$(DataFolderName+QWavename)
2567        Wave/Z SourceErrorWv=$(DataFolderName+ErrorWaveName)
2568        if(!WaveExists(SourceIntWv)||!WaveExists(SourceQWv)||!WaveExists(SourceErrorWv))
2569                Abort "Cannot find QRS data to export"
2570        endif
2571        //trim data to user selected range
2572        Duplicate/Free/R=[DataQstartPoint,DataQEndPoint] SourceQWv, ExportQ
2573        Duplicate/Free/R=[DataQstartPoint,DataQEndPoint] SourceIntWv, ExportInt
2574        Duplicate/Free/R=[DataQstartPoint,DataQEndPoint] SourceErrorWv, ExportErr
2575        //save the data file. Simply 3 columns, QRS
2576        Save/G/O/M="\n"/P=ATSASWorkPath ExportQ,ExportInt,ExportErr as "DataIn.dat"
2577        //create script file...
2578        string cmd, ATSASPath, OutputFilePath, InputFilePath
2579        ATSASPath = RemoveFromList("bin", DATGNOMLocation, ":")
2580        //notes on how to run this nightmare:
2581        //1. One needs to change directory to ATSAS folder.
2582        //2. there we can start ./bin/datpddf4
2583        //3. Input file must have absolute path to file
2584        //4. Need to specify absolute file to output file, or it will be created in ATSAS folder...
2585        //Oh dear...   
2586        string rminForce, rmaxForce, alphaValForce, NumBinsForce, RgForce, GnomWInPath, wincmd
2587        if(GnomForceRmin0)
2588                //rminForce=" --rmin=Yes "
2589                rminForce=""
2590        else
2591                rminForce=" --rmin=No "
2592        endif
2593        if(GnomForceRmax0)
2594                rmaxForce=""
2595                //rmaxForce=" --rmax=Yes "
2596        else
2597                rmaxForce=" --rmax=No "
2598        endif
2599        if(GnomAlfaValue>0.001)
2600                alphaValForce=" --alpha="+num2str(GnomAlfaValue)+" "
2601        else
2602                alphaValForce=""
2603        endif
2604        if(NumBinsInR>0.001)
2605                NumBinsForce=" --nr="+num2str(NumBinsInR)+" "
2606        else
2607                NumBinsForce=""
2608        endif
2609        RgForce = " --rmax="+Num2Str(DmaxEstimate)
2610        string unixCmd, igorCmd
2611        if(stringmatch(IgorInfo(2),"Windows"))                                                          //Windows script...     
2612                //this will need to be customized on Windows...
2613                GnomWInPath =  ParseFilePath(5, DATGNOMLocation, "\\", 0, 0)
2614                InputFilePath = ParseFilePath(5, PathToATSASWorkPath, "\\", 0, 0)+"DataIn.dat"
2615                OutputFilePath = ParseFilePath(5, PathToATSASWorkPath, "\\", 0, 0)+"DataOut.out"       
2616                if(PDDFUseGNOM)
2617                        //and now build it together
2618                        //note, this is needeed, see the " - whole command is "" as well as each part which may contain spaces.
2619                        //example from https://stackoverflow.com/questions/6376113/how-do-i-use-spaces-in-the-command-prompt
2620                        //  cmd /C ""C:\Program Files (x86)\WinRar\Rar.exe" a "D:\Hello 2\File.rar" "D:\Hello 2\*.*""
2621                        wincmd="cmd.exe /C \"\""+GnomWInPath+datgnomName+".exe\" \""+InputFilePath+"\""+RgForce+NumBinsForce+alphaValForce+rmaxForce+rminForce+" -o \""+OutputFilePath+"\"\""           
2622                        //print wincmd
2623                elseif(PDDFUseAutoGNOM)
2624                        wincmd="cmd.exe /C  \"\""+GnomWInPath+datgnomName+".exe\" \""+InputFilePath+"\" -r "+Num2Str(DmaxEstimate)+" -o \""+OutputFilePath+"\"\""                       
2625                        //print wincmd
2626                else
2627                        ABort "Unknown gnom executable selected"
2628                endif
2629                ExecuteScriptText/Z  wincmd
2630                if(V_Flag!=0)   //error happened
2631                        Abort "There was error scripting and running GNOM/DATGNOM"
2632                endif
2633                //Print S_value         // actually datgnom adn gnom do report anything contrary to datgnom4...
2634                //FittingResults = S_value
2635        else                                                                            //Mac, need to convert to Posix path
2636                ATSASPath = "'"+ParseFilePath(9, ATSASPath, "*", 0, 0)+"'"
2637                InputFilePath ="'"+ ParseFilePath(9, PathToATSASWorkPath, "*", 0, 0)+"DataIn.dat'"
2638                OutputFilePath = "'"+ParseFilePath(9, PathToATSASWorkPath, "*", 0, 0)+"DataOut.out'"   
2639                if(PDDFUseGNOM)
2640                        //and now build it together
2641                        unixCmd="cd "+ATSASPath+";./bin/"+datgnomName+" "+InputFilePath+RgForce+NumBinsForce+alphaValForce+rmaxForce+rminForce+" -o "+OutputFilePath           
2642                elseif(PDDFUseAutoGNOM)
2643                        unixCmd="cd "+ATSASPath+";./bin/"+datgnomName+" "+InputFilePath+" -r "+Num2Str(DmaxEstimate)+" -o "+OutputFilePath             
2644                else
2645                        ABort "Unknown gnom executable selected"
2646                endif
2647                //unixCmd="cd "+ATSASPath+";./bin/"+datgnomName+" "+InputFilePath+" -r "+Num2Str(DmaxEstimate)+" -o "+OutputFilePath   
2648                sprintf igorCmd, "do shell script \"%s\"", unixCmd
2649                //Print igorCmd         // For debugging only
2650                ExecuteScriptText/UNQ/Z igorCmd
2651                if(V_Flag!=0)   //error happened
2652                        Abort "There was error scripting and running GNOM/DATGNOM"
2653                endif
2654                //Print S_value         // actually datgnom adn gnom do report anything contrary to datgnom4...
2655                //FittingResults = S_value
2656        endif
2657        //import GNOM output file in Irena
2658        SetDataFolder root:Packages:Irena:PDDFInterface
2659        make/O/N=5000/T GNOMOutFileTextWave     
2660        GNOMOutFileTextWave = ""
2661        variable refNum, i=0
2662        string TmpStr
2663        Open /P=ATSASWorkPath/R refNum  as "DataOut.out"
2664        Do
2665                TmpStr = ""
2666                FReadLine /T="\n" refNum, TmpStr
2667                GNOMOutFileTextWave[i]=TmpStr
2668                i+=1
2669        while(strlen(TmpStr)>0)
2670        close refNum
2671        redimension/N=(i) GNOMOutFileTextWave
2672        KillDataFolder/Z root:Packages:Irena:PDDFTemp
2673        NewDataFolder/O/S root:Packages:Irena:PDDFTemp 
2674        LoadWave/G/D/Q/N/P=ATSASWorkPath "DataOut.out"
2675        variable NumLoadedWaves = ItemsInList(S_waveNames,";")
2676        //now looking at this...
2677        //last three waves are      R          P(R)      ERROR
2678        //lets call them something useful
2679        Wave pddfRad = $("wave"+num2str(NumLoadedWaves-3))
2680        Wave pddfPrr = $("wave"+num2str(NumLoadedWaves-2))
2681        Wave pddfEr = $("wave"+num2str(NumLoadedWaves-1))
2682        //five before that are:     S          J EXP       ERROR       J REG       I REG
2683        Wave pddfModelIntGunier = $("wave"+num2str(NumLoadedWaves-4))
2684        Wave pddfModelInt = $("wave"+num2str(NumLoadedWaves-5))
2685        Wave pddfInputErr = $("wave"+num2str(NumLoadedWaves-6))
2686        Wave pddfInputInt = $("wave"+num2str(NumLoadedWaves-7))
2687        Wave pddfQvec = $("wave"+num2str(NumLoadedWaves-8))                                     
2688        //and this is the main part where thre are all columns.
2689        //early part of column 1 and 5 are in
2690        Wave pddfQvecSt = $("wave"+num2str(NumLoadedWaves-10))                                 
2691        Wave pddfModelIntGunierSt = $("wave"+num2str(NumLoadedWaves-9))
2692        //great. how do we call this stuff???
2693        //fix for unknown data, columnd 5 designated as pddfModelErr seems to have copy fo column 4 in it
2694        //seems like extended model data to Q=0.
2695        //For now not sure what to do with it,. so set to 0
2696        //If possible, I would like to have three sets of SAXS data from this out file:
2697        //(1) col #1, #2, #3 (with same meaningful length);
2698        //(2) col #1, #4, #3; and
2699        //(3) col #1, #5
2700        //Last column is the fitted data with intensities extrapolating to q=0 using Guinier equation.
2701        //SAXS data (3) sometime is useful.
2702        SetDataFolder root:Packages:Irena:PDDFInterface:
2703        Duplicate/O pddfQvec, pddfInputQVector
2704        Duplicate/O pddfInputInt, pddfInputIntensity
2705        Duplicate/O pddfInputErr, pddfInputError
2706        Duplicate/O pddfQvec, pddfModelQvector
2707        Duplicate/O pddfModelInt, PDDFModelIntensity
2708        Duplicate/O pddfRad, pddfRadius
2709        Duplicate/O pddfPrr, pddfPr
2710        Duplicate/O pddfEr, pddfPrError
2711        //now the extetrapolated data
2712        Make/O/N=(numpnts(pddfModelIntGunierSt)+numpnts(pddfModelIntGunier)), pddfQvecExtrap, pddfModelIntExtrap
2713        pddfQvecExtrap[0,numpnts(pddfModelIntGunierSt)-1] = pddfQvecSt[p]
2714        pddfQvecExtrap[numpnts(pddfModelIntGunierSt), ] = pddfQvec[p-numpnts(pddfModelIntGunierSt)]
2715        pddfModelIntExtrap[0,numpnts(pddfModelIntGunierSt)-1] = pddfModelIntGunierSt[p]
2716        pddfModelIntExtrap[numpnts(pddfModelIntGunierSt), ] = pddfModelIntGunier[p-numpnts(pddfModelIntGunierSt)]
2717        //now parse this into a document and alfa
2718        Wave/T GNOMOutFileTextWave = root:Packages:Irena:PDDFInterface:GNOMOutFileTextWave
2719        //read values from out file... 
2720        NVAR GNOMAlfaResult = root:Packages:Irena:PDDFInterface:GNOMAlfaResult
2721        NVAR RealSpaceRg = root:Packages:Irena:PDDFInterface:RealSpaceRg
2722        NVAR RealSpaceI0 = root:Packages:Irena:PDDFInterface:RealSpaceI0
2723        make/Free/T/N=0 TempStrWave
2724        Grep /E="Current ALPHA:" GNOMOutFileTextWave as TempStrWave     
2725        GNOMAlfaResult = str2num(StringFromList(1, TempStrWave[0]+":", ":"))
2726        Grep /E="Real space Rg:" GNOMOutFileTextWave as TempStrWave     
2727        RealSpaceRg = str2num(StringFromList(1, TempStrWave[0]+":", ":"))
2728        Grep /E="Real space I" GNOMOutFileTextWave as TempStrWave       
2729        RealSpaceI0 = str2num(StringFromList(1, TempStrWave[0]+":", ":"))
2730        print "***************************************************************************"
2731        For(i=0;i<60;i+=1)
2732                if(strlen(GNOMOutFileTextWave[i])>5)
2733                        print RemoveEnding(GNOMOutFileTextWave[i], "\n")
2734                endif
2735        endfor
2736        print "***************************************************************************"
2737        //and delete the path we created...
2738        PathInfo ATSASWorkPath
2739        //IN2G_ForceDeleteFolder(S_Path)                //leave the file in Temporary folder, system will clean it up at some point.
2740        KillPath/Z DATGNOMPath
2741        KillPath/Z ATSASWorkPath
2742        //print "Delete following folder from your desktop : "+PathToATSASWorkPath
2743        setDataFolder OldDf
2744end
2745//**************************************************************************************
2746//**************************************************************************************
2747Static Function IRB1_SaveToGnomOutFile()
2748
2749        NVAR SaveToGNOMOut = root:Packages:Irena:PDDFInterface:SaveToGNOMOut
2750        Wave/Z/T GNOMOutFileTextWave = root:Packages:Irena:PDDFInterface:GNOMOutFileTextWave
2751        SVAR DataFolderName = root:Packages:Irena:PDDFInterface:DataFolderName
2752        if(SaveToGNOMOut && WaveExists(GNOMOutFileTextWave))
2753                //now we want to save this to where user Igor experiment is...
2754                PathInfo  home
2755                string PathToStore=S_path
2756                if(strlen(PathToStore)<1)       //Igor experiment not saved, no home path exists...
2757                        DoAlert 0, "You need to save this Igor experiment first, so we know where to put those GNOM out files"
2758                        SaveExperiment
2759                endif
2760                //OK, now Igor experiment is saved.
2761                //create a new path, which will be next to the Igor experiment and have GNOM out files.
2762                string ExpName=IgorInfo(1)
2763                string FldrName=ExpName+"_GNOM_Out"
2764                PathInfo home
2765                NewPath /C/O/Q GNOMOutFiles , S_Path+FldrName
2766                string FileNameOut=StringFromList(ItemsInList(DataFolderName, ":")-1, DataFolderName, ":")
2767                Duplicate/Free/T GNOMOutFileTextWave, TempStrWave
2768                TempStrWave = ReplaceString("\n", TempStrWave[p], "")
2769                TempStrWave = ReplaceString("\r", TempStrWave[p], "")
2770                GetFileFolderInfo /P=GNOMOutFiles /Q /Z (FileNameOut+".out")
2771                if(V_Flag==0)
2772                        DoAlert 1, "The file : "+ FileNameOut+".out" +" already exists, do you want to overwrite it?"
2773                        if(V_Flag!=1)
2774                                abort
2775                        endif
2776                endif
2777                Save/G/M="\n"/O/P=GNOMOutFiles TempStrWave as (FileNameOut+".out")
2778               
2779               
2780        endif
2781
2782end
2783
2784//**************************************************************************************
2785//**************************************************************************************
2786
2787static Function IRB1_PDDFRunIrenaPDDF()
2788       
2789        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
2790        DfRef OldDf=GetDataFolderDFR()
2791        //script old PDDF model here...
2792        //basically, need to run: IR2Pr_PdfFitting
2793        IR2Pr_InitializePDDF() 
2794        DoWIndow/K/Z IR2Pr_PDFInputGraph
2795        NVAR SlitSmearedData=root:Packages:Irena_PDDF:UseSMRData       
2796        SlitSmearedData = 0
2797        //done prep
2798        SVAR DataFolderName=root:Packages:Irena:PDDFInterface:DataFolderName
2799        SVAR IntensityWaveName=root:Packages:Irena:PDDFInterface:IntensityWaveName
2800        SVAR QWavename=root:Packages:Irena:PDDFInterface:QWavename
2801        SVAR ErrorWaveName=root:Packages:Irena:PDDFInterface:ErrorWaveName
2802        NVAR DataQEnd = root:Packages:Irena:PDDFInterface:DataQEnd
2803        NVAR DataQstart = root:Packages:Irena:PDDFInterface:DataQstart
2804        NVAR DataQEndPoint = root:Packages:Irena:PDDFInterface:DataQEndPoint
2805        NVAR DataQstartPoint = root:Packages:Irena:PDDFInterface:DataQstartPoint
2806        //COpy data where they belong:
2807        //this is IR2Pr_InputPanelButtonProc work:
2808        SVAR DFloc=root:Packages:Irena_PDDF:DataFolderName
2809        SVAR DFInt=root:Packages:Irena_PDDF:IntensityWaveName
2810        SVAR DFQ=root:Packages:Irena_PDDF:QWaveName
2811        SVAR DFE=root:Packages:Irena_PDDF:ErrorWaveName
2812        NVAR UseRegularization=root:Packages:Irena_PDDF:UseRegularization
2813        NVAR UseMoore=root:Packages:Irena_PDDF:UseMoore
2814        NVAR PDDFUseGNOM = root:Packages:Irena:PDDFInterface:PDDFUseGNOM
2815        NVAR PDDFuseMoore = root:Packages:Irena:PDDFInterface:PDDFuseMoore
2816        NVAR PDDFuseregularization = root:Packages:Irena:PDDFInterface:PDDFuseregularization
2817        NVAR Moore_DetNumFncts = root:Packages:Irena_PDDF:Moore_DetNumFncts
2818        NVAR Moore_HolDmaxSize = root:Packages:Irena_PDDF:Moore_HolDmaxSize
2819        NVAR MaximumR = root:Packages:Irena_PDDF:MaximumR
2820        NVAR NumberOfBins = root:Packages:Irena_PDDF:NumberOfBins
2821        NVAR DmaxBio=root:Packages:Irena:PDDFInterface:DmaxEstimate
2822        NVAR NumBinsBio=root:Packages:Irena:PDDFInterface:NumBinsInR
2823        NVAR MooreDetNumFnctsBio=root:Packages:Irena:PDDFInterface:MooreDetNumFunctions
2824        NVAR MooreFitMaxSizeBio=root:Packages:Irena:PDDFInterface:MooreFitMaxSize
2825        //set the values...
2826        UseRegularization = PDDFuseregularization
2827        UseMoore = PDDFuseMoore
2828        DFloc = DataFolderName
2829        DFInt = IntensityWaveName
2830        DFQ = QWavename
2831        DFE = ErrorWaveName
2832        Moore_DetNumFncts=MooreDetNumFnctsBio
2833        Moore_HolDmaxSize = MooreFitMaxSizeBio
2834        MaximumR = DmaxBio
2835        NumberOfBins = NumBinsBio
2836        if(NumberOfBins<100)
2837                NumberOfBins = 100
2838        endif
2839        //start processing
2840        IR2Pr_SelectAndCopyData()
2841        Execute("IR2Pr_PdfInputGraph()")                                //this creates the graph
2842        Cursor/P/W=IR2Pr_PDFInputGraph A  IntensityOriginal  DataQstartPoint
2843        Cursor/P /W=IR2Pr_PDFInputGraph B  IntensityOriginal  DataQEndPoint
2844        //IR2Pr_EstimateDmax()
2845        //and now run:  IR2Pr_PdfFitting
2846        IR2Pr_PdfFitting("EIther")
2847        DoWindow/K/Z IR2Pr_PDFInputGraph
2848        //now pickup the data from the folder and copy to current folder...
2849        Wave CurrentResultPdf = root:Packages:Irena_PDDF:CurrentResultPdf
2850        Wave R_distribution=root:Packages:Irena_PDDF:R_distribution
2851        Wave PDDFErrors = root:Packages:Irena_PDDF:PDDFErrors
2852        Wave Intensity = root:Packages:Irena_PDDF:Intensity
2853        Wave Q_vec=root:Packages:Irena_PDDF:Q_vec
2854        Wave Errors= root:Packages:Irena_PDDF:Errors
2855        Wave PdfFitIntensity = root:Packages:Irena_PDDF:PdfFitIntensity
2856        SVAR FittingResultsIrena = root:Packages:Irena_PDDF:FittingResults
2857        SVAR FittingResults=root:Packages:Irena:PDDFInterface:FittingResults
2858        setDataFolder root:Packages:Irena:PDDFInterface
2859        FittingResults = FittingResultsIrena   
2860        Duplicate/O Q_vec, pddfInputQVector
2861        Duplicate/O Intensity, pddfInputIntensity
2862        Duplicate/O Errors, pddfInputError
2863        Duplicate/O Q_vec, pddfModelQvector
2864        Duplicate/O PdfFitIntensity, PDDFModelIntensity
2865        Duplicate/O PDDFErrors, pddfModelError
2866        Duplicate/O R_distribution, pddfRadius
2867        Duplicate/O CurrentResultPdf, pddfPr
2868        Duplicate/O PDDFErrors, pddfPrError
2869        //DmaxBio = MaximumR
2870        //NumBinsBio = NumberOfBins
2871        KillWindow/Z IR2PR_GammaFunction
2872        setDataFolder OldDf
2873       
2874end
2875//**********************************************************************************************************
2876//**************************************************************************************
2877//**************************************************************************************
2878static Function IRB1_PDDFAppendPDDFModel()
2879
2880        DoWIndow IRB1_PDDFInterfacePanel
2881        if(!V_Flag)
2882                return 0
2883        endif
2884        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
2885        DfRef OldDf=GetDataFolderDFR()
2886        SetDataFolder root:Packages:Irena:PDDFInterface                                 //go into the folder
2887
2888        Wave/Z pddfInputQVector         =root:Packages:Irena:PDDFInterface:pddfInputQVector
2889        Wave/Z pddfInputIntensity       =root:Packages:Irena:PDDFInterface:pddfInputIntensity
2890        Wave/Z pddfInputError                   =root:Packages:Irena:PDDFInterface:pddfInputError
2891        Wave/Z pddfModelQvector         =root:Packages:Irena:PDDFInterface:pddfModelQvector
2892        Wave/Z PDDFModelIntensity       =root:Packages:Irena:PDDFInterface:PDDFModelIntensity
2893        //Wave/Z pddfModelError                 =root:Packages:Irena:PDDFInterface:pddfModelError
2894        Wave/Z pddfRadius                               =root:Packages:Irena:PDDFInterface:pddfRadius
2895        Wave/Z pddfPr                                   =root:Packages:Irena:PDDFInterface:pddfPr
2896        Wave/Z pddfPrError                              =root:Packages:Irena:PDDFInterface:pddfPrError
2897       
2898        if(WaveExists(pddfPr)&&WaveExists(pddfInputIntensity)&&WaveExists(PDDFModelIntensity))
2899                CheckDisplayed /W=IRB1_PDDFInterfacePanel#DataDisplay PDDFModelIntensity
2900                if(!V_flag)
2901                        AppendToGraph /W=IRB1_PDDFInterfacePanel#DataDisplay  PDDFModelIntensity  vs pddfModelQvector
2902                endif
2903                ModifyGraph/W=IRB1_PDDFInterfacePanel#DataDisplay mode(PDDFModelIntensity)=3,marker(PDDFModelIntensity)=8,msize(PDDFModelIntensity)=4,rgb(PDDFModelIntensity)=(0,0,65535)
2904               
2905                IN2G_RemoveDataFromGraph(topGraphStr = "IRB1_PDDFInterfacePanel#PDFDisplay")
2906                CheckDisplayed /W=IRB1_PDDFInterfacePanel#PDFDisplay pddfPr
2907                if(!V_flag)
2908                        AppendToGraph /W=IRB1_PDDFInterfacePanel#PDFDisplay  pddfPr  vs pddfRadius
2909                        ErrorBars /W=IRB1_PDDFInterfacePanel#PDFDisplay pddfPr Y,wave=(pddfPrError,pddfPrError)         
2910                endif
2911                ModifyGraph/W=IRB1_PDDFInterfacePanel#PDFDisplay mirror=1
2912                SetAxis/W=IRB1_PDDFInterfacePanel#PDFDisplay/A/E=0 left
2913        else
2914                DoAlert /T="Did not find GNOM data" 0, "Something went wrong, did not find PDDF data"
2915        endif
2916        Label/W=IRB1_PDDFInterfacePanel#PDFDisplay left "P(r)"
2917        Label/W=IRB1_PDDFInterfacePanel#PDFDisplay bottom "Radius [A]"
2918        SetDataFolder oldDf
2919end
2920//**************************************************************************************
2921//**************************************************************************************
2922//**************************************************************************************
2923//**************************************************************************************
2924//cannot be static, called from panel.
2925Function IRB1_PDDFAppendOneDataSet(FolderNameStr)
2926        string FolderNameStr
2927       
2928        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
2929        DfRef OldDf=GetDataFolderDFR()
2930        SetDataFolder root:Packages:Irena:PDDFInterface                                 //go into the folder
2931        SVAR DataStartFolder=root:Packages:Irena:PDDFInterface:DataStartFolder
2932        SVAR DataFolderName=root:Packages:Irena:PDDFInterface:DataFolderName
2933        SVAR IntensityWaveName=root:Packages:Irena:PDDFInterface:IntensityWaveName
2934        SVAR QWavename=root:Packages:Irena:PDDFInterface:QWavename
2935        SVAR ErrorWaveName=root:Packages:Irena:PDDFInterface:ErrorWaveName
2936        SVAR dQWavename=root:Packages:Irena:PDDFInterface:dQWavename
2937        NVAR UseIndra2Data=root:Packages:Irena:PDDFInterface:UseIndra2Data
2938        NVAR UseQRSdata=root:Packages:Irena:PDDFInterface:UseQRSdata
2939        //zero old values to prevent stale.
2940        IRB1_PDDFResetValuesToPreventStale      ()
2941        //get the names of waves, assume this tool actually works. May not under some conditions. In that case this tool will not work.
2942        IR3C_SelectWaveNamesData("Irena:PDDFInterface", FolderNameStr)                  //this routine will preset names in strings as needed,  DataFolderName = DataStartFolder+FolderNameStr
2943        Wave/Z SourceIntWv=$(DataFolderName+IntensityWaveName)
2944        Wave/Z SourceQWv=$(DataFolderName+QWavename)
2945        Wave/Z SourceErrorWv=$(DataFolderName+ErrorWaveName)
2946        Wave/Z SourcedQWv=$(DataFolderName+dQWavename)
2947        if(!WaveExists(SourceIntWv)||   !WaveExists(SourceQWv)||!WaveExists(SourceErrorWv))
2948                Abort "Data selection failed for Data"
2949        endif
2950        //copy to working folder, so we can work with the data when needed..
2951        Duplicate/O SourceIntWv, $("root:Packages:Irena:PDDFInterface:Intensity")
2952        Duplicate/O SourceQWv, $("root:Packages:Irena:PDDFInterface:Q_vec")
2953        Duplicate/O SourceErrorWv, $("root:Packages:Irena:PDDFInterface:Errors")
2954        //now attach to graph...
2955        IN2G_RemoveDataFromGraph(topGraphStr = "IRB1_PDDFInterfacePanel#DataDisplay")
2956        CheckDisplayed /W=IRB1_PDDFInterfacePanel#DataDisplay SourceIntWv
2957        if(!V_flag)
2958                AppendToGraph /W=IRB1_PDDFInterfacePanel#DataDisplay  SourceIntWv  vs SourceQWv
2959                ModifyGraph /W=IRB1_PDDFInterfacePanel#DataDisplay log=1, mirror=1
2960                Label /W=IRB1_PDDFInterfacePanel#DataDisplay left "Intensity 1"
2961                Label /W=IRB1_PDDFInterfacePanel#DataDisplay bottom "Q [A\\S-1\\M]"
2962                ErrorBars /W=IRB1_PDDFInterfacePanel#DataDisplay $(NameOfWave(SourceIntWv)) Y,wave=(SourceErrorWv,SourceErrorWv)
2963        endif
2964        //set cursors
2965        NVAR DataQEnd = root:Packages:Irena:PDDFInterface:DataQEnd
2966        NVAR DataQstart = root:Packages:Irena:PDDFInterface:DataQstart
2967        NVAR DataQEndPoint = root:Packages:Irena:PDDFInterface:DataQEndPoint
2968        NVAR DataQstartPoint = root:Packages:Irena:PDDFInterface:DataQstartPoint
2969        if(DataQstartPoint<1)
2970                DataQstartPoint=1
2971                DataQstart=SourceQWv[1]
2972        else
2973                DataQstartPoint = round(BinarySearchInterp(SourceQWv, DataQstart) )
2974        endif
2975        if(DataQEndPoint<10)
2976                DataQEndPoint=numpnts(SourceQWv)-5
2977                DataQEnd= SourceQWv[DataQEndPoint]
2978        else
2979                DataQEndPoint = round(BinarySearchInterp(SourceQWv, DataQEnd) )
2980        endif
2981        Cursor /P/W=IRB1_PDDFInterfacePanel#DataDisplay A  $(nameofWave(SourceIntWv))  DataQstartPoint
2982        Cursor /P/W=IRB1_PDDFInterfacePanel#DataDisplay B  $(nameofWave(SourceIntWv))  DataQEndPoint
2983       
2984        IN2G_ColorTopGrphRainbow(topGraphStr="IRB1_PDDFInterfacePanel#DataDisplay")
2985        IN2G_LegendTopGrphFldr(12, 20, 1, 0, topGraphStr="IRB1_PDDFInterfacePanel#DataDisplay")
2986        NVAR DisplayErrorBars = root:Packages:Irena:PDDFInterface:DisplayErrorBars
2987        IN2G_ShowHideErrorBars(DisplayErrorBars, topGraphStr="IRB1_PDDFInterfacePanel#DataDisplay")
2988       
2989       
2990        SetDataFolder oldDf
2991end
2992//**********************************************************************************************************
2993//**********************************************************************************************************
2994//**********************************************************************************************************
2995
2996Function IRB1_PDDFGraphWindowHook(s)
2997        STRUCT WMWinHookStruct &s
2998
2999        Variable hookResult = 0
3000
3001        switch(s.eventCode)
3002                case 0:                         // Activate
3003                        // Handle activate
3004                        break
3005
3006                case 1:                         // Deactivate
3007                        // Handle deactivate
3008                        break
3009                case 7:                         //coursor moved
3010                        IRB1_PDDFRecordCursorPosition(s.traceName,s.cursorName,s.pointNumber)
3011                        hookResult = 1
3012                // And so on . . .
3013        endswitch
3014
3015        return hookResult       // 0 if nothing done, else 1
3016End
3017
3018//**********************************************************************************************************
3019//**********************************************************************************************************
3020//**********************************************************************************************************
3021
3022static Function IRB1_PDDFRecordCursorPosition(traceName,CursorName,PointNumber)
3023        string traceName,CursorName
3024        variable PointNumber
3025
3026        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
3027        NVAR DataQEnd = root:Packages:Irena:PDDFInterface:DataQEnd
3028        NVAR DataQstart = root:Packages:Irena:PDDFInterface:DataQstart
3029        NVAR DataQEndPoint = root:Packages:Irena:PDDFInterface:DataQEndPoint
3030        NVAR DataQstartPoint = root:Packages:Irena:PDDFInterface:DataQstartPoint
3031        Wave/Z CursorAWave = CsrWaveRef(A, "IRB1_PDDFInterfacePanel#DataDisplay")
3032        Wave/Z CursorBWave = CsrWaveRef(B, "IRB1_PDDFInterfacePanel#DataDisplay")
3033        Wave/Z CursorAXWave= CsrXWaveRef(A, "IRB1_PDDFInterfacePanel#DataDisplay")
3034        Wave/Z CursorBXWave= CsrXWaveRef(B, "IRB1_PDDFInterfacePanel#DataDisplay")
3035        string CursorAWaveName = CsrWave(A, "IRB1_PDDFInterfacePanel#DataDisplay")
3036
3037        variable tempMaxQ, tempMaxQY, tempMinQY, maxY, minY, tempP, tempQ
3038        variable LinDataExist = 0
3039        //check if user removed cursor from graph, in which case do nothing for now...
3040        if(numtype(PointNumber)==0)
3041                if(stringmatch(CursorName,"A"))         //moved cursor A, which is start of Q range
3042                        DataQstartPoint = PointNumber
3043                        DataQstart = CursorAXWave[PointNumber]
3044                endif
3045                if(stringmatch(CursorName,"B"))         //moved cursor B, which is end of Q range
3046                        DataQEndPoint = PointNumber
3047                        DataQEnd = CursorBXWave[PointNumber]
3048                endif
3049                if(DataQstartPoint>DataQEndPoint)               //ths is confused, fix for users...
3050                        tempQ = DataQEnd
3051                        tempP =  DataQEndPoint
3052                        DataQEndPoint = DataQstartPoint
3053                        DataQEnd = DataQstart
3054                        DataQstartPoint = tempP
3055                        DataQstart = tempQ
3056                        Cursor/W=IRB1_PDDFInterfacePanel#DataDisplay A  CursorAWaveName  DataQstartPoint
3057                        Cursor/W=IRB1_PDDFInterfacePanel#DataDisplay B  CursorAWaveName  DataQEndPoint
3058                endif
3059        endif
3060end
3061//**********************************************************************************************************
3062//**********************************************************************************************************
3063//**********************************************************************************************************
3064static Function IRB1_PDDFInitialize()
3065       
3066        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
3067        DfRef OldDf=GetDataFolderDFR()
3068       
3069        NewDataFolder/O/S root:Packages
3070        NewDataFolder/O/S root:Packages:Irena
3071        NewDataFolder/O/S root:Packages:Irena:PDDFInterface
3072       
3073        string ListOfStrings
3074        string ListOfVariables
3075        variable i
3076       
3077        ListOfStrings = "DataPathName;DataExtension;IntName;QvecName;ErrorName;NewDataFolderName;NewIntensityWaveName;DataTypeToImport;"
3078        ListOfStrings+="NewQWaveName;NewErrorWaveName;NewQErrorWavename;NameMatchString;TooManyPointsWarning;RemoveStringFromName;"
3079        ListOfStrings+="DATGNOMLocation;FittingResults;"
3080
3081        ListOfVariables = "UseFileNameAsFolder;UseIndra2Names;UseQRSNames;DataContainErrors;UseQISNames;"
3082        ListOfVariables += "DisplayErrorBars;DataQEnd;DataQstart;DataQEndPoint;DataQstartPoint;"       
3083        ListOfVariables += "SleepBetweenDataProcesses;OverwriteExistingData;DisplayErrorBars;" 
3084        ListOfVariables += "PDDFUseGNOM;PDDFuseMoore;PDDFuseregularization;PDDFUseAutoGNOM;"   
3085        ListOfVariables += "DmaxEstimate;CalculateDmaxEstOnImport;GnomForceRmin0;GnomForceRmax0;NumBinsInR;GnomAlfaValue;"     
3086        ListOfVariables += "MooreNumFunctions;MooreDetNumFunctions;MooreFitMaxSize;"   
3087        ListOfVariables += "RealSpaceRg;RealSpaceI0;ConcentrationForCals;ScattLengthDensDifference;PDDFCalculatedMW;RealSpacePorodVolumeA3;"   
3088        ListOfVariables += "RamboTainerMWRecSpacekDa;InvariantCalcQmax8overRg;InvariantCalcQmax;InvariantCalcQmaxLog225;"
3089        ListOfVariables += "RamboTainerSubtractFlatBackground;RamboTainerFlatBackground;RamboTainerAutoSetBckg;"
3090        ListOfVariables += "SaveToFolder;SaveToNotebook;SaveToWaves;SaveToGNOMOut;"     
3091        ListOfVariables += "MWPorodInvariant;ReciprocalPorodVolumeA3;MWMassDensityProtein;SAXSMoW2MWRecSpacekDa;SAXSMoW2MWRealSpacekDa;"       
3092        ListOfVariables += "GNOMAlfaResult;ReciprocalSpaceI0;ReciprocalSpaceRg;PDDFUseProtein;PDDFUseNucleicAcid;ReciprocalSpaceB;ReciprocalSpacePorodSlope;"
3093
3094                //and here we create them
3095        for(i=0;i<itemsInList(ListOfVariables);i+=1)   
3096                IN2G_CreateItem("variable",StringFromList(i,ListOfVariables))
3097        endfor         
3098                                                               
3099        for(i=0;i<itemsInList(ListOfStrings);i+=1)     
3100                IN2G_CreateItem("string",StringFromList(i,ListOfStrings))
3101        endfor 
3102       
3103        Make/O/T/N=0 WaveOfFiles
3104        Make/O/N=0 WaveOfSelections
3105       
3106        SVAR DATGNOMLocation
3107        if(strlen(DATGNOMLocation)<1)
3108                DATGNOMLocation=" "
3109        endif
3110       
3111        NVAR PDDFUseGNOM
3112        NVAR PDDFuseMoore
3113        NVAR PDDFuseregularization
3114        NVAR PDDFUseAutoGNOM
3115        if(PDDFUseGNOM+PDDFuseMoore+PDDFuseregularization+PDDFUseAutoGNOM!=1)
3116                PDDFUseGNOM = 1
3117                PDDFuseMoore = 0
3118                PDDFuseregularization = 0
3119                PDDFUseAutoGNOM = 0
3120        endif
3121        NVAR DmaxEstimate
3122        if(DmaxEstimate<1)
3123                DmaxEstimate=30
3124        endif   
3125        NVAR GnomForceRmin0
3126        GnomForceRmin0 = 1
3127        NVAR GnomForceRmax0
3128        GnomForceRmax0 = 1
3129        NVAR NumBinsInR
3130//      if(NumBinsInR<10)
3131//              NumBinsInR = 100
3132//      endif
3133        NVAR GnomAlfaValue
3134        NVAR ConcentrationForCals
3135        if(ConcentrationForCals<0.0001)
3136                ConcentrationForCals=1
3137        endif
3138        NVAR MooreNumFunctions
3139        if(MooreNumFunctions<50)
3140                MooreNumFunctions = 101
3141        endif
3142        NVAR MooreFitMaxSize
3143        MooreFitMaxSize = 1
3144       
3145        NVAR PDDFUseProtein
3146        NVAR PDDFUseNucleicAcid
3147        NVAR MWMassDensityProtein
3148        NVAR ScattLengthDensDifference
3149        if(PDDFUseProtein+PDDFUseNucleicAcid!=1)
3150                PDDFUseProtein = 1
3151                PDDFUseNucleicAcid = 0
3152        endif
3153        IRB1_PDDFSetDensitySLD()       
3154        IRB1_PDDFResetValuesToPreventStale()
3155       
3156        NVAR SaveToFolder
3157        NVAR SaveToNotebook
3158        NVAR SaveToWaves
3159        if(SaveToFolder+SaveToNotebook+SaveToWaves<1)
3160                SaveToFolder=1
3161                SaveToNotebook=1
3162                SaveToWaves=1
3163        endif
3164        NVAR CalculateDmaxEstOnImport
3165        CalculateDmaxEstOnImport= 0
3166end
3167//**********************************************************************************************************
3168static Function IRB1_PDDFResetValuesToPreventStale()
3169        //zero old values to prevent stale.
3170        DFRef OldDF=GetDataFolderDFR()
3171        setDataFolder root:Packages:Irena:PDDFInterface
3172       
3173        NVAR MWPorodInvariant = root:Packages:Irena:PDDFInterface:MWPorodInvariant
3174        NVAR ReciprocalPorodVolumeA3 = root:Packages:Irena:PDDFInterface:ReciprocalPorodVolumeA3
3175        NVAR MWMassDensityProtein = root:Packages:Irena:PDDFInterface:MWMassDensityProtein
3176        NVAR SAXSMoW2MWRecSpacekDa = root:Packages:Irena:PDDFInterface:SAXSMoW2MWRecSpacekDa
3177        NVAR ReciprocalSpaceI0=root:Packages:Irena:PDDFInterface:ReciprocalSpaceI0
3178        NVAR ReciprocalSpaceRg=root:Packages:Irena:PDDFInterface:ReciprocalSpaceRg
3179        NVAR ReciprocalSpaceB=root:Packages:Irena:PDDFInterface:ReciprocalSpaceB
3180        NVAR ReciprocalSpacePorodSlope=root:Packages:Irena:PDDFInterface:ReciprocalSpacePorodSlope
3181        NVAR RealSpaceRg = root:Packages:Irena:PDDFInterface:RealSpaceRg
3182        NVAR RealSpaceI0 = root:Packages:Irena:PDDFInterface:RealSpaceI0
3183        NVAR PDDFCalculatedMW = root:Packages:Irena:PDDFInterface:PDDFCalculatedMW
3184        NVAR GNOMAlfaResult=root:Packages:Irena:PDDFInterface:GNOMAlfaResult
3185        NVAR RamboTainerMWRecSpacekDa = root:Packages:Irena:PDDFInterface:RamboTainerMWRecSpacekDa
3186        NVAR PDDFCalcRg=root:Packages:Irena:PDDFInterface:RealSpaceRg
3187        NVAR PDDFCalcI0=root:Packages:Irena:PDDFInterface:RealSpaceI0
3188        NVAR ConcentrationForCals=root:Packages:Irena:PDDFInterface:ConcentrationForCals
3189        NVAR ScattLengthDensDifference=root:Packages:Irena:PDDFInterface:ScattLengthDensDifference
3190        NVAR PDDFCalculatedMW=root:Packages:Irena:PDDFInterface:PDDFCalculatedMW
3191        NVAR GNOMAlfaResult = root:Packages:Irena:PDDFInterface:GNOMAlfaResult
3192        NVAR SAXSMoW2MWRealSpacekDa = root:Packages:Irena:PDDFInterface:SAXSMoW2MWRealSpacekDa
3193        NVAR RealSpacePorodVolumeA3=root:Packages:Irena:PDDFInterface:RealSpacePorodVolumeA3
3194        //these are variables used by the control procedure
3195        //NVAR UseResults=  root:Packages:Irena:PDDFInterface:UseResults
3196        //NVAR UseUserDefinedData=  root:Packages:Irena:PDDFInterface:UseUserDefinedData
3197        //NVAR UseModelData = root:Packages:Irena:PDDFInterface:UseModelData
3198        SAXSMoW2MWRealSpacekDa = 0
3199        RealSpacePorodVolumeA3 = 0
3200        //UseResults = 0
3201        //UseUserDefinedData = 0
3202        //UseModelData = 0
3203        //delete GNOM out file, if exists...
3204        //Wave/Z GNOMOutFileTextWave = root:Packages:Irena:PDDFInterface:GNOMOutFileTextWave
3205        KillWaves /Z GNOMOutFileTextWave
3206        PDDFCalcRg = 0
3207        PDDFCalcI0 = 0
3208        PDDFCalculatedMW = 0
3209        GNOMAlfaResult = 0
3210        //delete old waves
3211        KillWaves/Z pddfInputQVector, pddfInputIntensity, pddfInputError, pddfModelQvector, PDDFModelIntensity, pddfRadius, pddfPr, pddfPrError, pddfQvecExtrap, pddfModelIntExtrap
3212        //zero parameetrs
3213        MWPorodInvariant = 0
3214        ReciprocalPorodVolumeA3 = 0
3215        SAXSMoW2MWRecSpacekDa = 0
3216        ReciprocalSpaceI0 = 0
3217        ReciprocalSpaceRg = 0
3218        ReciprocalSpaceB = 0
3219        ReciprocalSpacePorodSlope = 0
3220        RamboTainerMWRecSpacekDa = 0
3221        MWPorodInvariant = 0
3222        ReciprocalPorodVolumeA3 = 0
3223        SAXSMoW2MWRecSpacekDa = 0
3224        ReciprocalSpaceI0 = 0
3225        ReciprocalSpaceRg = 0
3226        RealSpaceRg=0
3227        RealSpaceI0=0
3228        PDDFCalculatedMW=0
3229        GNOMAlfaResult = 0
3230        setDataFolder OldDF
3231end
3232//**********************************************************************************************************
3233
3234static Function IRB1_PDDFSetDensitySLD()
3235
3236        NVAR PDDFUseProtein             =root:Packages:Irena:PDDFInterface:PDDFUseProtein
3237        NVAR PDDFUseNucleicAcid =root:Packages:Irena:PDDFInterface:PDDFUseNucleicAcid
3238        NVAR MWMassDensityProtein=root:Packages:Irena:PDDFInterface:MWMassDensityProtein
3239        NVAR ScattLengthDensDifference=root:Packages:Irena:PDDFInterface:ScattLengthDensDifference
3240
3241        if(PDDFUseProtein+PDDFUseNucleicAcid!=1)
3242                PDDFUseProtein = 1
3243                PDDFUseNucleicAcid = 0
3244        endif
3245        if(PDDFUseProtein)
3246                MWMassDensityProtein = 1.37
3247                ScattLengthDensDifference = 2.086               //average protein
3248        else
3249                MWMassDensityProtein = 1.85
3250                ScattLengthDensDifference = 1.5*2.086           //average nucleaic acid, needs to be fixed by Xiaobong ASAP.
3251        endif
3252
3253end
3254//**********************************************************************************************************
3255//**********************************************************************************************************
3256//**********************************************************************************************************
3257//**********************************************************************************************************
3258static Function IRB1_PDDFSaveResultsToNotebook()
3259
3260        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
3261        DFref oldDf= GetDataFolderDFR()
3262        setDataFolder root:Packages:Irena:PDDFInterface
3263        NVAR SaveToFolder=root:Packages:Irena:PDDFInterface:SaveToFolder
3264        NVAR SaveToNotebook=root:Packages:Irena:PDDFInterface:SaveToNotebook
3265        NVAR SaveToWaves=root:Packages:Irena:PDDFInterface:SaveToWaves
3266        if(SaveToNotebook!=1)
3267                setDataFolder OldDf
3268                return 0
3269        endif
3270        IR1_CreateResultsNbk()
3271        SVAR DataFolderName=root:Packages:Irena:PDDFInterface:DataFolderName
3272        SVAR IntensityWaveName=root:Packages:Irena:PDDFInterface:IntensityWaveName
3273        SVAR QWavename=root:Packages:Irena:PDDFInterface:QWavename
3274        SVAR ErrorWaveName=root:Packages:Irena:PDDFInterface:ErrorWaveName
3275        NVAR DataQEnd = root:Packages:Irena:PDDFInterface:DataQEnd
3276        NVAR DataQstart = root:Packages:Irena:PDDFInterface:DataQstart
3277        NVAR DataQEndPoint = root:Packages:Irena:PDDFInterface:DataQEndPoint
3278        NVAR DataQstartPoint = root:Packages:Irena:PDDFInterface:DataQstartPoint
3279
3280        //reciprocal space results, result of Guinier fitting (I(0) and Rg, Porod volume, invariant etc.)
3281        NVAR ReciprocalPorodVolumeA3 = root:Packages:Irena:PDDFInterface:ReciprocalPorodVolumeA3
3282        NVAR ReciprocalSpaceI0           = root:Packages:Irena:PDDFInterface:ReciprocalSpaceI0
3283        NVAR ReciprocalSpaceRg           = root:Packages:Irena:PDDFInterface:ReciprocalSpaceRg
3284        NVAR SAXSMoW2MWRecSpacekDa       = root:Packages:Irena:PDDFInterface:SAXSMoW2MWRecSpacekDa
3285        NVAR RamboTainerMWRecSpacekDa                            = root:Packages:Irena:PDDFInterface:RamboTainerMWRecSpacekDa
3286
3287        //Real space results, result of GNOM (I(0), Rg, Output extrapolated data, Porod volume, invariant etc.)
3288        NVAR RealSpacePorodVolumeA3             = root:Packages:Irena:PDDFInterface:RealSpacePorodVolumeA3
3289        NVAR RealSpaceI0                                        = root:Packages:Irena:PDDFInterface:RealSpaceI0
3290        NVAR RealSpaceRg                                        = root:Packages:Irena:PDDFInterface:RealSpaceRg
3291        NVAR SAXSMoW2MWRealSpacekDa             = root:Packages:Irena:PDDFInterface:SAXSMoW2MWRealSpacekDa
3292        NVAR PDDFCalculatedMW                   = root:Packages:Irena:PDDFInterface:PDDFCalculatedMW
3293        NVAR GNOMAlfaResult                             = root:Packages:Irena:PDDFInterface:GNOMAlfaResult
3294
3295        NVAR PDDFCalculatedMW=root:Packages:Irena:PDDFInterface:PDDFCalculatedMW
3296        NVAR ConcentrationForCals=root:Packages:Irena:PDDFInterface:ConcentrationForCals
3297        NVAR ScattLengthDensDifference=root:Packages:Irena:PDDFInterface:ScattLengthDensDifference
3298        NVAR MWMassDensityProtein = root:Packages:Irena:PDDFInterface:MWMassDensityProtein
3299
3300        string MethodRun
3301        NVAR PDDFUseGNOM = root:Packages:Irena:PDDFInterface:PDDFUseGNOM
3302        NVAR PDDFuseMoore = root:Packages:Irena:PDDFInterface:PDDFuseMoore
3303        NVAR PDDFuseregularization = root:Packages:Irena:PDDFInterface:PDDFuseregularization
3304        NVAR PPDFUseAutoGNOM=root:Packages:Irena:PDDFInterface:PDDFUseAutoGNOM
3305        if(PPDFUseAutoGNOM)     
3306                MethodRun = "AutoGNOM"
3307        elseif(PDDFUseGNOM)
3308                MethodRun = "GNOM"
3309        elseif(PDDFuseMoore)
3310                MethodRun = "Moore"
3311        elseif(PDDFuseregularization)
3312                MethodRun = "Regularization"
3313        endif
3314
3315        IR1_AppendAnyText("\r Results of Pair distance distribution function fitting\r",1)     
3316        IR1_AppendAnyText("Date & time: \t"+Date()+"   "+time(),0)     
3317        IR1_AppendAnyText("Data from folder: \t"+DataFolderName,0)     
3318        IR1_AppendAnyText("Intensity: \t"+IntensityWaveName,0) 
3319        IR1_AppendAnyText("Q: \t"+QWavename,0) 
3320        IR1_AppendAnyText("Error: \t"+ErrorWaveName,0) 
3321        IR1_AppendAnyText("Method used: \t"+MethodRun,0)       
3322        IR1_AppendAnyText(" ",0)
3323        IR1_AppendAnyText("Real space (PDDF) results, GNOM OUT or direct calcs.",0)     
3324        IR1_AppendAnyText("Rg [A] = \t"+num2str(RealSpaceRg),0)
3325        IR1_AppendAnyText("I0     = \t"+num2str(RealSpaceI0),0)
3326        IR1_AppendAnyText("Porod Volume [cm3] = \t"+num2str(ReciprocalPorodVolumeA3),0)
3327        IR1_AppendAnyText("Assumed Concentration [mg/ml] = \t"+num2str(ConcentrationForCals),0)
3328        IR1_AppendAnyText("Assumed SLD [10^10 cm^-2] = \t"+num2str(ScattLengthDensDifference),0)       
3329        IR1_AppendAnyText("GNOM alfa final value = \t"+num2str(GNOMAlfaResult),0)       
3330        IR1_AppendAnyText("** SAXSMoW2 MW [kDa] = \t"+num2str(SAXSMoW2MWRealSpacekDa)+" ** ",0)
3331        IR1_AppendAnyText("** Abs. Int. Estimated MW [kDa] = \t"+num2str(PDDFCalculatedMW)+" ** ",0)   
3332        IR1_AppendAnyText(" ",0)
3333        IR1_AppendAnyText("Reciprocal space (Guinier fit) results",0)   
3334        IR1_AppendAnyText("Rg [A] = \t"+num2str(ReciprocalSpaceRg),0)   
3335        IR1_AppendAnyText("I0     = \t"+num2str(ReciprocalSpaceI0),0)   
3336        IR1_AppendAnyText("Porod Volume [cm3] = \t"+num2str(RealSpacePorodVolumeA3),0) 
3337        IR1_AppendAnyText("Assumed Density prot [g/cm3] = \t"+num2str(MWMassDensityProtein),0) 
3338        IR1_AppendAnyText("** SAXSMoW2 MW [kDa] = \t"+num2str(SAXSMoW2MWRecSpacekDa)+" ** ",0) 
3339        IR1_AppendAnyText("** Rambo-Tainer MW [kDa] = \t"+num2str(RamboTainerMWRecSpacekDa)+" ** ",0)   
3340       
3341        DoWindow/K/Z DupWindwFromPanel                                  //kill the window...
3342        IN2G_DuplGraphInPanelSubwndw("IRB1_PDDFInterfacePanel#DataDisplay")
3343        MoveWindow /W=DataDisplay 20, 20, 920, 520
3344        IR1_AppendAnyGraph("DataDisplay")
3345        DoWindow/K/Z DataDisplay                                        //kill the window...
3346        IN2G_DuplGraphInPanelSubwndw("IRB1_PDDFInterfacePanel#PDFDisplay")
3347        MoveWindow /W=PDFDisplay 20, 20, 920, 520
3348        IR1_AppendAnyGraph("PDFDisplay")
3349        DoWindow/K/Z PDFDisplay                                 //kill the window...
3350       
3351        //save data here... For Moore include "Fittingresults" which is Intensity Fit stuff
3352        //SVAR FittingResults=root:Packages:Irena:PDDFInterface:FittingResults
3353        //IR1_AppendAnyText(FittingResults,0)   
3354        IR1_AppendAnyText("******************************************\r",0)     
3355        SetDataFolder OldDf
3356        SVAR/Z nbl=root:Packages:Irena:ResultsNotebookName     
3357        DoWindow/F $nbl
3358        setDataFolder OldDf
3359end
3360
3361//**********************************************************************************************************
3362//**********************************************************************************************************
3363//**********************************************************************************************************
3364static Function IRB1_PDDFSaveToWaves()
3365
3366        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
3367        DFref oldDf= GetDataFolderDFR()
3368        NVAR SaveToFolder=root:Packages:Irena:PDDFInterface:SaveToFolder
3369        NVAR SaveToNotebook=root:Packages:Irena:PDDFInterface:SaveToNotebook
3370        NVAR SaveToWaves=root:Packages:Irena:PDDFInterface:SaveToWaves
3371        if(SaveToWaves!=1)
3372                setDataFolder OldDf
3373                return 0
3374        endif
3375
3376        SVAR DataFolderName = root:Packages:Irena:PDDFInterface:DataFolderName
3377
3378        //reciprocal space results, result of Guinier fitting (I(0) and Rg, Porod volume, invariant etc.)
3379        NVAR ReciprocalPorodVolumeA3 = root:Packages:Irena:PDDFInterface:ReciprocalPorodVolumeA3
3380        NVAR ReciprocalSpaceI0           = root:Packages:Irena:PDDFInterface:ReciprocalSpaceI0
3381        NVAR ReciprocalSpaceRg           = root:Packages:Irena:PDDFInterface:ReciprocalSpaceRg
3382        NVAR SAXSMoW2MWRecSpacekDa       = root:Packages:Irena:PDDFInterface:SAXSMoW2MWRecSpacekDa
3383        NVAR RamboTainerMWRecSpacekDa= root:Packages:Irena:PDDFInterface:RamboTainerMWRecSpacekDa
3384
3385        //Real space results, result of GNOM (I(0), Rg, Output extrapolated data, Porod volume, invariant etc.)
3386        NVAR RealSpacePorodVolumeA3             = root:Packages:Irena:PDDFInterface:RealSpacePorodVolumeA3
3387        NVAR RealSpaceI0                                        = root:Packages:Irena:PDDFInterface:RealSpaceI0
3388        NVAR RealSpaceRg                                        = root:Packages:Irena:PDDFInterface:RealSpaceRg
3389        NVAR SAXSMoW2MWRealSpacekDa             = root:Packages:Irena:PDDFInterface:SAXSMoW2MWRealSpacekDa
3390        NVAR PDDFCalculatedMW                   = root:Packages:Irena:PDDFInterface:PDDFCalculatedMW
3391        NVAR GNOMAlfaResult                             = root:Packages:Irena:PDDFInterface:GNOMAlfaResult
3392
3393        NVAR PDDFCalculatedMW=root:Packages:Irena:PDDFInterface:PDDFCalculatedMW
3394        NVAR ConcentrationForCals=root:Packages:Irena:PDDFInterface:ConcentrationForCals
3395        NVAR ScattLengthDensDifference=root:Packages:Irena:PDDFInterface:ScattLengthDensDifference
3396        NVAR MWMassDensityProtein = root:Packages:Irena:PDDFInterface:MWMassDensityProtein
3397
3398        NVAR PDDFUseGNOM = root:Packages:Irena:PDDFInterface:PDDFUseGNOM
3399        NVAR PDDFuseMoore = root:Packages:Irena:PDDFInterface:PDDFuseMoore
3400        NVAR PDDFuseregularization = root:Packages:Irena:PDDFInterface:PDDFuseregularization
3401        NVAR PPDFUseAutoGNOM=root:Packages:Irena:PDDFInterface:PDDFUseAutoGNOM
3402        string Methodused=""
3403        if(PPDFUseAutoGNOM)     
3404                Methodused = "AutoGNOM"
3405        elseif(PDDFUseGNOM)
3406                Methodused = "GNOM"
3407        elseif(PDDFuseMoore)
3408                Methodused = "Moore"
3409        elseif(PDDFuseregularization)
3410                Methodused = "Regularization"
3411        endif
3412        NewDATAFolder/O/S root:PDDFFitResults
3413        Wave/Z RealSpace_Rg
3414        if(!WaveExists(RealSpace_Rg))
3415                make/O/N=0 RealSpace_Rg, RealSpace_I0, RealSpace_MW, RealSpaceSAXSMo2_MW, RealSpace_PorodVolume, ConcForCals, ScattLengthDensDiff
3416                make/O/N=0 GnomAlfaFinal, RecipSpace_PorodVolume, RecipSpace_I0, RecipSpace_Rg, RecipSpaceSAXSMoW2_MW, RecipSpaceRamboTainer_MW, MassDensityProtein
3417                make/O/N=0/T SampleName, MethodName
3418                SetScale/P x 0,1,"A", RealSpace_Rg
3419                SetScale/P x 0,1,"A", RecipSpace_Rg
3420                SetScale/P x 0,1,"kDa", RealSpace_MW
3421                SetScale/P x 0,1,"kDa", RecipSpaceRamboTainer_MW
3422                SetScale/P x 0,1,"kDa", RealSpaceSAXSMo2_MW
3423                SetScale/P x 0,1,"kDa", RecipSpaceSAXSMoW2_MW
3424                SetScale/P x 0,1,"1/cm", RealSpace_I0
3425                SetScale/P x 0,1,"1/cm", RecipSpace_I0
3426                SetScale/P x 0,1,"mg/ml", ConcForCals
3427                SetScale/P x 0,1,"10^10 cm^-2", ScattLengthDensDiff
3428                SetScale/P x 0,1,"cm3", RealSpace_PorodVolume
3429                SetScale/P x 0,1,"cm3", RecipSpace_PorodVolume
3430                SetScale/P x 0,1,"g/cm3", MassDensityProtein
3431        endif
3432        variable curlength = numpnts(RealSpace_Rg)
3433        redimension/N=(curlength+1) SampleName,MethodName, RealSpace_Rg, RealSpace_I0, RealSpace_MW, RealSpaceSAXSMo2_MW, RealSpace_PorodVolume, ConcForCals, ScattLengthDensDiff
3434        redimension/N=(curlength+1) GnomAlfaFinal, RecipSpace_PorodVolume, RecipSpace_I0, RecipSpace_Rg, RecipSpaceSAXSMoW2_MW, RecipSpaceRamboTainer_MW, MassDensityProtein
3435
3436        SampleName[curlength]                                   = stringFromList(ItemsInList(DataFolderName, ":")-1, DataFolderName,":")
3437        MethodName[curlength]                                   = Methodused
3438        RealSpace_Rg[curlength]                                         = RealSpaceRg
3439        RealSpace_I0[curlength]                                         = RealSpaceI0
3440        RealSpace_MW[curlength]                                         = PDDFCalculatedMW
3441        RealSpaceSAXSMo2_MW[curlength]                  = SAXSMoW2MWRealSpacekDa       
3442        RealSpace_PorodVolume[curlength]                = RealSpacePorodVolumeA3
3443        ConcForCals[curlength]                                  = ConcentrationForCals
3444        ScattLengthDensDiff[curlength]                  = ScattLengthDensDifference
3445        GnomAlfaFinal[curlength]                                = GNOMAlfaResult
3446       
3447        RecipSpace_PorodVolume[curlength]               = ReciprocalPorodVolumeA3
3448        RecipSpace_I0[curlength]                                = ReciprocalSpaceI0
3449        RecipSpace_Rg[curlength]                                = ReciprocalSpaceRg
3450        RecipSpaceSAXSMoW2_MW[curlength]                = SAXSMoW2MWRecSpacekDa
3451        RecipSpaceRamboTainer_MW[curlength]     = RamboTainerMWRecSpacekDa
3452        MassDensityProtein[curlength]                   = MWMassDensityProtein
3453
3454        DoWindow IRB1_PDDFFitResultsTable
3455        if(V_Flag)
3456                DoWIndow/F IRB1_PDDFFitResultsTable
3457        else
3458                IRB1_PDDFFitResultsTableFnct()
3459        endif           
3460        setDataFolder OldDf     
3461end
3462
3463//*****************************************************************************************************************
3464//*****************************************************************************************************************
3465static Function IRB1_PDDFFitResultsTableFnct() : Table
3466        PauseUpdate; Silent 1           // building window...
3467        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
3468        DFref oldDf= GetDataFolderDFR()
3469        if(!DataFolderExists("root:PDDFFitResults:"))
3470                Abort "No PDDF Fit data exist."
3471        endif
3472        SetDataFolder root:PDDFFitResults:
3473        Wave/T SampleName, MethodName
3474        Wave RealSpace_Rg, RealSpace_I0, RealSpace_MW, RealSpaceSAXSMo2_MW, RealSpace_PorodVolume, ConcForCals, ScattLengthDensDiff
3475        Wave GnomAlfaFinal, RecipSpace_PorodVolume, RecipSpace_I0, RecipSpace_Rg, RecipSpaceSAXSMoW2_MW, RecipSpaceRamboTainer_MW, MassDensityProtein
3476       
3477        Edit/K=1/W=(860,772,1831,1334)/N=IRB1_PDDFFitResultsTable SampleName,RealSpace_Rg, RealSpace_I0, RealSpace_MW, RealSpaceSAXSMo2_MW, MethodName as "PDDF fitting results Table"
3478        AppendToTable RecipSpace_Rg, RecipSpace_I0, RecipSpaceSAXSMoW2_MW, RecipSpaceRamboTainer_MW, RecipSpace_PorodVolume, GnomAlfaFinal
3479        AppendToTable RealSpace_PorodVolume, ConcForCals, ScattLengthDensDiff, RecipSpace_PorodVolume, MassDensityProtein
3480        ModifyTable format(Point)=1,width(SampleName)=150,title(SampleName)="Sample Folder"
3481//      ModifyTable width(MethodName)=100,title(MethodName)="Method"
3482//      ModifyTable alignment(PDDF_Rg)=1,sigDigits(PDDF_Rg)=4,title(PDDF_Rg)="Rg [A]"
3483//      ModifyTable alignment(PDDF_I0)=1,sigDigits(PDDF_I0)=4,width(PDDF_I0)=100,title(PDDF_I0)="I0"
3484//      ModifyTable alignment(PDDF_MW)=1,sigDigits(PDDF_MW)=4,width(PDDF_MW)=104
3485//      ModifyTable title(PDDF_MW)="MW"
3486//      ModifyTable alignment(PDDF_Conc)=1,sigDigits(PDDF_Conc)=4
3487//      ModifyTable width(PDDF_Conc)=92,title(PDDF_Conc)="Conc [mg/ml]",alignment(PDDF_SLD)=1
3488//      ModifyTable sigDigits(PDDF_SLD)=4,width(PDDF_SLD)=110,title(PDDF_SLD)="SLD [10^10 cm^2]"
3489//      ModifyTable alignment(InvariantPDDFCalculatedMW)=1,sigDigits(InvariantPDDFCalculatedMW)=4,width(InvariantPDDFCalculatedMW)=104
3490//      ModifyTable title(InvariantPDDFCalculatedMW)="MW (Porod)"
3491//      ModifyTable alignment(PorodInvariant)=1,sigDigits(PorodInvariant)=4,width(PorodInvariant)=104
3492//      ModifyTable title(PorodInvariant)="Porod Invariant"
3493//      ModifyTable alignment(PorodTrueVolume)=1,sigDigits(PorodTrueVolume)=4,width(PorodTrueVolume)=104
3494//      ModifyTable title(PorodTrueVolume)="Porod Volume"
3495//      ModifyTable alignment(MassDensityProtein)=1,sigDigits(MassDensityProtein)=4,width(MassDensityProtein)=104
3496//      ModifyTable title(MassDensityProtein)="Density Protein"
3497//      ModifyTable alignment(GnomAlfaFinal)=1,sigDigits(GnomAlfaFinal)=4,width(GnomAlfaFinal)=104
3498//      ModifyTable title(GnomAlfaFinal)="GNOM ALfa res."
3499//
3500
3501
3502        SetDataFolder oldDf
3503EndMacro
3504//*****************************************************************************************************************
3505
3506//*****************************************************************************************************************
3507//*****************************************************************************************************************
3508
3509
3510static Function IRB1_PDDFSaveResultsToFldr()
3511        DFref oldDf= GetDataFolderDFR()
3512
3513        IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
3514        setDataFolder root:Packages:Irena:PDDFInterface
3515
3516        NVAR SaveToFolder=root:Packages:Irena:PDDFInterface:SaveToFolder
3517        NVAR SaveToNotebook=root:Packages:Irena:PDDFInterface:SaveToNotebook
3518        NVAR SaveToWaves=root:Packages:Irena:PDDFInterface:SaveToWaves
3519        if(SaveToFolder!=1)
3520                return 0
3521        endif
3522        //save data here... For Moore include "Fittingresults" which is Intensity Fit stuff
3523        //Parameters:
3524        SVAR DataFolderName=root:Packages:Irena:PDDFInterface:DataFolderName
3525        SVAR IntensityWaveName=root:Packages:Irena:PDDFInterface:IntensityWaveName
3526        SVAR QWavename=root:Packages:Irena:PDDFInterface:QWavename
3527        SVAR ErrorWaveName=root:Packages:Irena:PDDFInterface:ErrorWaveName
3528        NVAR DataQEnd = root:Packages:Irena:PDDFInterface:DataQEnd
3529        NVAR DataQstart = root:Packages:Irena:PDDFInterface:DataQstart
3530        NVAR DataQEndPoint = root:Packages:Irena:PDDFInterface:DataQEndPoint
3531        NVAR DataQstartPoint = root:Packages:Irena:PDDFInterface:DataQstartPoint
3532        //additional Porod results...
3533        //reciprocal space results, result of Guinier fitting (I(0) and Rg, Porod volume, invariant etc.)
3534        NVAR ReciprocalPorodVolumeA3 = root:Packages:Irena:PDDFInterface:ReciprocalPorodVolumeA3
3535        NVAR ReciprocalSpaceI0           = root:Packages:Irena:PDDFInterface:ReciprocalSpaceI0
3536        NVAR ReciprocalSpaceRg           = root:Packages:Irena:PDDFInterface:ReciprocalSpaceRg
3537        NVAR SAXSMoW2MWRecSpacekDa       = root:Packages:Irena:PDDFInterface:SAXSMoW2MWRecSpacekDa
3538        NVAR RamboTainerMWRecSpacekDa = root:Packages:Irena:PDDFInterface:RamboTainerMWRecSpacekDa
3539
3540        //Real space results, result of GNOM (I(0), Rg, Output extrapolated data, Porod volume, invariant etc.)
3541        NVAR RealSpacePorodVolumeA3             = root:Packages:Irena:PDDFInterface:RealSpacePorodVolumeA3
3542        NVAR RealSpaceI0                                        = root:Packages:Irena:PDDFInterface:RealSpaceI0
3543        NVAR RealSpaceRg                                        = root:Packages:Irena:PDDFInterface:RealSpaceRg
3544        NVAR SAXSMoW2MWRealSpacekDa             = root:Packages:Irena:PDDFInterface:SAXSMoW2MWRealSpacekDa
3545        NVAR PDDFCalculatedMW                   = root:Packages:Irena:PDDFInterface:PDDFCalculatedMW
3546        NVAR GNOMAlfaResult                             = root:Packages:Irena:PDDFInterface:GNOMAlfaResult
3547
3548        NVAR PDDFCalculatedMW                           =       root:Packages:Irena:PDDFInterface:PDDFCalculatedMW
3549        NVAR ConcentrationForCals               =       root:Packages:Irena:PDDFInterface:ConcentrationForCals
3550        NVAR ScattLengthDensDifference  =       root:Packages:Irena:PDDFInterface:ScattLengthDensDifference
3551        NVAR MWMassDensityProtein               =       root:Packages:Irena:PDDFInterface:MWMassDensityProtein
3552       
3553        string MethodRun
3554        NVAR PDDFUseGNOM = root:Packages:Irena:PDDFInterface:PDDFUseGNOM
3555        NVAR PDDFuseMoore = root:Packages:Irena:PDDFInterface:PDDFuseMoore
3556        NVAR PDDFuseregularization = root:Packages:Irena:PDDFInterface:PDDFuseregularization
3557        NVAR PPDFUseAutoGNOM=root:Packages:Irena:PDDFInterface:PDDFUseAutoGNOM
3558        if(PPDFUseAutoGNOM)     
3559                MethodRun = "AutoGNOM"
3560        elseif(PDDFUseGNOM)
3561                MethodRun = "GNOM"
3562        elseif(PDDFuseMoore)
3563                MethodRun = "Moore"
3564        elseif(PDDFuseregularization)
3565                MethodRun = "Regularization"
3566        endif
3567        Wave pddfInputIntensity = root:Packages:Irena:PDDFInterface:pddfInputIntensity
3568        string oldNote=note(pddfInputIntensity)
3569        variable i
3570        //SVAR FittingResults=root:Packages:Irena:PDDFInterface:FittingResults
3571        string ResultsComment="PDDFMetod="+MethodRun+";PDDFQmin="+num2str(DataQstart)+";PDDFQmax="+num2str(DataQEnd)+";"
3572        ResultsComment="RealSpaceEstimatedMW="+num2str(PDDFCalculatedMW)+";"
3573        ResultsComment="RealSpaceSAXSMoW2MW="+num2str(SAXSMoW2MWRealSpacekDa)+";"
3574        ResultsComment="RealSpaceRg="+num2str(RealSpaceRg)+";"
3575        ResultsComment="RealSpaceI0="+num2str(RealSpaceI0)+";"
3576        ResultsComment="RealSpacePorodVolume="+num2str(RealSpacePorodVolumeA3)+";"
3577        ResultsComment="AssumedConcentration="+num2str(ConcentrationForCals)+";"
3578        ResultsComment="AssumedSLD="+num2str(ScattLengthDensDifference)+";"
3579        ResultsComment="GNOMAlfaFinal="+num2str(GNOMAlfaResult)+";"
3580        //and now real space parameters
3581        ResultsComment="RecipSpaceSAXSMoW2MW="+num2str(SAXSMoW2MWRecSpacekDa)+";"
3582        ResultsComment="RecipSpaceRamoTainerMW="+num2str(RamboTainerMWRecSpacekDa)+";"
3583        ResultsComment="RecipSpaceRg="+num2str(RealSpaceRg)+";"
3584        ResultsComment="RecipSpaceI0="+num2str(ReciprocalSpaceI0)+";"
3585        ResultsComment="RecipSpacePorodVolume="+num2str(ReciprocalPorodVolumeA3)+";"
3586        ResultsComment="AssumedDensityProtein="+num2str(MWMassDensityProtein)+";"
3587        String NewWaveNote="PDDF analysis;"+date()+";"+time()+ResultsComment
3588        NewWaveNote+=oldNote
3589
3590        Wave/Z pddfInputQVector         =root:Packages:Irena:PDDFInterface:pddfInputQVector
3591        Wave/Z pddfInputIntensity       =root:Packages:Irena:PDDFInterface:pddfInputIntensity
3592        Wave/Z pddfInputError                   =root:Packages:Irena:PDDFInterface:pddfInputError
3593        Wave/Z pddfModelQvector         =root:Packages:Irena:PDDFInterface:pddfModelQvector
3594        Wave/Z PDDFModelIntensity       =root:Packages:Irena:PDDFInterface:PDDFModelIntensity
3595        //Wave/Z pddfModelError                 =root:Packages:Irena:PDDFInterface:pddfModelError
3596        Wave/Z pddfRadius                               =root:Packages:Irena:PDDFInterface:pddfRadius
3597        Wave/Z pddfPr                                   =root:Packages:Irena:PDDFInterface:pddfPr
3598        Wave/Z pddfPrError                              =root:Packages:Irena:PDDFInterface:pddfPrError
3599        Wave/Z NormalizedResidual       =root:Packages:Irena:PDDFInterface:NormalizedResidual
3600        Wave/Z ChisquaredWave                   =root:Packages:Irena:PDDFInterface:ChisquaredWave
3601        Wave/Z CurrentResultsGamma      =root:Packages:Irena:PDDFInterface:CurrentResultsGamma
3602        Wave/Z GNOMOutFileTextWave = root:Packages:Irena:PDDFInterface:GNOMOutFileTextWave
3603
3604        Duplicate/O pddfRadius, tempR_distribution
3605        Duplicate/O pddfPr, tempCurrentResultPdf
3606        Duplicate/O CurrentResultsGamma, tempCurrentResultsGamma
3607        //Duplicate/O pddfModelError, tempPDDFErrors
3608        Duplicate/O pddfInputQVector, tempQ_vec
3609        Duplicate/O ChisquaredWave, tempCurrentChiSq
3610        Duplicate/O PDDFModelIntensity, tempPdfFitIntensity
3611        string ListOfWavesForNotes="tempR_distribution;tempCurrentResultPdf;tempQ_vec;tempPdfFitIntensity;tempCurrentChiSq;tempCurrentResultsGamma;"
3612        For(i=0;i<ItemsInList(ListOfWavesForNotes);i+=1)
3613                IN2G_AddListToWaveNote(stringFromList(i,ListOfWavesForNotes),NewWavenote)
3614                //IN2G_AddListToWaveNote(stringFromList(i,ListOfWavesForNotes),Fittingresults)
3615        endfor
3616        setDataFolder $DataFolderName
3617        string tempname
3618        variable ii=0
3619        For(ii=0;ii<1000;ii+=1)
3620                tempname="PDDFIntensity_"+num2str(ii)
3621                if (checkname(tempname,1)==0)
3622                        break
3623                endif
3624        endfor
3625        Duplicate /O tempPdfFitIntensity, $tempname
3626        tempname="PDDFQvector_"+num2str(ii)
3627        Duplicate /O tempQ_vec, $tempname
3628        tempname="PDDFChiSquared_"+num2str(ii)
3629        Duplicate /O tempCurrentChiSq, $tempname
3630        tempname="PDDFDistFunction_"+num2str(ii)
3631        Duplicate /O tempCurrentResultPdf, $tempname
3632        //tempname="PDDFErrors_"+num2str(ii)
3633        //Duplicate /O tempPDDFErrors, $tempname
3634        tempname="PDDFDistances_"+num2str(ii)
3635        Duplicate /O tempR_distribution, $tempname
3636        tempname="PDDFGammaFunction_"+num2str(ii)
3637        Duplicate /O tempCurrentResultsGamma, $tempname
3638        if(WaveExists(GNOMOutFileTextWave))
3639                tempname="GnomOutFile"+num2str(ii)
3640                Duplicate/O GNOMOutFileTextWave, $(tempname)
3641        endif
3642       
3643        print "Saved data to folder "+getDataFolder(1)+" , data generation is "+num2str(ii)
3644        Killwaves/Z tempR_distribution, tempCurrentResultPdf, tempQ_vec, tempCurrentChiSq, tempPdfFitIntensity, tempPDDFErrors, tempCurrentResultsGamma
3645       
3646        SetDataFolder OldDf
3647end
3648//*****************************************************************************************************************
3649//*****************************************************************************************************************
3650//*****************************************************************************************************************
3651
Note: See TracBrowser for help on using the repository browser.