Changeset 4840
- Timestamp:
- Mar 5, 2021 1:54:34 PM (3 years ago)
- Location:
- trunk
- Files:
-
- 6 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/GSASIIdataGUI.py
r4837 r4840 753 753 754 754 item = parent.Append(wx.ID_ANY,'&Refine\tCTRL+R','Perform a refinement') 755 if len(self.Refine): # extend state for new menus to match main (on mac)755 if len(self.Refine): # extend state for new menus to match main 756 756 state = self.Refine[0].IsEnabled() 757 757 else: … … 760 760 self.Refine.append(item) 761 761 self.Bind(wx.EVT_MENU, self.OnRefine, id=item.GetId()) 762 item = parent.Append(wx.ID_ANY,'&LeBail fit\tCTRL+B','Fit LeBail intensities only') 763 item.Enable(state) 764 self.Refine.append(item) 765 self.Bind(wx.EVT_MENU, self.OnLeBail, id=item.GetId()) 762 766 763 767 item = parent.Append(wx.ID_ANY,'&Run Fprime','X-ray resonant scattering') … … 797 801 seqSetting = None 798 802 803 for item in self.Refine: 804 if 'LeBail' in item.GetItemLabel(): 805 if seqSetting: item.Enable(False) 806 elif seqSetting: 807 item.SetItemLabel('Se&quential refine\tCtrl+R') #might fail on old wx 808 else: 809 item.SetItemLabel('&Refine\tCtrl+R') #might fail on old wx 799 810 if seqSetting: 800 for item in self.Refine:801 item.SetItemLabel('Se&quential refine\tCtrl+R') #might fail on old wx802 811 seqMode = True 803 812 else: 804 for item in self.Refine:805 item.SetItemLabel('&Refine\tCtrl+R') #might fail on old wx806 813 seqMode = False 807 814 for menu,Id in self.ExportSeq: … … 810 817 menu.Enable(Id,not seqMode) 811 818 return seqSetting 812 813 819 814 820 def PreviewFile(self,filename): … … 5149 5155 dlg.ShowModal() 5150 5156 dlg.Destroy() 5151 5157 5152 5158 def OnRefine(self,event): 5153 5159 '''Perform a refinement or a sequential refinement (depending on controls setting) … … 5212 5218 dlg2 = wx.MessageDialog(self,text,'Refinement results, Rw =%.3f'%(Rw),wx.OK|wx.CANCEL) 5213 5219 dlg2.CenterOnParent() 5214 dlg2.Raise()5220 #dlg2.Raise() # crashes sometimes on Mac 5215 5221 try: 5216 5222 if dlg2.ShowModal() == wx.ID_OK: … … 5238 5244 else: 5239 5245 self.ErrorDialog('Refinement error',Rvals['msg']) 5246 5247 def OnLeBail(self,event): 5248 seqList = self.testSeqRefineMode() 5249 if seqList: 5250 self.ErrorDialog('Not for Sequential Fits', 5251 'This command is not yet implemented for sequential fitting') 5252 return 5253 item = GetGPXtreeItemId(self,self.root,'Covariance') 5254 covData = self.GPXtree.GetItemPyData(item) 5255 GOF0 = covData['Rvals']['GOF'] 5256 5257 dlg = wx.ProgressDialog('Residual','All data Rw =',101.0, 5258 style = wx.PD_ELAPSED_TIME|wx.PD_AUTO_HIDE|wx.PD_CAN_ABORT|wx.STAY_ON_TOP,parent=self) 5259 Size = dlg.GetSize() 5260 if 50 < Size[0] < 500: # sanity check on size, since this fails w/Win & wx3.0 5261 dlg.SetSize((int(Size[0]*1.2),Size[1])) # increase size a bit along x 5262 dlg.CenterOnParent() 5263 dlg.Raise() 5264 self.SaveTreeSetting() # save the current tree selection 5265 self.GPXtree.SaveExposedItems() # save the exposed/hidden tree items 5266 if self.PatternId and self.GPXtree.GetItemText(self.PatternId).startswith('PWDR '): 5267 refPlotUpdate = G2plt.PlotPatterns(self,refineMode=True) # prepare for plot updating 5268 else: 5269 refPlotUpdate = None 5270 5271 try: 5272 OK,Rvals = G2stMn.DoLeBail(self.GSASprojectfile,dlg,refPlotUpdate=refPlotUpdate) 5273 finally: 5274 dlg.Update(101.) # forces the Auto_Hide; needed after move w/Win & wx3.0 5275 dlg.Destroy() 5276 if OK: 5277 text = '' 5278 rtext = 'LeBail+only fit done. ' 5279 Rwp = Rvals.get('Rwp','?') 5280 if 'GOF' in Rvals: 5281 txt = 'Final Reduced Chi^2: {:.3f} (before ref: {:.3f})\n'.format( 5282 Rvals['GOF']**2,GOF0**2) 5283 text += txt 5284 rtext += txt 5285 text += '\nLoad new result?' 5286 dlg2 = wx.MessageDialog(self,text,'LeBail fit: Rwp={:.3f}' 5287 .format(Rwp),wx.OK|wx.CANCEL) 5288 dlg2.CenterOnParent() 5289 try: 5290 if dlg2.ShowModal() == wx.ID_OK: 5291 if refPlotUpdate: refPlotUpdate({},restore=True) 5292 wx.CallAfter(self.reloadFromGPX,rtext) 5293 else: 5294 if refPlotUpdate: refPlotUpdate({},restore=True) 5295 finally: 5296 dlg2.Destroy() 5297 else: 5298 self.ErrorDialog('LeBail error',Rvals['msg']) 5240 5299 5241 5300 def reloadFromGPX(self,rtext=None): -
trunk/GSASIImath.py
r4839 r4840 359 359 nfev += 1 360 360 try: 361 M = func(x0,*args) 361 if icycle == 0: # no parameter changes, skip recalc 362 M = M2 363 else: 364 M = func(x0,*args) 362 365 except Exception as Msg: 363 366 if not hasattr(Msg,'msg'): Msg.msg = str(Msg) -
trunk/GSASIIplot.py
r4837 r4840 6757 6757 G2frame.G2plotNB.status.SetStatusText('',1) 6758 6758 G2frame.G2plotNB.status.SetStatusWidths([G2frame.G2plotNB.status.firstLen,-1]) 6759 acolor = mpl.cm.get_cmap(G2frame.VcovColor) 6760 Img = Plot.imshow(Page.covArray,aspect='equal',cmap=acolor,interpolation='nearest',origin='lower', 6761 vmin=-1.,vmax=1.) 6762 imgAx = Img.axes 6763 ytics = imgAx.get_yticks() 6764 ylabs = [Page.varyList[int(i)] for i in ytics[:-1]] 6765 imgAx.set_yticklabels(ylabs) 6766 Page.figure.colorbar(Img) 6767 Plot.set_title('V-Cov matrix'+title) 6768 Plot.set_xlabel('Variable number') 6769 Plot.set_ylabel('Variable name') 6759 if Page.varyList: 6760 acolor = mpl.cm.get_cmap(G2frame.VcovColor) 6761 Img = Plot.imshow(Page.covArray,aspect='equal',cmap=acolor,interpolation='nearest',origin='lower', 6762 vmin=-1.,vmax=1.) 6763 imgAx = Img.axes 6764 ytics = imgAx.get_yticks() 6765 ylabs = [Page.varyList[int(i)] for i in ytics[:-1]] 6766 imgAx.set_yticklabels(ylabs) 6767 Page.figure.colorbar(Img) 6768 Plot.set_title('V-Cov matrix'+title) 6769 Plot.set_xlabel('Variable number') 6770 Plot.set_ylabel('Variable name') 6770 6771 Page.canvas.draw() 6771 6772 -
trunk/GSASIIstrIO.py
r4839 r4840 1076 1076 (RBModel['rbRef'][0],RBModel['rbRef'][1],RBModel['rbRef'][0],RBModel['rbRef'][2])) 1077 1077 1078 if Print and pFile is None: raise Exception("specify pFile or Print=False") 1078 1079 rbVary = [] 1079 1080 rbDict = {} … … 1432 1433 phaseVary += [name,] 1433 1434 1435 if Print and pFile is None: raise Exception("specify pFile or Print=False") 1434 1436 if Print: 1435 1437 pFile.write('\n Phases:\n') … … 2160 2162 ########################################################################## 2161 2163 # SetPhaseData starts here 2162 pFile.write('\n Phases:\n')2164 if pFile: pFile.write('\n Phases:\n') 2163 2165 for phase in Phases: 2164 pFile.write(' Result for phase: %s\n'%phase)2165 pFile.write(135*'='+'\n')2166 if pFile: pFile.write(' Result for phase: %s\n'%phase) 2167 if pFile: pFile.write(135*'='+'\n') 2166 2168 Phase = Phases[phase] 2167 2169 General = Phase['General'] … … 2178 2180 A,sigA = cellFill(pfx,SGData,parmDict,sigDict) 2179 2181 cellSig = getCellEsd(pfx,SGData,A,covData) #includes sigVol 2180 pFile.write(' Reciprocal metric tensor: \n')2182 if pFile: pFile.write(' Reciprocal metric tensor: \n') 2181 2183 ptfmt = "%15.9f" 2182 2184 names = ['A11','A22','A33','A12','A13','A23'] … … 2191 2193 else: 2192 2194 sigstr += 15*' ' 2193 pFile.write(namstr+'\n')2194 pFile.write(ptstr+'\n')2195 pFile.write(sigstr+'\n')2195 if pFile: pFile.write(namstr+'\n') 2196 if pFile: pFile.write(ptstr+'\n') 2197 if pFile: pFile.write(sigstr+'\n') 2196 2198 cell[1:7] = G2lat.A2cell(A) 2197 2199 cell[7] = G2lat.calc_V(A) 2198 pFile.write(' New unit cell:\n')2200 if pFile: pFile.write(' New unit cell:\n') 2199 2201 ptfmt = ["%12.6f","%12.6f","%12.6f","%12.4f","%12.4f","%12.4f","%12.3f"] 2200 2202 names = ['a','b','c','alpha','beta','gamma','Volume'] … … 2209 2211 else: 2210 2212 sigstr += 12*' ' 2211 pFile.write(namstr+'\n')2212 pFile.write(ptstr+'\n')2213 pFile.write(sigstr+'\n')2213 if pFile: pFile.write(namstr+'\n') 2214 if pFile: pFile.write(ptstr+'\n') 2215 if pFile: pFile.write(sigstr+'\n') 2214 2216 ik = 6 #for Pawley stuff below 2215 2217 if General.get('Modulated',False): … … 2217 2219 Vec,vRef,maxH = General['SuperVec'] 2218 2220 if vRef: 2219 pFile.write(' New modulation vector:\n')2221 if pFile: pFile.write(' New modulation vector:\n') 2220 2222 namstr = ' names :' 2221 2223 ptstr = ' values:' … … 2229 2231 else: 2230 2232 sigstr += 12*' ' 2231 pFile.write(namstr+'\n')2232 pFile.write(ptstr+'\n')2233 pFile.write(sigstr+'\n')2233 if pFile: pFile.write(namstr+'\n') 2234 if pFile: pFile.write(ptstr+'\n') 2235 if pFile: pFile.write(sigstr+'\n') 2234 2236 2235 2237 General['Mass'] = 0. … … 2247 2249 RRBIds = RBIds['Residue'] 2248 2250 RBModels = Phase['RBModels'] 2249 for irb,RBObj in enumerate(RBModels.get('Vector',[])): 2250 jrb = VRBIds.index(RBObj['RBId']) 2251 rbsx = str(irb)+':'+str(jrb) 2252 pFile.write(' Vector rigid body parameters:\n') 2253 PrintRBObjPOAndSig('RBV',rbsx) 2254 PrintRBObjTLSAndSig('RBV',rbsx,RBObj['ThermalMotion'][0]) 2255 for irb,RBObj in enumerate(RBModels.get('Residue',[])): 2256 jrb = RRBIds.index(RBObj['RBId']) 2257 rbsx = str(irb)+':'+str(jrb) 2258 pFile.write(' Residue rigid body parameters:\n') 2259 PrintRBObjPOAndSig('RBR',rbsx) 2260 PrintRBObjTLSAndSig('RBR',rbsx,RBObj['ThermalMotion'][0]) 2261 PrintRBObjTorAndSig(rbsx) 2251 if pFile: 2252 for irb,RBObj in enumerate(RBModels.get('Vector',[])): 2253 jrb = VRBIds.index(RBObj['RBId']) 2254 rbsx = str(irb)+':'+str(jrb) 2255 pFile.write(' Vector rigid body parameters:\n') 2256 PrintRBObjPOAndSig('RBV',rbsx) 2257 PrintRBObjTLSAndSig('RBV',rbsx,RBObj['ThermalMotion'][0]) 2258 for irb,RBObj in enumerate(RBModels.get('Residue',[])): 2259 jrb = RRBIds.index(RBObj['RBId']) 2260 rbsx = str(irb)+':'+str(jrb) 2261 pFile.write(' Residue rigid body parameters:\n') 2262 PrintRBObjPOAndSig('RBR',rbsx) 2263 PrintRBObjTLSAndSig('RBR',rbsx,RBObj['ThermalMotion'][0]) 2264 PrintRBObjTorAndSig(rbsx) 2262 2265 atomsSig = {} 2263 2266 wavesSig = {} … … 2325 2328 if pfx+name in sigDict: 2326 2329 wavesSig[name] = sigDict[pfx+name] 2327 2328 PrintAtomsAndSig(General,Atoms,atomsSig)2329 if General['Type'] == 'magnetic':2330 2331 if pFile: PrintAtomsAndSig(General,Atoms,atomsSig) 2332 if pFile and General['Type'] == 'magnetic': 2330 2333 PrintMomentsAndSig(General,Atoms,atomsSig) 2331 if General.get('Modulated',False):2334 if pFile and General.get('Modulated',False): 2332 2335 PrintWavesAndSig(General,Atoms,wavesSig) 2333 2336 2334 2337 density = G2mth.getDensity(General)[0] 2335 pFile.write('\n Density: {:.4f} g/cm**3\n'.format(density))2338 if pFile: pFile.write('\n Density: {:.4f} g/cm**3\n'.format(density)) 2336 2339 2337 2340 … … 3614 3617 sampSig = SetSampleParms(pfx,Sample,parmDict,sigDict) 3615 3618 3616 if not seq:3619 if Print and not seq: 3617 3620 pFile.write('\n Histogram: %s histogram Id: %d\n'%(histogram,hId)) 3618 3621 pFile.write(135*'='+'\n') 3619 pFile.write(' PWDR histogram weight factor = '+'%.3f\n'%(Histogram['wtFactor'])) 3620 pFile.write(' Final refinement wR = %.2f%% on %d observations in this histogram\n'% 3622 if Print: 3623 pFile.write(' PWDR histogram weight factor = '+'%.3f\n'%(Histogram['wtFactor'])) 3624 pFile.write(' Final refinement wR = %.2f%% on %d observations in this histogram\n'% 3621 3625 (Histogram['Residuals']['wR'],Histogram['Residuals']['Nobs'])) 3622 pFile.write(' Other residuals: R = %.2f%%, R-bkg = %.2f%%, wR-bkg = %.2f%% wRmin = %.2f%%\n'%3626 pFile.write(' Other residuals: R = %.2f%%, R-bkg = %.2f%%, wR-bkg = %.2f%% wRmin = %.2f%%\n'% 3623 3627 (Histogram['Residuals']['R'],Histogram['Residuals']['Rb'],Histogram['Residuals']['wR'],Histogram['Residuals']['wRmin'])) 3624 if Print:3625 3628 pFile.write(' Instrument type: %s\n'%Sample['Type']) 3626 3629 if calcControls != None: #skipped in seqRefine -
trunk/GSASIIstrMain.py
r4825 r4840 288 288 ReportProblems(result,Rvals,varyList) 289 289 # process singular variables 290 psing = result[2].get('psing',[])291 290 if dlg: break # refining interactively 292 # non-interactive refinement293 #for val in sorted(psing,reverse=True):294 # G2fil.G2Print ('Removing parameter: '+varyList[val])295 # del(varyList[val])296 #if not psing: break # removed variable(s), try again297 291 else: 298 292 G2fil.G2Print ('**** Refinement failed - singular matrix ****',mode='error') … … 304 298 break 305 299 if IfOK: 300 if CheckLeBail(Phases): # only needed for LeBail extraction 301 G2stMth.errRefine(values,[Histograms,Phases,restraintDict,rigidbodyDict], 302 parmDict,varyList,calcControls,pawleyLookup,dlg) 303 306 304 G2stMth.GetFobsSq(Histograms,Phases,parmDict,calcControls) 307 305 if chisq0 is not None: … … 483 481 Rvals['msg'] = Msg.msg 484 482 return False,Rvals 485 483 486 484 #for testing purposes, create a file for testderiv 487 485 if GSASIIpath.GetConfigValue('debug'): # and IfOK: … … 501 499 G2fil.G2Print ('Reported from refinement:',mode='warn') 502 500 G2fil.G2Print (Rvals['msg'],mode='warn') 501 502 def CheckLeBail(Phases): 503 '''Check if there is a LeBail extraction in any histogram 504 505 :returns: True if there is at least one LeBail flag turned on, False otherwise 506 ''' 507 for key in Phases: 508 phase = Phases[key] 509 for h in phase['Histograms']: 510 #phase['Histograms'][h] 511 if not phase['Histograms'][h]['Use']: continue 512 if phase['Histograms'][h]['LeBail']: 513 return True 514 return False 515 516 def DoLeBail(GPXfile,dlg=None,cycles=3,refPlotUpdate=None): 517 '''Fit LeBail intensities without changes to any other refined parameters. 518 This is a stripped-down version of :func:`Refine` that does not perform 519 any refinement cycles 520 ''' 521 import GSASIImpsubs as G2mp 522 G2mp.InitMP() 523 import pytexture as ptx 524 ptx.pyqlmninit() #initialize fortran arrays for spherical harmonics 525 526 #varyList = [] 527 parmDict = {} 528 Controls = G2stIO.GetControls(GPXfile) 529 calcControls = {} 530 calcControls.update(Controls) 531 constrDict,fixedList = G2stIO.GetConstraints(GPXfile) 532 restraintDict = {} 533 Histograms,Phases = G2stIO.GetUsedHistogramsAndPhases(GPXfile) 534 if not Phases: 535 G2fil.G2Print (' *** ERROR - you have no phases to refine! ***') 536 return False,{'msg':'No phases'} 537 if not Histograms: 538 G2fil.G2Print (' *** ERROR - you have no data to refine with! ***') 539 return False,{'msg':'No data'} 540 if not CheckLeBail(Phases): 541 msg = 'Warning: There are no histograms with LeBail extraction enabled' 542 G2fil.G2Print ('*** '+msg+' ***') 543 return False,{'msg': msg} 544 rigidbodyDict = G2stIO.GetRigidBodies(GPXfile) 545 rbIds = rigidbodyDict.get('RBIds',{'Vector':[],'Residue':[]}) 546 rbVary,rbDict = G2stIO.GetRigidBodyModels(rigidbodyDict,Print=False) 547 (Natoms,atomIndx,phaseVary,phaseDict,pawleyLookup,FFtables,BLtables,MFtables, 548 maxSSwave) = G2stIO.GetPhaseData(Phases,restraintDict,rbIds,Print=False) 549 calcControls['atomIndx'] = atomIndx 550 calcControls['Natoms'] = Natoms 551 calcControls['FFtables'] = FFtables 552 calcControls['BLtables'] = BLtables 553 calcControls['MFtables'] = MFtables 554 calcControls['maxSSwave'] = maxSSwave 555 hapVary,hapDict,controlDict = G2stIO.GetHistogramPhaseData(Phases,Histograms,Print=False) 556 calcControls.update(controlDict) 557 histVary,histDict,controlDict = G2stIO.GetHistogramData(Histograms,Print=False) 558 calcControls.update(controlDict) 559 parmDict.update(rbDict) 560 parmDict.update(phaseDict) 561 parmDict.update(hapDict) 562 parmDict.update(histDict) 563 G2stIO.GetFprime(calcControls,Histograms) 564 parmFrozenList = Controls['parmFrozen']['FrozenList'] 565 try: 566 for i in range(cycles): 567 M = G2stMth.errRefine([],[Histograms,Phases,restraintDict,rigidbodyDict],parmDict,[],calcControls,pawleyLookup,dlg) 568 G2stMth.GetFobsSq(Histograms,Phases,parmDict,calcControls) 569 if refPlotUpdate is not None: refPlotUpdate(Histograms,i) 570 Rvals = {} 571 Rvals['chisq'] = np.sum(M**2) 572 Rvals['Nobs'] = Histograms['Nobs'] 573 Rvals['Rwp'] = np.sqrt(Rvals['chisq']/Histograms['sumwYo'])*100. #to % 574 Rvals['GOF'] = np.sqrt(Rvals['chisq']/(Histograms['Nobs'])) # no variables 575 576 covData = {'variables':0,'varyList':[],'sig':[],'Rvals':Rvals, 577 'varyListStart':[], 578 'covMatrix':np.zeros([0,0]),'title':GPXfile, 579 #'newAtomDict':newAtomDict,'newCellDict':newCellDict, 580 'freshCOV':True} 581 582 G2stIO.SetUsedHistogramsAndPhases(GPXfile,Histograms,Phases,rigidbodyDict,covData,parmFrozenList,True) 583 G2fil.G2Print (' ***** LeBail fit completed *****') 584 return True,Rvals 585 except Exception as Msg: 586 G2fil.G2Print (' ***** LeBail fit error *****') 587 if not hasattr(Msg,'msg'): Msg.msg = str(Msg) 588 if GSASIIpath.GetConfigValue('debug'): 589 import traceback 590 print(traceback.format_exc()) 591 return False,{'msg':Msg.msg} 503 592 504 593 def phaseCheck(phaseVary,Phases,histogram): -
trunk/GSASIIstrMath.py
r4834 r4840 496 496 if 'General' == pName.split(':')[1]: 497 497 # initialize for General restraint(s) here 498 GeneralInit = True499 498 parmDict0 = parmDict.copy() 500 499 # setup steps for each parameter … … 3944 3943 else: 3945 3944 dMdV = np.concatenate((dMdV.T,np.sqrt(wtFactor)*dMdvh.T)).T 3946 3945 3947 3946 GetFobsSq(Histograms,Phases,parmDict,calcControls) 3948 3947 pNames,pVals,pWt,pWsum,pWnum = penaltyFxn(HistoPhases,calcControls,parmDict,varylist)
Note: See TracChangeset
for help on using the changeset viewer.