source: sans/Dev/trunk/NCNR_User_Procedures/Analysis/Alpha/Auto_Fit.ipf @ 911

Last change on this file since 911 was 911, checked in by srkline, 10 years ago

Updated the NGB attenuator tables with Katie's new measurements from May 2013.

Made some changes to Auto-Fit to make it more useable. Will turn it "on" when documentation is finished.

Changed how the random deviate function is calculated to improve the estimates of multiple scattering. Now the q-range of integration is shifted to lower q for the USANS calculation (using very large objects). Also, the number of points used in the integration is chosen adaptively until a constant value of scattering cross section is obtained. There are still some functions where the integration fails (power laws). These will always fail. My best solution currently is to flag the times when the XS>100. Then the estimates are invalid. The 1D simulation is fine, the 2D is reasonably fine, but anything to do with multile scattering is incorrect.

File size: 61.8 KB
Line 
1#pragma rtGlobals=1             // Use modern global access method.
2
3
4// This was originally written 2001-2003 ish. This works very differently than SANSview, and I haven't
5// mentioned that this exists, so that their ideas will be new. Still, some of this may be
6// serviceable for use within the Igor package, with some cleanup of the interface and functionality.
7//
8//
9//
10// to do - July 2010
11//
12// X- smeared models don't work at all (now they work)
13// x- the report is good, but the parsing is not great - the format
14//      could be more convenient to read back in to a table (text col, num cols (matrix that can be plotted?)
15//      x- Maybe the report could be compiled as waves. Then they would be numeric. Nothing to plot them against
16//                      other than file names, but with a table of values and names, one could manually enter a meaningful
17//                      column of values to plot against.
18// x- Make_HoldConstraintEps_Waves() is  currently disabled, both on the macros menu and the checkbox on the panel
19//                      Constraints and holds are part of the matrix already, so this would only be for epsilon
20// x- Many of the items on the Macros menu are just junk. Remove them.
21//
22// x- savePath is obsolete. Remove the button. Report saving is sent to the procedure defined in Wrapper.ipf, and uses the home path
23// x- add a checkbox for "all" to select all data files (function is already set -- CheckAllFiles())
24//
25// x- make it easy for the user to save the results in a whole table.
26// x- remind to rename the results (or move to a folder?) before another batch is run
27// x- what to plot against?
28//
29// x- add a little text box of explanation on each of the tabs at the bottom - to give simple
30//    instructions of what to do on each tab. This will need to change with each tab.
31//
32// x- need a help button to link to the help file
33// -- Comprehensive instructions (after features are finalized)
34
35
36
37Menu "Macros"
38        SubMenu "Auto Fit"
39                "Initialize AutoFit Panel"
40                "-"
41//              "Generate_Data_Checklist"
42//              "Make_HoldConstraintEps_Waves"          //this is currently disabled
43//              "-"
44//              "CompileAndLoadReports"
45                "Compile_Reports"
46                "Load Compiled Reports"
47//              "Compile_GlobalFit_Reports"
48                "-"
49                "Close Open Notebooks"
50                "Print Open Notebooks"
51                "-"
52                "Generate_PNG_list"
53                "Layout_PNGs"
54               
55        End
56End
57
58
59//***********
60//Automatic fitting routines for SANS or NSE data
61//requires model functions and their associated files
62//
63//**************
64
65
66
67//path to the data
68// ? have this automatically do the listing?
69Function PDPButton(ctrlName) : ButtonControl
70        String ctrlName
71       
72        //set the global string to the selected pathname
73        NewPath/O/M="pick the data folder" dataPath
74        PathInfo/S dataPath
75        Return(0)
76End
77
78Function SavePathButtonProc(ctrlName) : ButtonControl
79        String ctrlName
80
81        //set the global string to the selected pathname
82        NewPath/O/M="pick the save folder" savePath
83        PathInfo/S savePath
84        Return(0)
85End
86
87//
88// this re-sizes AND re-initializes the guessMatrix
89// and is only done when the files are re-listed, using the list button - since the
90// new list will screw up the correspondence with the guess matrix
91//
92Function FileListButtonProc(ctrlName) : ButtonControl
93        String ctrlName
94
95        DoAlert 1,"This will re-initialize the file list and ALL of the entries in the guess matrix. Do you want to proceed?"
96        if(V_flag!=1)           //if the answer is not yes, get out
97                return(0)
98        endif
99       
100        String fileList=""
101        fileList = IndexedFile(dataPath,-1,"????")
102        fileList = RemoveFromList(".DS_Store", fileList, ";",0)
103        List2TextWave(Filelist,";","root:AutoFit:fileListWave")
104        Wave/T lw = $"root:AutoFit:fileListWave"
105        Redimension/N=(-1,2) lw
106        lw[][1] = ""
107        Variable num = DimSize(lw,0)
108       
109        Wave sw = $"root:AutoFit:fileSelWave"
110        Redimension/B/N=(num,2) sw
111        sw[][1] = (sw[p][1] == 0) ? 2^5 : sw[p][1]              //if the element is zero, make it 32, otherwise leave it alone
112       
113        // force a re-size (and re-initialization) of the guess-hold-constr-range matrices
114        ToMatrixButtonProc("")
115       
116        return(0)
117End
118
119
120//currently set up to toggle state, based on the first row
121//
122Function CheckAllFiles(ctrlName,checked) : CheckBoxControl
123        String ctrlName
124        Variable checked
125
126        WAVE sel = root:AutoFit:fileSelWave
127        if( (sel[0][1] & 0x10) == 16 ) //first box is checked
128                sel[][1] = 2^5                  // uncheck them all
129        else
130                sel[][1] = 2^5 + 2^4            //bit 5== checkbox, bit 4== checked
131        endif
132        return(0)
133End
134
135
136//
137// this re-sizes AND re-initializes the guessMatrix
138// and is only done when the files are re-listed, using the list button - since the
139// new list will screw up the correspondence with the guess matrix
140//
141Function ToMatrixButtonProc(ctrlName) : ButtonControl
142        String ctrlName
143       
144        SetDataFolder root:AutoFit
145        WAVE sel = fileSelWave
146        NVAR numPar=numPar
147        Variable jj,numSelFiles=0
148       
149        //update the number of steps for the progress bar
150        // commented out - SRK - 28MAR05
151//      NVAR cur=curProgress
152//      NVAR totSteps=endProgress
153//      cur=0
154//      totSteps=numSelFiles*3          //3 fits per file
155//      ValDisplay progressValdisp,limits={0,totSteps,0}
156//      ControlUpdate/W=AutoFitPanel progressValdisp
157       
158        //redimension the matrices and lists
159        Redimension/N=(numPar,DimSize(sel,0)) guessMatrix,HoldMatrix,constrMatrix,rangeMatrix
160        Redimension/N=(numPar) guessList,holdList,constrList,rangeList,guessSel,holdSel,constrSel,rangeSel
161       
162        //Set the matrices to zero
163        WAVE/T aa = guessMatrix
164        WAVE/T bb = holdMatrix
165        WAVE/T cc = constrMatrix
166        WAVE/T rr = rangeMatrix
167        aa="1"
168        bb="0"
169        cc=""           //set to no constraints
170        rr="0"          // zero in points 0 and 1 force a fit of all of the data (default)
171        //set the Lists to "0"
172        WAVE/T dd=guessList
173        WAVE/T ee=holdList
174        WAVE/T ff=constrList
175        WAVE/T rrl=rangeList
176        dd="0"
177        ee="0"
178        ff="0"
179        rrl="0"
180        //Set the sel waves to 2 (editable)
181        WAVE gg=guessSel
182        WAVE hh=holdSel
183        WAVE ii=constrSel
184        WAVE rrs=rangeSel
185        gg=2
186        hh=2
187        ii=2
188        rrs=2
189       
190        SetDataFolder root:
191       
192        DisplayGuess()
193        tabProc("",0)           //force the Guess tab to top
194        TabControl tabC,value=0
195       
196        return(0)
197End
198
199
200//updates the lists (text waves) to display, depending on the current highlighted file
201Function DisplayGuess()
202       
203        //find the selected data file -[][0] is the file, not the checkbox
204        Variable row
205        row = FindSelectedRowInLB(0)    // send 0 to look at the column with filenames
206
207        //update the text waves based on the values in the matrix
208        WAVE/T gm = root:AutoFit:guessMatrix
209        WAVE/T gl = root:AutoFit:guessList
210       
211        // the hold matrix
212        WAVE/T hm=root:AutoFit:holdMatrix
213        WAVE/T hl=root:AutoFit:holdList
214       
215        // the constraint matrix
216        WAVE/T cm=root:AutoFit:constrMatrix
217        WAVE/T cl=root:AutoFit:constrList
218       
219        // the range matrix
220        WAVE/T rm=root:AutoFit:rangeMatrix
221        WAVE/T rl=root:AutoFit:rangeList
222       
223        WAVE sel = root:AutoFit:fileSelWave
224        if( (sel[row][1] & 0x10) == 16 ) //box is checked
225               
226                gl = gm[p][row]
227                hl = hm[p][row]
228                cl = cm[p][row]
229                rl = rm[p][row]
230        else
231                //file is not checked, don't display guess
232                gl = "Not checked"
233                hl = "Not checked"
234                cl = "Not checked"
235                rl = "Not checked"
236        endif
237       
238        return(0)
239End
240
241
242//column 0 is the filenames, 1 is the checkboxes
243//returns the row that is selected, -1 if not found
244Function  FindSelectedRowInLB(col)
245        Variable col
246       
247        WAVE sel = root:AutoFit:fileSelWave
248        Variable jj=0,row=-1
249        if(col==0)
250                do
251                        if( (sel[jj][0] & 0x01) == 1 )                  //returns 1 (bit 0) if selected, 0 otherwise   
252                                row=jj
253                                //print "Row = ",jj
254                                break
255                        endif
256                        jj+=1
257                while(jj<DimSize(sel,0))
258        else
259                do
260                        if( (sel[jj][1] & 0x01) == 1 )                  //the checkbox is selected, but not necessarily checked!
261                                row=jj
262                                //print "Row = ",jj
263                                break
264                        endif
265                        jj+=1
266                while(jj<DimSize(sel,0))
267        endif
268       
269        return(row)
270end
271
272
273Proc InitializeAutoFitPanel()
274        if (wintype("AutoFitPanel") == 0)
275                InitializeAutoFit()
276                AutoFitPanel()
277                tabProc("",0)           //force the tab control to display correctly
278        else
279                DoWindow/F AutoFitPanel
280        endif
281//      RangeCheckProc("",1)            //check the box to use all of the data
282End
283
284Function InitializeAutoFit()
285        //set up all of the globals for the lists, globals, etc...
286        NewDataFolder/O/S root:AutoFit
287        Make/O/T/N=(1,2) fileListWave           //list boxes need text waves
288        Make/O/B/N=(1,2) fileSelWave            //for the checkboxes
289        Make/O/T/N=1 guessList,holdList,ConstrList,rangeList            //list boxes need text waves
290        Make/O/T/N=(1,1) guessMatrix,holdMatrix,rangeMatrix                     //guesses, etc... need real values (later)
291        Make/O/T/N=(1,1) constrMatrix                                   //constraint matrix is text
292        Make/O/B/N=1 guessSel,holdSel,ConstrSel,rangeSel                                                //SelWave is byte data
293        Variable/G numPar=0,ptLow=0,ptHigh=0,fitTol=1e-3,curProgress=0,endProgress=10
294        Variable/G startTicks=0
295       
296        String/G gStatFormat="\K(65535,0,0)\f01"
297        String/G gStatus=gStatFormat+"the fit engine is currently idle"
298        string/g gExt="ABC"
299       
300        String/G guessStr = "Guess is based on\rthe unsmeared\rcoefficients on the\rCurve Fit Setup\rpanel"
301        String/G holdStr = "Enter 0 to fit\rEnter 1 to hold"
302        String/G constStr = "Enter low and\rhigh range as:\rlow;high\rfor each parameter\rLeave blank if\rno constraints"
303        String/G rangeStr = "Enter the point\rrange as:\rfirst pt in 1st row\rlast pt in 2nd row\rLeave blank to\r fit all data"
304       
305       
306        fileListWave = ""
307       
308        //make the second column of the file sel wave a checkbox (set bit 5)
309        fileSelWave[][1] = 2^5
310       
311        SetDataFolder root:
312End
313
314Window AutoFitPanel()
315        PauseUpdate; Silent 1           // building window...
316        NewPanel /W=(685,44,1001,740) /K=1
317        DoWindow/C AutoFitPanel
318        SetDrawLayer UserBack
319//      DrawText 11,418,"Point Range"
320//      DrawText 5,167,"Suffix"
321        DrawLine 8,362,287,362
322        PopupMenu popup0,pos={2,2},size={175,20},title="pick a function"
323        PopupMenu popup0,mode=1,value= #"User_FunctionPopupList()",proc=AF_FuncPopupProc
324               
325        ListBox lb pos={11,90},size={280,230},proc=FileListboxProc
326        ListBox lb listWave=root:AutoFit:fileListWave,selWave=root:AutoFit:fileSelWave
327        ListBox lb editStyle=1,mode=5
328        ListBox lb userColumnResize=1,widths={200,80}
329       
330//      Button DelButton,pos={245,61},size={40,20},proc=DelButtonProc,title="Del",disable=2
331        Button PathButton,pos={6,61},size={50,20},proc=PDPButton,title="Path..."
332        Button FileListButton,pos={82,61},size={50,20},proc=FileListButtonProc,title="List"
333        CheckBox AllFilesCheck,pos={182,64},size={32,14},proc=CheckAllFiles,title="Select All Files"
334        CheckBox AllFilesCheck,value= 0
335        ListBox guessBox,pos={24,398},size={145,208},disable=1,proc=UpdateGuessMatrixProc
336        ListBox guessBox,frame=2,listWave=root:AutoFit:guessList
337        ListBox guessBox,selWave=root:AutoFit:guessSel,mode= 2,selRow= 0
338        Button FillAllGuessButton,pos={196,406},size={50,20},disable=1,proc=FillAllGuessButtonProc,title="Fill All"
339        Button FillAllHoldButton,pos={196,406},size={50,20},disable=1,proc=FillAllHoldButtonProc,title="Fill All"
340        Button FillAllConstrButton,pos={196,406},size={50,20},proc=FillAllConstrButtonProc,title="Fill All"
341        Button FillAllRangeB,pos={196,406},size={50,20},disable=1,proc=FillAllRangeButtonProc,title="Fill All"
342        SetVariable NumParams,pos={7,34},size={150,15},proc=SetNumParamProc,title="Number of Parameters"
343        SetVariable NumParams,limits={2,Inf,0},value= root:AutoFit:numPar
344//      CheckBox typeCheck,pos={207,31},size={32,14},title="NSE Data?",value=0
345//      SetVariable fitTol,pos={80,208},size={80,15},title="Fit Tol"
346//      SetVariable fitTol,limits={0.0001,0.1,0},value= root:AutoFit:fitTol
347        CheckBox epsilonCheck,pos={156,335},size={32,14},value=0,title="Use Epsilon Wave?"
348
349        TabControl tabC,pos={13,371},size={273,244},proc=tabProc,tabLabel(0)="Guess"
350        TabControl tabC,tabLabel(1)="Hold",tabLabel(2)="Constraint",tabLabel(3)="Range",value= 0
351//      CheckBox rangeCheck,pos={92,404},size={32,14},proc=RangeCheckProc,title="All"
352//      CheckBox rangeCheck,value= 1,disable=2
353
354        SetVariable lowPt,pos={136,404},size={60,15},title="low"
355        SetVariable lowPt,limits={0,Inf,0},value= root:AutoFit:ptLow,noedit=1,disable=1
356        SetVariable highPt,pos={201,404},size={60,15},title=" to "
357        SetVariable highPt,limits={0,Inf,0},value= root:AutoFit:ptHigh,noedit=1,disable=1
358        ListBox holdBox,pos={24,398},size={145,208},disable=1,proc=UpdateHoldMatrixProc
359        ListBox holdBox,frame=2,listWave=root:AutoFit:holdList
360        ListBox holdBox,selWave=root:AutoFit:holdSel,mode= 2,selRow= 2
361        ListBox ConstrBox,pos={24,398},size={145,208},proc=UpdateConstrMatrixProc
362        ListBox ConstrBox,frame=2,listWave=root:AutoFit:ConstrList
363        ListBox ConstrBox,selWave=root:AutoFit:ConstrSel,mode= 2,selRow= 2
364        ListBox RangeBox,pos={24,398},size={145,208},proc=UpdateRangeMatrixProc
365        ListBox RangeBox,frame=2,listWave=root:AutoFit:rangeList
366        ListBox RangeBox,selWave=root:AutoFit:RangeSel,mode= 2,selRow= 2
367//      Button MatrixButton,pos={12,205},size={60,20},proc=ToMatrixButtonProc,title="Matrix",disable=2
368        Button DoItButton,pos={21,632},size={80,20},proc=DoTheFitsButtonProc,title="Do the fits"
369//      Button savePathButton,pos={82,61},size={80,20},proc=SavePathButtonProc,title="Save Path..."
370        TitleBox tb1,pos={139,634},size={128,12},anchor=MC,variable=root:AutoFit:gStatus,frame=0
371        Button button0,pos={14,331},size={40,20},title="Plot",proc=LoadForGuessProc
372//      SetVariable extStr,pos={4,170},size={40,15},title=" ",value= root:AutoFit:gExt
373       
374        Button GuessCoefB,pos={198,440},size={50,20},title="Guess",proc=UseCoefAsGuess
375        Button GuessHoldB,pos={198,440},size={50,20},title="Guess",disable=1,proc=UseHoldAsGuess
376        Button GuessConstrB,pos={198,440},size={50,20},title="Guess",disable=1,proc=UseConstraintsAsGuess
377       
378        TitleBox infoTitleBox pos={180,470},fixedSize=1,size={96,130},variable=root:AutoFit:guessStr
379       
380        ValDisplay progressValdisp,pos={113,663},size={161,7},title="00:00"
381        ValDisplay progressValdisp,limits={0,root:AutoFit:endProgress,0},barmisc={0,0},value= root:AutoFit:curProgress
382       
383        Button AF_DoneButton,pos={174,30},size={70,20},proc=AF_DoneButtonProc,title="Done"
384        Button AF_HelpButton,pos={260,30},size={30,20},proc=AF_HelpButtonProc,title="?"
385
386EndMacro
387
388// close the panel
389// + other windows?
390//
391Proc AF_DoneButtonProc(ctrlName): ButtonControl
392        String ctrlName
393        DoWindow/K AutoFitPanel
394end
395
396//open the Help file for the AutoFit Panel
397Function AF_HelpButtonProc(ba) : ButtonControl
398        STRUCT WMButtonAction &ba
399
400        switch( ba.eventCode )
401                case 2: // mouse up
402                        // click code here
403                        DisplayHelpTopic/Z/K=1 "Auto Fit"
404                        if(V_flag !=0)
405                                DoAlert 0,"The Auto Fit Help file could not be found"
406                        endif
407                        break
408        endswitch
409
410        return 0
411End
412
413
414Function AF_FuncPopupProc(pa) : PopupMenuControl
415        STRUCT WMPopupAction &pa
416
417        switch( pa.eventCode )
418                case 2: // mouse up
419                        Variable popNum = pa.popNum
420                        String popStr = pa.popStr
421                        String name=pa.ctrlName
422                        Variable num=0,nc
423                       
424                        String coefStr = getFunctionCoef(popStr)
425                        String str
426                       
427                        NVAR pts1 = root:AutoFit:numPar
428                        SVAR suff = root:AutoFit:gExt
429                       
430                        Wave/Z coef=$("root:"+coefStr)
431                        if(WaveExists(coef))
432                                num=numpnts(coef)
433                                suff = getModelSuffix(popStr)           //get the suffix from the unsmeared model function
434                        else
435                                //try getting rid of "Smeared" from the beginning of the function string
436                                nc = strlen(popStr)
437                                str = getFunctionCoef(popStr[7,nc-1])
438                                Wave/Z cw = $("root:"+str)
439                                if(WaveExists(cw))
440                                        num=numpnts(cw)
441                                endif
442                                suff = getModelSuffix(popStr[7,nc-1])           //get the suffix from the unsmeared model function
443                        endif
444                       
445                        // set the globals
446                        pts1 = num
447                       
448                       
449                       
450                        // set the size of the matrix of initial guesses
451                        SetNumParamProc("",num,"","")
452                       
453                        break
454        endswitch
455
456        return 0
457End
458
459
460Function tabProc(name,tab)
461        String name
462        Variable tab
463       
464        String infoStr="",guessStr,holdStr,constStr,rangeStr
465        SVAR str0 = root:AutoFit:guessStr
466        SVAR str1 = root:AutoFit:holdStr
467        SVAR str2 = root:AutoFit:constStr
468        SVAR str3 = root:AutoFit:rangeStr
469       
470       
471       
472        Button FillAllGuessButton disable= (tab!=0)
473        Button GuessCoefB disable=(tab!=0)
474        ListBox guessBox disable= (tab!=0)
475       
476       
477        Button FillAllHoldButton disable= (tab!=1)
478        Button GuessHoldB disable=(tab!=1)
479        ListBox holdBox disable=(tab!=1)
480       
481        Button FillAllConstrButton disable= (tab!=2)
482        Button GuessConstrB disable=(tab!=2)
483        ListBox ConstrBox disable=(tab!=2)
484       
485        //no buttons on the range tab
486        ListBox RangeBox disable=(tab!=3)
487        Button FillAllRangeB disable= (tab!=3)
488       
489        if(tab==0)
490                TitleBox infoTitleBox variable=str0
491        endif
492        if(tab==1)
493                TitleBox infoTitleBox variable=str1
494        endif
495        if(tab==2)
496                TitleBox infoTitleBox variable=str2
497        endif
498        if(tab==3)
499                TitleBox infoTitleBox variable=str3
500        endif
501       
502       
503        return(0)
504End
505
506
507Function FillAllGuessButtonProc(ctrlName) : ButtonControl
508        String ctrlName
509
510        //fills all of the guesses with the "current" list of guesses
511        WAVE/T gl=root:AutoFit:guessList
512        WAVE/T gm=root:AutoFit:guessMatrix
513        gm[][] = gl[p]
514        return(0)
515End
516
517Function FillAllHoldButtonProc(ctrlName) : ButtonControl
518        String ctrlName
519
520        //fills all of the guesses with the "current" list of guesses
521        WAVE/T hl=root:AutoFit:holdList
522        WAVE/T hm=root:AutoFit:holdMatrix
523        hm[][] = hl[p]
524        return(0)
525End
526
527Function FillAllConstrButtonProc(ctrlName) : ButtonControl
528        String ctrlName
529
530        //fills all of the guesses with the "current" list of guesses
531        WAVE/T cl=root:AutoFit:constrList
532        WAVE/T cm=root:AutoFit:ConstrMatrix
533        cm[][] = cl[p]
534        return(0)
535End
536
537Function FillAllRangeButtonProc(ctrlName) : ButtonControl
538        String ctrlName
539
540        //fills all of the range values with the top values
541        WAVE/T rl=root:AutoFit:rangeList
542        WAVE/T rm=root:AutoFit:rangeMatrix
543        rm[][] = rl[p]
544        return(0)
545End
546
547Function SetNumParamProc(ctrlName,varNum,varStr,varName) : SetVariableControl
548        String ctrlName
549        Variable varNum
550        String varStr
551        String varName
552
553        //set the number of parameters for the function
554        Variable/G numPar=varNum
555       
556        // adjust the number of parameters in the guesses
557        SetMatrixRows(varNum)
558       
559        return(0)
560End
561
562//expand or collapse the matrices to the number of parameters
563Function SetMatrixRows(newRows)
564        Variable newRows
565       
566        SetDataFolder root:AutoFit
567       
568        WAVE/T aa = guessMatrix
569        WAVE/T bb = holdMatrix
570        WAVE/T cc = constrMatrix
571        WAVE/T rr = rangeMatrix
572       
573        Redimension/N=(newRows,-1) aa,bb,cc,rr
574       
575        //redimension the lists too
576        WAVE/T dd=guessList
577        WAVE/T ee=holdList
578        WAVE/T ff=constrList
579        WAVE/T rrl=rangeList
580        Redimension/N=(newRows) dd,ee,ff,rrl
581       
582        WAVE gg=guessSel
583        WAVE hh=holdSel
584        WAVE ii=constrSel
585        WAVE rrs=rangeSel
586        //set the selection wave for the individual lists to 2 == editable
587        Redimension/N=(newRows) gg,hh,ii,rrs
588        gg=2
589        hh=2
590        ii=2
591        rrs=2
592       
593        SetDataFolder root:
594       
595        return 0
596end
597
598
599Function FileListboxProc(ctrlName,row,col,event)
600        String ctrlName     // name of this control
601        Variable row        // row if click in interior, -1 if click in title
602        Variable col        // column number
603        Variable event      // event code
604       
605        if(event==4 && col==0)          //selection of a file, not a checkbox
606                //then update the listbox display of guesses for the new file
607        //      Print "file selected"
608                DisplayGuess()
609        Endif
610       
611        return 0            // other return values reserved
612End
613
614Function UpdateGuessMatrixProc(ctrlName,row,col,event)
615        String ctrlName     // name of this control
616        Variable row        // row if click in interior, -1 if click in title
617        Variable col        // column number
618        Variable event      // event code
619       
620        if(event==7)            //finished edit of a cell, update the matrix of guesses
621                //Print "updating"
622                WAVE/T gl=root:AutoFit:guessList
623                WAVE/T gm=root:AutoFit:guessMatrix
624                //put new value in guessMatrix
625                Variable datafile
626                datafile = FindSelectedRowInLB(0)               //selected row in file list
627                gm[row][datafile] = gl[row]
628                //print "row= ",row
629        Endif
630        return 0            // other return values reserved
631End
632
633Function UpdateHoldMatrixProc(ctrlName,row,col,event)
634        String ctrlName     // name of this control
635        Variable row        // row if click in interior, -1 if click in title
636        Variable col        // column number
637        Variable event      // event code
638       
639        if(event==7)            //finished edit of a cell, update the matrix of guesses
640                //Print "updating"     
641                WAVE/T hl=root:AutoFit:holdList
642                WAVE/T hm=root:AutoFit:holdMatrix
643                // put new value in holdMatrix
644                Variable datafile
645                datafile = FindSelectedRowInLB(0)
646                hm[row][datafile] = hl[row]
647                //print "row= ",row
648        Endif
649        return 0            // other return values reserved
650End
651
652Function UpdateConstrMatrixProc(ctrlName,row,col,event)
653        String ctrlName     // name of this control
654        Variable row        // row if click in interior, -1 if click in title
655        Variable col        // column number
656        Variable event      // event code
657       
658        if(event==7)            //finished edit of a cell, update the matrix of guesses
659                //Print "updating"
660                WAVE/T cl=root:AutoFit:ConstrList
661                WAVE/T cm=root:AutoFit:constrMatrix
662                //put new value in constrMatrix
663                Variable datafile
664                datafile = FindSelectedRowInLB(0)
665                cm[row][datafile] = cl[row]
666                //print "row= ",row
667        Endif
668        return 0            // other return values reserved
669End
670
671Function UpdateRangeMatrixProc(ctrlName,row,col,event)
672        String ctrlName     // name of this control
673        Variable row        // row if click in interior, -1 if click in title
674        Variable col        // column number
675        Variable event      // event code
676       
677        if(event==7)            //finished edit of a cell, update the matrix of guesses
678                //Print "updating"
679                WAVE/T cl=root:AutoFit:RangeList
680                WAVE/T cm=root:AutoFit:RangeMatrix
681                //put new value in constrMatrix
682                Variable datafile
683                datafile = FindSelectedRowInLB(0)
684                cm[row][datafile] = cl[row]
685                //print "row= ",row
686        Endif
687        return 0            // other return values reserved
688End
689
690//returns the total number of files checked
691Function numChecked()
692       
693        WAVE sel = root:AutoFit:fileSelWave
694       
695        Variable ii,num=0
696        for(ii=0;ii<DimSize(sel,0);ii+=1)
697                if( (sel[ii][1] & 0x10) == 16 )
698                        num += 1
699                endif
700        endfor
701        return num
702       
703End
704
705
706//Function RangeCheckProc(ctrlName,checked) : CheckBoxControl
707//      String ctrlName
708//      Variable checked
709//     
710//      SetVariable lowPt disable=(checked)
711//      SetVariable highPt disable=(checked)
712//End
713
714Function DoTheFitsButtonProc(ctrlName) : ButtonControl
715        String ctrlName
716
717        //read the values from the panel
718        ControlInfo/W=AutoFitPanel popup0
719        String funcStr=S_Value
720        String fileName
721        NVAR numPar=root:AutoFit:numPar
722        NVAR startTicks=root:AutoFit:startTicks
723        NVAR curProgress=root:AutoFit:curProgress
724        NVAR endProgress=root:AutoFit:endProgress
725       
726        WAVE/T fileWave=root:AutoFit:fileListWave
727        WAVE sel = root:AutoFit:fileSelWave
728       
729        WAVE/T guessMatrix=root:AutoFit:guessMatrix
730        WAVE/T holdMatrix=root:AutoFit:holdMatrix
731        WAVE/T constrMatrix=root:AutoFit:constrMatrix
732        WAVE/T rangeMatrix=root:AutoFit:rangeMatrix
733               
734        Variable ii=0,numFiles=DimSize(fileWave,0),t1=ticks,t2,matrixindex,count=0
735        //print numFiles
736        //for the timer-progress bar - timer shows time, bar shows number of fits remaining
737        curProgress = 0
738        endProgress = 3*numChecked()                    //3 fits per file that is fit
739        ValDisplay progressValdisp,limits={0,endProgress,0}
740        ControlUpdate/W=AutoFitPanel progressValdisp
741       
742        //print "numChecked() = ",numChecked()
743        startTicks=t1                   //starting now
744        for(ii=0;ii<numFiles;ii+=1)             //loop over everything in the file list, dispatching only checked items
745                if( (sel[ii][1] & 0x10) == 16 )         //the box is checked, then go fit it
746                        fileName = fileWave[ii][0]
747                        DoOneFit(funcStr,fileName,numPar,fileWave,ii,guessMatrix,holdMatrix,constrMatrix,rangeMatrix)
748                        count+=1
749                endif
750        endfor
751        UpdateStatusString("All files processed")
752        t2=ticks
753        t1=(t2-t1)/60
754        Printf "All %d files processed in %g seconds =(%g minutes) =(%g hours)\r",count,t1,t1/60,t1/60/60
755        return(0)
756End
757
758
759Function DoOneFit(funcStr,fileName,numPar,fileWave,ii,guessMatrix,holdMatrix,constrMatrix,rangeMatrix)
760        String funcStr,fileName
761        Variable numPar
762        WAVE/T fileWave //length <= ii
763        Variable ii             //index in the full list
764        WAVE/T guessMatrix,holdMatrix,constrMatrix,rangeMatrix
765       
766        String list="",fullName="",dataname="",str=""
767        //be sure all is clear (no data, window... etc)
768        DoWindow/K AutoGraph                            //no error is reported
769        DoWindow/K AutoGraph_NSE                               
770        list=WaveList("*__*",";","")            //not case sensitive?
771        DoKillList(list)                                                //get rid of all of the old data
772        list=WaveList("wave*",";","")           //"wave(n)" can be generated if not all NSE times are collected
773        DoKillList(list)
774       
775        //SANS or NSE data?
776        ControlInfo/W=AutoFitPanel typeCheck
777        Variable isNSE=v_value
778        //load in the data
779        PathInfo dataPath
780        fullName = S_path
781        //fullName += fileWave[ii]
782        fullName += fileName
783        if(isNSE)
784                //load, don't plot
785                str = "A_LoadNSEDataWithName(\""+fullName+"\",0)"
786                Execute str
787//              A_LoadNSEDataWithName(fullName,0)                               //load, don't plot
788        else
789                //load, default name, no plot, overwrite data if needed
790                str = "A_LoadOneDDataToName(\""+fullName+"\",\"\",0,1)"
791                Execute str
792//              A_LoadOneDDataToName(fullName,"",0,1)           //load, default name, no plot, overwrite data if needed
793        endif
794        dataName=GetFileNameFromPathNoSemi(fullName)
795        dataname=CleanupName(dataname,0)
796       
797        //graph it - creates window named "AutoGraph"
798        if(isNSE)
799                Execute "DoGraph_NSE(\""+dataname+"\")"
800        else
801                Execute "DoGraph(\""+dataname+"\")"
802        endif
803       
804        //generate the needed strings to add to the execute stmt
805        // rangeStr, guessStr,constrStr,holdStr
806        // and waves - the coefficient wave and paramter wave
807        Variable useRes,useEps,useCursors,useConstr
808        Variable val,pt1,pt2
809        useEps = 0
810        useConstr = 0
811        useCursors = 0
812        useRes = 0
813       
814        String holdStr="",rangeStr="",cStr="",epsilonStr=""
815        String DF="root:"+dataname+":" 
816
817       
818        Make/O/D/N=(numPar) myCoef              //always named "myCoef"
819        Wave cw = root:myCoef
820
821        //range string
822        useCursors = ParseRangeString(ii,dataname,rangeMatrix,pt1,pt2)          //read range from the matrix, return values and set flag
823
824       
825        //params to hold
826        holdStr = ParseHoldString(ii,numpar,holdMatrix)
827        //initial guesses
828        ParseGuessString(ii,numpar,guessMatrix,"myCoef")
829        //constraints
830        cStr = ParseConstraints(ii,numpar,constrMatrix,"myConstraints")
831        WAVE/Z constr = $"myConstraints"
832        if(strlen(cStr)!=0)
833                useConstr = 1
834        endif
835        //epsilon wave
836        epsilonStr = GetEpsilonWave()
837        if(strlen(epsilonStr) > 0)
838                Wave eps=$epsilonStr            //in the root folder
839                useEps = 1
840        endif
841       
842        //fit it
843        //these two global variables must be created for IGOR to set them, so that
844        //any errors in the fitting can be diagnosed
845        Variable/G V_FitError=0                         //0=no err, 1=error,(2^1+2^0)=3=singular matrix
846        Variable/G V_FitQuitReason=0            //0=ok,1=maxiter,2=user stop,3=no chisq decrease
847        NVAR tol=root:AutoFit:fitTol
848        Variable/G V_FitTol=tol         //default is 0.0001
849        Variable/G V_fitOptions=4               //suppress the dialog during fitting (we're not waiting for OK, anyways)
850
851
852        Wave yw = $(DF+dataName+"_i")
853        Wave xw = $(DF+dataName+"_q")
854        Wave sw = $(DF+dataName+"_s")
855       
856        if(stringmatch(funcStr, "Smear*"))              // if it's a smeared function, need a struct
857                useRes=1
858        endif
859       
860        Struct ResSmearAAOStruct fs
861        WAVE/Z resW = $(DF+dataName+"_res")                     //these may not exist, if 3-column data is used
862        WAVE/Z fs.resW =  resW
863        WAVE yw=$(DF+dataName+"_i")
864        WAVE xw=$(DF+dataName+"_q")
865        WAVE sw=$(DF+dataName+"_s")
866        Wave fs.coefW = cw
867        Wave fs.yW = yw
868        Wave fs.xW = xw
869       
870        Duplicate/O yw $(DF+"FitYw")
871        WAVE fitYw = $(DF+"FitYw")
872        fitYw = NaN
873       
874        NVAR useGenCurveFit = root:Packages:NIST:gUseGenCurveFit
875        ///// SEE FitWrapper() for more details.
876       
877        Variable nPass = 1
878       
879        do      // outer do is the loop over passes
880        do      // this inner loop is abig switch to select the correct FutFunc to dispatch
881                if(useGenCurveFit)
882#if !(exists("GenCurveFit"))
883                        // XOP not available
884                        useGenCurveFit = 0
885                        Abort "Genetic Optimiztion XOP not available. Reverting to normal optimization."       
886#endif
887                        //send everything to a function, to reduce the clutter
888                        // useEps and useConstr are not needed
889                        // pass the structure to get the current waves, including the trimmed USANS matrix
890                        Variable chi,pt
891
892                        chi = DoGenCurveFit(useRes,useCursors,sw,fitYw,fs,funcStr,ParseHoldString(ii,numpar,holdMatrix),val,lolim,hilim,pt1,pt2)
893                        pt = val
894
895                        break
896                       
897                endif
898               
899               
900                if(useRes && useEps && useCursors && useConstr)         //do it all
901                        FuncFit/H=ParseHoldString(ii,numpar,holdMatrix) /NTHR=0 $funcStr cw, yw[pt1,pt2] /X=xw /W=sw /I=1 /E=eps /D=fitYw /C=constr /STRC=fs
902                        break
903                endif
904               
905                if(useRes && useEps && useCursors)              //no constr
906                        FuncFit/H=ParseHoldString(ii,numpar,holdMatrix) /NTHR=0 $funcStr cw, yw[pt1,pt2] /X=xw /W=sw /I=1 /E=eps /D=fitYw /STRC=fs
907                        break
908                endif
909               
910                if(useRes && useEps && useConstr)               //no crsr
911                        FuncFit/H=ParseHoldString(ii,numpar,holdMatrix) /NTHR=0 $funcStr cw, yw /X=xw /W=sw /I=1 /E=eps /D=fitYw /C=constr /STRC=fs
912                        break
913                endif
914               
915                if(useRes && useCursors && useConstr)           //no eps
916                        FuncFit/H=ParseHoldString(ii,numpar,holdMatrix) /NTHR=0 $funcStr cw, yw[pt1,pt2] /X=xw /W=sw /I=1 /D=fitYw /C=constr /STRC=fs
917                        break
918                endif
919               
920                if(useRes && useCursors)                //no eps, no constr
921                        FuncFit/H=ParseHoldString(ii,numpar,holdMatrix) /NTHR=0 $funcStr cw, yw[pt1,pt2] /X=xw /W=sw /I=1 /D=fitYw /STRC=fs
922                        break
923                endif
924               
925                if(useRes && useEps)            //no crsr, no constr
926                        FuncFit/H=ParseHoldString(ii,numpar,holdMatrix) /NTHR=0 $funcStr cw, yw /X=xw /W=sw /I=1 /E=eps /D=fitYw /STRC=fs
927                        break
928                endif
929       
930                if(useRes && useConstr)         //no crsr, no eps
931                        FuncFit/H=ParseHoldString(ii,numpar,holdMatrix) /NTHR=0 $funcStr cw, yw /X=xw /W=sw /I=1 /D=fitYw /C=constr /STRC=fs
932                        break
933                endif
934               
935                if(useRes)              //just res
936                        FuncFit/H=ParseHoldString(ii,numpar,holdMatrix) /NTHR=0 $funcStr cw, yw /X=xw /W=sw /I=1 /D=fitYw /STRC=fs
937                        break
938                endif
939               
940/////   same as above, but all without useRes (no /STRC flag)
941                if(useEps && useCursors && useConstr)           //do it all
942                        FuncFit/H=ParseHoldString(ii,numpar,holdMatrix) /NTHR=0 $funcStr cw, yw[pt1,pt2] /X=xw /W=sw /I=1 /E=eps /D=fitYw /C=constr
943                        break
944                endif
945               
946                if(useEps && useCursors)                //no constr
947                        FuncFit/H=ParseHoldString(ii,numpar,holdMatrix) /NTHR=0 $funcStr cw, yw[pt1,pt2] /X=xw /W=sw /I=1 /E=eps /D=fitYw
948                        break
949                endif
950               
951                if(useEps && useConstr)         //no crsr
952                        FuncFit/H=ParseHoldString(ii,numpar,holdMatrix) /NTHR=0 $funcStr cw, yw /X=xw /W=sw /I=1 /E=eps /D=fitYw /C=constr
953                        break
954                endif
955               
956                if(useCursors && useConstr)             //no eps
957                        FuncFit/H=ParseHoldString(ii,numpar,holdMatrix) /NTHR=0 $funcStr cw, yw[pt1,pt2] /X=xw /W=sw /I=1 /D=fitYw /C=constr
958                        break
959                endif
960               
961                if(useCursors)          //no eps, no constr
962                        FuncFit/H=ParseHoldString(ii,numpar,holdMatrix) /NTHR=0 $funcStr cw, yw[pt1,pt2] /X=xw /W=sw /I=1 /D=fitYw
963                        break
964                endif
965               
966                if(useEps)              //no crsr, no constr
967                        FuncFit/H=ParseHoldString(ii,numpar,holdMatrix) /NTHR=0 $funcStr cw, yw /X=xw /W=sw /I=1 /E=eps /D=fitYw
968                        break
969                endif
970       
971                if(useConstr)           //no crsr, no eps
972                        FuncFit/H=ParseHoldString(ii,numpar,holdMatrix) /NTHR=0 $funcStr cw, yw /X=xw /W=sw /I=1 /D=fitYw /C=constr
973                        break
974                endif
975               
976                //just a plain vanilla fit
977                FuncFit/H=ParseHoldString(ii,numpar,holdMatrix) /NTHR=0 $funcStr cw, yw /X=xw /W=sw /I=1 /D=fitYw
978       
979        while(0)                //always exit the inner do to select the FutFunc syntax. The break will exit this loop
980       
981                if(nPass == 1)
982                        UpdateStatusString(dataname +" Fit #1")
983                        Variable/G gChiSq1 = V_chisq
984                endif
985               
986                if(nPass == 2)
987                        UpdateStatusString(dataname +" Fit #2")
988                        Variable/G gChiSq2 = V_chisq
989                endif
990               
991                if(nPass == 3)
992                        UpdateStatusString(dataname +" Fit #3")
993                endif
994               
995                nPass += 1
996        while(nPass < 4)
997
998        // append the fit
999        // need to manage duplicate copies
1000        // Don't plot the full curve if cursors were used (set fitYw to NaN on entry...)
1001        String traces=TraceNameList("", ";", 1 )                //"" as first parameter == look on the target graph
1002        if(strsearch(traces,"FitYw",0) == -1)
1003                if(useGenCurveFit && useCursors)
1004                        WAVE trimX = trimX
1005                        AppendtoGraph fitYw vs trimX
1006                else
1007                        AppendToGraph FitYw vs xw
1008                endif
1009        else
1010                RemoveFromGraph FitYw
1011                if(useGenCurveFit && useCursors)
1012                        WAVE trimX = trimX
1013                        AppendtoGraph fitYw vs trimX
1014                else
1015                        AppendToGraph FitYw vs xw
1016                endif
1017        endif
1018        ModifyGraph lsize(FitYw)=2,rgb(FitYw)=(52428,1,1)
1019
1020
1021        //do the report calling the function, not the proc
1022        String topGraph= WinName(0,1)   //this is the topmost graph
1023        SVAR suffix = root:AutoFit:gExt         //don't try to read as getModelSuffix(funcStr), since the smeared() may not be plotted
1024        String parStr=GetWavesDataFolder(cw,1)+ WaveList("*param*"+"_"+suffix, "", "TEXT:1," )          // this is *hopefully* one wave
1025
1026        if(isNSE)
1027                GenerateReport_NSE(funcStr,dataname,"par","myCoef",1)
1028        else
1029                W_GenerateReport(funcStr,dataname,$parStr,$"myCoef",1,V_chisq,W_sigma,V_npnts,V_FitError,V_FitQuitReason,V_startRow,V_endRow,topGraph)
1030
1031//              AutoFit_GenerateReport(funcStr,dataname,"par","myCoef",1)       
1032        endif
1033       
1034        return(0)
1035End
1036
1037//// to be able to simply fill in the pt range of the yw[lo,hi]
1038//Function LowRange()
1039//      NVAR val = root:AutoFit:ptLow
1040//      return(val)
1041//End
1042//
1043//Function HighRange()
1044//      NVAR val = root:AutoFit:ptHigh
1045//      return(val)
1046//End
1047
1048//updates the status string, forcing a redraw twice, to overcome what seems to be a bug in Igor4
1049//also updates the progress bar and the countdown
1050Function UpdateStatusString(newStr)
1051        String newStr
1052       
1053        SVAR gStatus=root:AutoFit:gStatus
1054        SVAR gStatFormat=root:AutoFit:gStatFormat
1055        gStatus=""
1056        ControlUpdate/W=AutoFitPanel tb1                //clears the line
1057        gStatus=gStatFormat+newStr
1058        ControlUpdate/W=AutoFitPanel tb1
1059       
1060        //update the progress bar and timer
1061        NVAR cur=root:AutoFit:curProgress
1062        NVAR endProgress=root:AutoFit:endProgress
1063        NVAR startTicks=root:AutoFit:startTicks
1064        cur+=1
1065       
1066//      Print "****"
1067//      Print "cur = ",cur
1068       
1069        Variable t2=ticks,projTot,projRemain
1070        String titleStr=""
1071       
1072        projTot = (t2-startTicks)/(cur-1)*endProgress
1073        projRemain = projTot - (t2-startTicks)
1074        projRemain /= 60.15             //to seconds
1075        DoWindow/F AutoFitPanel
1076        ValDisplay progressValdisp,title=Secs2time(projRemain,5)
1077        ControlUpdate/W=AutoFitPanel progressValdisp
1078       
1079//      Print "End Progress = ",endProgress
1080//      Print "ProjTot = ",projTot/60.15
1081//      Print "ProjRemain = ",projRemain
1082       
1083        return(0)
1084End
1085
1086// returns a string with the name of the epsilon wave, or null if it doesn't exist
1087Function/S GetEpsilonWave()
1088       
1089        String retStr="",testStr
1090        SVAR extStr = root:AutoFit:gExt
1091        //do you want to use epsilon wave?
1092        ControlInfo/W=AutoFitPanel epsilonCheck
1093        if(V_Value == 0)                //not checked
1094                return(retStr)
1095        endif
1096       
1097        testStr = "Epsilon_"+extStr
1098        if(waveexists($testStr) != 0)
1099//              return(" /E="+testStr)
1100                return(testStr)
1101        endif
1102        return(retStr)
1103End
1104
1105//returns the y data to fit - "_i" suffix, and range if selected
1106// enter the range as the first element[0] as low point, second element[1] as high point
1107// leave the other elements blank
1108//
1109// if either point value is not entered, the whole data set is used
1110//
1111// -- if both of the elements are between 0 and 1, assume they are q-values (check for fractional part)
1112// and find the appropriate points...
1113//
1114Function ParseRangeString(set,dataStr,rMat,lo,hi)
1115        Variable set
1116        String dataStr
1117        WAVE/T rMat
1118        Variable &lo,&hi
1119       
1120        Variable useCursors
1121                       
1122        lo = str2num(rMat[0][set])
1123        hi = str2num(rMat[1][set])
1124       
1125        if(lo == 0 && hi == 0)
1126                return(0)
1127        endif
1128       
1129        if(numtype(lo) != 0 || numtype(hi) != 0)                //not a normal number
1130                return(0)               //don't use cursor values, use all of the dataset
1131        endif
1132       
1133       
1134        if(lo>=hi) //error in specification, or all data desired (both zero or undefined)
1135                return(0)               //use all of the dataset
1136        endif
1137       
1138       
1139        if(trunc(lo) != lo || trunc(hi) != hi)          //values have fractional parts
1140                WAVE xW = $("root:"+dataStr+":"+dataStr + "_q")
1141                FindLevel/P/Q xW, lo
1142                lo = trunc(V_levelX)            //find the corresponding point values
1143                FindLevel/P/Q xW, hi
1144                hi = trunc(V_levelX)
1145        endif
1146       
1147        Variable/G root:AutoFit:ptLow = lo
1148        Variable/G root:AutoFit:ptHigh = hi
1149
1150        return(1)
1151End
1152
1153//returns the holdStr, i.e. "1010101"
1154Function/S ParseHoldString(set,npar,hMat)
1155        Variable set,npar
1156        WAVE/T hMat
1157       
1158        Variable ii
1159        String retStr=""
1160       
1161        for(ii=0;ii<npar;ii+=1)
1162                if(strlen(hMat[ii][set]) == 0)
1163                        retStr += "0"
1164                else
1165                        retStr += hMat[ii][set]
1166                endif
1167        endfor
1168
1169//      Print retStr
1170       
1171        return(retStr)
1172End
1173
1174//returns only error - wave must already exist
1175Function ParseGuessString(set,npar,gMat,outWStr)
1176        Variable set,npar
1177        WAVE/T gMat
1178        String outWStr
1179       
1180        Variable ii
1181        String retStr=outWStr
1182       
1183        WAVE outWave=$outWStr
1184        for(ii=0;ii<npar;ii+=1)
1185                outWave[ii] = str2num(gMat[ii][set])
1186        endfor
1187        return(0)
1188End
1189
1190//the constraint wave is created here
1191Function/S ParseConstraints(set,npar,cMat,outWStr)
1192        Variable set,npar
1193        WAVE/T cMat
1194        String outWStr
1195       
1196        String retStr="",loStr="",hiStr=""
1197        Variable ii=0,jj=0     
1198        Make/O/T/N=0 $outWStr
1199        WAVE/T cw = $outWStr   
1200        //return "/C="+outWStr if parsed ok, or null if not
1201
1202        String listStr=""
1203        for(ii=0;ii<npar;ii+=1)
1204                listStr=cMat[ii][set]
1205                loStr=StringFromList(0, listStr ,";")
1206                hiStr=StringFromList(1, listStr ,";")
1207                if(cmpstr(loStr,"")!=0) //something there...
1208                        InsertPoints jj,1,cw            //insert before element jj
1209                        cw[jj] = "K"+num2Str(ii)+">"+loStr
1210                        jj+=1
1211                endif
1212                if(cmpstr(hiStr,"")!=0) //something there...
1213                        InsertPoints jj,1,cw            //insert before element jj
1214                        cw[jj] = "K"+num2Str(ii)+"<"+hiStr
1215                        jj+=1
1216                endif
1217        endfor
1218        if(numpnts(cw) > 0 )
1219                retStr = "/C=" + outWStr
1220        Endif
1221//      print "strlen, conStr= ",strlen(retStr),retstr
1222
1223        return(retStr)  //null string will be returned if no constraints
1224End
1225
1226
1227//*************************
1228Proc DoGraph(dataname)
1229        String dataname
1230       
1231        SetDataFolder $dataname
1232
1233        PauseUpdate; Silent 1           // building window...
1234        Display /W=(5,42,301,313)/K=1 $(dataname+"_i") vs $(dataname+"_q")
1235        DoWindow/C AutoGraph
1236        ModifyGraph mode($(dataname+"_i"))=3
1237        ModifyGraph marker($(dataname+"_i"))=19
1238        ModifyGraph rgb($(dataname+"_i"))=(1,4,52428)
1239        ModifyGraph msize($(dataname+"_i"))=2
1240        ModifyGraph grid=1
1241        ModifyGraph log=1
1242        ModifyGraph tickUnit=1
1243        //
1244        ModifyGraph mirror=2
1245        //
1246        ErrorBars $(dataname+"_i") Y,wave=($(dataname+"_s"),$(dataname+"_s"))
1247//      Legend/A=LB
1248//      Legend/A=LB/X=0.00/Y=-32                //defaults to the top right
1249        Legend/A=MT/E           // /X=-16.16/Y=5.17/E
1250       
1251        SetDataFolder root:
1252       
1253EndMacro
1254
1255Proc DoGraph_NSE(dataname)
1256        String dataname
1257       
1258        SetDataFolder $dataname
1259
1260        PauseUpdate; Silent 1           // building window...
1261        Display /W=(5,42,301,313)/K=1 $(dataname+"_i") vs $(dataname+"_q")
1262        DoWindow/C AutoGraph_NSE
1263        ModifyGraph mode($(dataname+"_i"))=3
1264        ModifyGraph marker($(dataname+"_i"))=19
1265        ModifyGraph rgb($(dataname+"_i"))=(1,4,52428)
1266        ModifyGraph msize($(dataname+"_i"))=3
1267        ModifyGraph zColor($(dataname+"_i"))={$(dataname+"__Q"),$(dataname+"__Q")[0]*0.99,*,Rainbow}
1268        ModifyGraph grid=1
1269        ModifyGraph mirror=2
1270        ModifyGraph log(left)=1
1271        ErrorBars $(dataname+"_i") Y,wave=($(dataname+"_s"),$(dataname+"_s"))
1272        Legend/A=MB
1273        SetAxis/A/E=1 bottom
1274        ModifyGraph standoff=0
1275        SetAxis left 0.1,1
1276        //ModifyGraph tickUnit(left)=1
1277EndMacro
1278
1279//*************************
1280
1281
1282//**************************
1283// Generate the report
1284//**************************
1285
1286////must have AutoGraph as the name of the graph window (any size)
1287//// func is the name of the function (for print only)
1288////par and coef are the exact names of the waves
1289////yesSave==1 will save the file(name=func+time)
1290////
1291////
1292//// general report function from the wrapper is used instead
1293////    W_GenerateReport(funcStr,folderStr,$parStr,cw,yesSave,V_chisq,W_sigma,V_npnts,V_FitError,V_FitQuitReason,V_startRow,V_endRow,topGraph)
1294////
1295//Function AutoFit_GenerateReport(func,dataname,par,myCoef,yesSave)
1296//      String func,dataname,par,myCoef
1297//      Variable yesSave
1298//     
1299//      String str,pictStr="P_"
1300//      Wave sigWave=$"W_sigma"
1301//      Wave ans=$myCoef
1302////    Wave/T param=$par
1303//      SVAR ext=root:AutoFit:gExt
1304//      Wave/T param=$"parameters_"+ext
1305//     
1306//      NVAR V_chisq = V_chisq
1307//      NVAR V_npnts = V_npnts
1308//      NVAR V_FitError = V_FitError
1309//      NVAR V_FitQuitReason = V_FitQuitReason
1310//      NVAR chi1=gChiSq1
1311//      NVAR chi2=gChiSq2
1312//      NVAR V_startRow = V_startRow
1313//      NVAR V_endRow = V_endRow
1314//     
1315//      // bring report up
1316//      DoWindow/F Report
1317//      if (V_flag == 0)                // Report notebook doesn't exist ?
1318//              NewNotebook/W=(10,45,550,620)/F=1/N=Report as "Report"
1319//      endif
1320//     
1321//      // delete old stuff
1322//      Notebook Report selection={startOfFile, endOfFile}, text="\r", selection={startOfFile, startOfFile}
1323//     
1324//      // insert title
1325//      Notebook Report newRuler=Title, justification=1, rulerDefaults={"Times", 16, 1, (0, 0, 0)}
1326//      sprintf str, "Fit to %s, %s, %s\r\r", func,Secs2Date(datetime, 0), time()
1327//      Notebook Report ruler=Title, text=str
1328//     
1329//      // insert fit results
1330//      Variable num=numpnts(ans),ii=0
1331//      Notebook Report ruler=Normal; Notebook Report  margins={18,18,504}, tabs={63 + 3*8192}
1332//      str = "Data file: " + dataname + "\r\r"
1333//      Notebook Report text=str
1334//      do
1335//              sprintf str, "%s = %g±%g\r", param[ii],ans[ii],sigwave[ii]
1336//              Notebook Report text=str
1337//              ii+=1
1338//      while(ii<num)
1339//     
1340//      //
1341//      Wave dataXw = $(dataname+"_q")
1342//      Variable nData=numpnts(dataXw)
1343//     
1344//      //
1345//      sprintf str,"chisq = %g , %g , %g\r",chi1,chi2,V_chisq
1346//      Notebook Report textRGB=(65000,0,0),fstyle=1,text=str
1347//      sprintf str,"Npnts = %g, sqrt(X^2/N) = %g\r",V_npnts,sqrt(V_chisq/V_npnts)
1348//      Notebook Report textRGB=(0,0,0),fstyle=0, text=str
1349//      sprintf str "Fitted range = [%d,%d] = %g < Q < %g\r",V_startRow,V_endRow,dataXw(V_startRow),dataXw(V_endRow)
1350//      Notebook Report textRGB=(0,0,0),fstyle=0, text=str
1351//      sprintf str,"V_FitError = %g\t\tV_FitQuitReason = %g\r",V_FitError,V_FitQuitReason
1352//      Notebook Report textRGB=(65000,0,0),fstyle=1,text=str
1353//      Notebook Report ruler=Normal
1354//     
1355//      // insert graphs
1356//      Notebook Report picture={AutoGraph(0, 0, 400, 300), 0, 1}, text="\r"
1357//     
1358//
1359//      //Notebook Report picture={Table1, 0, 0}, text="\r"
1360//     
1361//      // show the top of the report
1362//      Notebook Report  selection= {startOfFile, startOfFile},  findText={"", 1}
1363//     
1364//      //save the notebook
1365//      if(yesSave)
1366//              String nameStr=CleanupName(func,0)
1367//              nameStr = nameStr[0,8]  //shorten the name
1368//              nameStr += "_"+dataname
1369//              //make sure the name is no more than 31 characters
1370//              namestr = namestr[0,30]         //if shorter than 31, this will NOT pad to 31 characters
1371//              Print "file saved as ",nameStr
1372//              SaveNotebook /O/P=savePath/S=2 Report as nameStr
1373//              //save the graph separately as a PICT file, 2x screen
1374//              pictStr += nameStr
1375//              pictStr = pictStr[0,28]         //need a shorter name - why?
1376//              DoWindow/F AutoGraph
1377//              // E=-5 is png @screen resolution
1378//              // E=2 is PICT @2x screen resolution
1379//              SavePICT /E=2/O/I/P=savePath /W=(0,0,3,3) as pictStr
1380//      Endif
1381//     
1382//      // ???maybe print the notebook too?
1383//End
1384
1385
1386
1387//
1388//Proc DoGenerateReport(fname,dataname,param,coef,yesno)
1389//      String fname,dataname="",param,coef,yesno="No"
1390//      Prompt fname,"function name",popup,FunctionList("!Sme*",";","KIND:15,")
1391//      Prompt dataname,"name of the dataset"
1392//      Prompt param,"parameter names",popup,WaveList("par*",";","")
1393//      Prompt coef,"coefficient wave",popup,WaveList("coe*",";","")
1394//      Prompt yesno,"Save the report?",popup,"Yes;No;"
1395//     
1396//      //Print "fname = ",fname
1397//      //Print "param = ",param
1398//      //Print "coef = ",coef
1399//      //Print "yesno = ",yesno
1400//     
1401//      Variable doSave=0
1402//      if(cmpstr(yesno,"Yes")==0)
1403//              doSave=1
1404//      Endif
1405//      GenerateReport(fname,dataname,param,coef,dosave)
1406//     
1407//End
1408
1409
1410
1411//must have AutoGraph_NSE as the name of the graph window (any size)
1412// func is the name of the function (for print only)
1413//par and coef are the exact names of the waves
1414//yesSave==1 will save the file(name=func+time)
1415//
1416Function GenerateReport_NSE(func,dataname,par,coef,yesSave)
1417        String func,dataname,par,coef
1418        Variable yesSave
1419       
1420        String str
1421        Wave sigWave=$"W_sigma"
1422        Wave ans=$coef
1423        Wave/T param=$par
1424       
1425        NVAR V_chisq = V_chisq
1426        NVAR V_npnts = V_npnts
1427        NVAR V_FitError = V_FitError
1428        NVAR V_FitQuitReason = V_FitQuitReason
1429       
1430        // bring report up
1431        DoWindow/F Report
1432        if (V_flag == 0)                // Report notebook doesn't exist ?
1433                NewNotebook/W=(10,45,550,620)/F=1/N=Report as "Report"
1434        endif
1435       
1436        // delete old stuff
1437        Notebook Report selection={startOfFile, endOfFile}, text="\r", selection={startOfFile, startOfFile}
1438       
1439        // insert title
1440        Notebook Report newRuler=Title, justification=1, rulerDefaults={"Times", 16, 1, (0, 0, 0)}
1441        sprintf str, "Fit to %s, %s, %s\r\r", func,Secs2Date(datetime, 0), time()
1442        Notebook Report ruler=Title, text=str
1443       
1444        // insert fit results
1445        Variable num=numpnts(ans),ii=0
1446        Notebook Report ruler=Normal; Notebook Report  margins={18,18,504}, tabs={63 + 3*8192}
1447        str = "Data file: " + dataname + "\r\r"
1448        Notebook Report text=str
1449        do
1450                sprintf str, "%s = %g±%g\r", param[ii],ans[ii],sigwave[ii]
1451                Notebook Report text=str
1452                ii+=1
1453        while(ii<num)
1454               
1455        sprintf str,"chisq = %g\r",V_chisq
1456        Notebook Report textRGB=(65000,0,0),fstyle=1,text=str
1457        sprintf str,"Npnts = %g\r",V_npnts
1458        Notebook Report textRGB=(0,0,0),fstyle=0, text=str
1459        sprintf str,"V_FitError = %g\rV_FitQuitReason = %g\r",V_FitError,V_FitQuitReason
1460        Notebook Report textRGB=(65000,0,0),fstyle=1,text=str
1461        Notebook Report ruler=Normal
1462       
1463        // insert graphs
1464        Notebook Report picture={AutoGraph_NSE(0, 0, 400, 300), 0, 1}, text="\r"
1465        //Notebook Report picture={Table1, 0, 0}, text="\r"
1466       
1467        // show the top of the report
1468        Notebook Report  selection= {startOfFile, startOfFile},  findText={"", 1}
1469       
1470        //save the notebook
1471        if(yesSave)
1472                String nameStr=CleanupName(func,0)
1473                nameStr = nameStr[0,8]  //shorten the name
1474                nameStr += "_"+dataname
1475                //make sure the name is no more than 31 characters
1476                namestr = namestr[0,30]         //if shorter than 31, this will NOT pad to 31 characters
1477                Print "file saved as ",nameStr
1478//              SaveNotebook /O/P=savePath/S=2 Report as nameStr
1479                SaveNotebook /O/P=home/S=2 Report as nameStr
1480        Endif
1481
1482        //save a pict file, just of the graph
1483        namestr = "PNG_" + namestr
1484        namestr = namestr[0,28]         //PICT names in IGOR must be shorter, to allow auto-naming?
1485        DoWindow/F AutoGraph_NSE
1486//      SavePICT /E=2/O/I/P=savePath /W=(0,0,3,3) as nameStr
1487        SavePICT /E=2/O/I/P=home /W=(0,0,3,3) as nameStr
1488End
1489
1490
1491//*********************
1492//
1493//*********************
1494// List utilities
1495//*********************
1496//
1497// List2TextWave is also in SANS_Utilities.ipf, but to keep from having big lists of dependencies,
1498// have definitions here that are local and Static
1499
1500//
1501Static Function List2TextWave(list,sep,waveStr)
1502        String list,sep,waveStr
1503       
1504        Variable n= ItemsInList(list,sep)
1505        Make/O/T/N=(n) $waveStr= StringFromList(p,list,sep)
1506End
1507
1508Function List2NumWave(list,sep,waveStr)
1509        String list,sep,waveStr
1510       
1511        Variable n= ItemsInList(list,sep)
1512        Make/O/D/N=(n) $waveStr= str2num( StringFromList(p,list,sep) )
1513End
1514
1515Function/S TextWave2List(w,sep)
1516        Wave/T w
1517        String sep
1518       
1519        String newList=""
1520        Variable n=numpnts(w),ii=0
1521        do
1522                newList += w[ii] + sep
1523                ii+=1
1524        while(ii<n)
1525        return(newList)
1526End
1527
1528//for single precision numerical waves
1529Function/S NumWave2List(w,sep)
1530        Wave w
1531        String sep
1532       
1533        String newList="",temp=""
1534        Variable n=numpnts(w),ii=0,val
1535        do
1536                val=w[ii]
1537                temp=""
1538                sprintf temp,"%g",val
1539                newList += temp
1540                newList += sep
1541                ii+=1
1542        while(ii<n)
1543        return(newList)
1544End
1545
1546Function DoKillList(list)
1547        String list
1548       
1549        String item=""
1550        do
1551                item = StringFromList(0, list ,";" )
1552                KillWaves/Z $item
1553                list = RemoveFromList(item, list, ";")
1554        while(ItemsInList(list, ";")>0)
1555End
1556
1557//*********************
1558
1559
1560
1561//*******************
1562//Notebook Utils
1563//*******************
1564
1565Proc PrintOpenNotebooks()
1566
1567        String list=WinList("*", ";", "WIN:16")
1568        String item = ""
1569        do
1570                item=StringFromList(0,list,";")
1571                Print item
1572                PrintNotebook $item
1573                list = RemoveFromList(item, list, ";")
1574        while(ItemsInList(list, ";")>0)
1575End
1576
1577Proc CloseOpenNotebooks()
1578
1579        String list=WinList("*", ";", "WIN:16")
1580        String item = ""
1581        do
1582                item=StringFromList(0,list,";")
1583                DoWindow/K $item
1584                list = RemoveFromList(item, list, ";")
1585        while(ItemsInList(list, ";")>0)
1586End
1587
1588Proc Generate_PNG_list()
1589        fGenerate_PNG_list()
1590End
1591
1592//spits up a list of PNGS
1593Function fGenerate_PNG_list()
1594
1595//      String List=IndexedFile(savePath, -1, ".png")
1596        String List=IndexedFile(home, -1, ".png")
1597        List2TextWave(List,";","PNG_files")
1598        WAVE/T PNGs=$"PNG_files"
1599        Edit/K=1 PNGs
1600End
1601
1602Proc Layout_PNGS(pStr)
1603        String pStr=""
1604        Prompt pStr,"wave of PNGs to use",popup,WaveList("PNG_f*", ";", "")
1605               
1606        String List=TextWave2List($pStr,";")
1607        String item = ""
1608        //kill old picts from memory
1609        KillPicts/A/Z
1610        //make a new layout
1611        Layout/C=1 as "PNG_Layout"
1612        DoWindow/C PNGLayout
1613        do
1614                item=StringFromList(0,List,";")
1615                //load each PNG, and append it to the layout
1616                Print "load item = ",item
1617//              LoadPICT /O/Q/P=savePath item
1618                LoadPICT /O/Q/P=home item
1619                DoWindow/F PNGLayout            //be sure layout is on top
1620                AppendLayoutObject /F=1/W=PNGLayout picture  $CleanupName(item,0)
1621                //AppendToLayout $item
1622                //Print item
1623                List = RemoveFromList(item, List, ";")
1624        while(ItemsInList(List, ";")>0)
1625        //tile the PNGs in the layout
1626        Tile/O=8
1627End
1628
1629//spit up a list of everything in the folder that is a text file
1630Proc Generate_Data_Checklist()
1631        fGenerate_Data_list()
1632End
1633Function fGenerate_Data_list()
1634
1635        String List=IndexedFile(dataPath, -1, "TEXT")
1636        List2TextWave(List,";","data_files")
1637        WAVE/T files=$"data_files"
1638        Duplicate/O/T files ModelToUse,Done
1639        ModelToUse = ""
1640        Done = ""
1641        Edit/K=1 files,ModelToUse,Done
1642End
1643
1644//***************
1645
1646// with all of the notebooks open for a given model (with N parameters)
1647// this will comile the reports, save the text notebook, then load it back in
1648// and put it in a table for easy printing
1649//
1650Proc CompileAndLoadReports()
1651        Compile_Reports()
1652//      SaveNotebook /O/P=savePath/S=2 Compilation
1653        SaveNotebook /O/P=home/S=2 Compilation
1654//      Print "Saved as:  ",S_Path
1655        DoWindow/K Compilation
1656        LoadCompiledReports(S_Path)
1657End
1658
1659Proc LoadCompiledReports(str)
1660        String str
1661        LoadWave/J/D/W/E=1/K=0/V={"\t"," $",0,0} str
1662End
1663
1664Proc Compile_Reports(Number_of_Parameters,tagStr)
1665        Variable Number_of_Parameters=(root:AutoFit:numPar)
1666        String tagStr="v1"
1667
1668        fCompile_ReportsTable(Number_of_Parameters,tagStr)
1669
1670        fCompile_Reports(Number_of_Parameters)
1671       
1672        DoWindow/F AutoFitResults
1673
1674End
1675
1676Proc Compile_GlobalFit_Reports(WhichParameter,FileStr,ParamStr,ParamErrStr)
1677        Variable WhichParameter=7
1678        String FileStr="FileName_",ParamStr="par_",ParamErrStr="parErr_"
1679        fCompile_GlobalFit_Reports(WhichParameter,FileStr,ParamStr,ParamErrStr)
1680End
1681
1682////
1683Function fCompile_Reports(nPar)
1684        Variable nPar
1685       
1686        String list=WinList("*", ";", "WIN:16")
1687        String item = "",textStr="",newStr=""
1688        Variable sstop,dum,chi
1689       
1690        Variable ii
1691        NewNotebook/F=0 /N=Compilation as "Compilation"
1692        Notebook Compilation text="Variable Name \tValues\tErrors\r"
1693        do
1694                item=StringFromList(0,list,";")
1695                DoWindow/F $item
1696               
1697                Notebook $item selection={(2,0), (3,0)}         //paragraph 3 (starts from 0) = filename
1698                GetSelection notebook,$item,2
1699                textStr=S_Selection
1700                textStr=textStr[0,strlen(textStr)-2]            //remove CR
1701                textStr=textStr[10,strlen(textStr)-1]           //remove "DATA FILE:
1702                Notebook Compilation text="File:\t"+textStr+"\t"
1703                Notebook Compilation text=textStr+"_err\r"
1704               
1705//              printf "%s %s\r",textStr,textStr+"_err"
1706//
1707// results are written as:  "%s = \t%g\t±\t%g\r"
1708//
1709                for(ii=0;ii<nPar;ii+=1)         //gather the parameters
1710               
1711                        Notebook $item selection={(ii+4,0), (ii+5,0)}           //paragraph 5           = parameter 0
1712                        GetSelection notebook,$item,2
1713                        textStr=S_Selection
1714                        textStr=textStr[0,strlen(textStr)-2]
1715                        //textStr=textStr[13,strlen(textStr)-1]         // remove "parameter"
1716                        textStr = ReplaceString("=",textStr,"")
1717                        textStr = ReplaceString("±\t",textStr,"")
1718                        Notebook Compilation text=textStr+"\r"
1719                        //printf "%s\r",textStr
1720                        //Print strlen(textStr)
1721                endfor
1722                //get the chi-squared/N value
1723                ii+=1
1724                Notebook $item selection={(ii+4,0), (ii+5,0)}           //
1725                GetSelection notebook,$item,2
1726                textStr=S_Selection
1727               
1728//              Print textStr
1729               
1730                sscanf textStr,"Npnts = %g\t\tSqrt(X^2/N) = %g\r",dum,chi
1731                sprintf textStr,"Sqrt(X^2/N)\t%s\t\r",num2str(chi)
1732                Notebook Compilation text=textStr
1733               
1734                Notebook Compilation text="\r"          //separate items
1735               
1736                list = RemoveFromList(item, list, ";")
1737        while(ItemsInList(list, ";")>0)
1738       
1739        DoWindow/F Compilation
1740        Notebook Compilation selection={startOfFile,startOfFile}
1741End
1742
1743////
1744// compiles the results into a table.
1745// add tagStr to the end to (try) to make sure that the compilations are unique
1746Function fCompile_ReportsTable(nPar,tagStr)
1747        Variable nPar
1748        String tagStr
1749       
1750        String list=WinList("*", ";", "WIN:16")
1751        String item = "",textStr="",newStr="",str
1752        Variable sstop,dum,chi
1753       
1754        Variable ii,numRep,jj,val1,val2,pt
1755        numRep=ItemsInList(list,";")
1756       
1757        Make/O/T/N=(numRep) $("fittedFiles"+"_"+tagStr)
1758        Make/O/D/N=(numRep) $("chiSQ"+"_"+tagStr)
1759        Wave/T fittedFiles = $("fittedFiles"+"_"+tagStr)
1760        Wave chiSq = $("chiSQ"+"_"+tagStr)
1761        Edit/N=AutoFitResults fittedFiles,chiSQ
1762       
1763        for(ii=0;ii<nPar;ii+=1)         //waves for the parameters
1764                Make/O/D/N=(numRep) $("par"+num2str(ii)+"_"+tagStr),$("par"+num2str(ii)+"_err"+"_"+tagStr)
1765                AppendToTable $("par"+num2str(ii)+"_"+tagStr),$("par"+num2str(ii)+"_err"+"_"+tagStr)
1766        endfor
1767       
1768        for(jj=0;jj<numRep;jj+=1)
1769
1770                item=StringFromList(jj,list,";")
1771                DoWindow/F $item
1772                Notebook $item selection={(2,0), (3,0)}         //paragraph 3 (starts from 0) = filename
1773                GetSelection notebook,$item,2
1774                textStr=S_Selection
1775                textStr=textStr[0,strlen(textStr)-2]            //remove CR
1776                textStr=textStr[10,strlen(textStr)-1]           //remove "DATA FILE:
1777               
1778                fittedFiles[jj] = textStr
1779//
1780// results are written as:  "%s = \t%g\t±\t%g\r"
1781//
1782                for(ii=0;ii<nPar;ii+=1)         //gather the parameters
1783                        Notebook $item selection={(ii+4,0), (ii+5,0)}           //paragraph 5           = parameter 0
1784                        GetSelection notebook,$item,2
1785                        textStr=S_Selection
1786                        textStr=textStr[0,strlen(textStr)-2]
1787                        // find the "="
1788                        pt = strsearch(textStr,"=",0,0)
1789                        textStr = textStr[pt,strlen(textStr)-1]
1790                        sscanf textStr,"= \t%g\t ± \t%g\r",val1,val2
1791                       
1792//                      Print textStr
1793                                               
1794                        Wave w1 = $("par"+num2str(ii)+"_"+tagStr)
1795                        Wave w2 = $("par"+num2str(ii)+"_err"+"_"+tagStr)
1796                       
1797                        w1[jj] = val1
1798                        w2[jj] = val2
1799                       
1800                        //textStr = ReplaceString("=",textStr,"")
1801                        //textStr = ReplaceString("±\t",textStr,"")
1802                        //Notebook Compilation text=textStr+"\r"
1803                        //printf "%s\r",textStr
1804                        //Print strlen(textStr)
1805                endfor
1806                //get the chi-squared/N value
1807                ii += 1
1808                Notebook $item selection={(ii+4,0), (ii+5,0)}           //
1809                GetSelection notebook,$item,2
1810                textStr=S_Selection
1811               
1812//              Print textStr
1813               
1814                sscanf textStr,"Npnts = %g\t\tSqrt(X^2/N) = %g\r",dum,chi
1815               
1816                chiSQ[jj] = chi
1817        endfor
1818       
1819       
1820        return(0)
1821End
1822
1823
1824////
1825Function fCompile_GlobalFit_Reports(nPar,Files,Param,Param_err)
1826        Variable nPar
1827        String Files,Param,Param_Err
1828       
1829        String list=SortList(WinList("*", ";", "WIN:16"))
1830        String item = "",textStr="",fileStr,funcStr,dumStr
1831        Variable sstop,dum,chi,nFiles,val1,val2
1832       
1833        Variable ii,jj
1834
1835        nFiles = ItemsInList(list)
1836        Make/O/D/N=(nFiles) $Param,$Param_err
1837        Make/O/T/N=(nFiles) $Files
1838        WAVE pw = $Param
1839        WAVE pw_err = $Param_err
1840        WAVE/T fw = $Files
1841       
1842        for(jj=0;jj<nFiles;jj+=1)
1843       
1844                item=StringFromList(jj,list,";")
1845                DoWindow/F $item
1846               
1847                Notebook $item selection={(6,0), (7,0)}         //paragraph 7 (starts from 0) = filename
1848                GetSelection notebook,$item,2
1849                textStr=S_Selection
1850                sscanf textStr,"Data Set:%s ; Function:%s\r",fileStr,funcStr
1851                fw[jj] = fileStr
1852//              Notebook Compilation text=fileStr+"\r"
1853//              Notebook Compilation text=funcStr+"\r"
1854               
1855               
1856//              printf "%s %s\r",textStr,textStr+"_err"
1857
1858                for(ii=nPar;ii<=nPar;ii+=1)             //gather the parameters
1859               
1860                        Notebook $item selection={(ii+7,0), (ii+8,0)}           //paragraph 8           = parameter 0
1861                        GetSelection notebook,$item,2
1862                        textStr=S_Selection
1863//                      Print textStr
1864                        sscanf textStr,"%s %g +- %g\r",dumStr,val1,val2
1865                        pw[jj] = val1
1866                        pw_err[jj] = val2
1867                endfor
1868               
1869        endfor
1870
1871End
1872
1873
1874
1875//DOES NOT graph the data, does not create a weighting wave
1876//NSE data assumed to be 4-column
1877//q (all the same) - t(ns) - I(q,t) - dI(q,t)
1878Static Function LoadNSEDataWithName(fileStr)
1879        String fileStr
1880        //Load the waves, using default waveX names
1881        //if no path or file is specified for LoadWave, the default Mac open dialog will appear
1882        LoadWave/G/D/A/Q fileStr
1883        String fileName = S_fileName
1884       
1885       
1886        String w0,w1,w2,n0,n1,n2,wt,w3,n3
1887        Variable rr,gg,bb
1888       
1889        // put the names of the four loaded waves into local names
1890        n0 = StringFromList(0, S_waveNames ,";" )
1891        n1 = StringFromList(1, S_waveNames ,";" )
1892        n2 = StringFromList(2, S_waveNames ,";" )
1893        n3 = StringFromList(3, S_waveNames ,";" )
1894       
1895       
1896        //remove the semicolon AND period from files from the VAX
1897        w0 = CleanupName((S_fileName+"__Q"),0)
1898        w1 = CleanupName((S_fileName+"__X"),0)
1899        w2 = CleanupName((S_fileName+"__Y"),0)
1900        w3 = CleanupName((S_fileName+"__S"),0)
1901       
1902        if(exists(w0) !=0)
1903                //waves already exist
1904                KillWaves $n0,$n1,$n2,$n3               // kill the default waveX that were loaded
1905                return(0)
1906        endif
1907       
1908        // Rename to give nice names
1909        Rename $n0, $w0
1910        Rename $n1, $w1
1911        Rename $n2, $w2
1912        Rename $n3, $w3
1913
1914End
1915
1916/////
1917//wStr is the coef_ wave with the initial guess
1918Function FillCoefGuess(wStr)
1919        String wStr
1920       
1921        Wave w=$wStr
1922        if (! WaveExists(w) )
1923                DoAlert 0, "The coefficient wave "+wStr+" does not exist. Either create the wave or enter the correct suffix"
1924                return(0)
1925        endif
1926        Wave/T guess=root:AutoFit:guessMatrix
1927        Variable ii=0,num=numpnts(w)
1928        Variable tmp
1929       
1930        Variable selRow,matrixRow
1931        selRow = FindSelectedRowInLB(0) // send 0 to look at the column with filenames
1932
1933        do
1934                tmp=w[ii]
1935                guess[ii][selRow] = num2str(tmp)
1936                ii+=1
1937        while(ii<num)
1938End
1939
1940/////
1941//wStr is the hold_ wave with the initial guess
1942Function FillHoldGuess(wStr)
1943        String wStr
1944       
1945        Wave w=$wStr
1946        if (! WaveExists(w) )
1947                DoAlert 0, "The hold wave "+wStr+" does not exist. Either create the wave or enter the correct suffix"
1948                return(0)
1949        endif
1950        Wave/T hold=root:AutoFit:holdMatrix
1951        Variable ii=0,num=numpnts(w)
1952        Variable tmp
1953       
1954        Variable selRow,matrixRow
1955        selRow = FindSelectedRowInLB(0) // send 0 to look at the column with filenames
1956       
1957        do
1958                tmp=w[ii]
1959                hold[ii][selRow] = num2str(tmp)
1960                ii+=1
1961        while(ii<num)
1962End
1963
1964/////
1965//wStr is the Constr_ wave with the initial guess
1966// --- this is a Text wave
1967Function FillConstrGuess(wStr)
1968        String wStr
1969       
1970        Wave/T w=$wStr
1971        if (! WaveExists(w) )
1972                DoAlert 0, "The Constraint wave "+wStr+" does not exist. Either create the (TEXT) wave or enter the correct suffix"
1973                return(0)
1974        endif
1975        Wave/T constr=root:AutoFit:constrMatrix
1976        Variable ii=0,num=numpnts(w)
1977        String tmp
1978       
1979        Variable selRow,matrixRow
1980        selRow = FindSelectedRowInLB(0) // send 0 to look at the column with filenames
1981
1982        do
1983                tmp=w[ii]
1984                constr[ii][selRow] = tmp
1985                ii+=1
1986        while(ii<num)
1987End
1988
1989////
1990//need the extension of the model wave to append
1991//
1992// it will plot the UN-smeared model for generating the initial guesses
1993// -- fitting will use Smeared or unsmeared, depending on the popup selection
1994//
1995//
1996Function fLoadSelected(extStr)
1997        string extStr
1998
1999        Variable datafile,ii
2000        String fullName,dataName,str
2001       
2002        WAVE/T fileWave=root:AutoFit:fileListWave
2003        Wave sel = root:AutoFit:fileSelWave
2004        ii=0
2005        do
2006                if((sel[ii][0] & 0x01) == 1)    // the file is selected in the list box
2007                        datafile = ii
2008                        break
2009                endif
2010                ii+=1
2011        while(ii<numpnts(sel))
2012       
2013        //load in the data
2014        PathInfo dataPath
2015        fullName = S_path
2016        fullName += fileWave[datafile][0]
2017
2018        str = "A_LoadOneDDataToName(\""+fullName+"\",\"\",0,1)"         //don't plot, force overwrite
2019        Execute str             
2020       
2021        dataName=GetFileNameFromPathNoSemi(fullName)
2022        dataname=CleanupName(dataname,0)
2023       
2024        //graph it - creates window named "AutoGraph"
2025        DoWindow/K tmpGraph
2026        Execute "DoGraph(\""+dataname+"\")"
2027        DoWindow/C tmpGraph
2028//      Wave/Z yw = $("ywave_"+extStr)
2029//      Wave/Z xw = $("xwave_"+extStr)
2030
2031        if(exists("ywave_"+extStr) && exists("xwave_"+extStr))
2032                AppendtoGraph $("ywave_"+extStr) vs $("xwave_"+extStr)
2033        else
2034                DoAlert 0,"Model data with the suffix \""+extStr+"\" does not exist. Either plot the model or enter the correct suffix"
2035        endif
2036
2037//      ControlInfo/W=AutoFitPanel popup0
2038//      if(cmpstr(S_Value[0,4], "Smear" ) == 0 )
2039//              SetDataFolder $dataname
2040//              if(exists("smeared_"+extStr) && exists("smeared_qvals"))
2041//                     
2042//                      AppendtoGraph $("smeared_"+extStr) vs $("smeared_qvals")
2043//              else
2044//                      SetDataFolder root:
2045//                      DoAlert 0,"Smeared Model data with the suffix \""+extStr+"\" does not exist. Either plot the model or enter the correct suffix"
2046//              endif
2047//             
2048//      else
2049//              if(exists("ywave_"+extStr) && exists("xwave_"+extStr))
2050//                      AppendtoGraph $("ywave_"+extStr) vs $("xwave_"+extStr)
2051//              else
2052//                      DoAlert 0,"Model data with the suffix \""+extStr+"\" does not exist. Either plot the model or enter the correct suffix"
2053//              endif
2054//      endif
2055
2056
2057        SetDataFolder root:
2058        return(0)
2059End
2060
2061//loads the selected file in a temporary graph
2062Function LoadForGuessProc(ctrlName) : ButtonControl
2063        String ctrlName
2064       
2065        SVAR ext=root:AutoFit:gExt
2066        fLoadSelected(ext)
2067        return(0)
2068End
2069
2070//makes the holdWave and Constraint wave that are needed to set the values in the list boxes (and the matrix)
2071// these are not generated when plotting a model.
2072Function Make_HoldConstraintEps_Waves()
2073       
2074        SVAR  ext=root:AutoFit:gExt
2075        Variable num=numpnts($("coef_"+ext))
2076        if(WaveExists($("coef_"+ext)) == 0 )
2077                DoAlert 0,"coef_"+ext+" does not exist. You must set the prefix correctly and plot the model first"
2078        else
2079                Make/O/D/N=(num) $("Hold_"+ext)
2080                Make/O/T/N=(num) $("Constr_"+ext)
2081                Make/O/D/N=(num) $("Epsilon_"+ext)=0.0003
2082       
2083                String str=WinList("*", ";","WIN:2"),sel
2084                Prompt sel, "Select Table to Append Waves", popup str
2085                DoPrompt "asdf",sel
2086                if (V_Flag)
2087                        return 0        // user canceled
2088                endif
2089                DoWindow/F $sel
2090                AppendToTable $("Hold_"+ext), $("Constr_"+ext), $("Epsilon_"+ext)
2091        endif
2092End
2093//needs the name (as a string) of the coefficient wave
2094//it assumes "coef_" plus an extension
2095//
2096Function UseCoefAsGuess(ctrlName) : ButtonControl
2097        String ctrlName
2098       
2099        String wStr = "coef_"
2100        SVAR ext=root:AutoFit:gExt
2101        FillCoefGuess(wStr+ext)
2102        DisplayGuess()
2103        return(0)
2104End
2105
2106//needs the name (as a string) of the hold string wave
2107//it assumes "hold_" plus an extension
2108//
2109Function UseHoldAsGuess(ctrlName) : ButtonControl
2110        String ctrlName
2111       
2112//      String wStr = "hold_"
2113//      SVAR ext=root:AutoFit:gExt
2114//      FillHoldGuess(wStr+ext)
2115//      DisplayGuess()
2116        return(0)
2117End
2118
2119//needs the name (as a string) of the coefficient wave
2120//it assumes "constr" plus an extension
2121//
2122Function UseConstraintsAsGuess(ctrlName) : ButtonControl
2123        String ctrlName
2124       
2125//      String wStr = "Constr_"
2126//      SVAR ext=root:AutoFit:gExt
2127//      FillConstrGuess(wStr+ext)
2128//      DisplayGuess()
2129        return(0)
2130End
2131
Note: See TracBrowser for help on using the repository browser.