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

Last change on this file since 1163 was 1163, checked in by ilavsky, 13 months ago

New Installer, fix bioSAXS tools saving _sub data when NOT using liberal names.

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