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

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

Adding to batch fitting. Now automatically saves the fit XY waves and coefficients as separate text files that can be loaded and appended later, or imported into a different program.

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