Changeset 1312
- Timestamp:
- Apr 30, 2014 9:42:51 PM (10 years ago)
- Location:
- trunk
- Files:
-
- 7 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/GSASII.py
r1304 r1312 3315 3315 self.main.Show() 3316 3316 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 3317 3321 return True 3318 3322 def MacOpenFile(self, filename): -
trunk/GSASIIexprGUI.py
r1299 r1312 66 66 If set to False, derivate step values and refinement flags are not shown 67 67 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). 68 72 ''' 69 73 def __init__(self, parent, parmDict, exprObj=None, 70 74 header='Enter restraint expression here', 71 75 wintitle='Expression Editor', 72 fit=True ):76 fit=True,VarLabel=None,depVarDict=None): 73 77 self.fit = fit 78 self.depVarDict = depVarDict 74 79 self.parmDict = {} 75 80 '''A copy of the G2 parameter dict (parmDict) except only numerical … … 102 107 self.expr = '' 103 108 'Expression as a text string' 109 self.depVar = [None,None] 110 'index # and name for dependent variable selection when depVarDict is specified' 104 111 105 112 # process dictionary of values and create an index … … 119 126 for i in (1,2,3,4): 120 127 self.parmLists[i] = [] 121 for i in s elf.parmDict.keys():128 for i in sorted(self.parmDict.keys()): 122 129 if i.startswith("::") or i.find(':') == -1: # globals 123 130 self.parmLists[4].append(i) … … 142 149 label = wx.StaticText(self, wx.ID_ANY, header) 143 150 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 144 167 self.exCtrl = wx.TextCtrl(self, wx.ID_ANY, size=(150,-1),style=wx.TE_PROCESS_ENTER) 145 168 self.exCtrl.Bind(wx.EVT_CHAR, self.OnChar) 146 169 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) 148 173 self.mainsizer.Add((-1,5),0,wx.EXPAND,1) 149 174 … … 180 205 self.varRefflag, 181 206 ) 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 182 215 self.exCtrl.SetValue(self.expr) 183 216 self.OnValidate(None) … … 207 240 self.varStep, 208 241 self.varRefflag, 209 ) 242 ) 243 if self.depVarDict: 244 exprObj.SetDepVar(self.depVar[1]) 210 245 return exprObj 211 246 else: … … 216 251 self.result.SetLabel(msg) 217 252 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 218 262 def OnChar(self,event): 219 263 '''Called as each character is entered. Cancels any running timer … … 222 266 Disables the OK button until a validity check is complete. 223 267 ''' 224 if self.timer.IsRunning(): 225 self.timer.Stop() 226 self.timer.Start(2000,oneShot=True) 268 self.RestartTimer() 227 269 self.OKbtn.Disable() 228 270 event.Skip() … … 311 353 0,wx.ALIGN_CENTER) 312 354 lbls = ('varib. type\nselection','variable\nname','value') 355 self.choices = ['Free','Phase','Hist./Phase','Hist.','Global'] 313 356 if self.fit: 314 357 lbls += ('derivative\nstep','refine\nflag') 315 self.choices = ('Free','Phase','Hist./Phase','Hist.',316 'Global')317 358 else: 318 359 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 321 364 for lbl in lbls: 322 365 w = wx.StaticText(self.varbox,wx.ID_ANY,lbl,style=wx.CENTER) … … 365 408 vs = G2obj.LookupWildCard(var,self.parmDict.keys()) 366 409 s = '('+str(len(vs))+' values)' 367 el se:410 elif var in self.parmDict: 368 411 val = self.parmDict[var] 369 412 s = G2py3.FormatSigFigs(val).rstrip('0') 413 else: 414 s = '?' 370 415 wid = wx.StaticText(self.varbox,wx.ID_ANY,s) 371 416 GridSiz.Add(wid,0,wx.ALIGN_LEFT,0) … … 399 444 self.Layout() 400 445 return 446 447 def GetDepVar(self): 448 '''Returns the name of the dependent variable, when depVarDict is used. 449 ''' 450 return self.depVar[1] 401 451 402 452 def OnChoice(self,event): … … 534 584 return 535 585 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) 537 595 self.OKbtn.Enable() 538 596 539 597 if __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 540 624 import cPickle 541 625 def showEQ(calcobj): -
trunk/GSASIIgrid.py
r1306 r1312 22 22 import cPickle 23 23 import sys 24 import os 24 25 import numpy as np 25 26 import numpy.ma as ma 26 import os27 import scipy.optimize as so 27 28 import wx.html # could postpone this for quicker startup 28 29 import webbrowser # could postpone this for quicker startup … … 759 760 class G2CheckBox(wx.CheckBox): 760 761 '''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. 762 764 763 765 :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. 765 767 :param str label: text to put on check button 766 768 :param dict/list loc: the dict or list with the initial value to be … … 780 782 def _OnCheckBox(self,event): 781 783 self.loc[self.key] = self.GetValue() 784 ################################################################################ 785 class 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() 782 830 ################################################################################ 783 831 def CallScrolledMultiEditor(parent,dictlst,elemlst,prelbl=[],postlbl=[], … … 3734 3782 'strip a histogram number from a var name' 3735 3783 sv = var.split(':') 3784 if len(sv) <= 1: return var 3736 3785 sv[1] = insChar 3737 3786 return ':'.join(sv) … … 3792 3841 'Edit an existing expression' 3793 3842 choices = Controls['SeqPseudoVars'].keys() 3794 parmDict = dict(zip(colLabels,zip(*colList)[0]))3795 3843 if len(choices) == 1: 3796 selected = [0]3844 selected = 0 3797 3845 else: 3798 3846 selected = ItemSelector( … … 3802 3850 header='Edit expression') 3803 3851 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) 3808 3858 newobj = dlg.Show(True) 3809 3859 if newobj: … … 3815 3865 def AddNewSeqExpression(event): 3816 3866 '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) 3821 3872 obj = dlg.Show(True) 3822 3873 dlg.Destroy() … … 3853 3904 'Edit an existing function' 3854 3905 choices = Controls['SeqParFitFxns'].keys() 3855 parmDict = dict(zip(colLabels,zip(*colList)[0]))3856 3906 if len(choices) == 1: 3857 selected = [0]3907 selected = 0 3858 3908 else: 3859 3909 selected = ItemSelector( … … 3864 3914 if selected is not None: 3865 3915 dlg = G2exG.ExpressionDialog( 3866 G2frame.dataDisplay, parmDict,3916 G2frame.dataDisplay,indepVarDict, 3867 3917 Controls['SeqParFitFxns'][choices[selected]], 3918 depVarDict=depVarDict, 3868 3919 header="Edit this minimization function's formula") 3869 3920 newobj = dlg.Show(True) … … 3875 3926 3876 3927 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' 3879 3929 dlg = G2exG.ExpressionDialog( 3880 G2frame.dataDisplay,parmDict, 3930 G2frame.dataDisplay,indepVarDict, 3931 depVarDict=depVarDict, 3881 3932 header='Enter a function to minimize in the parametric fit') 3882 3933 obj = dlg.Show(True) … … 3887 3938 EnableParFitFxnMenus() 3888 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 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 3889 3950 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 3891 3954 for expr in Controls['SeqParFitFxns']: 3892 print expr3893 3955 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) 3894 3992 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 3899 4007 #====================================================================== 3900 4008 # start processing sequential results here … … 3930 4038 ESDlookup[newCellDict[item][0]] = item 3931 4039 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] 3932 4045 3933 4046 # get unit cell & symmetry for all phases … … 3975 4088 Types = [] 3976 4089 nRows = len(histNames) 3977 # addRwp values4090 # start with Rwp values 3978 4091 colList += [[data[name]['Rvals']['Rwp'] for name in histNames]] 3979 4092 colSigs += [None] … … 3986 4099 Types += [wg.GRID_VALUE_FLOAT,] 3987 4100 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 3996 4102 for key in sampleParms: 3997 4103 colList += [sampleParms[key]] … … 3999 4105 colLabels += [key] 4000 4106 Types += [wg.GRID_VALUE_FLOAT,] 4001 4002 # add cell parameters 4107 # add unique cell parameters 4003 4108 for pId in sorted(Alist): 4004 4109 pfx = str(pId)+'::' # prefix for A values from phase … … 4006 4111 cellESDs = [] 4007 4112 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,] 4009 4115 for name in histNames: 4010 4116 covData['varyList'] = [Dlookup.get(striphist(v),v) for v in data[name]['varyList']] … … 4024 4130 # convert to direct cell & add only unique values to table 4025 4131 c = G2lat.A2cell(A) 4132 vol = G2lat.calc_V(A) 4026 4133 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]]] 4029 4136 colList += zip(*cells) 4030 4137 colSigs += zip(*cellESDs) 4031 4032 4138 # add the variables that were refined; change from rows to columns 4033 4139 colList += zip(*[data[name]['variables'] for name in histNames]) … … 4035 4141 Types += len(data[histNames[0]]['varyList'])*[wg.GRID_VALUE_FLOAT] 4036 4142 colSigs += zip(*[data[name]['sig'] for name in histNames]) 4037 4143 4038 4144 # process the dependent constrained variables, removing histogram numbers if needed 4039 4145 # from parameter label … … 4050 4156 depValDict[svar].append(val) 4051 4157 depSigDict[svar].append(sig) 4052 4053 4158 # add the dependent constrained variables 4054 4159 for var in sorted(depValDict): … … 4059 4164 colList += [depValDict[var]] 4060 4165 4061 # add atom parameters to list4166 # add atom parameters to table 4062 4167 colLabels += atomList.keys() 4063 4168 Types += len(atomList)*[wg.GRID_VALUE_FLOAT] 4064 for parm in atomList:4169 for parm in sorted(atomList): 4065 4170 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 4068 4201 for expr in Controls['SeqPseudoVars']: 4069 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] 4070 4206 calcobj = G2obj.ExpressionCalcObj(obj) 4071 4207 valList = [] 4072 for row in zip(*colList): 4208 esdList = [] 4209 for j,row in enumerate(zip(*colList)): 4210 name = histNames[j] 4073 4211 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) 4075 4223 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)))) 4077 4230 colList += [valList] 4231 colSigs += [esdList] 4078 4232 colLabels += [expr] 4079 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 4080 4278 rowList = [c for c in zip(*colList)] # convert from columns to rows 4081 4279 G2frame.SeqTable = Table(rowList,colLabels=colLabels,rowLabels=histNames,types=Types) … … 4096 4294 4097 4295 G2frame.dataDisplay = GSGrid(parent=G2frame.dataFrame) 4098 # colSigs += [None]4099 # colLabels += ['Cnvg']4100 # Types += [wg.GRID_VALUE_BOOL,]4101 4296 G2frame.dataDisplay.SetTable(G2frame.SeqTable, True) 4102 4297 G2frame.dataDisplay.EnableEditing(False) … … 4116 4311 elif deltaChi > 1.0: 4117 4312 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 4120 4339 def UpdateSASDSeqResults(G2frame,data,prevSize=None): 4121 4340 … … 4249 4468 colSigs += zip(*[data[name]['sig'] for name in histNames]) 4250 4469 # # add Pseudovars 4251 # for exp in Controls['SeqPseudoVars']:4252 # obj = Controls['SeqPseudoVars'][exp ]4470 # for expr in Controls['SeqPseudoVars']: 4471 # obj = Controls['SeqPseudoVars'][expr] 4253 4472 # calcobj = G2obj.ExpressionCalcObj(obj) 4254 4473 # valList = [] … … 4259 4478 # colList += [valList] 4260 4479 # colSigs += [None] 4261 # colLabels += [exp ]4480 # colLabels += [expr] 4262 4481 # Types += [wg.GRID_VALUE_FLOAT,] 4263 4482 -
trunk/GSASIIobj.py
r1298 r1312 1242 1242 'Vol' : 'Unit cell volume', 1243 1243 # 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', 1245 1246 'AUiso':'Atomic isotropic displacement parameter', 1246 1247 'AU([123][123])':'Atomic anisotropic displacement parameter U\\1', … … 1568 1569 * a flag to determine if the variable is refined. 1569 1570 ''' 1571 self.depVar = None 1570 1572 1571 1573 self.lastError = ('','') … … 1645 1647 return ["::"+self.freeVars[v][0] for v in self.freeVars if self.freeVars[v][3]] 1646 1648 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 1647 1665 def CheckVars(self): 1648 1666 '''Check that the expression can be parsed, all functions are … … 1685 1703 to the save. 1686 1704 1687 :returns: a list of variablesused variables1705 :returns: a list of used variables 1688 1706 ''' 1689 1707 self.lastError = ('','') … … 1705 1723 return pkgdict,fxnobj 1706 1724 except (AttributeError, NameError): 1707 return None 1725 return None,None 1708 1726 else: 1709 1727 try: … … 1804 1822 return varlist,pkgdict 1805 1823 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 1806 1831 #========================================================================== 1807 1832 class ExpressionCalcObj(object): … … 1906 1931 self.exprDict.update(self.fxnpkgdict) 1907 1932 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 1908 1941 def EvalExpression(self): 1909 1942 '''Evaluate an expression. Note that the expression … … 1912 1945 :returns: a single value for the expression. If parameter 1913 1946 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. 1915 1948 1916 1949 For example, if the expression is ``'A*B'``, … … 1928 1961 return val 1929 1962 1930 def EvalDeriv(self,varname ):1963 def EvalDeriv(self,varname,step=None): 1931 1964 '''Evaluate the expression derivative with respect to a 1932 1965 GSAS-II variable name. … … 1935 1968 :returns: the derivative 1936 1969 ''' 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] 1938 1973 if varname not in self.lblLookup: return 0.0 1939 step = self.derivStep[varname]1940 1974 lbl = self.lblLookup[varname] # what label does this map to in expression? 1941 1975 origval = self.exprDict[lbl] -
trunk/GSASIIplot.py
r1306 r1312 2299 2299 ##### PlotSeq 2300 2300 ################################################################################ 2301 def PlotSelectedSequence(G2frame,ColumnList,TableGet,SelectX ):2301 def PlotSelectedSequence(G2frame,ColumnList,TableGet,SelectX,fitnum=None,fitvals=None): 2302 2302 '''Plot a result from a sequential refinement 2303 2303 … … 2310 2310 number (or None) as the X-axis selection 2311 2311 ''' 2312 G2frame.seqYaxisList = ColumnList2313 G2frame.seqTableGet = TableGet2314 2312 G2frame.seqXselect = SelectX 2315 2313 try: … … 2329 2327 G2frame.seqXaxis = G2frame.seqXselect() 2330 2328 Draw() 2329 if fitnum is None: 2330 label = 'Sequential refinement' 2331 else: 2332 label = 'Parametric fit #'+str(fitnum+1) 2331 2333 try: 2332 plotNum = G2frame.G2plotNB.plotList.index( 'Sequential refinement')2334 plotNum = G2frame.G2plotNB.plotList.index(label) 2333 2335 Page = G2frame.G2plotNB.nb.GetPage(plotNum) 2334 2336 Page.figure.clf() … … 2337 2339 Page.Show() 2338 2340 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) 2341 2343 Page = G2frame.G2plotNB.nb.GetPage(plotNum) 2342 2344 Page.canvas.mpl_connect('key_press_event', OnKeyPress) … … 2344 2346 Page.Choice = ['s to select plot x-axis'] 2345 2347 Page.keyPress = OnKeyPress 2348 Page.seqYaxisList = ColumnList 2349 Page.seqTableGet = TableGet 2350 Page.fitvals = fitvals 2346 2351 2347 2352 def Draw(): … … 2350 2355 Plot.clear() 2351 2356 if G2frame.seqXaxis is not None: 2352 xName,X,Xsig = G2frame.seqTableGet(G2frame.seqXaxis)2357 xName,X,Xsig = Page.seqTableGet(G2frame.seqXaxis) 2353 2358 else: 2354 2359 X = np.arange(0,G2frame.SeqTable.GetNumberRows(),1) 2355 2360 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) 2358 2363 if sig: 2359 2364 Plot.errorbar(X,Y,yerr=sig,label=name) … … 2361 2366 Plot.plot(X,Y) 2362 2367 Plot.plot(X,Y,'o',label=name) 2368 if Page.fitvals: 2369 Plot.plot(X,fitvals) 2370 Plot.plot(X,fitvals,'*',label='Fit') 2371 2363 2372 Plot.legend(loc='best') 2364 2373 Plot.set_ylabel('Parameter values') -
trunk/GSASIIstrIO.py
r1299 r1312 1278 1278 var = np.diag(sigMat) 1279 1279 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 1282 1281 1283 1282 def SetPhaseData(parmDict,sigDict,Phases,RBIds,covData,RestraintDict=None,pFile=None): -
trunk/GSASIIstrMath.py
r1308 r1312 859 859 return [parmdict[key] for key in varylist] 860 860 861 def Values2Dict(parmdict, varylist, values):862 ''' Use after call to leastsq to update the parameter dictionary with863 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)) 865 865 866 866 def GetNewCellParms(parmDict,varyList): … … 1981 1981 'Needs a doc string' 1982 1982 parmDict.update(zip(varylist,values)) 1983 Values2Dict(parmDict, varylist, values)1983 #Values2Dict(parmDict, varylist, values) # BHT -- seems to duplicate previous statement 1984 1984 G2mv.Dict2Map(parmDict,varylist) 1985 1985 Histograms,Phases,restraintDict,rigidbodyDict = HistoPhases
Note: See TracChangeset
for help on using the changeset viewer.