Changeset 1322


Ignore:
Timestamp:
May 4, 2014 10:30:16 PM (8 years ago)
Author:
toby
Message:

rework pseudovars and parametric fitting; remove step size for derivatives from expression objects

Location:
trunk
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIexprGUI.py

    r1312 r1322  
    6464      what they will do here; default is "Enter restraint expression here"
    6565    :param bool fit: determines if the expression will be used in fitting (default=True).
    66       If set to False, derivate step values and refinement flags are not shown
     66      If set to False, and refinement flags are not shown
    6767      and Free parameters are not offered as an assignment option.
    6868    :param str VarLabel: an optional variable label to include before the expression
     
    9999        self.varName = {}
    100100        'Name assigned to each variable'
    101         self.varStep = {}
    102         'Step size for each variable'
    103101        self.varValue = {}
    104102        'Value for a variable (Free parameters only)'
     
    202200                self.varName,
    203201                self.varValue,
    204                 self.varStep,
    205202                self.varRefflag,
    206203                )
     
    238235                self.varName,
    239236                self.varValue,
    240                 self.varStep,
    241237                self.varRefflag,
    242238                )
     
    315311                    else:
    316312                        msg += 'Value '+str(val)+' invalid for '+str(v)
    317             # step assignment
    318             val = self.varStep.get(v)
    319             vf = 1.0
    320             try:
    321                 vf = float(val)
    322             except ValueError,TypeError:
    323                 invalid += 1
    324                 if msg: msg += "; "
    325                 if val is None:
    326                     msg += 'No step value for '+str(v)
    327                 else:
    328                     msg += 'Step value '+str(val)+' invalid for '+str(v)
    329             if vf == 0.0:
    330                 invalid += 1
    331                 if msg: msg += "; "
    332                 msg += 'Zero is not valid as a step for '+str(v)
    333313        if invalid:
    334314            return '('+msg+')'       
     
    348328                          'Assign variables to labels'),
    349329            0,wx.EXPAND|wx.ALIGN_CENTER,0)
    350         GridSiz = wx.FlexGridSizer(len(self.exprVarLst)+1,6,2,2)
     330        GridSiz = wx.FlexGridSizer(len(self.exprVarLst)+1,5,2,2)
    351331        GridSiz.Add(
    352332            wx.StaticText(self.varbox,wx.ID_ANY,'label',style=wx.CENTER),
     
    355335        self.choices = ['Free','Phase','Hist./Phase','Hist.','Global']
    356336        if self.fit:
    357             lbls += ('derivative\nstep','refine\nflag')
     337            lbls += ('refine\nflag',)
    358338        else:
    359             lbls += ('','')
     339            lbls += ('',)
    360340            self.choices[0] = ''
    361341        for i in (1,2,3,4): # remove empty menus from choice list
     
    416396                GridSiz.Add(wid,0,wx.ALIGN_LEFT,0)
    417397
    418             # step
    419             if self.varSelect.get(v) != 0 or not self.fit:
    420                 wid = (-1,-1)
    421             else:
    422             #if self.varSelect.get(v) == 0:
    423                 wid = G2gd.ValidatedTxtCtrl(self.varbox,self.varStep,v,
    424                                             #OnLeave=self.OnTxtLeave,
    425                                             size=(50,-1))
    426             GridSiz.Add(wid,0,wx.ALIGN_LEFT|wx.EXPAND,0)
    427 
    428398            # show a refine flag for Free Vars only
    429399            if self.varSelect.get(v) == 0 and self.fit:
     
    473443                return
    474444            self.varName[v] = var
    475         self.varStep[v] = self.varStep.get(v,0.0001)
    476445        self.OnValidate(None)
    477446
     
    570539            self.varName,
    571540            self.varValue,
    572             self.varStep,
    573541            self.varRefflag,
    574542            )
     
    601569    PSvarDict = {'::a':1.0,'::b':1.1,'0::c':1.2}
    602570    #PSvars = PSvarDict.keys()
    603     indepvarDict = {'Temperature':1.0,'Pressure':1.1,'Phase of Moon':1.2}
     571    indepvarDict = {'Temperature':1.0,'Pressure':1.1,'Phase of Moon':1.2,'1:1:HAP':1.3}
    604572    dlg = ExpressionDialog(frm,indepvarDict,
    605573                           header="Edit the PseudoVar expression",
     
    617585    print dlg.GetDepVar()
    618586    import sys
    619     sys.exit()
     587    #sys.exit()
    620588
    621589    #app.MainLoop()
     
    632600    obj = G2obj.ExpressionObj()
    633601    obj.expression = "A*np.exp(B)"
    634     obj.assgnVars =  {'B': ['0::Afrac:*', 0.0001]}
    635     obj.freeVars =  {'A': [u'A', 0.5, 0.0001, True]}
     602    obj.assgnVars =  {'B': '0::Afrac:*'}
     603    obj.freeVars =  {'A': [u'A', 0.5, True]}
    636604    obj.CheckVars()
    637605    parmDict2 = {'0::Afrac:0':1.0, '0::Afrac:1': 1.0}
     
    644612   
    645613    obj.expression = "A*np.exp(-2/B)"
    646     obj.assgnVars =  {'A': ['0::Afrac:0', 0.0001], 'B': ['0::Afrac:1', 0.0001]}
     614    obj.assgnVars =  {'A': '0::Afrac:0', 'B': '0::Afrac:1'}
    647615    obj.freeVars =  {}
    648616    parmDict1 = {'0::Afrac:0':1.0, '0::Afrac:1': -2.0}
  • trunk/GSASIIgrid.py

    r1312 r1322  
    31713171        #this is to satisfy structure drawing stuff in G2plt when focus changes
    31723172        return None
     3173
     3174    def InstallGridToolTip(self, rowcolhintcallback):
     3175        '''code to display a tooltip for each item on a grid
     3176        from http://wiki.wxpython.org/wxGrid%20ToolTips
     3177
     3178        :param function rowcolhintcallback: a routine that returns a text
     3179          string depending on the selected row and column
     3180        '''
     3181        prev_rowcol = [None,None]
     3182        def OnMouseMotion(evt):
     3183            # evt.GetRow() and evt.GetCol() would be nice to have here,
     3184            # but as this is a mouse event, not a grid event, they are not
     3185            # available and we need to compute them by hand.
     3186            x, y = self.CalcUnscrolledPosition(evt.GetPosition())
     3187            row = self.YToRow(y)
     3188            col = self.XToCol(x)
     3189
     3190            if (row,col) != prev_rowcol and row >= 0 and col >= 0:
     3191                prev_rowcol[:] = [row,col]
     3192                hinttext = rowcolhintcallback(row, col)
     3193                if hinttext is None:
     3194                    hinttext = ''
     3195                self.GetGridWindow().SetToolTipString(hinttext)
     3196            evt.Skip()
     3197
     3198        wx.EVT_MOTION(self.GetGridWindow(), OnMouseMotion)
    31733199                                               
    31743200################################################################################
     
    36313657        sampleParmDict = {'Temperature':[],'Pressure':[],
    36323658                          'FreePrm1':[],'FreePrm2':[],'FreePrm3':[],}
     3659        Controls = G2frame.PatternTree.GetItemPyData(
     3660            GetPatternTreeItemId(G2frame,G2frame.root, 'Controls'))
    36333661        sampleParm = {}
    36343662        for name in histNames:
     
    36403668            frstValue = sampleParmDict[item][0]
    36413669            if np.any(np.array(sampleParmDict[item])-frstValue):
    3642                 sampleParm[item] = sampleParmDict[item]           
     3670                if item.startswith('FreePrm'):
     3671                    sampleParm[Controls[item]] = sampleParmDict[item]
     3672                else:
     3673                    sampleParm[item] = sampleParmDict[item]
    36433674        return sampleParm
    36443675
    36453676    def GetColumnInfo(col):
    3646         '''returns column label, lists of values and errors (or None) for each column in the table.
    3647         label is reformatted from Unicode to MatPlotLib
     3677        '''returns column label, lists of values and errors (or None) for each column in the table
     3678        for plotting. The column label is reformatted from Unicode to MatPlotLib encoding
    36483679        '''
    36493680        plotName = plotSpCharFix(G2frame.SeqTable.GetColLabelValue(col))
     
    37643795        finally:
    37653796            dlg.Destroy()
    3766            
    3767     # lookup table for unique cell parameters by symmetry
    3768     cellGUIlist = [
    3769         [['m3','m3m'],(0,)],
    3770         [['3R','3mR'],(0,3)],
    3771         [['3','3m1','31m','6/m','6/mmm','4/m','4/mmm'],(0,2)],
    3772         [['mmm'],(0,1,2)],
    3773         [['2/m'+'a'],(0,1,2,3)],
    3774         [['2/m'+'b'],(0,1,2,4)],
    3775         [['2/m'+'c'],(0,1,2,5)],
    3776         [['-1'],(0,1,2,3,4,5)],
    3777         ]
    3778     # cell labels
    3779     cellUlbl = ('a','b','c',u'\u03B1',u'\u03B2',u'\u03B3') # unicode a,b,c,alpha,beta,gamma
    3780    
     3797               
    37813798    def striphist(var,insChar=''):
    37823799        'strip a histogram number from a var name'
     
    38153832        return col
    38163833   
    3817     def EnableSeqExpressionMenus():
     3834    def EnablePseudoVarMenus():
    38183835        'Enables or disables the PseudoVar menu items that require existing defs'
    38193836        if Controls['SeqPseudoVars']:
     
    38243841        G2frame.dataFrame.SequentialPvars.Enable(wxEDITSEQVAR,val)
    38253842
    3826     def DelSeqExpression(event):
    3827         'Ask the user to select expression to delete'
     3843    def DelPseudoVar(event):
     3844        'Ask the user to select a pseudo var expression to delete'
    38283845        choices = Controls['SeqPseudoVars'].keys()
    38293846        selected = ItemSelector(
     
    38383855            UpdateSeqResults(G2frame,data,G2frame.dataDisplay.GetSize()) # redisplay variables
    38393856
    3840     def EditSeqExpression(event):
    3841         'Edit an existing expression'
     3857    def EditPseudoVar(event):
     3858        'Edit an existing pseudo var expression'
    38423859        choices = Controls['SeqPseudoVars'].keys()
    38433860        if len(choices) == 1:
     
    38633880                UpdateSeqResults(G2frame,data,G2frame.dataDisplay.GetSize()) # redisplay variables
    38643881       
    3865     def AddNewSeqExpression(event):
    3866         'Create a new expression'
     3882    def AddNewPseudoVar(event):
     3883        'Create a new pseudo var expression'
    38673884        dlg = G2exG.ExpressionDialog(
    38683885            G2frame.dataDisplay,PSvarDict,
     
    38773894            UpdateSeqResults(G2frame,data,G2frame.dataDisplay.GetSize()) # redisplay variables
    38783895
    3879     def EnableParFitFxnMenus():
     3896    def CreatePSvarDict(seqnum,name):
     3897        '''Create a parameter dict (parmDict) for everything that might be used
     3898        in a PseudoVar.
     3899        Also creates a list of revised labels (modVaryList) for the covariance matrix to
     3900        match the items in the parameter dict and a matching list of ESDs (ESDvaryList).
     3901       
     3902        :param int seqnum: the sequence number of the histogram in the sequential
     3903          refinement
     3904        :param str name: the name of the histogram in the data tree
     3905
     3906        :returns: parmDict,modVaryList,ESDvaryList
     3907        '''
     3908        parmDict = {}
     3909        modVaryList = []
     3910        for i,(key,val) in enumerate(zip(data[name]['varyList'],data[name]['variables'])):
     3911            skey = striphist(key)
     3912            if skey in data[name]['newAtomDict']:
     3913                # replace coordinate shifts with equivalents from lookup table
     3914                repkey,repval = data[name]['newAtomDict'][skey]
     3915                parmDict[repkey] = repval
     3916                modVaryList.append(repkey)
     3917            elif skey in data[name]['newCellDict']:
     3918                # replace recip. cell term shifts with equivalents from lookup table       
     3919                repkey,repval = data[name]['newCellDict'][skey]
     3920                parmDict[repkey] = repval
     3921                modVaryList.append(repkey)
     3922            else:
     3923                parmDict[key] = val
     3924                modVaryList.append(key)
     3925        # create a cell parm dict, override initial settings with values in parmDict
     3926        for phase in Phases:
     3927            phasedict = Phases[phase]
     3928            pId = phasedict['pId']
     3929            cell = Rcelldict.copy()
     3930            cell.update(
     3931                {lbl:parmDict[lbl] for lbl in RcellLbls[pId] if lbl in parmDict}
     3932                )
     3933            pfx = str(pId)+'::' # prefix for A values from phase
     3934            A,zeros = G2stIO.cellFill(pfx,SGdata[pId],cell,zeroDict[pId])
     3935            parmDict.update({pfx+cellUlbl[i]:val for i,val in
     3936                             enumerate(G2lat.A2cell(A))
     3937                             if i in uniqCellIndx[pId]
     3938                             })
     3939            parmDict[pfx+"vol"] = G2lat.calc_V(A)
     3940        # now add misc terms to dict
     3941        parmDict['Rwp'] = data[name]['Rvals']['Rwp']
     3942        parmDict[u'\u0394\u03C7\u00B2 (%)'] = 100.*data[name]['Rvals'].get('DelChi2',-1)
     3943        for key in sampleParms:
     3944            parmDict[key] = sampleParms[key][seqnum]
     3945        return parmDict,modVaryList,data[name]['sig']
     3946
     3947    def EvalPSvarDeriv(calcobj,parmDict,var,step):
     3948        '''Evaluate an expression derivative with respect to a
     3949        GSAS-II variable name.
     3950        '''
     3951        varList = [var]
     3952        origVals = [parmDict[var]]
     3953        minusVals = [parmDict[var]-step]
     3954        plusVals = [parmDict[var]+step]
     3955        if var in Rcelldict:
     3956            pId = var.split(':')[0] # get phase number
     3957            pfx = pId + '::'
     3958            pId = int(pId)
     3959            Rcell = Rcelldict.copy()
     3960            Rcell.update({v:parmDict[v] for v in Rcelldict if v in parmDict})
     3961            Rcell[var] = parmDict[var] - step
     3962            Aminus,zeros = G2stIO.cellFill(pfx,SGdata[pId],Rcell,zeroDict[pId])
     3963            Rcell[var] =  parmDict[var] + step
     3964            Aplus,zeros = G2stIO.cellFill(pfx,SGdata[pId],Rcell,zeroDict[pId])
     3965            for i,(mval,pval) in enumerate(zip(G2lat.A2cell(Aminus),G2lat.A2cell(Aplus))):
     3966                if i in uniqCellIndx[pId]:
     3967                    lbl = pfx+cellUlbl[i]
     3968                    varList.append(lbl)
     3969                    origVals.append(parmDict[lbl])
     3970                    minusVals.append(mval)
     3971                    plusVals.append(pval)
     3972            lbl = pfx+'vol'
     3973            varList.append(lbl)
     3974            origVals.append(parmDict[lbl])
     3975            minusVals.append(G2lat.calc_V(Aminus))
     3976            plusVals.append(G2lat.calc_V(Aplus))
     3977
     3978        calcobj.UpdateVars(varList,plusVals)
     3979        pVal = calcobj.EvalExpression()
     3980        calcobj.UpdateVars(varList,minusVals)
     3981        mVal = calcobj.EvalExpression()
     3982        calcobj.UpdateVars(varList,origVals)
     3983        return (pVal - mVal) / (2.*step)
     3984
     3985    def EnableParFitEqMenus():
    38803986        'Enables or disables the Parametric Fit menu items that require existing defs'
    3881         if Controls['SeqParFitFxns']:
     3987        if Controls['SeqParFitEqs']:
    38823988            val = True
    38833989        else:
    38843990            val = False
    3885         #G2frame.dataFrame.SequentialPfit.Enable(wxADDPARFIT,val) # TODO: remove when testing done
    38863991        G2frame.dataFrame.SequentialPfit.Enable(wxDELPARFIT,val)
    38873992        G2frame.dataFrame.SequentialPfit.Enable(wxEDITPARFIT,val)
    38883993        G2frame.dataFrame.SequentialPfit.Enable(wxDOPARFIT,val)
    38893994
    3890     def DelParFitFxn(event):
     3995    def DelParFitEq(event):
    38913996        'Ask the user to select function to delete'
    3892         choices = Controls['SeqParFitFxns'].keys()
     3997        choices = Controls['SeqParFitEqs'].keys()
    38933998        selected = ItemSelector(
    38943999            choices,G2frame.dataFrame,
     
    38984003        if selected is None: return
    38994004        for item in selected:
    3900             del Controls['SeqParFitFxns'][choices[item]]
    3901         EnableParFitFxnMenus()
    3902        
    3903     def EditParFitFxn(event):
    3904         'Edit an existing function'
    3905         choices = Controls['SeqParFitFxns'].keys()
     4005            del Controls['SeqParFitEqs'][choices[item]]
     4006        EnableParFitEqMenus()
     4007        if Controls['SeqParFitEqs']: DoParEqFit(event)
     4008       
     4009    def EditParFitEq(event):
     4010        'Edit an existing parametric equation'
     4011        choices = Controls['SeqParFitEqs'].keys()
    39064012        if len(choices) == 1:
    39074013            selected = 0
     
    39154021            dlg = G2exG.ExpressionDialog(
    39164022                G2frame.dataDisplay,indepVarDict,
    3917                 Controls['SeqParFitFxns'][choices[selected]],
     4023                Controls['SeqParFitEqs'][choices[selected]],
    39184024                depVarDict=depVarDict,
    39194025                header="Edit this minimization function's formula")
     
    39214027            if newobj:
    39224028                calcobj = G2obj.ExpressionCalcObj(newobj)
    3923                 del Controls['SeqParFitFxns'][choices[selected]]
    3924                 Controls['SeqParFitFxns'][calcobj.eObj.expression] = newobj
    3925             EnableParFitFxnMenus()
    3926 
    3927     def AddNewParFitFxn(event):
    3928         'Create a new expression to be fit to sequential results'
     4029                del Controls['SeqParFitEqs'][choices[selected]]
     4030                Controls['SeqParFitEqs'][calcobj.eObj.expression] = newobj
     4031            EnableParFitEqMenus()
     4032        if Controls['SeqParFitEqs']: DoParEqFit(event)
     4033
     4034    def AddNewParFitEq(event):
     4035        'Create a new parametric equation to be fit to sequential results'
    39294036        dlg = G2exG.ExpressionDialog(
    39304037            G2frame.dataDisplay,indepVarDict,
     
    39354042        if obj:
    39364043            calcobj = G2obj.ExpressionCalcObj(obj)
    3937             Controls['SeqParFitFxns'][calcobj.eObj.expression] = obj
    3938             EnableParFitFxnMenus()
    3939 
    3940     def ParEval(values,calcObjList,varyList):
    3941         'Evaluate the parametric expression(s)'
    3942         #for var,val in zip(varyList,values):
    3943         #    print 'var, value = ',var,val
     4044            Controls['SeqParFitEqs'][calcobj.eObj.expression] = obj
     4045            EnableParFitEqMenus()
     4046        if Controls['SeqParFitEqs']: DoParEqFit(event)
     4047           
     4048    def ParEqEval(Values,calcObjList,varyList):
     4049        '''Evaluate the parametric expression(s)
     4050        :param list Values: a list of values for each variable parameter
     4051        :param list calcObjList: a list of :class:`GSASIIobj.ExpressionCalcObj`
     4052          expression objects to evaluate
     4053        :param list varyList: a list of variable names for each value in Values
     4054        '''
    39444055        result = []
    39454056        for calcobj in calcObjList:
    3946             calcobj.UpdateVars(varyList,values)
     4057            calcobj.UpdateVars(varyList,Values)
    39474058            result.append((calcobj.depVal-calcobj.EvalExpression())/calcobj.depSig)
    39484059        return result
    39494060
    3950     def DoParFit(event):
     4061    def DoParEqFit(event):
    39514062        'Parametric fit minimizer'
    39524063        varyValueDict = {} # dict of variables and their initial values
    39534064        calcObjList = [] # expression objects, ready to go for each data point
    3954         for expr in Controls['SeqParFitFxns']:
    3955             obj = Controls['SeqParFitFxns'][expr]
     4065        for expr in Controls['SeqParFitEqs']:
     4066            obj = Controls['SeqParFitEqs'][expr]
    39564067            # assemble refined vars for this equation
    39574068            varyValueDict.update({var:val for var,val in obj.GetVariedVarVal()})
     
    39784089        varyList = varyValueDict.keys()
    39794090        varyValues = [varyValueDict[key] for key in varyList]
    3980         result = so.leastsq(ParEval,varyValues,full_output=True,   #ftol=Ftol,
     4091        result = so.leastsq(ParEqEval,varyValues,full_output=True,   #ftol=Ftol,
    39814092                            args=(calcObjList,varyList)
    39824093                            )
     
    39874098        for i,(var,val) in enumerate(zip(varyList,values)):
    39884099            print '  ',var,' =',G2mth.ValEsd(val,np.sqrt(covar[i,i]))
    3989         for fitnum,expr in enumerate(Controls['SeqParFitFxns']):
    3990             obj = Controls['SeqParFitFxns'][expr]
     4100        for fitnum,expr in enumerate(Controls['SeqParFitEqs']):
     4101            obj = Controls['SeqParFitEqs'][expr]
    39914102            obj.UpdateVariedVars(varyList,values)
    39924103            calcobj = G2obj.ExpressionCalcObj(obj)
     
    40054116                                           fitnum,fitvals)
    40064117                               
     4118    def GridSetToolTip(row,col):
     4119        '''Routine to show standard uncertainties for each element in table
     4120        as a tooltip
     4121        '''
     4122        if colSigs[col]:
     4123            return u'\u03c3 = '+str(colSigs[col][row])
     4124        return ''
     4125   
     4126    # lookup table for unique cell parameters by symmetry
     4127    cellGUIlist = [
     4128        [['m3','m3m'],(0,)],
     4129        [['3R','3mR'],(0,3)],
     4130        [['3','3m1','31m','6/m','6/mmm','4/m','4/mmm'],(0,2)],
     4131        [['mmm'],(0,1,2)],
     4132        [['2/m'+'a'],(0,1,2,3)],
     4133        [['2/m'+'b'],(0,1,2,4)],
     4134        [['2/m'+'c'],(0,1,2,5)],
     4135        [['-1'],(0,1,2,3,4,5)],
     4136        ]
     4137    # cell labels
     4138    cellUlbl = ('a','b','c',u'\u03B1',u'\u03B2',u'\u03B3') # unicode a,b,c,alpha,beta,gamma
     4139
    40074140    #======================================================================
    4008     # start processing sequential results here
     4141    # start processing sequential results here (UpdateSeqResults)
     4142    #======================================================================
    40094143    if not data:
    40104144        print 'No sequential refinement results'
     
    40124146    Histograms,Phases = G2frame.GetUsedHistogramsAndPhasesfromTree()
    40134147    Controls = G2frame.PatternTree.GetItemPyData(GetPatternTreeItemId(G2frame,G2frame.root,'Controls'))
    4014     if 'SeqPseudoVars' not in Controls: # create a place to store Pseudo Vars, if needed
    4015         Controls['SeqPseudoVars'] = {}
    4016     if 'SeqParFitFxns' not in Controls: # create a place to store Parametric Fit functions, if needed
    4017         Controls['SeqParFitFxns'] = {}
     4148    # create a place to store Pseudo Vars & Parametric Fit functions, if needed
     4149    if 'SeqPseudoVars' not in Controls: Controls['SeqPseudoVars'] = {}
     4150    if 'SeqParFitEqs' not in Controls: Controls['SeqParFitEqs'] = {}
    40184151    histNames = data['histNames']
    40194152    if G2frame.dataDisplay:
     
    40234156        Status.SetStatusText("Select column to export; Double click on column to plot data; on row for Covariance")
    40244157    sampleParms = GetSampleParms()
     4158
    40254159    # make dict of varied atom coords keyed by absolute position
    40264160    newAtomDict = data[histNames[0]]['newAtomDict'] # dict with atom positions; relative & absolute
    40274161    # Possible error: the next might need to be data[histNames[0]]['varyList']
    40284162    # error will arise if there constraints on coordinates?
    4029     atomList = {newAtomDict[item][0]:item for item in newAtomDict if item in data['varyList']}
     4163    atomLookup = {newAtomDict[item][0]:item for item in newAtomDict if item in data['varyList']}
    40304164   
    40314165    # make dict of varied cell parameters equivalents
     
    40394173            Dlookup[item] = newCellDict[item][0]
    40404174    # add coordinate equivalents to lookup table
    4041     for parm in atomList:
    4042 #        print parm,atomList[parm],data[name]['newAtomDict'][atomList[parm]]
    4043         Dlookup[atomList[parm]] = parm
    4044         ESDlookup[parm] = atomList[parm]
    4045 
    4046     # get unit cell & symmetry for all phases
    4047     Alist = {}
     4175    for parm in atomLookup:
     4176        Dlookup[atomLookup[parm]] = parm
     4177        ESDlookup[parm] = atomLookup[parm]
     4178
     4179    # get unit cell & symmetry for all phases & initial stuff for later use
     4180    RecpCellTerms = {}
    40484181    SGdata = {}
    4049     covData = {}
    4050     uniqCellParms = {}
     4182    uniqCellIndx = {}
     4183    initialCell = {}
     4184    RcellLbls = {}
     4185    zeroDict = {}
     4186    Rcelldict = {}
    40514187    for phase in Phases:
    40524188        phasedict = Phases[phase]
    40534189        pId = phasedict['pId']
    4054         Alist[pId] = G2lat.cell2A(phasedict['General']['Cell'][1:7])
     4190        pfx = str(pId)+'::' # prefix for A values from phase
     4191        RcellLbls[pId] = [pfx+'A'+str(i) for i in range(6)]
     4192        RecpCellTerms[pId] = G2lat.cell2A(phasedict['General']['Cell'][1:7])
     4193        zeroDict[pId] = dict(zip(RcellLbls[pId],6*[0.,]))
    40554194        SGdata[pId] = phasedict['General']['SGData']
     4195        Rcelldict.update({lbl:val for lbl,val in zip(RcellLbls[pId],RecpCellTerms[pId])})
    40564196        laue = SGdata[pId]['SGLaue']
    40574197        if laue == '2/m':
     
    40594199        for symlist,celllist in cellGUIlist:
    40604200            if laue in symlist:
    4061                 uniqCellParms[pId] = celllist
     4201                uniqCellIndx[pId] = celllist
    40624202                break
    40634203        else: # should not happen
    4064             uniqCellParms[pId] = range(6)
     4204            uniqCellIndx[pId] = range(6)
     4205        for i in uniqCellIndx[pId]:
     4206            initialCell[str(pId)+'::A'+str(i)] =  RecpCellTerms[pId][i]
    40654207
    40664208    SetDataMenuBar(G2frame,G2frame.dataFrame.SequentialMenu)
     
    40724214    G2frame.dataFrame.Bind(wx.EVT_MENU, OnSaveSelSeqCSV, id=wxID_SAVESEQSELCSV)
    40734215    G2frame.dataFrame.Bind(wx.EVT_MENU, OnPlotSelSeq, id=wxID_PLOTSEQSEL)
    4074     G2frame.dataFrame.Bind(wx.EVT_MENU, AddNewSeqExpression, id=wxADDSEQVAR)
    4075     G2frame.dataFrame.Bind(wx.EVT_MENU, DelSeqExpression, id=wxDELSEQVAR)
    4076     G2frame.dataFrame.Bind(wx.EVT_MENU, EditSeqExpression, id=wxEDITSEQVAR)
    4077     G2frame.dataFrame.Bind(wx.EVT_MENU, AddNewParFitFxn, id=wxADDPARFIT)
    4078     G2frame.dataFrame.Bind(wx.EVT_MENU, DelParFitFxn, id=wxDELPARFIT)
    4079     G2frame.dataFrame.Bind(wx.EVT_MENU, EditParFitFxn, id=wxEDITPARFIT)
    4080     G2frame.dataFrame.Bind(wx.EVT_MENU, DoParFit, id=wxDOPARFIT)
    4081     EnableSeqExpressionMenus()
    4082     EnableParFitFxnMenus()
    4083 
    4084     # build up the data table one column at a time
     4216    G2frame.dataFrame.Bind(wx.EVT_MENU, AddNewPseudoVar, id=wxADDSEQVAR)
     4217    G2frame.dataFrame.Bind(wx.EVT_MENU, DelPseudoVar, id=wxDELSEQVAR)
     4218    G2frame.dataFrame.Bind(wx.EVT_MENU, EditPseudoVar, id=wxEDITSEQVAR)
     4219    G2frame.dataFrame.Bind(wx.EVT_MENU, AddNewParFitEq, id=wxADDPARFIT)
     4220    G2frame.dataFrame.Bind(wx.EVT_MENU, DelParFitEq, id=wxDELPARFIT)
     4221    G2frame.dataFrame.Bind(wx.EVT_MENU, EditParFitEq, id=wxEDITPARFIT)
     4222    G2frame.dataFrame.Bind(wx.EVT_MENU, DoParEqFit, id=wxDOPARFIT)
     4223    EnablePseudoVarMenus()
     4224    EnableParFitEqMenus()
     4225
     4226    #-----------------------------------------------------------------------------------
     4227    # build up the data table by columns -----------------------------------------------
    40854228    colList = []
    40864229    colSigs = []
     
    41064249        Types += [wg.GRID_VALUE_FLOAT,]
    41074250    # add unique cell parameters
    4108     for pId in sorted(Alist):
     4251    for pId in sorted(RecpCellTerms):
    41094252        pfx = str(pId)+'::' # prefix for A values from phase
    41104253        cells = []
    41114254        cellESDs = []
    4112         colLabels += [pfx+cellUlbl[i] for i in uniqCellParms[pId]]
     4255        colLabels += [pfx+cellUlbl[i] for i in uniqCellIndx[pId]]
    41134256        colLabels += [pfx+'Vol']
    4114         Types += (1+len(uniqCellParms[pId]))*[wg.GRID_VALUE_FLOAT,]
     4257        Types += (1+len(uniqCellIndx[pId]))*[wg.GRID_VALUE_FLOAT,]
    41154258        for name in histNames:
    4116             covData['varyList'] = [Dlookup.get(striphist(v),v) for v in data[name]['varyList']]
    4117             covData['covMatrix'] = data[name]['covMatrix']
    4118             A = Alist[pId][:] # make copy of starting A values
     4259            covData = {
     4260                'varyList': [Dlookup.get(striphist(v),v) for v in data[name]['varyList']],
     4261                'covMatrix': data[name]['covMatrix']
     4262                }
     4263            A = RecpCellTerms[pId][:] # make copy of starting A values
    41194264            # update with refined values
    41204265            for i in range(6):
     
    41264271            Albls = [pfx+'A'+str(i) for i in range(6)]
    41274272            cellDict = dict(zip(Albls,A))
    4128             zeroDict = dict(zip(Albls,6*[0.,]))
    4129             A,zeros = G2stIO.cellFill(pfx,SGdata[pId],cellDict,zeroDict)
     4273            A,zeros = G2stIO.cellFill(pfx,SGdata[pId],cellDict,zeroDict[pId])
    41304274            # convert to direct cell & add only unique values to table
    41314275            c = G2lat.A2cell(A)
    41324276            vol = G2lat.calc_V(A)
    41334277            cE = G2stIO.getCellEsd(pfx,SGdata[pId],A,covData)
    4134             cells += [[c[i] for i in uniqCellParms[pId]]+[vol]]
    4135             cellESDs += [[cE[i] for i in uniqCellParms[pId]]+[cE[-1]]]
     4278            cells += [[c[i] for i in uniqCellIndx[pId]]+[vol]]
     4279            cellESDs += [[cE[i] for i in uniqCellIndx[pId]]+[cE[-1]]]
    41364280        colList += zip(*cells)
    41374281        colSigs += zip(*cellESDs)
     
    41424286    colSigs += zip(*[data[name]['sig'] for name in histNames])
    41434287
    4144     # process the dependent constrained variables, removing histogram numbers if needed
     4288    # tabulate constrained variables, removing histogram numbers if needed
    41454289    # from parameter label
    41464290    depValDict = {}
     
    41564300               depValDict[svar].append(val)
    41574301               depSigDict[svar].append(sig)
    4158     # add the dependent constrained variables
     4302    # add the dependent constrained variables to the table
    41594303    for var in sorted(depValDict):
    41604304        if len(depValDict[var]) != len(histNames): continue
     
    41654309
    41664310    # add atom parameters to table
    4167     colLabels += atomList.keys()
    4168     Types += len(atomList)*[wg.GRID_VALUE_FLOAT]
    4169     for parm in sorted(atomList):
    4170         colList += [[data[name]['newAtomDict'][atomList[parm]][1] for name in histNames]]
    4171         if atomList[parm] in data[histNames[0]]['varyList']:
    4172             col = data[histNames[0]]['varyList'].index(atomList[parm])
     4311    colLabels += atomLookup.keys()
     4312    Types += len(atomLookup)*[wg.GRID_VALUE_FLOAT]
     4313    for parm in sorted(atomLookup):
     4314        colList += [[data[name]['newAtomDict'][atomLookup[parm]][1] for name in histNames]]
     4315        if atomLookup[parm] in data[histNames[0]]['varyList']:
     4316            col = data[histNames[0]]['varyList'].index(atomLookup[parm])
    41734317            colSigs += [[data[name]['sig'][col] for name in histNames]]
    41744318        else:
    41754319            colSigs += [None] # should not happen
     4320    # evaluate Pseudovars, their ESDs and add them to grid
     4321    for expr in Controls['SeqPseudoVars']:
     4322        obj = Controls['SeqPseudoVars'][expr]
     4323        calcobj = G2obj.ExpressionCalcObj(obj)
     4324        valList = []
     4325        esdList = []
     4326        for seqnum,name in enumerate(histNames):
     4327            parmDict,modVaryL,ESDL = CreatePSvarDict(seqnum,name)
     4328            calcobj.SetupCalc(parmDict)
     4329            valList.append(calcobj.EvalExpression())
     4330            derivs = np.array(
     4331                [EvalPSvarDeriv(calcobj,parmDict,var,ESD/10.) for var,ESD in zip(modVaryL,ESDL)]
     4332                )
     4333            esdList.append(np.sqrt(
     4334                np.inner(derivs,np.inner(data[name]['covMatrix'],derivs.T))
     4335                ))
     4336        colList += [valList]
     4337        colSigs += [esdList]
     4338        colLabels += [expr]
     4339        Types += [wg.GRID_VALUE_FLOAT,]
     4340    #---- table build done -------------------------------------------------------------
     4341
    41764342    # Make dict needed for creating & editing pseudovars (PSvarDict).
    4177     # These are variables that are in the CoVar matrix, or related vars that are
    4178     # directly are mapped to a var in that matrix.
    4179     # Also dicts of [in]dependent vars for Parametric fitting (indepVarDict & depVarDict)
     4343    PSvarDict,unused,unused = CreatePSvarDict(0,histNames[0])
     4344    # Also dicts of dependent (depVarDict) & independent vars (indepVarDict)
     4345    # for Parametric fitting from the data table
    41804346    parmDict = dict(zip(colLabels,zip(*colList)[0])) # scratch dict w/all values in table
    4181     parmDict.update({var:val for var,val in data[name]['newCellDict'].values()}) #  add varied
    4182     #     reciprocal cell terms
     4347    parmDict.update(
     4348        {var:val for var,val in data[name]['newCellDict'].values()} #  add varied reciprocal cell terms
     4349    )
    41834350    name = histNames[0]
    4184     # Create labels for CoVar matrix that maps vars appropriately
    4185     PSvaryList = [Dlookup.get(striphist(var),var) for var in data[name]['varyList']]
    4186     # dict containing variables and values for use in PseudoVars defs
    4187     #    pick out only the refined terms or their surrogates
    4188     PSvarDict = {var:parmDict.get(var) for var in PSvaryList}
    41894351    indepVarDict = {     #  values in table w/o ESDs
    41904352        var:colList[i][0] for i,var in enumerate(colLabels) if colSigs[i] is None
    41914353        }
    4192     PSvarDict.update(indepVarDict) # add values in table w/o ESDs
    41934354    # make dict of dependent vars (w/ESDs) that are not converted (Dij to Ak or dAx to Ax)
    41944355    depVarDict = {
     
    41984359    # add recip cell coeff. values
    41994360    depVarDict.update({var:val for var,val in data[name]['newCellDict'].values()})
    4200     # evaluate Pseudovars and add them to grid
    4201     for expr in Controls['SeqPseudoVars']:
    4202         obj = Controls['SeqPseudoVars'][expr]
    4203         name = histNames[0]
    4204         PSvars = [var for var,step in obj.assgnVars.values()] # variables used in this expression
    4205         PSderivList = [var for var in PSvaryList if var in PSvars]
    4206         calcobj = G2obj.ExpressionCalcObj(obj)
    4207         valList = []
    4208         esdList = []
    4209         for j,row in enumerate(zip(*colList)):
    4210             name = histNames[j]
    4211             parmDict = dict(zip(colLabels,row))
    4212             parmDict.update({var:val for var,val in data[name]['newCellDict'].values()})
    4213             # Create dict of values for each variable in expression
    4214             varDict = {Dlookup.get(striphist(var),var):
    4215                        parmDict.get(Dlookup.get(striphist(var),var))
    4216                        for var in PSvars}
    4217             # Create dict of s.u. values for each variable in expression
    4218             esdDict = {Dlookup.get(striphist(var),var):esd
    4219                          for var,esd in zip(data[name]['varyList'],data[name]['sig'])
    4220                          if Dlookup.get(striphist(var),var) in PSderivList}
    4221             # compute the value for the PseudoVar
    4222             calcobj.SetupCalc(varDict)
    4223             valList.append(calcobj.EvalExpression())
    4224             # compute ESD on this Pseudovar
    4225             derivs = np.array(
    4226                 [calcobj.EvalDeriv(var,esdDict[var]/10) for var in PSderivList])
    4227             vcov = G2mth.getVCov(PSderivList,PSvaryList,data[name]['covMatrix'])
    4228             esd = np.sqrt(np.inner(derivs,np.inner(vcov,derivs.T)))
    4229             esdList.append(np.sqrt(np.inner(derivs,np.inner(vcov,derivs.T))))
    4230         colList += [valList]
    4231         colSigs += [esdList]
    4232         colLabels += [expr]
    4233         Types += [wg.GRID_VALUE_FLOAT,]
    4234            
    4235         # name = histNames[0]
    4236         # print 'obj.assgnVars',obj.assgnVars
    4237         # print data[name]['varyList']
    4238         # #vList = [Dlookup.get(striphist(v),v) for v in data[name]['varyList']]
    4239         # #print vList
    4240         # #covData['covMatrix'] = data[name]['covMatrix']
    4241         # lookupList = [var for var,step in obj.assgnVars.values() if var in data[name]['varyList']]
    4242         # indexList = [data[name]['varyList'].index(var) for var in lookupList]
    4243         # print indexList
    4244         # siglist = [data[name]['sig'][data[name]['varyList'].index(var)] for var in lookupList]
    4245         # print siglist
    4246         # row = zip(*colList)[0]
    4247         # parmDict = dict(zip(colLabels,row))
    4248         # calcobj.SetupCalc(parmDict)
    4249         # print calcobj.lblLookup
    4250         # derivs = []
    4251         # for var in lookupList:
    4252         #     index = data[name]['varyList'].index(var)
    4253         #     sig = data[name]['sig'][index]
    4254         #     print var,sig
    4255         #     print calcobj.EvalDeriv(var,sig)
    4256         #     derivs.append(calcobj.EvalDeriv(var,sig/10))
    4257            
    4258         # derivs = np.array(derivs)
    4259         # #print 'derivs=',derivs       
    4260         # vcov = G2mth.getVCov(lookupList,data[name]['varyList'],data[name]['covMatrix'])
    4261         # #print 'vcov =',vcov
    4262         # esd = np.sqrt(np.inner(derivs,np.inner(vcov,derivs.T)))
    4263         # print 'val,esd =',calcobj.EvalExpression(),esd
    4264         #======================================================================
    4265         # valList = []
    4266         #PSvarDict = {Dlookup.get(striphist(var),var):
    4267         #         parmDict.get(Dlookup.get(striphist(var),var))
    4268         #         for var in data[name]['varyList']}
    4269         # for row in zip(*colList):
    4270         #     parmDict = dict(zip(colLabels,row))
    4271         #     calcobj.SetupCalc(parmDict)
    4272         #     valList.append(calcobj.EvalExpression())
    4273         # colList += [valList]
    4274         # colSigs += [None]
    4275         # colLabels += [exp]
    4276         # Types += [wg.GRID_VALUE_FLOAT,]
    4277 
    4278     rowList = [c for c in zip(*colList)]     # convert from columns to rows
    4279     G2frame.SeqTable = Table(rowList,colLabels=colLabels,rowLabels=histNames,types=Types)
    4280 
    4281     # old Table contents generator, keep for comparison for right now.
    4282     # Rwps = [data[name]['Rvals']['Rwp'] for name in histNames]
    4283     # seqList = [[Rwps[i],]+list(data[name]['variables']) for i,name in enumerate(histNames)]
    4284     # for i,item in enumerate(seqList):
    4285     #      newAtomDict = data[histNames[i]]['newAtomDict']
    4286     #      newCellDict = data[histNames[i]]['newCellDict']
    4287     #      item += [newAtomDict[atomList[parm]][1] for parm in atomList.keys()]
    4288     #      item += [newCellDict[ESDlookup[parm]][1] for parm in ESDlookup.keys()]
    4289     # colLabels = ['Rwp',]+data['varyList']  +atomList.keys()+ESDlookup.keys()
    4290     # Types = (len(data['varyList'] +atomList.keys()+ESDlookup.keys()
    4291     #              )+1)*[wg.GRID_VALUE_FLOAT,]
    4292     # G2frame.SeqTable = Table(seqList,colLabels=colLabels,rowLabels=histNames,types=Types
    4293     #                         )
    42944361   
    42954362    G2frame.dataDisplay = GSGrid(parent=G2frame.dataFrame)
     4363    G2frame.SeqTable = Table(
     4364        [c for c in zip(*colList)],     # convert from columns to rows
     4365        colLabels=colLabels,rowLabels=histNames,types=Types)
    42964366    G2frame.dataDisplay.SetTable(G2frame.SeqTable, True)
    42974367    G2frame.dataDisplay.EnableEditing(False)
     
    43114381        elif deltaChi > 1.0:
    43124382            G2frame.dataDisplay.SetCellStyle(row,deltaChiCol,color=wx.Color(255,255,0))
    4313 
    4314     # make dict with vars for use in PseudoVars
    4315     # name = histNames[0]
    4316     # parmDict = dict(zip(colLabels,zip(*colList)[0]))
    4317     # # create a dict with the refined Ax values for all phases (only)
    4318     # refCellDict = {var:val for var,val in data[name]['newCellDict'].values()}
    4319     # # compute the Ai values for each phase, updated with refined values and
    4320     # # with symmetry constraints applied
    4321     # for pId in Alist:     # loop over phases
    4322     #     Albls = [str(pId)+'::A'+str(i) for i in range(6)]
    4323     #     cellDict = {var:refCellDict.get(var,val) for var,val in zip(Albls,Alist[pId])}
    4324     #     zeroDict = {var:0.0 for var in Albls}
    4325     #     A,zeros = G2stIO.cellFill(str(pId)+'::',SGdata[pId],cellDict,zeroDict)
    4326     #     parmDict.update(dict(zip(Albls,A)))
    4327 
    4328 #    print data[name]['varyList']
    4329 #           
    4330     # print 'vars for PVar dict'
    4331     # for i,(var,val) in enumerate(zip(colLabels,zip(*colList)[0])):
    4332     #     if var in data[name]['varyList']:
    4333     #         print var,Dlookup.get(striphist(var),var),val,parmDict.get(Dlookup.get(striphist(var),var))
    4334     #         pass
    4335     #     #else:
    4336     #     #    print i,var,colSigs[i]
    4337     # print 'vars for PVar dict again'
     4383    G2frame.dataDisplay.InstallGridToolTip(GridSetToolTip)
     4384    #======================================================================
     4385    # end UpdateSeqResults; done processing sequential results
     4386    #======================================================================
    43384387
    43394388def UpdateSASDSeqResults(G2frame,data,prevSize=None):
     
    44384487#    G2frame.dataFrame.Bind(wx.EVT_MENU, OnSaveSelSeqCSV, id=wxID_SAVESASDSEQSELCSV)
    44394488    G2frame.dataFrame.Bind(wx.EVT_MENU, OnPlotSelSeq, id=wxID_PLOTSASDSEQSEL)
    4440 #    G2frame.dataFrame.Bind(wx.EVT_MENU, AddNewSeqExpression, id=wxADDSEQVAR)
    4441 #    G2frame.dataFrame.Bind(wx.EVT_MENU, DelSeqExpression, id=wxDELSEQVAR)
    4442 #    G2frame.dataFrame.Bind(wx.EVT_MENU, EditSeqExpression, id=wxEDITSEQVAR)
    4443 #    EnableSeqExpressionMenus()
     4489#    G2frame.dataFrame.Bind(wx.EVT_MENU, AddNewPseudoVar, id=wxADDSEQVAR)
     4490#    G2frame.dataFrame.Bind(wx.EVT_MENU, DelPseudoVar, id=wxDELSEQVAR)
     4491#    G2frame.dataFrame.Bind(wx.EVT_MENU, EditPseudoVar, id=wxEDITSEQVAR)
     4492#    EnablePseudoVarMenus()
    44444493    # build up the data table one column at a time
    44454494    colList = []
  • trunk/GSASIIobj.py

    r1312 r1322  
    15651565
    15661566         * a name assigned to the parameter
    1567          * a value for to the parameter
    1568          * a derivative step size and
     1567         * a value for to the parameter and
    15691568         * a flag to determine if the variable is refined.
    15701569        '''
     
    15751574        (list of 1-3 str values)'''
    15761575
    1577     def LoadExpression(self,expr,exprVarLst,varSelect,varName,varValue,varStep,varRefflag):
     1576    def LoadExpression(self,expr,exprVarLst,varSelect,varName,varValue,varRefflag):
    15781577        '''Load the expression and associated settings into the object. Raises
    15791578        an exception if the expression is not parsed, if not all functions
     
    15911590        :param dict varName: Defines a name (str) associated with each free parameter
    15921591        :param dict varValue: Defines a value (float) associated with each free parameter
    1593         :param dict varStep: Defines a derivative step size (float) for each
    1594           parameter labels found in the expression
    15951592        :param dict varRefflag: Defines a refinement flag (bool)
    15961593          associated with each free parameter
     
    16051602                    varName.get(v),
    16061603                    varValue.get(v),
    1607                     varStep.get(v),
    16081604                    varRefflag.get(v),
    16091605                    ]
    16101606            else:
    1611                 self.assgnVars[v] = [
    1612                     varName[v],
    1613                     varStep.get(v),
    1614                     ]
     1607                self.assgnVars[v] = varName[v]
    16151608        self.CheckVars()
    16161609
    1617     def EditExpression(self,exprVarLst,varSelect,varName,varValue,varStep,varRefflag):
     1610    def EditExpression(self,exprVarLst,varSelect,varName,varValue,varRefflag):
    16181611        '''Load the expression and associated settings from the object into
    16191612        arrays used for editing.
     
    16241617        :param dict varName: Defines a name (str) associated with each free parameter
    16251618        :param dict varValue: Defines a value (float) associated with each free parameter
    1626         :param dict varStep: Defines a derivative step size (float) for each
    1627           parameter labels found in the expression
    16281619        :param dict varRefflag: Defines a refinement flag (bool)
    16291620          associated with each free parameter
     
    16351626            varName[v] = self.freeVars[v][0]
    16361627            varValue[v] = self.freeVars[v][1]
    1637             varStep[v] = self.freeVars[v][2]
    1638             varRefflag[v] = self.freeVars[v][3]
     1628            varRefflag[v] = self.freeVars[v][2]
    16391629        for v in self.assgnVars:
    16401630            varSelect[v] = 1
    1641             varName[v] = self.assgnVars[v][0]
    1642             varStep[v] = self.assgnVars[v][1]
     1631            varName[v] = self.assgnVars[v]
    16431632        return self.expression
    16441633
    16451634    def GetVaried(self):
    16461635        'Returns the names of the free parameters that will be refined'
    1647         return ["::"+self.freeVars[v][0] for v in self.freeVars if self.freeVars[v][3]]
     1636        return ["::"+self.freeVars[v][0] for v in self.freeVars if self.freeVars[v][2]]
    16481637
    16491638    def GetVariedVarVal(self):
    16501639        'Returns the names and values of the free parameters that will be refined'
    1651         return [("::"+self.freeVars[v][0],self.freeVars[v][1]) for v in self.freeVars if self.freeVars[v][3]]
     1640        return [("::"+self.freeVars[v][0],self.freeVars[v][1]) for v in self.freeVars if self.freeVars[v][2]]
    16521641
    16531642    def UpdateVariedVars(self,varyList,values):
    16541643        'Updates values for the free parameters (after a refinement); only updates refined vars'
    16551644        for v in self.freeVars:
    1656             if not self.freeVars[v][3]: continue
     1645            if not self.freeVars[v][2]: continue
    16571646            if "::"+self.freeVars[v][0] not in varyList: continue
    16581647            indx = varyList.index("::"+self.freeVars[v][0])
     
    16611650    def GetIndependentVars(self):
    16621651        'Returns the names of the required independent parameters used in expression'
    1663         return [self.assgnVars[v][0] for v in self.assgnVars]
     1652        return [self.assgnVars[v] for v in self.assgnVars]
    16641653
    16651654    def CheckVars(self):
     
    18461835        referenced by functions
    18471836        '''
    1848         self.derivStep = {}
    1849         '''Contains step sizes for derivatives for variables used in the expression;
    1850         if a variable is not included in this the derivatives will be computed as zero
    1851         '''
    18521837        self.lblLookup = {}
    18531838        '''Lookup table that specifies the expression label name that is
     
    18871872        # set up the dicts needed to speed computations
    18881873        self.exprDict = {}
    1889         self.derivStep = {}
    18901874        self.lblLookup = {}
    18911875        self.varLookup = {}
     
    18961880            self.varLookup[v] = varname
    18971881            if parmsInList:
    1898                 parmDict[varname] = [self.eObj.freeVars[v][1],self.eObj.freeVars[v][3]]
     1882                parmDict[varname] = [self.eObj.freeVars[v][1],self.eObj.freeVars[v][2]]
    18991883            else:
    19001884                parmDict[varname] = self.eObj.freeVars[v][1]
    19011885            self.exprDict[v] = self.eObj.freeVars[v][1]
    1902             if self.eObj.freeVars[v][3]:
    1903                 self.derivStep[varname] = self.eObj.freeVars[v][2]
    19041886        for v in self.eObj.assgnVars:
    1905             step = self.eObj.assgnVars[v][1]
    1906             varname = self.eObj.assgnVars[v][0]
     1887            varname = self.eObj.assgnVars[v]
    19071888            if '*' in varname:
    19081889                varlist = LookupWildCard(varname,parmDict.keys())
     
    19111892                for var in varlist:
    19121893                    self.lblLookup[var] = v
    1913                     self.derivStep[var] = np.array(
    1914                         [step if var1 == var else 0 for var1 in varlist]
    1915                         )
    19161894                if parmsInList:
    19171895                    self.exprDict[v] = np.array([parmDict[var][0] for var in varlist])
     
    19261904                else:
    19271905                    self.exprDict[v] = parmDict[varname]
    1928                 self.derivStep[varname] = step
    19291906            else:
    19301907                raise Exception,"No value for variable "+str(v)
     
    19611938        return val
    19621939
    1963     def EvalDeriv(self,varname,step=None):
    1964         '''Evaluate the expression derivative with respect to a
    1965         GSAS-II variable name.
    1966 
    1967         :param str varname: a G2 variable name (will not have a wild-card)
    1968         :returns: the derivative
    1969         '''
    1970         if step is None:
    1971             if varname not in self.derivStep: return 0.0
    1972             step = self.derivStep[varname]
    1973         if varname not in self.lblLookup: return 0.0
    1974         lbl = self.lblLookup[varname] # what label does this map to in expression?
    1975         origval = self.exprDict[lbl]
    1976 
    1977         self.exprDict[lbl] = origval + step
    1978         val1 = eval(self.compiledExpr,globals(),self.exprDict)
    1979 
    1980         self.exprDict[lbl] = origval - step
    1981         val2 = eval(self.compiledExpr,globals(),self.exprDict)
    1982 
    1983         self.exprDict[lbl] = origval # reset back to central value
    1984 
    1985         val = (val1 - val2) / (2.*np.max(step))
    1986         if not np.isscalar(val):
    1987             val = np.sum(val)
    1988         return val
    19891940
    19901941if __name__ == "__main__":
     
    19951946        for v in sorted(calcobj.varLookup):
    19961947            print "  ",v,'=',calcobj.exprDict[v],'=',calcobj.varLookup[v]
    1997         print '  Derivatives'
    1998         for v in calcobj.derivStep.keys():
    1999             print '    d(Expr)/d('+v+') =',calcobj.EvalDeriv(v)
     1948        # print '  Derivatives'
     1949        # for v in calcobj.derivStep.keys():
     1950        #     print '    d(Expr)/d('+v+') =',calcobj.EvalDeriv(v)
    20001951
    20011952    obj = ExpressionObj()
    20021953
    20031954    obj.expression = "A*np.exp(B)"
    2004     obj.assgnVars =  {'B': ['0::Afrac:1', 0.0001]}
    2005     obj.freeVars =  {'A': [u'A', 0.5, 0.0001, True]}
     1955    obj.assgnVars =  {'B': '0::Afrac:1'}
     1956    obj.freeVars =  {'A': [u'A', 0.5, True]}
    20061957    #obj.CheckVars()
    20071958    parmDict2 = {'0::Afrac:0':[0.0,True], '0::Afrac:1': [1.0,False]}
     
    20111962
    20121963    obj.expression = "A*np.exp(B)"
    2013     obj.assgnVars =  {'B': ['0::Afrac:*', 0.0001]}
    2014     obj.freeVars =  {'A': [u'Free Prm A', 0.5, 0.0001, True]}
     1964    obj.assgnVars =  {'B': '0::Afrac:*'}
     1965    obj.freeVars =  {'A': [u'Free Prm A', 0.5, True]}
    20151966    #obj.CheckVars()
    20161967    parmDict1 = {'0::Afrac:0':1.0, '0::Afrac:1': 1.0}
  • trunk/GSASIIstrMath.py

    r1320 r1322  
    19801980def errRefine(values,HistoPhases,parmDict,varylist,calcControls,pawleyLookup,dlg):       
    19811981    'Needs a doc string'
    1982     parmDict.update(zip(varylist,values))
    1983     #Values2Dict(parmDict, varylist, values) # BHT -- seems to duplicate previous statement
     1982    Values2Dict(parmDict, varylist, values)
    19841983    G2mv.Dict2Map(parmDict,varylist)
    19851984    Histograms,Phases,restraintDict,rigidbodyDict = HistoPhases
Note: See TracChangeset for help on using the changeset viewer.