Changeset 1312


Ignore:
Timestamp:
Apr 30, 2014 9:42:51 PM (8 years ago)
Author:
toby
Message:

Parametric fit; work on PseudoVars? (more 2 come); minor code cleanups

Location:
trunk
Files:
7 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASII.py

    r1304 r1312  
    33153315        self.main.Show()
    33163316        self.SetTopWindow(self.main)
     3317        # DEBUG: jump to sequential results
     3318        #Id = G2gd.GetPatternTreeItemId(self.main,self.main.root,'Sequential results')
     3319        #self.main.PatternTree.SelectItem(Id)
     3320        # end DEBUG
    33173321        return True
    33183322    def MacOpenFile(self, filename):
  • trunk/GSASIIexprGUI.py

    r1299 r1312  
    6666      If set to False, derivate step values and refinement flags are not shown
    6767      and Free parameters are not offered as an assignment option.
     68    :param str VarLabel: an optional variable label to include before the expression
     69      input. Ignored if None (default)
     70    :param list depVarDict: a dict of choices for the dependent variable to be
     71      fitted to the expression and their values. Ignored if None (default).
    6872    '''
    6973    def __init__(self, parent, parmDict, exprObj=None,
    7074                 header='Enter restraint expression here',
    7175                 wintitle='Expression Editor',
    72                  fit=True):
     76                 fit=True,VarLabel=None,depVarDict=None):
    7377        self.fit = fit
     78        self.depVarDict = depVarDict
    7479        self.parmDict = {}
    7580        '''A copy of the G2 parameter dict (parmDict) except only numerical
     
    102107        self.expr = ''
    103108        'Expression as a text string'
     109        self.depVar = [None,None]
     110        'index # and name for dependent variable selection when depVarDict is specified'
    104111       
    105112        # process dictionary of values and create an index
     
    119126        for i in (1,2,3,4):
    120127            self.parmLists[i] = []
    121         for i in self.parmDict.keys():
     128        for i in sorted(self.parmDict.keys()):
    122129            if i.startswith("::") or i.find(':') == -1: # globals
    123130                self.parmLists[4].append(i)
     
    142149        label = wx.StaticText(self,  wx.ID_ANY, header)
    143150        self.mainsizer.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
     151
     152        self.exsizer = wx.BoxSizer(wx.HORIZONTAL)
     153        if VarLabel:
     154            label = wx.StaticText(self,  wx.ID_ANY, VarLabel + ' = ')
     155            self.exsizer.Add(label, 0, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER_VERTICAL, 0)
     156        elif depVarDict:
     157            choice = G2gd.G2ChoiceButton(
     158                self,
     159                sorted(depVarDict.keys()),
     160                self.depVar,0,
     161                self.depVar,1,
     162                self.RestartTimer)
     163            self.exsizer.Add(choice, 0, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER_VERTICAL, 0)
     164            label = wx.StaticText(self,  wx.ID_ANY, ' = ')
     165            self.exsizer.Add(label, 0, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER_VERTICAL, 0)
     166
    144167        self.exCtrl = wx.TextCtrl(self,  wx.ID_ANY, size=(150,-1),style=wx.TE_PROCESS_ENTER)
    145168        self.exCtrl.Bind(wx.EVT_CHAR, self.OnChar)
    146169        self.exCtrl.Bind(wx.EVT_TEXT_ENTER, self.OnValidate)
    147         self.mainsizer.Add(self.exCtrl, 0, wx.ALL|wx.EXPAND, 5)
     170        self.exsizer.Add(self.exCtrl, 1, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER_VERTICAL, 0)
     171        #self.mainsizer.Add(self.exCtrl, 0, wx.ALL|wx.EXPAND, 5)
     172        self.mainsizer.Add(self.exsizer, 0, wx.ALL|wx.EXPAND, 5)
    148173        self.mainsizer.Add((-1,5),0,wx.EXPAND,1)
    149174
     
    180205                self.varRefflag,
    181206                )
     207            # set the initial value for the dependent value
     208            if self.depVarDict:
     209                var = exprObj.GetDepVar()
     210                if var in self.depVarDict:
     211                    indx = sorted(self.depVarDict.keys()).index(var)
     212                    choice.SetSelection(indx)
     213                    self.depVar = [indx,var]
     214                   
    182215        self.exCtrl.SetValue(self.expr)
    183216        self.OnValidate(None)
     
    207240                self.varStep,
    208241                self.varRefflag,
    209                 )               
     242                )
     243            if self.depVarDict:
     244                exprObj.SetDepVar(self.depVar[1])
    210245            return exprObj
    211246        else:
     
    216251        self.result.SetLabel(msg)
    217252
     253    def RestartTimer(self):
     254        '''Cancels any running timer and starts a new one.
     255        The timer causes a check of syntax after 2 seconds unless there is further input.
     256        Disables the OK button until a validity check is complete.
     257        '''
     258        if self.timer.IsRunning():
     259            self.timer.Stop()
     260        self.timer.Start(2000,oneShot=True)
     261       
    218262    def OnChar(self,event):
    219263        '''Called as each character is entered. Cancels any running timer
     
    222266        Disables the OK button until a validity check is complete.
    223267        '''
    224         if self.timer.IsRunning():
    225             self.timer.Stop()
    226         self.timer.Start(2000,oneShot=True)
     268        self.RestartTimer()
    227269        self.OKbtn.Disable()
    228270        event.Skip()
     
    311353            0,wx.ALIGN_CENTER)
    312354        lbls = ('varib. type\nselection','variable\nname','value')
     355        self.choices = ['Free','Phase','Hist./Phase','Hist.','Global']
    313356        if self.fit:
    314357            lbls += ('derivative\nstep','refine\nflag')
    315             self.choices = ('Free','Phase','Hist./Phase','Hist.',
    316                            'Global')
    317358        else:
    318359            lbls += ('','')
    319             self.choices = ('','Phase','Hist./Phase','Hist.',
    320                            'Global')
     360            self.choices[0] = ''
     361        for i in (1,2,3,4): # remove empty menus from choice list
     362            if not len(self.parmLists[i]): self.choices[i] = ''
     363
    321364        for lbl in lbls:
    322365            w = wx.StaticText(self.varbox,wx.ID_ANY,lbl,style=wx.CENTER)
     
    365408                    vs = G2obj.LookupWildCard(var,self.parmDict.keys())
    366409                    s = '('+str(len(vs))+' values)'
    367                 else:
     410                elif var in self.parmDict:
    368411                    val = self.parmDict[var]
    369412                    s = G2py3.FormatSigFigs(val).rstrip('0')
     413                else:
     414                    s = '?'
    370415                wid = wx.StaticText(self.varbox,wx.ID_ANY,s)
    371416                GridSiz.Add(wid,0,wx.ALIGN_LEFT,0)
     
    399444        self.Layout()
    400445        return
     446
     447    def GetDepVar(self):
     448        '''Returns the name of the dependent variable, when depVarDict is used.
     449        '''
     450        return self.depVar[1]
    401451       
    402452    def OnChoice(self,event):
     
    534584            return
    535585        s = G2py3.FormatSigFigs(val).rstrip('0')
    536         self.setEvalResult("Expression evaluates to: "+str(s))
     586        depVal = ""
     587        if self.depVarDict:
     588            if not self.depVar[1]:
     589                self.setEvalResult("A dependent variable must be selected.")
     590                return
     591            depVal = '; Variable "' + self.depVar[1] + '" = ' + str(
     592                self.depVarDict.get(self.depVar[1],'?')
     593                )
     594        self.setEvalResult("Expression evaluates to: "+str(s)+depVal)
    537595        self.OKbtn.Enable()
    538596       
    539597if __name__ == "__main__":
     598    app = wx.PySimpleApp() # create the App
     599    frm = wx.Frame(None)
     600    frm.Show()
     601    PSvarDict = {'::a':1.0,'::b':1.1,'0::c':1.2}
     602    #PSvars = PSvarDict.keys()
     603    indepvarDict = {'Temperature':1.0,'Pressure':1.1,'Phase of Moon':1.2}
     604    dlg = ExpressionDialog(frm,indepvarDict,
     605                           header="Edit the PseudoVar expression",
     606                           fit=False,
     607                           depVarDict=PSvarDict,
     608                           #VarLabel="New PseudoVar",                           
     609                           )
     610    print dlg.GetDepVar()
     611    newobj = dlg.Show(True)
     612    print dlg.GetDepVar()
     613    dlg = ExpressionDialog(frm,PSvarDict,
     614                           header="Edit the PseudoVar expression",
     615                           fit=True)
     616    newobj = dlg.Show(True)
     617    print dlg.GetDepVar()
     618    import sys
     619    sys.exit()
     620
     621    #app.MainLoop()
     622
     623
    540624    import cPickle
    541625    def showEQ(calcobj):
  • trunk/GSASIIgrid.py

    r1306 r1312  
    2222import cPickle
    2323import sys
     24import os
    2425import numpy as np
    2526import numpy.ma as ma
    26 import os
     27import scipy.optimize as so
    2728import wx.html        # could postpone this for quicker startup
    2829import webbrowser     # could postpone this for quicker startup
     
    759760class G2CheckBox(wx.CheckBox):
    760761    '''A customized version of a CheckBox that automatically initializes
    761     the control to match a supplied
     762    the control to a supplied list or dict entry and updates that
     763    entry as the widget is used.
    762764
    763765    :param wx.Panel parent: name of panel or frame that will be
    764       the parent to the TextCtrl. Can be None.
     766      the parent to the widget. Can be None.
    765767    :param str label: text to put on check button
    766768    :param dict/list loc: the dict or list with the initial value to be
     
    780782    def _OnCheckBox(self,event):
    781783        self.loc[self.key] = self.GetValue()
     784################################################################################
     785class G2ChoiceButton(wx.Choice):
     786    '''A customized version of a wx.Choice that automatically initializes
     787    the control to match a supplied value and saves the choice directly
     788    into an array or list. Optionally a function can be called each time a
     789    choice is selected.
     790
     791    :param wx.Panel parent: name of panel or frame that will be
     792      the parent to the widget. Can be None.
     793    :param list choiceList: a list or tuple of choices to offer the user.
     794    :param dict/list indLoc: a dict or list with the initial value to be
     795      placed in the Choice button.
     796    :param int/str indKey: the dict key or the list index for the value to be
     797      edited by the Choice button. The ``indLoc[indKey]`` element must exist.
     798      The value for this should be None or an integer in range(len(choiceList)).
     799      The Choice button will be initialized to the choice corresponding to the
     800      value in this element if not None.
     801    :param dict/list strLoc: a dict or list with the string value corresponding to
     802      indLoc/indKey. Default (None) means that this is not used.
     803    :param int/str strKey: the dict key or the list index for the string value
     804      The ``strLoc[strKey]`` element must exist or strLoc must be None (default).
     805    :param function onChoice: name of a   
     806    '''
     807    def __init__(self,parent,choiceList,indLoc,indKey,strLoc=None,strKey=None,
     808                 onChoice=None,**kwargs):
     809        wx.Choice.__init__(self,parent,choices=choiceList,id=wx.ID_ANY,**kwargs)
     810        self.choiceList = choiceList
     811        self.indLoc = indLoc
     812        self.indKey = indKey
     813        self.strLoc = strLoc
     814        self.strKey = strKey
     815        self.onChoice = None
     816        if self.indLoc[self.indKey] is not None:
     817            self.SetSelection(self.indLoc[self.indKey])
     818        else:
     819            self.SetSelection(wx.NOT_FOUND)
     820        self.Bind(wx.EVT_CHOICE, self._OnChoice)
     821        if self.strLoc is not None: # make sure strLoc gets initialized
     822            self._OnChoice(None) # note that onChoice will not be called
     823        self.onChoice = onChoice
     824    def _OnChoice(self,event):
     825        self.indLoc[self.indKey] = self.GetSelection()
     826        if self.strLoc is not None:
     827            self.strLoc[self.strKey] = self.GetStringSelection()
     828        if self.onChoice:
     829            self.onChoice()
    782830################################################################################   
    783831def CallScrolledMultiEditor(parent,dictlst,elemlst,prelbl=[],postlbl=[],
     
    37343782        'strip a histogram number from a var name'
    37353783        sv = var.split(':')
     3784        if len(sv) <= 1: return var
    37363785        sv[1] = insChar
    37373786        return ':'.join(sv)
     
    37923841        'Edit an existing expression'
    37933842        choices = Controls['SeqPseudoVars'].keys()
    3794         parmDict = dict(zip(colLabels,zip(*colList)[0]))
    37953843        if len(choices) == 1:
    3796             selected = [0]
     3844            selected = 0
    37973845        else:
    37983846            selected = ItemSelector(
     
    38023850                header='Edit expression')
    38033851        if selected is not None:
    3804             dlg = G2exG.ExpressionDialog(G2frame.dataDisplay,parmDict,
    3805                                          Controls['SeqPseudoVars'][choices[selected]],
    3806                                          header="Edit this expression's formula",
    3807                                          fit=False)
     3852            dlg = G2exG.ExpressionDialog(
     3853                G2frame.dataDisplay,PSvarDict,
     3854                Controls['SeqPseudoVars'][choices[selected]],
     3855                header="Edit the PseudoVar expression",
     3856                VarLabel="PseudoVar #"+str(selected+1),
     3857                fit=False)
    38083858            newobj = dlg.Show(True)
    38093859            if newobj:
     
    38153865    def AddNewSeqExpression(event):
    38163866        'Create a new expression'
    3817         parmDict = dict(zip(colLabels,zip(*colList)[0]))
    3818         dlg = G2exG.ExpressionDialog(G2frame.dataDisplay,parmDict,
    3819                                      header='Enter an expression here',
    3820                                      fit=False)
     3867        dlg = G2exG.ExpressionDialog(
     3868            G2frame.dataDisplay,PSvarDict,
     3869            header='Enter an expression for a PseudoVar here',
     3870            VarLabel = "New PseudoVar",
     3871            fit=False)
    38213872        obj = dlg.Show(True)
    38223873        dlg.Destroy()
     
    38533904        'Edit an existing function'
    38543905        choices = Controls['SeqParFitFxns'].keys()
    3855         parmDict = dict(zip(colLabels,zip(*colList)[0]))
    38563906        if len(choices) == 1:
    3857             selected = [0]
     3907            selected = 0
    38583908        else:
    38593909            selected = ItemSelector(
     
    38643914        if selected is not None:
    38653915            dlg = G2exG.ExpressionDialog(
    3866                 G2frame.dataDisplay,parmDict,
     3916                G2frame.dataDisplay,indepVarDict,
    38673917                Controls['SeqParFitFxns'][choices[selected]],
     3918                depVarDict=depVarDict,
    38683919                header="Edit this minimization function's formula")
    38693920            newobj = dlg.Show(True)
     
    38753926
    38763927    def AddNewParFitFxn(event):
    3877         'Create a new expression'
    3878         parmDict = dict(zip(colLabels,zip(*colList)[0]))
     3928        'Create a new expression to be fit to sequential results'
    38793929        dlg = G2exG.ExpressionDialog(
    3880             G2frame.dataDisplay,parmDict,
     3930            G2frame.dataDisplay,indepVarDict,
     3931            depVarDict=depVarDict,
    38813932            header='Enter a function to minimize in the parametric fit')
    38823933        obj = dlg.Show(True)
     
    38873938            EnableParFitFxnMenus()
    38883939
     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
     3944        result = []
     3945        for calcobj in calcObjList:
     3946            calcobj.UpdateVars(varyList,values)
     3947            result.append((calcobj.depVal-calcobj.EvalExpression())/calcobj.depSig)
     3948        return result
     3949
    38893950    def DoParFit(event):
    3890         print 'This is the future home for the parametric fit minimizer'
     3951        'Parametric fit minimizer'
     3952        varyValueDict = {} # dict of variables and their initial values
     3953        calcObjList = [] # expression objects, ready to go for each data point
    38913954        for expr in Controls['SeqParFitFxns']:
    3892             print expr
    38933955            obj = Controls['SeqParFitFxns'][expr]
     3956            # assemble refined vars for this equation
     3957            varyValueDict.update({var:val for var,val in obj.GetVariedVarVal()})
     3958            # lookup dependent var position
     3959            depVar = obj.GetDepVar()
     3960            if depVar in colLabels:
     3961                indx = colLabels.index(depVar)
     3962            else:
     3963                raise Exception('Dependent variable '+depVar+' not found')
     3964            # assemble a list of the independent variables
     3965            indepVars = obj.GetIndependentVars()
     3966            # loop over each datapoint
     3967            for j,row in enumerate(zip(*colList)):
     3968                # assemble equations to fit
     3969                calcobj = G2obj.ExpressionCalcObj(obj)
     3970                # prepare a dict of needed independent vars for this expression
     3971                indepVarDict = {var:row[i] for i,var in enumerate(colLabels) if var in indepVars}
     3972                calcobj.SetupCalc(indepVarDict)               
     3973                # values and sigs for current value of dependent var
     3974                calcobj.depVal = row[indx]
     3975                calcobj.depSig = colSigs[indx][j]
     3976                calcObjList.append(calcobj)
     3977        # varied parameters
     3978        varyList = varyValueDict.keys()
     3979        varyValues = [varyValueDict[key] for key in varyList]
     3980        result = so.leastsq(ParEval,varyValues,full_output=True,   #ftol=Ftol,
     3981                            args=(calcObjList,varyList)
     3982                            )
     3983        # create a plot for each parametric variable
     3984        values = result[0]
     3985        covar = result[1]
     3986        print 'Fit Results'
     3987        for i,(var,val) in enumerate(zip(varyList,values)):
     3988            print '  ',var,' =',G2mth.ValEsd(val,np.sqrt(covar[i,i]))
     3989        for fitnum,expr in enumerate(Controls['SeqParFitFxns']):
     3990            obj = Controls['SeqParFitFxns'][expr]
     3991            obj.UpdateVariedVars(varyList,values)
    38943992            calcobj = G2obj.ExpressionCalcObj(obj)
    3895             for row in zip(*colList):
    3896                 parmDict = dict(zip(colLabels,row))
    3897 
    3898 
     3993            # lookup dependent var position
     3994            indx = colLabels.index(obj.GetDepVar())
     3995            # assemble a list of the independent variables
     3996            indepVars = obj.GetIndependentVars()           
     3997            # loop over each datapoint
     3998            fitvals = []
     3999            for j,row in enumerate(zip(*colList)):
     4000                calcobj.SetupCalc(
     4001                    {var:row[i] for i,var in enumerate(colLabels) if var in indepVars}
     4002                    )
     4003                fitvals.append(calcobj.EvalExpression())
     4004            G2plt.PlotSelectedSequence(G2frame,[indx],GetColumnInfo,SelectXaxis,
     4005                                           fitnum,fitvals)
     4006                               
    38994007    #======================================================================
    39004008    # start processing sequential results here
     
    39304038            ESDlookup[newCellDict[item][0]] = item
    39314039            Dlookup[item] = newCellDict[item][0]
     4040    # 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]
    39324045
    39334046    # get unit cell & symmetry for all phases
     
    39754088    Types = []
    39764089    nRows = len(histNames)
    3977     # add Rwp values
     4090    # start with Rwp values
    39784091    colList += [[data[name]['Rvals']['Rwp'] for name in histNames]]
    39794092    colSigs += [None]
     
    39864099    Types += [wg.GRID_VALUE_FLOAT,]
    39874100    deltaChiCol = len(colLabels)-1
    3988 
    3989     # adds checkbox for converged (Bob wants to change color of previous instead)
    3990     # colList += [[data[name]['Rvals']['converged'] for name in histNames]]
    3991     # colSigs += [None]
    3992     # colLabels += ['Cnvg']
    3993     # Types += [wg.GRID_VALUE_BOOL,]
    3994 
    3995     # add sample parameters
     4101    # add changing sample parameters to table
    39964102    for key in sampleParms:
    39974103        colList += [sampleParms[key]]
     
    39994105        colLabels += [key]
    40004106        Types += [wg.GRID_VALUE_FLOAT,]
    4001 
    4002     # add cell parameters
     4107    # add unique cell parameters
    40034108    for pId in sorted(Alist):
    40044109        pfx = str(pId)+'::' # prefix for A values from phase
     
    40064111        cellESDs = []
    40074112        colLabels += [pfx+cellUlbl[i] for i in uniqCellParms[pId]]
    4008         Types += len(uniqCellParms[pId])*[wg.GRID_VALUE_FLOAT,]
     4113        colLabels += [pfx+'Vol']
     4114        Types += (1+len(uniqCellParms[pId]))*[wg.GRID_VALUE_FLOAT,]
    40094115        for name in histNames:
    40104116            covData['varyList'] = [Dlookup.get(striphist(v),v) for v in data[name]['varyList']]
     
    40244130            # convert to direct cell & add only unique values to table
    40254131            c = G2lat.A2cell(A)
     4132            vol = G2lat.calc_V(A)
    40264133            cE = G2stIO.getCellEsd(pfx,SGdata[pId],A,covData)
    4027             cells += [[c[i] for i in uniqCellParms[pId]]]
    4028             cellESDs += [[cE[i] for i in uniqCellParms[pId]]]
     4134            cells += [[c[i] for i in uniqCellParms[pId]]+[vol]]
     4135            cellESDs += [[cE[i] for i in uniqCellParms[pId]]+[cE[-1]]]
    40294136        colList += zip(*cells)
    40304137        colSigs += zip(*cellESDs)
    4031 
    40324138    # add the variables that were refined; change from rows to columns
    40334139    colList += zip(*[data[name]['variables'] for name in histNames])
     
    40354141    Types += len(data[histNames[0]]['varyList'])*[wg.GRID_VALUE_FLOAT]
    40364142    colSigs += zip(*[data[name]['sig'] for name in histNames])
    4037    
     4143
    40384144    # process the dependent constrained variables, removing histogram numbers if needed
    40394145    # from parameter label
     
    40504156               depValDict[svar].append(val)
    40514157               depSigDict[svar].append(sig)
    4052                
    40534158    # add the dependent constrained variables
    40544159    for var in sorted(depValDict):
     
    40594164        colList += [depValDict[var]]
    40604165
    4061     # add atom parameters to list
     4166    # add atom parameters to table
    40624167    colLabels += atomList.keys()
    40634168    Types += len(atomList)*[wg.GRID_VALUE_FLOAT]
    4064     for parm in atomList:
     4169    for parm in sorted(atomList):
    40654170        colList += [[data[name]['newAtomDict'][atomList[parm]][1] for name in histNames]]
    4066         colSigs += [None]   #why not the values?
    4067     # add Pseudovars
     4171        if atomList[parm] in data[histNames[0]]['varyList']:
     4172            col = data[histNames[0]]['varyList'].index(atomList[parm])
     4173            colSigs += [[data[name]['sig'][col] for name in histNames]]
     4174        else:
     4175            colSigs += [None] # should not happen
     4176    # 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)
     4180    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
     4183    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}
     4189    indepVarDict = {     #  values in table w/o ESDs
     4190        var:colList[i][0] for i,var in enumerate(colLabels) if colSigs[i] is None
     4191        }
     4192    PSvarDict.update(indepVarDict) # add values in table w/o ESDs
     4193    # make dict of dependent vars (w/ESDs) that are not converted (Dij to Ak or dAx to Ax)
     4194    depVarDict = {
     4195        var:colList[i][0] for i,var in enumerate(colLabels)
     4196        if colSigs[i] is not None and striphist(var) not in Dlookup
     4197        }
     4198    # add recip cell coeff. values
     4199    depVarDict.update({var:val for var,val in data[name]['newCellDict'].values()})
     4200    # evaluate Pseudovars and add them to grid
    40684201    for expr in Controls['SeqPseudoVars']:
    40694202        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]
    40704206        calcobj = G2obj.ExpressionCalcObj(obj)
    40714207        valList = []
    4072         for row in zip(*colList):
     4208        esdList = []
     4209        for j,row in enumerate(zip(*colList)):
     4210            name = histNames[j]
    40734211            parmDict = dict(zip(colLabels,row))
    4074             calcobj.SetupCalc(parmDict)
     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)
    40754223            valList.append(calcobj.EvalExpression())
    4076         colSigs += [None]
     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))))
    40774230        colList += [valList]
     4231        colSigs += [esdList]
    40784232        colLabels += [expr]
    40794233        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
    40804278    rowList = [c for c in zip(*colList)]     # convert from columns to rows
    40814279    G2frame.SeqTable = Table(rowList,colLabels=colLabels,rowLabels=histNames,types=Types)
     
    40964294   
    40974295    G2frame.dataDisplay = GSGrid(parent=G2frame.dataFrame)
    4098     # colSigs += [None]
    4099     # colLabels += ['Cnvg']
    4100     # Types += [wg.GRID_VALUE_BOOL,]
    41014296    G2frame.dataDisplay.SetTable(G2frame.SeqTable, True)
    41024297    G2frame.dataDisplay.EnableEditing(False)
     
    41164311        elif deltaChi > 1.0:
    41174312            G2frame.dataDisplay.SetCellStyle(row,deltaChiCol,color=wx.Color(255,255,0))
    4118         # colList += [[data[name]['Rvals']['converged'] for name in histNames]]
    4119        
     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'
     4338
    41204339def UpdateSASDSeqResults(G2frame,data,prevSize=None):
    41214340   
     
    42494468    colSigs += zip(*[data[name]['sig'] for name in histNames])
    42504469#    # add Pseudovars
    4251 #    for exp in Controls['SeqPseudoVars']:
    4252 #        obj = Controls['SeqPseudoVars'][exp]
     4470#    for expr in Controls['SeqPseudoVars']:
     4471#        obj = Controls['SeqPseudoVars'][expr]
    42534472#        calcobj = G2obj.ExpressionCalcObj(obj)
    42544473#        valList = []
     
    42594478#        colList += [valList]
    42604479#        colSigs += [None]
    4261 #        colLabels += [exp]
     4480#        colLabels += [expr]
    42624481#        Types += [wg.GRID_VALUE_FLOAT,]
    42634482
  • trunk/GSASIIobj.py

    r1298 r1312  
    12421242        'Vol' : 'Unit cell volume',
    12431243        # Atom vars (p::<var>:a)
    1244         'dA([xyz])' : 'change to atomic position \\1',
     1244        'dA([xyz])' : 'change to atomic coordinate, \\1',
     1245        'A([xyz])$' : '\\1 fractional atomic coordinate',
    12451246        'AUiso':'Atomic isotropic displacement parameter',
    12461247        'AU([123][123])':'Atomic anisotropic displacement parameter U\\1',
     
    15681569         * a flag to determine if the variable is refined.
    15691570        '''
     1571        self.depVar = None
    15701572
    15711573        self.lastError = ('','')
     
    16451647        return ["::"+self.freeVars[v][0] for v in self.freeVars if self.freeVars[v][3]]
    16461648
     1649    def GetVariedVarVal(self):
     1650        '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]]
     1652
     1653    def UpdateVariedVars(self,varyList,values):
     1654        'Updates values for the free parameters (after a refinement); only updates refined vars'
     1655        for v in self.freeVars:
     1656            if not self.freeVars[v][3]: continue
     1657            if "::"+self.freeVars[v][0] not in varyList: continue
     1658            indx = varyList.index("::"+self.freeVars[v][0])
     1659            self.freeVars[v][1] = values[indx]
     1660
     1661    def GetIndependentVars(self):
     1662        'Returns the names of the required independent parameters used in expression'
     1663        return [self.assgnVars[v][0] for v in self.assgnVars]
     1664
    16471665    def CheckVars(self):
    16481666        '''Check that the expression can be parsed, all functions are
     
    16851703        to the save.
    16861704
    1687         :returns: a list of variables used variables
     1705        :returns: a list of used variables
    16881706        '''
    16891707        self.lastError = ('','')
     
    17051723                    return pkgdict,fxnobj
    17061724                except (AttributeError, NameError):
    1707                     return None
     1725                    return None,None
    17081726            else:
    17091727                try:
     
    18041822        return varlist,pkgdict
    18051823
     1824    def GetDepVar(self):
     1825        'return the dependent variable, or None'
     1826        return self.depVar
     1827
     1828    def SetDepVar(self,var):
     1829        'Set the dependent variable, if used'
     1830        self.depVar = var
    18061831#==========================================================================
    18071832class ExpressionCalcObj(object):
     
    19061931        self.exprDict.update(self.fxnpkgdict)
    19071932
     1933    def UpdateVars(self,varList,valList):
     1934        '''Update the dict for the expression with a set of values
     1935        :param list varList: a list of variable names
     1936        :param list valList: a list of corresponding values
     1937        '''
     1938        for var,val in zip(varList,valList):
     1939            self.exprDict[self.lblLookup.get(var,'undefined: '+var)] = val
     1940           
    19081941    def EvalExpression(self):
    19091942        '''Evaluate an expression. Note that the expression
     
    19121945        :returns: a single value for the expression. If parameter
    19131946        values are arrays (for example, from wild-carded variable names),
    1914         the sum of the resulting expression is return.
     1947        the sum of the resulting expression is returned.
    19151948
    19161949        For example, if the expression is ``'A*B'``,
     
    19281961        return val
    19291962
    1930     def EvalDeriv(self,varname):
     1963    def EvalDeriv(self,varname,step=None):
    19311964        '''Evaluate the expression derivative with respect to a
    19321965        GSAS-II variable name.
     
    19351968        :returns: the derivative
    19361969        '''
    1937         if varname not in self.derivStep: return 0.0
     1970        if step is None:
     1971            if varname not in self.derivStep: return 0.0
     1972            step = self.derivStep[varname]
    19381973        if varname not in self.lblLookup: return 0.0
    1939         step = self.derivStep[varname]
    19401974        lbl = self.lblLookup[varname] # what label does this map to in expression?
    19411975        origval = self.exprDict[lbl]
  • trunk/GSASIIplot.py

    r1306 r1312  
    22992299##### PlotSeq
    23002300################################################################################
    2301 def PlotSelectedSequence(G2frame,ColumnList,TableGet,SelectX):
     2301def PlotSelectedSequence(G2frame,ColumnList,TableGet,SelectX,fitnum=None,fitvals=None):
    23022302    '''Plot a result from a sequential refinement
    23032303
     
    23102310      number (or None) as the X-axis selection
    23112311    '''
    2312     G2frame.seqYaxisList = ColumnList
    2313     G2frame.seqTableGet = TableGet
    23142312    G2frame.seqXselect = SelectX
    23152313    try:
     
    23292327            G2frame.seqXaxis = G2frame.seqXselect()
    23302328            Draw()
     2329    if fitnum is None:
     2330        label = 'Sequential refinement'
     2331    else:
     2332        label = 'Parametric fit #'+str(fitnum+1)
    23312333    try:
    2332         plotNum = G2frame.G2plotNB.plotList.index('Sequential refinement')
     2334        plotNum = G2frame.G2plotNB.plotList.index(label)
    23332335        Page = G2frame.G2plotNB.nb.GetPage(plotNum)
    23342336        Page.figure.clf()
     
    23372339            Page.Show()
    23382340    except ValueError:
    2339         Plot = G2frame.G2plotNB.addMpl('Sequential refinement').gca()
    2340         plotNum = G2frame.G2plotNB.plotList.index('Sequential refinement')
     2341        Plot = G2frame.G2plotNB.addMpl(label).gca()
     2342        plotNum = G2frame.G2plotNB.plotList.index(label)
    23412343        Page = G2frame.G2plotNB.nb.GetPage(plotNum)
    23422344        Page.canvas.mpl_connect('key_press_event', OnKeyPress)
     
    23442346    Page.Choice = ['s to select plot x-axis']
    23452347    Page.keyPress = OnKeyPress
     2348    Page.seqYaxisList = ColumnList
     2349    Page.seqTableGet = TableGet
     2350    Page.fitvals = fitvals
    23462351       
    23472352    def Draw():
     
    23502355        Plot.clear()
    23512356        if G2frame.seqXaxis is not None:   
    2352             xName,X,Xsig = G2frame.seqTableGet(G2frame.seqXaxis)
     2357            xName,X,Xsig = Page.seqTableGet(G2frame.seqXaxis)
    23532358        else:
    23542359            X = np.arange(0,G2frame.SeqTable.GetNumberRows(),1)
    23552360            xName = 'Data sequence number'
    2356         for col in G2frame.seqYaxisList:
    2357             name,Y,sig = G2frame.seqTableGet(col)
     2361        for col in Page.seqYaxisList:
     2362            name,Y,sig = Page.seqTableGet(col)
    23582363            if sig:
    23592364                Plot.errorbar(X,Y,yerr=sig,label=name)
     
    23612366                Plot.plot(X,Y)
    23622367                Plot.plot(X,Y,'o',label=name)
     2368        if Page.fitvals:
     2369                Plot.plot(X,fitvals)
     2370                Plot.plot(X,fitvals,'*',label='Fit')
     2371           
    23632372        Plot.legend(loc='best')
    23642373        Plot.set_ylabel('Parameter values')
  • trunk/GSASIIstrIO.py

    r1299 r1312  
    12781278    var = np.diag(sigMat)
    12791279    CS = np.where(var>0.,np.sqrt(var),0.)
    1280     cellSig = [CS[0],CS[1],CS[2],CS[5],CS[4],CS[3],sigVol]  #exchange sig(alp) & sig(gam) to get in right order
    1281     return cellSig           
     1280    return [CS[0],CS[1],CS[2],CS[5],CS[4],CS[3],sigVol]  #exchange sig(alp) & sig(gam) to get in right order
    12821281   
    12831282def SetPhaseData(parmDict,sigDict,Phases,RBIds,covData,RestraintDict=None,pFile=None):
  • trunk/GSASIIstrMath.py

    r1308 r1312  
    859859    return [parmdict[key] for key in varylist]
    860860   
    861 def Values2Dict(parmdict, varylist, values):
    862     ''' Use after call to leastsq to update the parameter dictionary with
    863     values corresponding to keys in varylist'''
    864     parmdict.update(zip(varylist,values))
     861#def Values2Dict(parmdict, varylist, values):
     862#    ''' Use after call to leastsq to update the parameter dictionary with
     863#    values corresponding to keys in varylist'''
     864#    parmdict.update(zip(varylist,values))
    865865   
    866866def GetNewCellParms(parmDict,varyList):
     
    19811981    'Needs a doc string'
    19821982    parmDict.update(zip(varylist,values))
    1983     Values2Dict(parmDict, varylist, values)
     1983    #Values2Dict(parmDict, varylist, values) # BHT -- seems to duplicate previous statement
    19841984    G2mv.Dict2Map(parmDict,varylist)
    19851985    Histograms,Phases,restraintDict,rigidbodyDict = HistoPhases
Note: See TracChangeset for help on using the changeset viewer.