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

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

Added Auto-Fit (Batch fitting) to the Macros menu as a beta item

Updated broken links in Model_Docs

Added Auto-Fit help to the Analysis Help file as a new package

Updated the current version to 7.20, a new release for the web site

File size: 61.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=(685,44,1001,740) /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={2,2},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={6,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={182,64},size={32,14},proc=CheckAllFiles,title="Select All Files"
336        CheckBox AllFilesCheck,value= 0
337        ListBox guessBox,pos={24,398},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={196,406},size={50,20},disable=1,proc=FillAllGuessButtonProc,title="Fill All"
341        Button FillAllHoldButton,pos={196,406},size={50,20},disable=1,proc=FillAllHoldButtonProc,title="Fill All"
342        Button FillAllConstrButton,pos={196,406},size={50,20},proc=FillAllConstrButtonProc,title="Fill All"
343        Button FillAllRangeB,pos={196,406},size={50,20},disable=1,proc=FillAllRangeButtonProc,title="Fill All"
344        SetVariable NumParams,pos={7,34},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,335},size={32,14},value=0,title="Use Epsilon Wave?"
350
351        TabControl tabC,pos={13,371},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={24,398},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={24,398},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={24,398},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={21,632},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={139,634},size={128,12},anchor=MC,variable=root:AutoFit:gStatus,frame=0
373        Button button0,pos={14,331},size={40,20},title="Plot",proc=LoadForGuessProc
374//      SetVariable extStr,pos={4,170},size={40,15},title=" ",value= root:AutoFit:gExt
375       
376        Button GuessCoefB,pos={198,440},size={50,20},title="Guess",proc=UseCoefAsGuess
377        Button GuessHoldB,pos={198,440},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={180,470},fixedSize=1,size={96,130},variable=root:AutoFit:guessStr
381       
382        ValDisplay progressValdisp,pos={113,663},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={174,30},size={70,20},proc=AF_DoneButtonProc,title="Done"
386        Button AF_HelpButton,pos={260,30},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        return(0)
1037End
1038
1039//// to be able to simply fill in the pt range of the yw[lo,hi]
1040//Function LowRange()
1041//      NVAR val = root:AutoFit:ptLow
1042//      return(val)
1043//End
1044//
1045//Function HighRange()
1046//      NVAR val = root:AutoFit:ptHigh
1047//      return(val)
1048//End
1049
1050//updates the status string, forcing a redraw twice, to overcome what seems to be a bug in Igor4
1051//also updates the progress bar and the countdown
1052Function UpdateStatusString(newStr)
1053        String newStr
1054       
1055        SVAR gStatus=root:AutoFit:gStatus
1056        SVAR gStatFormat=root:AutoFit:gStatFormat
1057        gStatus=""
1058        ControlUpdate/W=AutoFitPanel tb1                //clears the line
1059        gStatus=gStatFormat+newStr
1060        ControlUpdate/W=AutoFitPanel tb1
1061       
1062        //update the progress bar and timer
1063        NVAR cur=root:AutoFit:curProgress
1064        NVAR endProgress=root:AutoFit:endProgress
1065        NVAR startTicks=root:AutoFit:startTicks
1066        cur+=1
1067       
1068//      Print "****"
1069//      Print "cur = ",cur
1070       
1071        Variable t2=ticks,projTot,projRemain
1072        String titleStr=""
1073       
1074        projTot = (t2-startTicks)/(cur-1)*endProgress
1075        projRemain = projTot - (t2-startTicks)
1076        projRemain /= 60.15             //to seconds
1077        DoWindow/F AutoFitPanel
1078        ValDisplay progressValdisp,title=Secs2time(projRemain,5)
1079        ControlUpdate/W=AutoFitPanel progressValdisp
1080       
1081//      Print "End Progress = ",endProgress
1082//      Print "ProjTot = ",projTot/60.15
1083//      Print "ProjRemain = ",projRemain
1084       
1085        return(0)
1086End
1087
1088// returns a string with the name of the epsilon wave, or null if it doesn't exist
1089Function/S GetEpsilonWave()
1090       
1091        String retStr="",testStr
1092        SVAR extStr = root:AutoFit:gExt
1093        //do you want to use epsilon wave?
1094        ControlInfo/W=AutoFitPanel epsilonCheck
1095        if(V_Value == 0)                //not checked
1096                return(retStr)
1097        endif
1098       
1099        testStr = "Epsilon_"+extStr
1100        if(waveexists($testStr) != 0)
1101//              return(" /E="+testStr)
1102                return(testStr)
1103        endif
1104        return(retStr)
1105End
1106
1107//returns the y data to fit - "_i" suffix, and range if selected
1108// enter the range as the first element[0] as low point, second element[1] as high point
1109// leave the other elements blank
1110//
1111// if either point value is not entered, the whole data set is used
1112//
1113// -- if both of the elements are between 0 and 1, assume they are q-values (check for fractional part)
1114// and find the appropriate points...
1115//
1116Function ParseRangeString(set,dataStr,rMat,lo,hi)
1117        Variable set
1118        String dataStr
1119        WAVE/T rMat
1120        Variable &lo,&hi
1121       
1122        Variable useCursors
1123                       
1124        lo = str2num(rMat[0][set])
1125        hi = str2num(rMat[1][set])
1126       
1127        if(lo == 0 && hi == 0)
1128                return(0)
1129        endif
1130       
1131        if(numtype(lo) != 0 || numtype(hi) != 0)                //not a normal number
1132                return(0)               //don't use cursor values, use all of the dataset
1133        endif
1134       
1135       
1136        if(lo>=hi) //error in specification, or all data desired (both zero or undefined)
1137                return(0)               //use all of the dataset
1138        endif
1139       
1140       
1141        if(trunc(lo) != lo || trunc(hi) != hi)          //values have fractional parts
1142                WAVE xW = $("root:"+dataStr+":"+dataStr + "_q")
1143                FindLevel/P/Q xW, lo
1144                lo = trunc(V_levelX)            //find the corresponding point values
1145                FindLevel/P/Q xW, hi
1146                hi = trunc(V_levelX)
1147        endif
1148       
1149        Variable/G root:AutoFit:ptLow = lo
1150        Variable/G root:AutoFit:ptHigh = hi
1151
1152        return(1)
1153End
1154
1155//returns the holdStr, i.e. "1010101"
1156Function/S ParseHoldString(set,npar,hMat)
1157        Variable set,npar
1158        WAVE/T hMat
1159       
1160        Variable ii
1161        String retStr=""
1162       
1163        for(ii=0;ii<npar;ii+=1)
1164                if(strlen(hMat[ii][set]) == 0)
1165                        retStr += "0"
1166                else
1167                        retStr += hMat[ii][set]
1168                endif
1169        endfor
1170
1171//      Print retStr
1172       
1173        return(retStr)
1174End
1175
1176//returns only error - wave must already exist
1177Function ParseGuessString(set,npar,gMat,outWStr)
1178        Variable set,npar
1179        WAVE/T gMat
1180        String outWStr
1181       
1182        Variable ii
1183        String retStr=outWStr
1184       
1185        WAVE outWave=$outWStr
1186        for(ii=0;ii<npar;ii+=1)
1187                outWave[ii] = str2num(gMat[ii][set])
1188        endfor
1189        return(0)
1190End
1191
1192//the constraint wave is created here
1193Function/S ParseConstraints(set,npar,cMat,outWStr)
1194        Variable set,npar
1195        WAVE/T cMat
1196        String outWStr
1197       
1198        String retStr="",loStr="",hiStr=""
1199        Variable ii=0,jj=0     
1200        Make/O/T/N=0 $outWStr
1201        WAVE/T cw = $outWStr   
1202        //return "/C="+outWStr if parsed ok, or null if not
1203
1204        String listStr=""
1205        for(ii=0;ii<npar;ii+=1)
1206                listStr=cMat[ii][set]
1207                loStr=StringFromList(0, listStr ,";")
1208                hiStr=StringFromList(1, listStr ,";")
1209                if(cmpstr(loStr,"")!=0) //something there...
1210                        InsertPoints jj,1,cw            //insert before element jj
1211                        cw[jj] = "K"+num2Str(ii)+">"+loStr
1212                        jj+=1
1213                endif
1214                if(cmpstr(hiStr,"")!=0) //something there...
1215                        InsertPoints jj,1,cw            //insert before element jj
1216                        cw[jj] = "K"+num2Str(ii)+"<"+hiStr
1217                        jj+=1
1218                endif
1219        endfor
1220        if(numpnts(cw) > 0 )
1221                retStr = "/C=" + outWStr
1222        Endif
1223//      print "strlen, conStr= ",strlen(retStr),retstr
1224
1225        return(retStr)  //null string will be returned if no constraints
1226End
1227
1228
1229//*************************
1230Proc DoGraph(dataname)
1231        String dataname
1232       
1233        SetDataFolder $dataname
1234
1235        PauseUpdate; Silent 1           // building window...
1236        Display /W=(5,42,301,313)/K=1 $(dataname+"_i") vs $(dataname+"_q")
1237        DoWindow/C AutoGraph
1238        ModifyGraph mode($(dataname+"_i"))=3
1239        ModifyGraph marker($(dataname+"_i"))=19
1240        ModifyGraph rgb($(dataname+"_i"))=(1,4,52428)
1241        ModifyGraph msize($(dataname+"_i"))=2
1242        ModifyGraph grid=1
1243        ModifyGraph log=1
1244        ModifyGraph tickUnit=1
1245        //
1246        ModifyGraph mirror=2
1247        //
1248        ErrorBars $(dataname+"_i") Y,wave=($(dataname+"_s"),$(dataname+"_s"))
1249//      Legend/A=LB
1250//      Legend/A=LB/X=0.00/Y=-32                //defaults to the top right
1251        Legend/A=MT/E           // /X=-16.16/Y=5.17/E
1252       
1253        SetDataFolder root:
1254       
1255EndMacro
1256
1257Proc DoGraph_NSE(dataname)
1258        String dataname
1259       
1260        SetDataFolder $dataname
1261
1262        PauseUpdate; Silent 1           // building window...
1263        Display /W=(5,42,301,313)/K=1 $(dataname+"_i") vs $(dataname+"_q")
1264        DoWindow/C AutoGraph_NSE
1265        ModifyGraph mode($(dataname+"_i"))=3
1266        ModifyGraph marker($(dataname+"_i"))=19
1267        ModifyGraph rgb($(dataname+"_i"))=(1,4,52428)
1268        ModifyGraph msize($(dataname+"_i"))=3
1269        ModifyGraph zColor($(dataname+"_i"))={$(dataname+"__Q"),$(dataname+"__Q")[0]*0.99,*,Rainbow}
1270        ModifyGraph grid=1
1271        ModifyGraph mirror=2
1272        ModifyGraph log(left)=1
1273        ErrorBars $(dataname+"_i") Y,wave=($(dataname+"_s"),$(dataname+"_s"))
1274        Legend/A=MB
1275        SetAxis/A/E=1 bottom
1276        ModifyGraph standoff=0
1277        SetAxis left 0.1,1
1278        //ModifyGraph tickUnit(left)=1
1279EndMacro
1280
1281//*************************
1282
1283
1284//**************************
1285// Generate the report
1286//**************************
1287
1288////must have AutoGraph as the name of the graph window (any size)
1289//// func is the name of the function (for print only)
1290////par and coef are the exact names of the waves
1291////yesSave==1 will save the file(name=func+time)
1292////
1293////
1294//// general report function from the wrapper is used instead
1295////    W_GenerateReport(funcStr,folderStr,$parStr,cw,yesSave,V_chisq,W_sigma,V_npnts,V_FitError,V_FitQuitReason,V_startRow,V_endRow,topGraph)
1296////
1297//Function AutoFit_GenerateReport(func,dataname,par,myCoef,yesSave)
1298//      String func,dataname,par,myCoef
1299//      Variable yesSave
1300//     
1301//      String str,pictStr="P_"
1302//      Wave sigWave=$"W_sigma"
1303//      Wave ans=$myCoef
1304////    Wave/T param=$par
1305//      SVAR ext=root:AutoFit:gExt
1306//      Wave/T param=$"parameters_"+ext
1307//     
1308//      NVAR V_chisq = V_chisq
1309//      NVAR V_npnts = V_npnts
1310//      NVAR V_FitError = V_FitError
1311//      NVAR V_FitQuitReason = V_FitQuitReason
1312//      NVAR chi1=gChiSq1
1313//      NVAR chi2=gChiSq2
1314//      NVAR V_startRow = V_startRow
1315//      NVAR V_endRow = V_endRow
1316//     
1317//      // bring report up
1318//      DoWindow/F Report
1319//      if (V_flag == 0)                // Report notebook doesn't exist ?
1320//              NewNotebook/W=(10,45,550,620)/F=1/N=Report as "Report"
1321//      endif
1322//     
1323//      // delete old stuff
1324//      Notebook Report selection={startOfFile, endOfFile}, text="\r", selection={startOfFile, startOfFile}
1325//     
1326//      // insert title
1327//      Notebook Report newRuler=Title, justification=1, rulerDefaults={"Times", 16, 1, (0, 0, 0)}
1328//      sprintf str, "Fit to %s, %s, %s\r\r", func,Secs2Date(datetime, 0), time()
1329//      Notebook Report ruler=Title, text=str
1330//     
1331//      // insert fit results
1332//      Variable num=numpnts(ans),ii=0
1333//      Notebook Report ruler=Normal; Notebook Report  margins={18,18,504}, tabs={63 + 3*8192}
1334//      str = "Data file: " + dataname + "\r\r"
1335//      Notebook Report text=str
1336//      do
1337//              sprintf str, "%s = %g±%g\r", param[ii],ans[ii],sigwave[ii]
1338//              Notebook Report text=str
1339//              ii+=1
1340//      while(ii<num)
1341//     
1342//      //
1343//      Wave dataXw = $(dataname+"_q")
1344//      Variable nData=numpnts(dataXw)
1345//     
1346//      //
1347//      sprintf str,"chisq = %g , %g , %g\r",chi1,chi2,V_chisq
1348//      Notebook Report textRGB=(65000,0,0),fstyle=1,text=str
1349//      sprintf str,"Npnts = %g, sqrt(X^2/N) = %g\r",V_npnts,sqrt(V_chisq/V_npnts)
1350//      Notebook Report textRGB=(0,0,0),fstyle=0, text=str
1351//      sprintf str "Fitted range = [%d,%d] = %g < Q < %g\r",V_startRow,V_endRow,dataXw(V_startRow),dataXw(V_endRow)
1352//      Notebook Report textRGB=(0,0,0),fstyle=0, text=str
1353//      sprintf str,"V_FitError = %g\t\tV_FitQuitReason = %g\r",V_FitError,V_FitQuitReason
1354//      Notebook Report textRGB=(65000,0,0),fstyle=1,text=str
1355//      Notebook Report ruler=Normal
1356//     
1357//      // insert graphs
1358//      Notebook Report picture={AutoGraph(0, 0, 400, 300), 0, 1}, text="\r"
1359//     
1360//
1361//      //Notebook Report picture={Table1, 0, 0}, text="\r"
1362//     
1363//      // show the top of the report
1364//      Notebook Report  selection= {startOfFile, startOfFile},  findText={"", 1}
1365//     
1366//      //save the notebook
1367//      if(yesSave)
1368//              String nameStr=CleanupName(func,0)
1369//              nameStr = nameStr[0,8]  //shorten the name
1370//              nameStr += "_"+dataname
1371//              //make sure the name is no more than 31 characters
1372//              namestr = namestr[0,30]         //if shorter than 31, this will NOT pad to 31 characters
1373//              Print "file saved as ",nameStr
1374//              SaveNotebook /O/P=savePath/S=2 Report as nameStr
1375//              //save the graph separately as a PICT file, 2x screen
1376//              pictStr += nameStr
1377//              pictStr = pictStr[0,28]         //need a shorter name - why?
1378//              DoWindow/F AutoGraph
1379//              // E=-5 is png @screen resolution
1380//              // E=2 is PICT @2x screen resolution
1381//              SavePICT /E=2/O/I/P=savePath /W=(0,0,3,3) as pictStr
1382//      Endif
1383//     
1384//      // ???maybe print the notebook too?
1385//End
1386
1387
1388
1389//
1390//Proc DoGenerateReport(fname,dataname,param,coef,yesno)
1391//      String fname,dataname="",param,coef,yesno="No"
1392//      Prompt fname,"function name",popup,FunctionList("!Sme*",";","KIND:15,")
1393//      Prompt dataname,"name of the dataset"
1394//      Prompt param,"parameter names",popup,WaveList("par*",";","")
1395//      Prompt coef,"coefficient wave",popup,WaveList("coe*",";","")
1396//      Prompt yesno,"Save the report?",popup,"Yes;No;"
1397//     
1398//      //Print "fname = ",fname
1399//      //Print "param = ",param
1400//      //Print "coef = ",coef
1401//      //Print "yesno = ",yesno
1402//     
1403//      Variable doSave=0
1404//      if(cmpstr(yesno,"Yes")==0)
1405//              doSave=1
1406//      Endif
1407//      GenerateReport(fname,dataname,param,coef,dosave)
1408//     
1409//End
1410
1411
1412
1413//must have AutoGraph_NSE as the name of the graph window (any size)
1414// func is the name of the function (for print only)
1415//par and coef are the exact names of the waves
1416//yesSave==1 will save the file(name=func+time)
1417//
1418Function GenerateReport_NSE(func,dataname,par,coef,yesSave)
1419        String func,dataname,par,coef
1420        Variable yesSave
1421       
1422        String str
1423        Wave sigWave=$"W_sigma"
1424        Wave ans=$coef
1425        Wave/T param=$par
1426       
1427        NVAR V_chisq = V_chisq
1428        NVAR V_npnts = V_npnts
1429        NVAR V_FitError = V_FitError
1430        NVAR V_FitQuitReason = V_FitQuitReason
1431       
1432        // bring report up
1433        DoWindow/F Report
1434        if (V_flag == 0)                // Report notebook doesn't exist ?
1435                NewNotebook/W=(10,45,550,620)/F=1/N=Report as "Report"
1436        endif
1437       
1438        // delete old stuff
1439        Notebook Report selection={startOfFile, endOfFile}, text="\r", selection={startOfFile, startOfFile}
1440       
1441        // insert title
1442        Notebook Report newRuler=Title, justification=1, rulerDefaults={"Times", 16, 1, (0, 0, 0)}
1443        sprintf str, "Fit to %s, %s, %s\r\r", func,Secs2Date(datetime, 0), time()
1444        Notebook Report ruler=Title, text=str
1445       
1446        // insert fit results
1447        Variable num=numpnts(ans),ii=0
1448        Notebook Report ruler=Normal; Notebook Report  margins={18,18,504}, tabs={63 + 3*8192}
1449        str = "Data file: " + dataname + "\r\r"
1450        Notebook Report text=str
1451        do
1452                sprintf str, "%s = %g±%g\r", param[ii],ans[ii],sigwave[ii]
1453                Notebook Report text=str
1454                ii+=1
1455        while(ii<num)
1456               
1457        sprintf str,"chisq = %g\r",V_chisq
1458        Notebook Report textRGB=(65000,0,0),fstyle=1,text=str
1459        sprintf str,"Npnts = %g\r",V_npnts
1460        Notebook Report textRGB=(0,0,0),fstyle=0, text=str
1461        sprintf str,"V_FitError = %g\rV_FitQuitReason = %g\r",V_FitError,V_FitQuitReason
1462        Notebook Report textRGB=(65000,0,0),fstyle=1,text=str
1463        Notebook Report ruler=Normal
1464       
1465        // insert graphs
1466        Notebook Report picture={AutoGraph_NSE(0, 0, 400, 300), 0, 1}, text="\r"
1467        //Notebook Report picture={Table1, 0, 0}, text="\r"
1468       
1469        // show the top of the report
1470        Notebook Report  selection= {startOfFile, startOfFile},  findText={"", 1}
1471       
1472        //save the notebook
1473        if(yesSave)
1474                String nameStr=CleanupName(func,0)
1475                nameStr = nameStr[0,8]  //shorten the name
1476                nameStr += "_"+dataname
1477                //make sure the name is no more than 31 characters
1478                namestr = namestr[0,30]         //if shorter than 31, this will NOT pad to 31 characters
1479                Print "file saved as ",nameStr
1480//              SaveNotebook /O/P=savePath/S=2 Report as nameStr
1481                SaveNotebook /O/P=home/S=2 Report as nameStr
1482        Endif
1483
1484        //save a pict file, just of the graph
1485        namestr = "PNG_" + namestr
1486        namestr = namestr[0,28]         //PICT names in IGOR must be shorter, to allow auto-naming?
1487        DoWindow/F AutoGraph_NSE
1488//      SavePICT /E=2/O/I/P=savePath /W=(0,0,3,3) as nameStr
1489        SavePICT /E=2/O/I/P=home /W=(0,0,3,3) as nameStr
1490End
1491
1492
1493//*********************
1494//
1495//*********************
1496// List utilities
1497//*********************
1498//
1499// List2TextWave is also in SANS_Utilities.ipf, but to keep from having big lists of dependencies,
1500// have definitions here that are local and Static
1501
1502//
1503Static Function List2TextWave(list,sep,waveStr)
1504        String list,sep,waveStr
1505       
1506        Variable n= ItemsInList(list,sep)
1507        Make/O/T/N=(n) $waveStr= StringFromList(p,list,sep)
1508End
1509
1510Function List2NumWave(list,sep,waveStr)
1511        String list,sep,waveStr
1512       
1513        Variable n= ItemsInList(list,sep)
1514        Make/O/D/N=(n) $waveStr= str2num( StringFromList(p,list,sep) )
1515End
1516
1517Function/S TextWave2List(w,sep)
1518        Wave/T w
1519        String sep
1520       
1521        String newList=""
1522        Variable n=numpnts(w),ii=0
1523        do
1524                newList += w[ii] + sep
1525                ii+=1
1526        while(ii<n)
1527        return(newList)
1528End
1529
1530//for single precision numerical waves
1531Function/S NumWave2List(w,sep)
1532        Wave w
1533        String sep
1534       
1535        String newList="",temp=""
1536        Variable n=numpnts(w),ii=0,val
1537        do
1538                val=w[ii]
1539                temp=""
1540                sprintf temp,"%g",val
1541                newList += temp
1542                newList += sep
1543                ii+=1
1544        while(ii<n)
1545        return(newList)
1546End
1547
1548Function DoKillList(list)
1549        String list
1550       
1551        String item=""
1552        do
1553                item = StringFromList(0, list ,";" )
1554                KillWaves/Z $item
1555                list = RemoveFromList(item, list, ";")
1556        while(ItemsInList(list, ";")>0)
1557End
1558
1559//*********************
1560
1561
1562
1563//*******************
1564//Notebook Utils
1565//*******************
1566
1567Proc PrintOpenNotebooks()
1568
1569        String list=WinList("*", ";", "WIN:16")
1570        String item = ""
1571        do
1572                item=StringFromList(0,list,";")
1573                Print item
1574                PrintNotebook $item
1575                list = RemoveFromList(item, list, ";")
1576        while(ItemsInList(list, ";")>0)
1577End
1578
1579Proc CloseOpenNotebooks()
1580
1581        String list=WinList("*", ";", "WIN:16")
1582        String item = ""
1583        do
1584                item=StringFromList(0,list,";")
1585                DoWindow/K $item
1586                list = RemoveFromList(item, list, ";")
1587        while(ItemsInList(list, ";")>0)
1588End
1589
1590Proc Generate_PNG_list()
1591        fGenerate_PNG_list()
1592End
1593
1594//spits up a list of PNGS
1595Function fGenerate_PNG_list()
1596
1597//      String List=IndexedFile(savePath, -1, ".png")
1598        String List=IndexedFile(home, -1, ".png")
1599        List2TextWave(List,";","PNG_files")
1600        WAVE/T PNGs=$"PNG_files"
1601        Edit/K=1 PNGs
1602End
1603
1604Proc Layout_PNGS(pStr)
1605        String pStr=""
1606        Prompt pStr,"wave of PNGs to use",popup,WaveList("PNG*", ";", "")
1607               
1608        String List=TextWave2List($pStr,";")
1609        String item = ""
1610        //kill old picts from memory
1611        KillPicts/A/Z
1612        //make a new layout
1613        Layout/C=1 as "PNG_Layout"
1614        DoWindow/C PNGLayout
1615        do
1616                item=StringFromList(0,List,";")
1617                //load each PNG, and append it to the layout
1618                Print "load item = ",item
1619//              LoadPICT /O/Q/P=savePath item
1620                LoadPICT /O/Q/P=home item
1621                DoWindow/F PNGLayout            //be sure layout is on top
1622                AppendLayoutObject /F=1/W=PNGLayout picture  $CleanupName(item,0)
1623                //AppendToLayout $item
1624                //Print item
1625                List = RemoveFromList(item, List, ";")
1626        while(ItemsInList(List, ";")>0)
1627        //tile the PNGs in the layout
1628        Tile/O=8
1629End
1630
1631//spit up a list of everything in the folder that is a text file
1632Proc Generate_Data_Checklist()
1633        fGenerate_Data_list()
1634End
1635Function fGenerate_Data_list()
1636
1637        String List=IndexedFile(dataPath, -1, "TEXT")
1638        List2TextWave(List,";","data_files")
1639        WAVE/T files=$"data_files"
1640        Duplicate/O/T files ModelToUse,Done
1641        ModelToUse = ""
1642        Done = ""
1643        Edit/K=1 files,ModelToUse,Done
1644End
1645
1646//***************
1647
1648// with all of the notebooks open for a given model (with N parameters)
1649// this will comile the reports, save the text notebook, then load it back in
1650// and put it in a table for easy printing
1651//
1652Proc CompileAndLoadReports()
1653        Compile_Reports()
1654//      SaveNotebook /O/P=savePath/S=2 Compilation
1655        SaveNotebook /O/P=home/S=2 Compilation
1656//      Print "Saved as:  ",S_Path
1657        DoWindow/K Compilation
1658        LoadCompiledReports(S_Path)
1659End
1660
1661Proc LoadCompiledReports(str)
1662        String str
1663        LoadWave/J/D/W/E=1/K=0/V={"\t"," $",0,0} str
1664End
1665
1666Proc Compile_Reports(Number_of_Parameters,tagStr)
1667        Variable Number_of_Parameters=(root:AutoFit:numPar)
1668        String tagStr="v1"
1669
1670        fCompile_ReportsTable(Number_of_Parameters,tagStr)
1671
1672        fCompile_Reports(Number_of_Parameters)
1673       
1674        DoWindow/F AutoFitResults
1675
1676End
1677
1678Proc Compile_GlobalFit_Reports(WhichParameter,FileStr,ParamStr,ParamErrStr)
1679        Variable WhichParameter=7
1680        String FileStr="FileName_",ParamStr="par_",ParamErrStr="parErr_"
1681        fCompile_GlobalFit_Reports(WhichParameter,FileStr,ParamStr,ParamErrStr)
1682End
1683
1684////
1685Function fCompile_Reports(nPar)
1686        Variable nPar
1687       
1688        String list=WinList("*", ";", "WIN:16")
1689        String item = "",textStr="",newStr=""
1690        Variable sstop,dum,chi
1691       
1692        Variable ii
1693        NewNotebook/F=0 /N=Compilation as "Compilation"
1694        Notebook Compilation text="Variable Name \tValues\tErrors\r"
1695        do
1696                item=StringFromList(0,list,";")
1697                DoWindow/F $item
1698               
1699                Notebook $item selection={(2,0), (3,0)}         //paragraph 3 (starts from 0) = filename
1700                GetSelection notebook,$item,2
1701                textStr=S_Selection
1702                textStr=textStr[0,strlen(textStr)-2]            //remove CR
1703                textStr=textStr[10,strlen(textStr)-1]           //remove "DATA FILE:
1704                Notebook Compilation text="File:\t"+textStr+"\t"
1705                Notebook Compilation text=textStr+"_err\r"
1706               
1707//              printf "%s %s\r",textStr,textStr+"_err"
1708//
1709// results are written as:  "%s = \t%g\t±\t%g\r"
1710//
1711                for(ii=0;ii<nPar;ii+=1)         //gather the parameters
1712               
1713                        Notebook $item selection={(ii+4,0), (ii+5,0)}           //paragraph 5           = parameter 0
1714                        GetSelection notebook,$item,2
1715                        textStr=S_Selection
1716                        textStr=textStr[0,strlen(textStr)-2]
1717                        //textStr=textStr[13,strlen(textStr)-1]         // remove "parameter"
1718                        textStr = ReplaceString("=",textStr,"")
1719                        textStr = ReplaceString("±\t",textStr,"")
1720                        Notebook Compilation text=textStr+"\r"
1721                        //printf "%s\r",textStr
1722                        //Print strlen(textStr)
1723                endfor
1724                //get the chi-squared/N value
1725                ii+=1
1726                Notebook $item selection={(ii+4,0), (ii+5,0)}           //
1727                GetSelection notebook,$item,2
1728                textStr=S_Selection
1729               
1730//              Print textStr
1731               
1732                sscanf textStr,"Npnts = %g\t\tSqrt(X^2/N) = %g\r",dum,chi
1733                sprintf textStr,"Sqrt(X^2/N)\t%s\t\r",num2str(chi)
1734                Notebook Compilation text=textStr
1735               
1736                Notebook Compilation text="\r"          //separate items
1737               
1738                list = RemoveFromList(item, list, ";")
1739        while(ItemsInList(list, ";")>0)
1740       
1741        DoWindow/F Compilation
1742        Notebook Compilation selection={startOfFile,startOfFile}
1743End
1744
1745////
1746// compiles the results into a table.
1747// add tagStr to the end to (try) to make sure that the compilations are unique
1748Function fCompile_ReportsTable(nPar,tagStr)
1749        Variable nPar
1750        String tagStr
1751       
1752        String list=WinList("*", ";", "WIN:16")
1753        String item = "",textStr="",newStr="",str
1754        Variable sstop,dum,chi
1755       
1756        Variable ii,numRep,jj,val1,val2,pt
1757        numRep=ItemsInList(list,";")
1758       
1759        Make/O/T/N=(numRep) $("fittedFiles"+"_"+tagStr)
1760        Make/O/D/N=(numRep) $("chiSQ"+"_"+tagStr)
1761        Wave/T fittedFiles = $("fittedFiles"+"_"+tagStr)
1762        Wave chiSq = $("chiSQ"+"_"+tagStr)
1763        Edit/N=AutoFitResults fittedFiles,chiSQ
1764       
1765        for(ii=0;ii<nPar;ii+=1)         //waves for the parameters
1766                Make/O/D/N=(numRep) $("par"+num2str(ii)+"_"+tagStr),$("par"+num2str(ii)+"_err"+"_"+tagStr)
1767                AppendToTable $("par"+num2str(ii)+"_"+tagStr),$("par"+num2str(ii)+"_err"+"_"+tagStr)
1768        endfor
1769       
1770        for(jj=0;jj<numRep;jj+=1)
1771
1772                item=StringFromList(jj,list,";")
1773                DoWindow/F $item
1774                Notebook $item selection={(2,0), (3,0)}         //paragraph 3 (starts from 0) = filename
1775                GetSelection notebook,$item,2
1776                textStr=S_Selection
1777                textStr=textStr[0,strlen(textStr)-2]            //remove CR
1778                textStr=textStr[10,strlen(textStr)-1]           //remove "DATA FILE:
1779               
1780                fittedFiles[jj] = textStr
1781//
1782// results are written as:  "%s = \t%g\t±\t%g\r"
1783//
1784                for(ii=0;ii<nPar;ii+=1)         //gather the parameters
1785                        Notebook $item selection={(ii+4,0), (ii+5,0)}           //paragraph 5           = parameter 0
1786                        GetSelection notebook,$item,2
1787                        textStr=S_Selection
1788                        textStr=textStr[0,strlen(textStr)-2]
1789                        // find the "="
1790                        pt = strsearch(textStr,"=",0,0)
1791                        textStr = textStr[pt,strlen(textStr)-1]
1792                        sscanf textStr,"= \t%g\t ± \t%g\r",val1,val2
1793                       
1794//                      Print textStr
1795                                               
1796                        Wave w1 = $("par"+num2str(ii)+"_"+tagStr)
1797                        Wave w2 = $("par"+num2str(ii)+"_err"+"_"+tagStr)
1798                       
1799                        w1[jj] = val1
1800                        w2[jj] = val2
1801                       
1802                        //textStr = ReplaceString("=",textStr,"")
1803                        //textStr = ReplaceString("±\t",textStr,"")
1804                        //Notebook Compilation text=textStr+"\r"
1805                        //printf "%s\r",textStr
1806                        //Print strlen(textStr)
1807                endfor
1808                //get the chi-squared/N value
1809                ii += 1
1810                Notebook $item selection={(ii+4,0), (ii+5,0)}           //
1811                GetSelection notebook,$item,2
1812                textStr=S_Selection
1813               
1814//              Print textStr
1815               
1816                sscanf textStr,"Npnts = %g\t\tSqrt(X^2/N) = %g\r",dum,chi
1817               
1818                chiSQ[jj] = chi
1819        endfor
1820       
1821       
1822        return(0)
1823End
1824
1825
1826////
1827Function fCompile_GlobalFit_Reports(nPar,Files,Param,Param_err)
1828        Variable nPar
1829        String Files,Param,Param_Err
1830       
1831        String list=SortList(WinList("*", ";", "WIN:16"))
1832        String item = "",textStr="",fileStr,funcStr,dumStr
1833        Variable sstop,dum,chi,nFiles,val1,val2
1834       
1835        Variable ii,jj
1836
1837        nFiles = ItemsInList(list)
1838        Make/O/D/N=(nFiles) $Param,$Param_err
1839        Make/O/T/N=(nFiles) $Files
1840        WAVE pw = $Param
1841        WAVE pw_err = $Param_err
1842        WAVE/T fw = $Files
1843       
1844        for(jj=0;jj<nFiles;jj+=1)
1845       
1846                item=StringFromList(jj,list,";")
1847                DoWindow/F $item
1848               
1849                Notebook $item selection={(6,0), (7,0)}         //paragraph 7 (starts from 0) = filename
1850                GetSelection notebook,$item,2
1851                textStr=S_Selection
1852                sscanf textStr,"Data Set:%s ; Function:%s\r",fileStr,funcStr
1853                fw[jj] = fileStr
1854//              Notebook Compilation text=fileStr+"\r"
1855//              Notebook Compilation text=funcStr+"\r"
1856               
1857               
1858//              printf "%s %s\r",textStr,textStr+"_err"
1859
1860                for(ii=nPar;ii<=nPar;ii+=1)             //gather the parameters
1861               
1862                        Notebook $item selection={(ii+7,0), (ii+8,0)}           //paragraph 8           = parameter 0
1863                        GetSelection notebook,$item,2
1864                        textStr=S_Selection
1865//                      Print textStr
1866                        sscanf textStr,"%s %g +- %g\r",dumStr,val1,val2
1867                        pw[jj] = val1
1868                        pw_err[jj] = val2
1869                endfor
1870               
1871        endfor
1872
1873End
1874
1875
1876
1877//DOES NOT graph the data, does not create a weighting wave
1878//NSE data assumed to be 4-column
1879//q (all the same) - t(ns) - I(q,t) - dI(q,t)
1880Static Function LoadNSEDataWithName(fileStr)
1881        String fileStr
1882        //Load the waves, using default waveX names
1883        //if no path or file is specified for LoadWave, the default Mac open dialog will appear
1884        LoadWave/G/D/A/Q fileStr
1885        String fileName = S_fileName
1886       
1887       
1888        String w0,w1,w2,n0,n1,n2,wt,w3,n3
1889        Variable rr,gg,bb
1890       
1891        // put the names of the four loaded waves into local names
1892        n0 = StringFromList(0, S_waveNames ,";" )
1893        n1 = StringFromList(1, S_waveNames ,";" )
1894        n2 = StringFromList(2, S_waveNames ,";" )
1895        n3 = StringFromList(3, S_waveNames ,";" )
1896       
1897       
1898        //remove the semicolon AND period from files from the VAX
1899        w0 = CleanupName((S_fileName+"__Q"),0)
1900        w1 = CleanupName((S_fileName+"__X"),0)
1901        w2 = CleanupName((S_fileName+"__Y"),0)
1902        w3 = CleanupName((S_fileName+"__S"),0)
1903       
1904        if(exists(w0) !=0)
1905                //waves already exist
1906                KillWaves $n0,$n1,$n2,$n3               // kill the default waveX that were loaded
1907                return(0)
1908        endif
1909       
1910        // Rename to give nice names
1911        Rename $n0, $w0
1912        Rename $n1, $w1
1913        Rename $n2, $w2
1914        Rename $n3, $w3
1915
1916End
1917
1918/////
1919//wStr is the coef_ wave with the initial guess
1920Function FillCoefGuess(wStr)
1921        String wStr
1922       
1923        Wave w=$wStr
1924        if (! WaveExists(w) )
1925                DoAlert 0, "The coefficient wave "+wStr+" does not exist. Either create the wave or enter the correct suffix"
1926                return(0)
1927        endif
1928        Wave/T guess=root:AutoFit:guessMatrix
1929        Variable ii=0,num=numpnts(w)
1930        Variable tmp
1931       
1932        Variable selRow,matrixRow
1933        selRow = FindSelectedRowInLB(0) // send 0 to look at the column with filenames
1934
1935        do
1936                tmp=w[ii]
1937                guess[ii][selRow] = num2str(tmp)
1938                ii+=1
1939        while(ii<num)
1940End
1941
1942/////
1943//wStr is the hold_ wave with the initial guess
1944Function FillHoldGuess(wStr)
1945        String wStr
1946       
1947        Wave w=$wStr
1948        if (! WaveExists(w) )
1949                DoAlert 0, "The hold wave "+wStr+" does not exist. Either create the wave or enter the correct suffix"
1950                return(0)
1951        endif
1952        Wave/T hold=root:AutoFit:holdMatrix
1953        Variable ii=0,num=numpnts(w)
1954        Variable tmp
1955       
1956        Variable selRow,matrixRow
1957        selRow = FindSelectedRowInLB(0) // send 0 to look at the column with filenames
1958       
1959        do
1960                tmp=w[ii]
1961                hold[ii][selRow] = num2str(tmp)
1962                ii+=1
1963        while(ii<num)
1964End
1965
1966/////
1967//wStr is the Constr_ wave with the initial guess
1968// --- this is a Text wave
1969Function FillConstrGuess(wStr)
1970        String wStr
1971       
1972        Wave/T w=$wStr
1973        if (! WaveExists(w) )
1974                DoAlert 0, "The Constraint wave "+wStr+" does not exist. Either create the (TEXT) wave or enter the correct suffix"
1975                return(0)
1976        endif
1977        Wave/T constr=root:AutoFit:constrMatrix
1978        Variable ii=0,num=numpnts(w)
1979        String tmp
1980       
1981        Variable selRow,matrixRow
1982        selRow = FindSelectedRowInLB(0) // send 0 to look at the column with filenames
1983
1984        do
1985                tmp=w[ii]
1986                constr[ii][selRow] = tmp
1987                ii+=1
1988        while(ii<num)
1989End
1990
1991////
1992//need the extension of the model wave to append
1993//
1994// it will plot the UN-smeared model for generating the initial guesses
1995// -- fitting will use Smeared or unsmeared, depending on the popup selection
1996//
1997//
1998Function fLoadSelected(extStr)
1999        string extStr
2000
2001        Variable datafile,ii
2002        String fullName,dataName,str
2003       
2004        WAVE/T fileWave=root:AutoFit:fileListWave
2005        Wave sel = root:AutoFit:fileSelWave
2006        ii=0
2007        do
2008                if((sel[ii][0] & 0x01) == 1)    // the file is selected in the list box
2009                        datafile = ii
2010                        break
2011                endif
2012                ii+=1
2013        while(ii<numpnts(sel))
2014       
2015        //load in the data
2016        PathInfo dataPath
2017        fullName = S_path
2018        fullName += fileWave[datafile][0]
2019
2020        str = "A_LoadOneDDataToName(\""+fullName+"\",\"\",0,1)"         //don't plot, force overwrite
2021        Execute str             
2022       
2023        dataName=GetFileNameFromPathNoSemi(fullName)
2024        dataname=CleanupName(dataname,0)
2025       
2026        //graph it - creates window named "AutoGraph"
2027        DoWindow/K tmpGraph
2028        Execute "DoGraph(\""+dataname+"\")"
2029        DoWindow/C tmpGraph
2030//      Wave/Z yw = $("ywave_"+extStr)
2031//      Wave/Z xw = $("xwave_"+extStr)
2032
2033        if(exists("ywave_"+extStr) && exists("xwave_"+extStr))
2034                AppendtoGraph $("ywave_"+extStr) vs $("xwave_"+extStr)
2035        else
2036                DoAlert 0,"Model data with the suffix \""+extStr+"\" does not exist. Either plot the model or enter the correct suffix"
2037        endif
2038
2039//      ControlInfo/W=AutoFitPanel popup0
2040//      if(cmpstr(S_Value[0,4], "Smear" ) == 0 )
2041//              SetDataFolder $dataname
2042//              if(exists("smeared_"+extStr) && exists("smeared_qvals"))
2043//                     
2044//                      AppendtoGraph $("smeared_"+extStr) vs $("smeared_qvals")
2045//              else
2046//                      SetDataFolder root:
2047//                      DoAlert 0,"Smeared Model data with the suffix \""+extStr+"\" does not exist. Either plot the model or enter the correct suffix"
2048//              endif
2049//             
2050//      else
2051//              if(exists("ywave_"+extStr) && exists("xwave_"+extStr))
2052//                      AppendtoGraph $("ywave_"+extStr) vs $("xwave_"+extStr)
2053//              else
2054//                      DoAlert 0,"Model data with the suffix \""+extStr+"\" does not exist. Either plot the model or enter the correct suffix"
2055//              endif
2056//      endif
2057
2058
2059        SetDataFolder root:
2060        return(0)
2061End
2062
2063//loads the selected file in a temporary graph
2064Function LoadForGuessProc(ctrlName) : ButtonControl
2065        String ctrlName
2066       
2067        SVAR ext=root:AutoFit:gExt
2068        fLoadSelected(ext)
2069        return(0)
2070End
2071
2072//makes the holdWave and Constraint wave that are needed to set the values in the list boxes (and the matrix)
2073// these are not generated when plotting a model.
2074Function Make_HoldConstraintEps_Waves()
2075       
2076        SVAR  ext=root:AutoFit:gExt
2077        Variable num=numpnts($("coef_"+ext))
2078        if(WaveExists($("coef_"+ext)) == 0 )
2079                DoAlert 0,"coef_"+ext+" does not exist. You must set the prefix correctly and plot the model first"
2080        else
2081                Make/O/D/N=(num) $("Hold_"+ext)
2082                Make/O/T/N=(num) $("Constr_"+ext)
2083                Make/O/D/N=(num) $("Epsilon_"+ext)=0.0003
2084       
2085                String str=WinList("*", ";","WIN:2"),sel
2086                Prompt sel, "Select Table to Append Waves", popup str
2087                DoPrompt "asdf",sel
2088                if (V_Flag)
2089                        return 0        // user canceled
2090                endif
2091                DoWindow/F $sel
2092                AppendToTable $("Hold_"+ext), $("Constr_"+ext), $("Epsilon_"+ext)
2093        endif
2094End
2095//needs the name (as a string) of the coefficient wave
2096//it assumes "coef_" plus an extension
2097//
2098Function UseCoefAsGuess(ctrlName) : ButtonControl
2099        String ctrlName
2100       
2101        String wStr = "coef_"
2102        SVAR ext=root:AutoFit:gExt
2103        FillCoefGuess(wStr+ext)
2104        DisplayGuess()
2105        return(0)
2106End
2107
2108//needs the name (as a string) of the hold string wave
2109//it assumes "hold_" plus an extension
2110//
2111Function UseHoldAsGuess(ctrlName) : ButtonControl
2112        String ctrlName
2113       
2114        String wStr = "hold_"
2115        SVAR ext=root:AutoFit:gExt
2116        FillHoldGuess(wStr+ext)
2117        DisplayGuess()
2118        return(0)
2119End
2120
2121//needs the name (as a string) of the coefficient wave
2122//it assumes "constr" plus an extension
2123//
2124Function UseConstraintsAsGuess(ctrlName) : ButtonControl
2125        String ctrlName
2126       
2127//      String wStr = "Constr_"
2128//      SVAR ext=root:AutoFit:gExt
2129//      FillConstrGuess(wStr+ext)
2130//      DisplayGuess()
2131        return(0)
2132End
2133
Note: See TracBrowser for help on using the repository browser.