Changeset 1340 for trunk/GSASIIgrid.py


Ignore:
Timestamp:
May 10, 2014 8:12:27 PM (8 years ago)
Author:
toby
Message:

complete parametric fitting and tutorial

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIgrid.py

    r1335 r1340  
    25292529        self.SequentialMenu.Append(menu=self.SequentialPfit, title='Parametric Fit')
    25302530        self.SequentialPfit.Append(
    2531             id=wxADDPARFIT, kind=wx.ITEM_NORMAL,text='Add function',
    2532             help='Add a new function to minimize')
     2531            id=wxADDPARFIT, kind=wx.ITEM_NORMAL,text='Add equation',
     2532            help='Add a new equation to minimize')
    25332533        self.SequentialPfit.Append(
    2534             id=wxDELPARFIT, kind=wx.ITEM_NORMAL,text='Delete function',
    2535             help='Delete a function for parametric minimization')
     2534            id=wxDELPARFIT, kind=wx.ITEM_NORMAL,text='Delete equation',
     2535            help='Delete an equation for parametric minimization')
    25362536        self.SequentialPfit.Append(
    2537             id=wxEDITPARFIT, kind=wx.ITEM_NORMAL,text='Edit function',
    2538             help='Edit an existing parametric minimization function')
     2537            id=wxEDITPARFIT, kind=wx.ITEM_NORMAL,text='Edit equation',
     2538            help='Edit an existing parametric minimization equation')
    25392539        self.SequentialPfit.Append(
    2540             id=wxDOPARFIT, kind=wx.ITEM_NORMAL,text='Fit to function(s)',
     2540            id=wxDOPARFIT, kind=wx.ITEM_NORMAL,text='Fit to equation(s)',
    25412541            help='Perform a parametric minimization')
    25422542        self.PostfillDataMenu()
     
    38683868            UpdateSeqResults(G2frame,data,G2frame.dataDisplay.GetSize()) # redisplay variables
    38693869
     3870    # PATCH: this routine can go away eventually
    38703871    def CreatePSvarDict(seqnum,name):
    38713872        '''Create a parameter dict (parmDict) for everything that might be used
     
    40174018        G2frame.dataFrame.SequentialPfit.Enable(wxDOPARFIT,val)
    40184019
    4019     def DelParFitEq(event):
    4020         'Ask the user to select function to delete'
    4021         choices = Controls['SeqParFitEqs'].keys()
    4022         selected = ItemSelector(
    4023             choices,G2frame.dataFrame,
    4024             multiple=True,
    4025             title='Select functions to remove',
    4026             header='Delete function')
    4027         if selected is None: return
    4028         for item in selected:
    4029             del Controls['SeqParFitEqs'][choices[item]]
    4030         EnableParFitEqMenus()
    4031         if Controls['SeqParFitEqs']: DoParEqFit(event)
    4032        
    4033     def EditParFitEq(event):
    4034         'Edit an existing parametric equation'
    4035         choices = Controls['SeqParFitEqs'].keys()
    4036         if len(choices) == 1:
    4037             selected = 0
    4038         else:
    4039             selected = ItemSelector(
    4040                 choices,G2frame.dataFrame,
    4041                 multiple=False,
    4042                 title='Select a function to edit',
    4043                 header='Edit function')
    4044         if selected is not None:
    4045             dlg = G2exG.ExpressionDialog(
    4046                 G2frame.dataDisplay,indepVarDict,
    4047                 Controls['SeqParFitEqs'][choices[selected]],
    4048                 depVarDict=depVarDict,
    4049                 header="Edit this minimization function's formula")
    4050             newobj = dlg.Show(True)
    4051             if newobj:
    4052                 calcobj = G2obj.ExpressionCalcObj(newobj)
    4053                 del Controls['SeqParFitEqs'][choices[selected]]
    4054                 Controls['SeqParFitEqs'][calcobj.eObj.expression] = newobj
    4055             EnableParFitEqMenus()
    4056         if Controls['SeqParFitEqs']: DoParEqFit(event)
    4057 
    4058     def AddNewParFitEq(event):
    4059         'Create a new parametric equation to be fit to sequential results'
    4060         dlg = G2exG.ExpressionDialog(
    4061             G2frame.dataDisplay,indepVarDict,
    4062             depVarDict=depVarDict,
    4063             header='Enter a function to minimize in the parametric fit')
    4064         obj = dlg.Show(True)
    4065         dlg.Destroy()
    4066         if obj:
    4067             calcobj = G2obj.ExpressionCalcObj(obj)
    4068             Controls['SeqParFitEqs'][calcobj.eObj.expression] = obj
    4069             EnableParFitEqMenus()
    4070         if Controls['SeqParFitEqs']: DoParEqFit(event)
    4071            
    40724020    def ParEqEval(Values,calcObjList,varyList):
    40734021        '''Evaluate the parametric expression(s)
     
    40834031        return result
    40844032
    4085     def DoParEqFit(event):
     4033    def DoParEqFit(event,eqObj=None):
    40864034        'Parametric fit minimizer'
    40874035        varyValueDict = {} # dict of variables and their initial values
    40884036        calcObjList = [] # expression objects, ready to go for each data point
    4089         for expr in Controls['SeqParFitEqs']:
    4090             obj = Controls['SeqParFitEqs'][expr]
     4037        if eqObj is not None:
     4038            eqObjDict = {eqObj.expression:eqObj}
     4039        else:
     4040            eqObjDict = Controls['SeqParFitEqs']
     4041        for expr in eqObjDict.keys():
     4042            obj = eqObjDict[expr]
    40914043            # assemble refined vars for this equation
    40924044            varyValueDict.update({var:val for var,val in obj.GetVariedVarVal()})
     
    41124064        # varied parameters
    41134065        varyList = varyValueDict.keys()
    4114         varyValues = [varyValueDict[key] for key in varyList]
    4115         result = so.leastsq(ParEqEval,varyValues,full_output=True,   #ftol=Ftol,
    4116                             args=(calcObjList,varyList)
    4117                             )
     4066        values = varyValues = [varyValueDict[key] for key in varyList]
     4067        if not varyList:
     4068            print 'no variables to refine!'
     4069        else:
     4070            try:
     4071                print 'Fit Results'
     4072                result = so.leastsq(ParEqEval,varyValues,full_output=True,   #ftol=Ftol,
     4073                                    args=(calcObjList,varyList)
     4074                                    )
     4075                values = result[0]
     4076                covar = result[1]
     4077                if covar is None:
     4078                    raise Exception
     4079                for i,(var,val) in enumerate(zip(varyList,values)):
     4080                    print '  ',var,' =',G2mth.ValEsd(val,np.sqrt(covar[i,i]))
     4081            except:
     4082                print 'Fit failed'
     4083                return
    41184084        # create a plot for each parametric variable
    4119         values = result[0]
    4120         covar = result[1]
    4121         print 'Fit Results'
    4122         for i,(var,val) in enumerate(zip(varyList,values)):
    4123             print '  ',var,' =',G2mth.ValEsd(val,np.sqrt(covar[i,i]))
    4124         for fitnum,expr in enumerate(Controls['SeqParFitEqs']):
    4125             obj = Controls['SeqParFitEqs'][expr]
     4085        for fitnum,expr in enumerate(sorted(eqObjDict)):
     4086            obj = eqObjDict[expr]
    41264087            obj.UpdateVariedVars(varyList,values)
    41274088            calcobj = G2obj.ExpressionCalcObj(obj)
     
    41374098                    )
    41384099                fitvals.append(calcobj.EvalExpression())
    4139             G2plt.PlotSelectedSequence(G2frame,[indx],GetColumnInfo,SelectXaxis,
    4140                                            fitnum,fitvals)
    4141                                
     4100            G2plt.PlotSelectedSequence(
     4101                G2frame,[indx],GetColumnInfo,SelectXaxis,
     4102                fitnum,fitvals)
     4103
     4104    def SingleParEqFit(eqObj):
     4105        DoParEqFit(None,eqObj)
     4106
     4107    def DelParFitEq(event):
     4108        'Ask the user to select function to delete'
     4109        choices = sorted(Controls['SeqParFitEqs'].keys())
     4110        txtlst = [Controls['SeqParFitEqs'][i].GetDepVar()+' = '+i for i in choices]
     4111        selected = ItemSelector(
     4112            txtlst,G2frame.dataFrame,
     4113            multiple=True,
     4114            title='Select a parametric equation to remove',
     4115            header='Delete equation')
     4116        if selected is None: return
     4117        for item in selected:
     4118            del Controls['SeqParFitEqs'][choices[item]]
     4119        EnableParFitEqMenus()
     4120        if Controls['SeqParFitEqs']: DoParEqFit(event)
     4121       
     4122    def EditParFitEq(event):
     4123        'Edit an existing parametric equation'
     4124        choices = sorted(Controls['SeqParFitEqs'].keys())
     4125        txtlst = [Controls['SeqParFitEqs'][i].GetDepVar()+' = '+i for i in choices]
     4126        if len(choices) == 1:
     4127            selected = 0
     4128        else:
     4129            selected = ItemSelector(
     4130                txtlst,G2frame.dataFrame,
     4131                multiple=False,
     4132                title='Select a parametric equation to edit',
     4133                header='Edit equation')
     4134        if selected is not None:
     4135            dlg = G2exG.ExpressionDialog(
     4136                G2frame.dataDisplay,indepVarDict,
     4137                Controls['SeqParFitEqs'][choices[selected]],
     4138                depVarDict=depVarDict,
     4139                header="Edit the formula for this minimization function",
     4140                ExtraButton=['Fit',SingleParEqFit])
     4141            newobj = dlg.Show(True)
     4142            if newobj:
     4143                calcobj = G2obj.ExpressionCalcObj(newobj)
     4144                del Controls['SeqParFitEqs'][choices[selected]]
     4145                Controls['SeqParFitEqs'][calcobj.eObj.expression] = newobj
     4146                EnableParFitEqMenus()
     4147                if Controls['SeqParFitEqs']: DoParEqFit(event)
     4148
     4149    def AddNewParFitEq(event):
     4150        'Create a new parametric equation to be fit to sequential results'
     4151
     4152        # compile the variable names in previous freevars to avoid accidental name collisions
     4153        usedvarlist = []
     4154        for eq,obj in Controls['SeqParFitEqs'].items():
     4155            for var in obj.freeVars:
     4156                if obj.freeVars[var][0] not in usedvarlist: usedvarlist.append(obj.freeVars[var][0])
     4157
     4158        dlg = G2exG.ExpressionDialog(
     4159            G2frame.dataDisplay,indepVarDict,
     4160            depVarDict=depVarDict,
     4161            header='Define an equation to minimize in the parametric fit',
     4162            ExtraButton=['Fit',SingleParEqFit],
     4163            usedVars=usedvarlist)
     4164        obj = dlg.Show(True)
     4165        dlg.Destroy()
     4166        if obj:
     4167            calcobj = G2obj.ExpressionCalcObj(obj)
     4168            Controls['SeqParFitEqs'][calcobj.eObj.expression] = obj
     4169            EnableParFitEqMenus()
     4170            if Controls['SeqParFitEqs']: DoParEqFit(event)
     4171                                           
    41424172    def GridSetToolTip(row,col):
    41434173        '''Routine to show standard uncertainties for each element in table
     
    43714401                calcobj.UpdateDict(PSvarDict)
    43724402            else:
    4373                 PSvarDict,unused,unused = CreatePSvarDict(0,histNames[0])
     4403                # PATCH: this routine can go away eventually once parmDict is always in
     4404                # sequential refinement
     4405                PSvarDict,unused,unused = CreatePSvarDict(seqnum,name)
    43744406                calcobj.SetupCalc(PSvarDict)
    43754407            valList.append(calcobj.EvalExpression())
     
    43904422    else:
    43914423        print 'Sequential refinement needs to be rerun to obtain ESDs for PseudoVariables'
     4424        # PATCH: this routine can go away eventually
    43924425        PSvarDict,unused,unused = CreatePSvarDict(0,histNames[0])
    43934426    # Also dicts of dependent (depVarDict) & independent vars (indepVarDict)
Note: See TracChangeset for help on using the changeset viewer.