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

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

Fix for Igor 7.08

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