Changeset 1322
- Timestamp:
- May 4, 2014 10:30:16 PM (9 years ago)
- Location:
- trunk
- Files:
-
- 4 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/GSASIIexprGUI.py
r1312 r1322 64 64 what they will do here; default is "Enter restraint expression here" 65 65 :param bool fit: determines if the expression will be used in fitting (default=True). 66 If set to False, derivate step valuesand refinement flags are not shown66 If set to False, and refinement flags are not shown 67 67 and Free parameters are not offered as an assignment option. 68 68 :param str VarLabel: an optional variable label to include before the expression … … 99 99 self.varName = {} 100 100 'Name assigned to each variable' 101 self.varStep = {}102 'Step size for each variable'103 101 self.varValue = {} 104 102 'Value for a variable (Free parameters only)' … … 202 200 self.varName, 203 201 self.varValue, 204 self.varStep,205 202 self.varRefflag, 206 203 ) … … 238 235 self.varName, 239 236 self.varValue, 240 self.varStep,241 237 self.varRefflag, 242 238 ) … … 315 311 else: 316 312 msg += 'Value '+str(val)+' invalid for '+str(v) 317 # step assignment318 val = self.varStep.get(v)319 vf = 1.0320 try:321 vf = float(val)322 except ValueError,TypeError:323 invalid += 1324 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 += 1331 if msg: msg += "; "332 msg += 'Zero is not valid as a step for '+str(v)333 313 if invalid: 334 314 return '('+msg+')' … … 348 328 'Assign variables to labels'), 349 329 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) 351 331 GridSiz.Add( 352 332 wx.StaticText(self.varbox,wx.ID_ANY,'label',style=wx.CENTER), … … 355 335 self.choices = ['Free','Phase','Hist./Phase','Hist.','Global'] 356 336 if self.fit: 357 lbls += (' derivative\nstep','refine\nflag')337 lbls += ('refine\nflag',) 358 338 else: 359 lbls += ('', '')339 lbls += ('',) 360 340 self.choices[0] = '' 361 341 for i in (1,2,3,4): # remove empty menus from choice list … … 416 396 GridSiz.Add(wid,0,wx.ALIGN_LEFT,0) 417 397 418 # step419 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 428 398 # show a refine flag for Free Vars only 429 399 if self.varSelect.get(v) == 0 and self.fit: … … 473 443 return 474 444 self.varName[v] = var 475 self.varStep[v] = self.varStep.get(v,0.0001)476 445 self.OnValidate(None) 477 446 … … 570 539 self.varName, 571 540 self.varValue, 572 self.varStep,573 541 self.varRefflag, 574 542 ) … … 601 569 PSvarDict = {'::a':1.0,'::b':1.1,'0::c':1.2} 602 570 #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} 604 572 dlg = ExpressionDialog(frm,indepvarDict, 605 573 header="Edit the PseudoVar expression", … … 617 585 print dlg.GetDepVar() 618 586 import sys 619 sys.exit()587 #sys.exit() 620 588 621 589 #app.MainLoop() … … 632 600 obj = G2obj.ExpressionObj() 633 601 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]} 636 604 obj.CheckVars() 637 605 parmDict2 = {'0::Afrac:0':1.0, '0::Afrac:1': 1.0} … … 644 612 645 613 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'} 647 615 obj.freeVars = {} 648 616 parmDict1 = {'0::Afrac:0':1.0, '0::Afrac:1': -2.0} -
trunk/GSASIIgrid.py
r1312 r1322 3171 3171 #this is to satisfy structure drawing stuff in G2plt when focus changes 3172 3172 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) 3173 3199 3174 3200 ################################################################################ … … 3631 3657 sampleParmDict = {'Temperature':[],'Pressure':[], 3632 3658 'FreePrm1':[],'FreePrm2':[],'FreePrm3':[],} 3659 Controls = G2frame.PatternTree.GetItemPyData( 3660 GetPatternTreeItemId(G2frame,G2frame.root, 'Controls')) 3633 3661 sampleParm = {} 3634 3662 for name in histNames: … … 3640 3668 frstValue = sampleParmDict[item][0] 3641 3669 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] 3643 3674 return sampleParm 3644 3675 3645 3676 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 MatPlotLib3677 '''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 3648 3679 ''' 3649 3680 plotName = plotSpCharFix(G2frame.SeqTable.GetColLabelValue(col)) … … 3764 3795 finally: 3765 3796 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 3781 3798 def striphist(var,insChar=''): 3782 3799 'strip a histogram number from a var name' … … 3815 3832 return col 3816 3833 3817 def Enable SeqExpressionMenus():3834 def EnablePseudoVarMenus(): 3818 3835 'Enables or disables the PseudoVar menu items that require existing defs' 3819 3836 if Controls['SeqPseudoVars']: … … 3824 3841 G2frame.dataFrame.SequentialPvars.Enable(wxEDITSEQVAR,val) 3825 3842 3826 def Del SeqExpression(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' 3828 3845 choices = Controls['SeqPseudoVars'].keys() 3829 3846 selected = ItemSelector( … … 3838 3855 UpdateSeqResults(G2frame,data,G2frame.dataDisplay.GetSize()) # redisplay variables 3839 3856 3840 def Edit SeqExpression(event):3841 'Edit an existing expression'3857 def EditPseudoVar(event): 3858 'Edit an existing pseudo var expression' 3842 3859 choices = Controls['SeqPseudoVars'].keys() 3843 3860 if len(choices) == 1: … … 3863 3880 UpdateSeqResults(G2frame,data,G2frame.dataDisplay.GetSize()) # redisplay variables 3864 3881 3865 def AddNew SeqExpression(event):3866 'Create a new expression'3882 def AddNewPseudoVar(event): 3883 'Create a new pseudo var expression' 3867 3884 dlg = G2exG.ExpressionDialog( 3868 3885 G2frame.dataDisplay,PSvarDict, … … 3877 3894 UpdateSeqResults(G2frame,data,G2frame.dataDisplay.GetSize()) # redisplay variables 3878 3895 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(): 3880 3986 'Enables or disables the Parametric Fit menu items that require existing defs' 3881 if Controls['SeqParFit Fxns']:3987 if Controls['SeqParFitEqs']: 3882 3988 val = True 3883 3989 else: 3884 3990 val = False 3885 #G2frame.dataFrame.SequentialPfit.Enable(wxADDPARFIT,val) # TODO: remove when testing done3886 3991 G2frame.dataFrame.SequentialPfit.Enable(wxDELPARFIT,val) 3887 3992 G2frame.dataFrame.SequentialPfit.Enable(wxEDITPARFIT,val) 3888 3993 G2frame.dataFrame.SequentialPfit.Enable(wxDOPARFIT,val) 3889 3994 3890 def DelParFit Fxn(event):3995 def DelParFitEq(event): 3891 3996 'Ask the user to select function to delete' 3892 choices = Controls['SeqParFit Fxns'].keys()3997 choices = Controls['SeqParFitEqs'].keys() 3893 3998 selected = ItemSelector( 3894 3999 choices,G2frame.dataFrame, … … 3898 4003 if selected is None: return 3899 4004 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() 3906 4012 if len(choices) == 1: 3907 4013 selected = 0 … … 3915 4021 dlg = G2exG.ExpressionDialog( 3916 4022 G2frame.dataDisplay,indepVarDict, 3917 Controls['SeqParFit Fxns'][choices[selected]],4023 Controls['SeqParFitEqs'][choices[selected]], 3918 4024 depVarDict=depVarDict, 3919 4025 header="Edit this minimization function's formula") … … 3921 4027 if newobj: 3922 4028 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' 3929 4036 dlg = G2exG.ExpressionDialog( 3930 4037 G2frame.dataDisplay,indepVarDict, … … 3935 4042 if obj: 3936 4043 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 ''' 3944 4055 result = [] 3945 4056 for calcobj in calcObjList: 3946 calcobj.UpdateVars(varyList, values)4057 calcobj.UpdateVars(varyList,Values) 3947 4058 result.append((calcobj.depVal-calcobj.EvalExpression())/calcobj.depSig) 3948 4059 return result 3949 4060 3950 def DoPar Fit(event):4061 def DoParEqFit(event): 3951 4062 'Parametric fit minimizer' 3952 4063 varyValueDict = {} # dict of variables and their initial values 3953 4064 calcObjList = [] # expression objects, ready to go for each data point 3954 for expr in Controls['SeqParFit Fxns']:3955 obj = Controls['SeqParFit Fxns'][expr]4065 for expr in Controls['SeqParFitEqs']: 4066 obj = Controls['SeqParFitEqs'][expr] 3956 4067 # assemble refined vars for this equation 3957 4068 varyValueDict.update({var:val for var,val in obj.GetVariedVarVal()}) … … 3978 4089 varyList = varyValueDict.keys() 3979 4090 varyValues = [varyValueDict[key] for key in varyList] 3980 result = so.leastsq(ParE val,varyValues,full_output=True, #ftol=Ftol,4091 result = so.leastsq(ParEqEval,varyValues,full_output=True, #ftol=Ftol, 3981 4092 args=(calcObjList,varyList) 3982 4093 ) … … 3987 4098 for i,(var,val) in enumerate(zip(varyList,values)): 3988 4099 print ' ',var,' =',G2mth.ValEsd(val,np.sqrt(covar[i,i])) 3989 for fitnum,expr in enumerate(Controls['SeqParFit Fxns']):3990 obj = Controls['SeqParFit Fxns'][expr]4100 for fitnum,expr in enumerate(Controls['SeqParFitEqs']): 4101 obj = Controls['SeqParFitEqs'][expr] 3991 4102 obj.UpdateVariedVars(varyList,values) 3992 4103 calcobj = G2obj.ExpressionCalcObj(obj) … … 4005 4116 fitnum,fitvals) 4006 4117 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 4007 4140 #====================================================================== 4008 # start processing sequential results here 4141 # start processing sequential results here (UpdateSeqResults) 4142 #====================================================================== 4009 4143 if not data: 4010 4144 print 'No sequential refinement results' … … 4012 4146 Histograms,Phases = G2frame.GetUsedHistogramsAndPhasesfromTree() 4013 4147 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'] = {} 4018 4151 histNames = data['histNames'] 4019 4152 if G2frame.dataDisplay: … … 4023 4156 Status.SetStatusText("Select column to export; Double click on column to plot data; on row for Covariance") 4024 4157 sampleParms = GetSampleParms() 4158 4025 4159 # make dict of varied atom coords keyed by absolute position 4026 4160 newAtomDict = data[histNames[0]]['newAtomDict'] # dict with atom positions; relative & absolute 4027 4161 # Possible error: the next might need to be data[histNames[0]]['varyList'] 4028 4162 # error will arise if there constraints on coordinates? 4029 atomL ist= {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']} 4030 4164 4031 4165 # make dict of varied cell parameters equivalents … … 4039 4173 Dlookup[item] = newCellDict[item][0] 4040 4174 # 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 = {} 4048 4181 SGdata = {} 4049 covData = {} 4050 uniqCellParms = {} 4182 uniqCellIndx = {} 4183 initialCell = {} 4184 RcellLbls = {} 4185 zeroDict = {} 4186 Rcelldict = {} 4051 4187 for phase in Phases: 4052 4188 phasedict = Phases[phase] 4053 4189 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.,])) 4055 4194 SGdata[pId] = phasedict['General']['SGData'] 4195 Rcelldict.update({lbl:val for lbl,val in zip(RcellLbls[pId],RecpCellTerms[pId])}) 4056 4196 laue = SGdata[pId]['SGLaue'] 4057 4197 if laue == '2/m': … … 4059 4199 for symlist,celllist in cellGUIlist: 4060 4200 if laue in symlist: 4061 uniqCell Parms[pId] = celllist4201 uniqCellIndx[pId] = celllist 4062 4202 break 4063 4203 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] 4065 4207 4066 4208 SetDataMenuBar(G2frame,G2frame.dataFrame.SequentialMenu) … … 4072 4214 G2frame.dataFrame.Bind(wx.EVT_MENU, OnSaveSelSeqCSV, id=wxID_SAVESEQSELCSV) 4073 4215 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 ----------------------------------------------- 4085 4228 colList = [] 4086 4229 colSigs = [] … … 4106 4249 Types += [wg.GRID_VALUE_FLOAT,] 4107 4250 # add unique cell parameters 4108 for pId in sorted( Alist):4251 for pId in sorted(RecpCellTerms): 4109 4252 pfx = str(pId)+'::' # prefix for A values from phase 4110 4253 cells = [] 4111 4254 cellESDs = [] 4112 colLabels += [pfx+cellUlbl[i] for i in uniqCell Parms[pId]]4255 colLabels += [pfx+cellUlbl[i] for i in uniqCellIndx[pId]] 4113 4256 colLabels += [pfx+'Vol'] 4114 Types += (1+len(uniqCell Parms[pId]))*[wg.GRID_VALUE_FLOAT,]4257 Types += (1+len(uniqCellIndx[pId]))*[wg.GRID_VALUE_FLOAT,] 4115 4258 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 4119 4264 # update with refined values 4120 4265 for i in range(6): … … 4126 4271 Albls = [pfx+'A'+str(i) for i in range(6)] 4127 4272 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]) 4130 4274 # convert to direct cell & add only unique values to table 4131 4275 c = G2lat.A2cell(A) 4132 4276 vol = G2lat.calc_V(A) 4133 4277 cE = G2stIO.getCellEsd(pfx,SGdata[pId],A,covData) 4134 cells += [[c[i] for i in uniqCell Parms[pId]]+[vol]]4135 cellESDs += [[cE[i] for i in uniqCell Parms[pId]]+[cE[-1]]]4278 cells += [[c[i] for i in uniqCellIndx[pId]]+[vol]] 4279 cellESDs += [[cE[i] for i in uniqCellIndx[pId]]+[cE[-1]]] 4136 4280 colList += zip(*cells) 4137 4281 colSigs += zip(*cellESDs) … … 4142 4286 colSigs += zip(*[data[name]['sig'] for name in histNames]) 4143 4287 4144 # process the dependentconstrained variables, removing histogram numbers if needed4288 # tabulate constrained variables, removing histogram numbers if needed 4145 4289 # from parameter label 4146 4290 depValDict = {} … … 4156 4300 depValDict[svar].append(val) 4157 4301 depSigDict[svar].append(sig) 4158 # add the dependent constrained variables 4302 # add the dependent constrained variables to the table 4159 4303 for var in sorted(depValDict): 4160 4304 if len(depValDict[var]) != len(histNames): continue … … 4165 4309 4166 4310 # add atom parameters to table 4167 colLabels += atomL ist.keys()4168 Types += len(atomL ist)*[wg.GRID_VALUE_FLOAT]4169 for parm in sorted(atomL ist):4170 colList += [[data[name]['newAtomDict'][atomL ist[parm]][1] for name in histNames]]4171 if atomL ist[parm] in data[histNames[0]]['varyList']:4172 col = data[histNames[0]]['varyList'].index(atomL ist[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]) 4173 4317 colSigs += [[data[name]['sig'][col] for name in histNames]] 4174 4318 else: 4175 4319 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 4176 4342 # Make dict needed for creating & editing pseudovars (PSvarDict). 4177 # These are variables that are in the CoVar matrix, or related vars that are4178 # 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 4180 4346 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 ) 4183 4350 name = histNames[0] 4184 # Create labels for CoVar matrix that maps vars appropriately4185 PSvaryList = [Dlookup.get(striphist(var),var) for var in data[name]['varyList']]4186 # dict containing variables and values for use in PseudoVars defs4187 # pick out only the refined terms or their surrogates4188 PSvarDict = {var:parmDict.get(var) for var in PSvaryList}4189 4351 indepVarDict = { # values in table w/o ESDs 4190 4352 var:colList[i][0] for i,var in enumerate(colLabels) if colSigs[i] is None 4191 4353 } 4192 PSvarDict.update(indepVarDict) # add values in table w/o ESDs4193 4354 # make dict of dependent vars (w/ESDs) that are not converted (Dij to Ak or dAx to Ax) 4194 4355 depVarDict = { … … 4198 4359 # add recip cell coeff. values 4199 4360 depVarDict.update({var:val for var,val in data[name]['newCellDict'].values()}) 4200 # evaluate Pseudovars and add them to grid4201 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 expression4205 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 expression4214 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 expression4218 esdDict = {Dlookup.get(striphist(var),var):esd4219 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 PseudoVar4222 calcobj.SetupCalc(varDict)4223 valList.append(calcobj.EvalExpression())4224 # compute ESD on this Pseudovar4225 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.assgnVars4237 # print data[name]['varyList']4238 # #vList = [Dlookup.get(striphist(v),v) for v in data[name]['varyList']]4239 # #print vList4240 # #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 indexList4244 # siglist = [data[name]['sig'][data[name]['varyList'].index(var)] for var in lookupList]4245 # print siglist4246 # row = zip(*colList)[0]4247 # parmDict = dict(zip(colLabels,row))4248 # calcobj.SetupCalc(parmDict)4249 # print calcobj.lblLookup4250 # derivs = []4251 # for var in lookupList:4252 # index = data[name]['varyList'].index(var)4253 # sig = data[name]['sig'][index]4254 # print var,sig4255 # print calcobj.EvalDeriv(var,sig)4256 # derivs.append(calcobj.EvalDeriv(var,sig/10))4257 4258 # derivs = np.array(derivs)4259 # #print 'derivs=',derivs4260 # vcov = G2mth.getVCov(lookupList,data[name]['varyList'],data[name]['covMatrix'])4261 # #print 'vcov =',vcov4262 # esd = np.sqrt(np.inner(derivs,np.inner(vcov,derivs.T)))4263 # print 'val,esd =',calcobj.EvalExpression(),esd4264 #======================================================================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 rows4279 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=Types4293 # )4294 4361 4295 4362 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) 4296 4366 G2frame.dataDisplay.SetTable(G2frame.SeqTable, True) 4297 4367 G2frame.dataDisplay.EnableEditing(False) … … 4311 4381 elif deltaChi > 1.0: 4312 4382 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 #====================================================================== 4338 4387 4339 4388 def UpdateSASDSeqResults(G2frame,data,prevSize=None): … … 4438 4487 # G2frame.dataFrame.Bind(wx.EVT_MENU, OnSaveSelSeqCSV, id=wxID_SAVESASDSEQSELCSV) 4439 4488 G2frame.dataFrame.Bind(wx.EVT_MENU, OnPlotSelSeq, id=wxID_PLOTSASDSEQSEL) 4440 # G2frame.dataFrame.Bind(wx.EVT_MENU, AddNew SeqExpression, id=wxADDSEQVAR)4441 # G2frame.dataFrame.Bind(wx.EVT_MENU, Del SeqExpression, id=wxDELSEQVAR)4442 # G2frame.dataFrame.Bind(wx.EVT_MENU, Edit SeqExpression, id=wxEDITSEQVAR)4443 # Enable SeqExpressionMenus()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() 4444 4493 # build up the data table one column at a time 4445 4494 colList = [] -
trunk/GSASIIobj.py
r1312 r1322 1565 1565 1566 1566 * 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 1569 1568 * a flag to determine if the variable is refined. 1570 1569 ''' … … 1575 1574 (list of 1-3 str values)''' 1576 1575 1577 def LoadExpression(self,expr,exprVarLst,varSelect,varName,varValue,var Step,varRefflag):1576 def LoadExpression(self,expr,exprVarLst,varSelect,varName,varValue,varRefflag): 1578 1577 '''Load the expression and associated settings into the object. Raises 1579 1578 an exception if the expression is not parsed, if not all functions … … 1591 1590 :param dict varName: Defines a name (str) associated with each free parameter 1592 1591 :param dict varValue: Defines a value (float) associated with each free parameter 1593 :param dict varStep: Defines a derivative step size (float) for each1594 parameter labels found in the expression1595 1592 :param dict varRefflag: Defines a refinement flag (bool) 1596 1593 associated with each free parameter … … 1605 1602 varName.get(v), 1606 1603 varValue.get(v), 1607 varStep.get(v),1608 1604 varRefflag.get(v), 1609 1605 ] 1610 1606 else: 1611 self.assgnVars[v] = [ 1612 varName[v], 1613 varStep.get(v), 1614 ] 1607 self.assgnVars[v] = varName[v] 1615 1608 self.CheckVars() 1616 1609 1617 def EditExpression(self,exprVarLst,varSelect,varName,varValue,var Step,varRefflag):1610 def EditExpression(self,exprVarLst,varSelect,varName,varValue,varRefflag): 1618 1611 '''Load the expression and associated settings from the object into 1619 1612 arrays used for editing. … … 1624 1617 :param dict varName: Defines a name (str) associated with each free parameter 1625 1618 :param dict varValue: Defines a value (float) associated with each free parameter 1626 :param dict varStep: Defines a derivative step size (float) for each1627 parameter labels found in the expression1628 1619 :param dict varRefflag: Defines a refinement flag (bool) 1629 1620 associated with each free parameter … … 1635 1626 varName[v] = self.freeVars[v][0] 1636 1627 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] 1639 1629 for v in self.assgnVars: 1640 1630 varSelect[v] = 1 1641 varName[v] = self.assgnVars[v][0] 1642 varStep[v] = self.assgnVars[v][1] 1631 varName[v] = self.assgnVars[v] 1643 1632 return self.expression 1644 1633 1645 1634 def GetVaried(self): 1646 1635 '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]] 1648 1637 1649 1638 def GetVariedVarVal(self): 1650 1639 '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]] 1652 1641 1653 1642 def UpdateVariedVars(self,varyList,values): 1654 1643 'Updates values for the free parameters (after a refinement); only updates refined vars' 1655 1644 for v in self.freeVars: 1656 if not self.freeVars[v][ 3]: continue1645 if not self.freeVars[v][2]: continue 1657 1646 if "::"+self.freeVars[v][0] not in varyList: continue 1658 1647 indx = varyList.index("::"+self.freeVars[v][0]) … … 1661 1650 def GetIndependentVars(self): 1662 1651 '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] 1664 1653 1665 1654 def CheckVars(self): … … 1846 1835 referenced by functions 1847 1836 ''' 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 zero1851 '''1852 1837 self.lblLookup = {} 1853 1838 '''Lookup table that specifies the expression label name that is … … 1887 1872 # set up the dicts needed to speed computations 1888 1873 self.exprDict = {} 1889 self.derivStep = {}1890 1874 self.lblLookup = {} 1891 1875 self.varLookup = {} … … 1896 1880 self.varLookup[v] = varname 1897 1881 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]] 1899 1883 else: 1900 1884 parmDict[varname] = self.eObj.freeVars[v][1] 1901 1885 self.exprDict[v] = self.eObj.freeVars[v][1] 1902 if self.eObj.freeVars[v][3]:1903 self.derivStep[varname] = self.eObj.freeVars[v][2]1904 1886 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] 1907 1888 if '*' in varname: 1908 1889 varlist = LookupWildCard(varname,parmDict.keys()) … … 1911 1892 for var in varlist: 1912 1893 self.lblLookup[var] = v 1913 self.derivStep[var] = np.array(1914 [step if var1 == var else 0 for var1 in varlist]1915 )1916 1894 if parmsInList: 1917 1895 self.exprDict[v] = np.array([parmDict[var][0] for var in varlist]) … … 1926 1904 else: 1927 1905 self.exprDict[v] = parmDict[varname] 1928 self.derivStep[varname] = step1929 1906 else: 1930 1907 raise Exception,"No value for variable "+str(v) … … 1961 1938 return val 1962 1939 1963 def EvalDeriv(self,varname,step=None):1964 '''Evaluate the expression derivative with respect to a1965 GSAS-II variable name.1966 1967 :param str varname: a G2 variable name (will not have a wild-card)1968 :returns: the derivative1969 '''1970 if step is None:1971 if varname not in self.derivStep: return 0.01972 step = self.derivStep[varname]1973 if varname not in self.lblLookup: return 0.01974 lbl = self.lblLookup[varname] # what label does this map to in expression?1975 origval = self.exprDict[lbl]1976 1977 self.exprDict[lbl] = origval + step1978 val1 = eval(self.compiledExpr,globals(),self.exprDict)1979 1980 self.exprDict[lbl] = origval - step1981 val2 = eval(self.compiledExpr,globals(),self.exprDict)1982 1983 self.exprDict[lbl] = origval # reset back to central value1984 1985 val = (val1 - val2) / (2.*np.max(step))1986 if not np.isscalar(val):1987 val = np.sum(val)1988 return val1989 1940 1990 1941 if __name__ == "__main__": … … 1995 1946 for v in sorted(calcobj.varLookup): 1996 1947 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) 2000 1951 2001 1952 obj = ExpressionObj() 2002 1953 2003 1954 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]} 2006 1957 #obj.CheckVars() 2007 1958 parmDict2 = {'0::Afrac:0':[0.0,True], '0::Afrac:1': [1.0,False]} … … 2011 1962 2012 1963 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]} 2015 1966 #obj.CheckVars() 2016 1967 parmDict1 = {'0::Afrac:0':1.0, '0::Afrac:1': 1.0} -
trunk/GSASIIstrMath.py
r1320 r1322 1980 1980 def errRefine(values,HistoPhases,parmDict,varylist,calcControls,pawleyLookup,dlg): 1981 1981 '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) 1984 1983 G2mv.Dict2Map(parmDict,varylist) 1985 1984 Histograms,Phases,restraintDict,rigidbodyDict = HistoPhases
Note: See TracChangeset
for help on using the changeset viewer.