- Timestamp:
- May 7, 2020 12:17:26 PM (3 years ago)
- Location:
- trunk
- Files:
-
- 8 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/GSASIIimage.py
r4350 r4415 571 571 dist = data['distance']/npcosd(tilt) 572 572 x0 = data['distance']*nptand(tilt) 573 x0x = x0*npcosd(data['rotation']) 574 x0y = x0*npsind(data['rotation']) 573 575 MN = -np.inner(makeMat(data['rotation'],2),makeMat(tilt,0)) 574 576 distsq = data['distance']**2 575 577 dx = x-data['center'][0] 576 578 dy = y-data['center'][1] 577 G = ((dx-x0 )**2+dy**2+distsq)/distsq #for geometric correction = 1/cos(2theta)^2 if tilt=0.579 G = ((dx-x0x)**2+(dy-x0y)**2+distsq)/distsq #for geometric correction = 1/cos(2theta)^2 if tilt=0. 578 580 Z = np.dot(np.dstack([dx.T,dy.T,np.zeros_like(dx.T)]),MN).T[2] 579 581 xyZ = dx**2+dy**2-Z**2 -
trunk/GSASIIlattice.py
r4268 r4415 298 298 return newAtoms,Codes 299 299 300 def TransformPhase(oldPhase,newPhase,Trans,Uvec,Vvec,ifMag ):300 def TransformPhase(oldPhase,newPhase,Trans,Uvec,Vvec,ifMag,Force=True): 301 301 '''Transform atoms from oldPhase to newPhase 302 302 M' is inv(M) … … 325 325 SGData = newPhase['General']['SGData'] 326 326 invTrans = nl.inv(Trans) 327 newAtoms,atCodes = FillUnitCell(oldPhase )327 newAtoms,atCodes = FillUnitCell(oldPhase,Force) 328 328 newAtoms,atCodes = ExpandCell(newAtoms,atCodes,cx,Trans) 329 329 if ifMag: … … 343 343 newPhase['Draw Atoms'] = [] 344 344 for atom in newAtoms: 345 xyz = TransformXYZ(atom[cx:cx+3]+Uvec,invTrans.T,Vvec)%1. 346 atom[cx:cx+3] = np.around(xyz,6)%1. 345 xyz = TransformXYZ(atom[cx:cx+3]+Uvec,invTrans.T,Vvec) 346 if Force: 347 xyz = np.around(xyz,6)%1. 348 atom[cx:cx+3] = xyz 347 349 if atom[cia] == 'A': 348 350 atom[cia+2:cia+8] = TransformU6(atom[cia+2:cia+8],Trans) … … 476 478 return phase 477 479 478 def FillUnitCell(Phase ):480 def FillUnitCell(Phase,Force=True): 479 481 Atoms = copy.deepcopy(Phase['Atoms']) 480 482 atomData = [] … … 489 491 for iat,atom in enumerate(Atoms): 490 492 XYZ = np.array(atom[cx:cx+3]) 491 xyz = XYZ%1. 493 xyz = XYZ 494 if Force: 495 xyz %= 1. 492 496 if atom[cia] == 'A': 493 497 Uij = atom[cia+2:cia+8] 494 result = G2spc.GenAtom(xyz,SGData,False,Uij, True)498 result = G2spc.GenAtom(xyz,SGData,False,Uij,False) 495 499 for item in result: 496 if item[0][2] >= .95: item[0][2] -= 1.500 # if item[0][2] >= .95: item[0][2] -= 1. 497 501 atom[cx:cx+3] = item[0] 498 502 atom[cia+2:cia+8] = item[1] -
trunk/GSASIImath.py
r4401 r4415 492 492 493 493 :param list atomData: Atom table to be used 494 :param int indx: pointer to position of atom id in atom record (typically cia+8) 494 495 495 496 :returns: dict atomLookUp: dictionary of atom indexes with atom IDs as keys 496 497 497 498 ''' 498 atomLookUp = {} 499 for iatm,atom in enumerate(atomData): 500 atomLookUp[atom[indx]] = iatm 501 return atomLookUp 499 return {atom[indx]:iatm for iatm,atom in enumerate(atomData)} 502 500 503 501 def GetAtomsById(atomData,atomLookUp,IdList): … … 636 634 for j in IndB[0]: 637 635 if j != Orig: 638 if AtNames[j] !=notName:636 if AtNames[j] not in notName: 639 637 Neigh.append([AtNames[j],dist[j],True]) 640 638 Ids.append(Atoms[j][cia+8]) … … 697 695 return bond,std,meanDisp,stdDisp,A,V,vecDisp 698 696 699 def FindAllNeighbors(phase,FrstName,AtNames,notName='' ):697 def FindAllNeighbors(phase,FrstName,AtNames,notName='',Orig=None,Short=False): 700 698 General = phase['General'] 701 699 cx,ct,cs,cia = General['AtomPtrs'] … … 713 711 radiusFactor = DisAglCtls['Factors'][0] 714 712 AtInfo = dict(zip(AtTypes,Radii)) #or General['BondRadii'] 715 Orig = atNames.index(FrstName) 713 if Orig is None: 714 Orig = atNames.index(FrstName) 716 715 OId = Atoms[Orig][cia+8] 717 716 OType = Atoms[Orig][ct] … … 739 738 else: 740 739 Topstr = ' +(%4d)'%(Top) 741 Neigh.append([AtNames[iA]+Topstr,atTypes[iA],dist[iU],dx[iU]]) 740 if Short: 741 Neigh.append([AtNames[iA],dist[iU],True]) 742 else: 743 Neigh.append([AtNames[iA]+Topstr,atTypes[iA],dist[iU],dx[iU]]) 742 744 Ids.append(Atoms[iA][cia+8]) 743 745 return Neigh,[OId,Ids] … … 1952 1954 vec[i] /= dist 1953 1955 angle = acosd(np.sum(vec[0]*vec[1])) 1954 # GSASIIpath.IPyBreak()1955 1956 return angle 1956 1957 -
trunk/GSASIIphsGUI.py
r4405 r4415 64 64 import numpy as np 65 65 import numpy.linalg as nl 66 import numpy.fft as fft 66 67 import atmdata 67 68 … … 2770 2771 nTet = 0 2771 2772 nElse = 0 2772 for atom in data['Atoms']:2773 for iatm,atom in enumerate(data['Atoms']): 2773 2774 if atom[ct] == Oatoms: 2774 results = G2mth.FindAllNeighbors(data,atom[ct-1],atNames )[0] #slow step2775 results = G2mth.FindAllNeighbors(data,atom[ct-1],atNames,Orig=iatm)[0] #slow step 2775 2776 if len(results) == 4: 2776 2777 bond,std,meanDisp,stdDisp,A,V,dVec = G2mth.FindTetrahedron(results) … … 3006 3007 dlg.Destroy() 3007 3008 elif Atoms.GetColLabelValue(c) == 'Uiso': #this needs to ask for value 3008 pass #& then change all 'I' atoms3009 return #& then change all 'I' atoms; now do nothing 3009 3010 else: 3010 3011 return … … 3977 3978 indx = GetSelectedAtoms() 3978 3979 DisAglCtls = {} 3979 if len(indx) == 1:3980 if indx is not None and len(indx) == 1: 3980 3981 generalData = data['General'] 3981 3982 if 'DisAglCtls' in generalData: … … 4503 4504 start += 1 4504 4505 Xlab = 'Q' 4505 if 'G(R)' in fileItem[2] :4506 if 'G(R)' in fileItem[2].upper(): 4506 4507 Xlab = 'R' 4507 4508 G2plt.PlotXY(G2frame,[XY.T,],labelX=Xlab, 4508 4509 labelY=fileItem[2],newPlot=True,Title=fileItem[0], 4509 4510 lines=True) 4511 4512 def OnCorrChk(event): 4513 Obj = event.GetEventObject() 4514 fil = Indx[Obj.GetId()] 4515 RMCPdict['files'][fil][3] = not RMCPdict['files'][fil][3] 4510 4516 4511 4517 Indx = {} … … 4522 4528 mainSizer.Add(wx.StaticText(G2frame.FRMC, 4523 4529 label=' NB: fullrmc data files must be 2 columns; all other lines preceeded by "#". Edit before use.'),0,WACV) 4524 ncol = 4 4525 Heads = ['Name','File','Weight','Plot'] 4530 Heads = ['Name','File','Weight','Plot','Corr'] 4526 4531 fileSizer = wx.FlexGridSizer(ncol,5,5) 4527 4532 Formats = ['RMC','GUDRUN','STOG'] … … 4549 4554 Indx[plotBtn.GetId()] = fil 4550 4555 fileSizer.Add(plotBtn,0,WACV) 4556 if G2frame.RMCchoice == 'fullrmc': 4557 lab = 'Apply sinc convolution? ' 4558 if 'G(r)' in fil: 4559 lab = 'Apply r*G(r) conversion? ' 4560 corrChk = wx.CheckBox(G2frame.FRMC,label=lab) 4561 #patch 4562 if len(RMCPdict['files'][fil]) < 4: 4563 RMCPdict['files'][fil].append(True) 4564 #end patch 4565 corrChk.SetValue(RMCPdict['files'][fil][3]) 4566 Indx[corrChk.GetId()] = fil 4567 corrChk.Bind(wx.EVT_CHECKBOX,OnCorrChk) 4568 fileSizer.Add(corrChk,0,WACV) 4551 4569 else: 4552 4570 RMCPdict['files'][fil][0] = 'Select' 4553 4571 fileSizer.Add((5,5),0) 4554 4572 fileSizer.Add((5,5),0) 4555 if G2frame.RMCchoice == 'RMCProfile': 4556 fileSizer.Add((5,5),0) 4573 fileSizer.Add((5,5),0) 4557 4574 return fileSizer 4558 4575 … … 4601 4618 Pairs += pair 4602 4619 Pairs = {pairs:[0.0,0.0,0.0] for pairs in Pairs} 4603 files = {'Neutron real space data; G(r): ':['Select',0.05,'G(r)'], 4604 'Neutron reciprocal space data; F(Q): ':['Select',0.05,'F(Q)'], 4605 'Neutron reciprocal space data; S(Q): ':['Select',0.05,'S(Q)'], 4606 'Xray real space data; G(r): ':['Select',0.01,'G(r)'], 4607 'Xray reciprocal space data; F(Q): ':['Select',0.01,'F(Q)'],} 4620 files = {'Neutron real space data; G(r): ':['Select',0.05,'G(r)',True], 4621 'Neutron reciprocal space data; F(Q): ':['Select',0.05,'F(Q)',True], 4622 'Xray real space data; G(r): ':['Select',0.01,'G(r)',True], 4623 'Xray reciprocal space data; F(Q): ':['Select',0.01,'F(Q)',True],} 4608 4624 data['RMC']['fullrmc'] = {'SuperCell':[1,1,1],'Box':[10.,10.,10.],'aTypes':aTypes,'byMolec':False, 4609 'Natoms':1,'atSeq':atSeq,'Pairs':Pairs,'files':files,'ReStart':[False,False], 4625 'Natoms':1,'atSeq':atSeq,'Pairs':Pairs,'files':files,'ReStart':[False,False],'Cycles':1, 4610 4626 'Swaps':[],'useBVS':False,'FitScale':False,'AveCN':[],'FxCN':[],'Angles':[],'Angle Weight':1.e-5, 4611 'moleculePdb':'Select','targetDensity':1.0,'maxRecursion':10000, 4612 'atomPDB':'' }4627 'moleculePdb':'Select','targetDensity':1.0,'maxRecursion':10000,'Torsions':[],'Torsion Weight':1.e-5, 4628 'atomPDB':'','Bond Weight':1.e-5,'min Contact':1.5} 4613 4629 RMCPdict = data['RMC']['fullrmc'] 4614 4630 … … 4686 4702 wx.CallAfter(UpdateRMC) 4687 4703 4704 def OnAddTorsion(event): 4705 RMCPdict['Torsions'].append(['','','','',0.,0.,0.,0.,0.,0.]) 4706 wx.CallAfter(UpdateRMC) 4707 4688 4708 def GetAngleSizer(): 4689 4709 … … 4722 4742 angleSizer.Add(G2G.ValidatedTxtCtrl(G2frame.FRMC,angle,4,min=0.,max=180.,OnLeave=SetRestart1,size=(50,25)),0,WACV) 4723 4743 return angleSizer 4744 4745 def GetTorsionSizer(): 4746 4747 def OnDelTorsion(event): 4748 Obj = event.GetEventObject() 4749 angle = Indx[Obj.GetId()] 4750 del RMCPdict['Torsions'][angle] 4751 wx.CallAfter(UpdateRMC) 4752 4753 def OnTorsionAtSel(event): 4754 Obj = event.GetEventObject() 4755 torsion,i = Indx[Obj.GetId()] 4756 RMCPdict['Torsions'][torsion][i] = Obj.GetStringSelection() 4757 4758 def SetRestart1(invalid,value,tc): 4759 RMCPdict['ReStart'][1] = True 4760 4761 Indx = {} 4762 torsionSizer = wx.FlexGridSizer(11,5,5) 4763 fxcnLabels = [' ','Atom-A','Atom-B','Atom-C','Atom-D',' min angle1',' max angle1',' min angle2',' max angle2',' min angle3',' max angle3'] 4764 for lab in fxcnLabels: 4765 torsionSizer.Add(wx.StaticText(G2frame.FRMC,label=lab),0,WACV) 4766 for ifx,torsion in enumerate(RMCPdict['Torsions']): 4767 delBtn = wx.Button(G2frame.FRMC,label='Delete') 4768 delBtn.Bind(wx.EVT_BUTTON,OnDelTorsion) 4769 Indx[delBtn.GetId()] = ifx 4770 torsionSizer.Add(delBtn,0,WACV) 4771 for i in [0,1,2,3]: 4772 atmSel = wx.ComboBox(G2frame.FRMC,choices=atNames,style=wx.CB_DROPDOWN|wx.TE_READONLY) 4773 atmSel.SetStringSelection(torsion[i]) 4774 atmSel.Bind(wx.EVT_COMBOBOX,OnTorsionAtSel) 4775 Indx[atmSel.GetId()] = [ifx,i] 4776 torsionSizer.Add(atmSel,0,WACV) 4777 for i in [4,5,6,7,8,9]: 4778 torsionSizer.Add(G2G.ValidatedTxtCtrl(G2frame.FRMC,torsion,i,min=0.,max=360.,OnLeave=SetRestart1,size=(50,25)),0,WACV) 4779 return torsionSizer 4724 4780 #patches 4725 4781 if 'useBVS' not in RMCPdict: … … 4737 4793 if 'Angles' not in RMCPdict: 4738 4794 RMCPdict.update({'Angles':[],'Angle Weight':1.e-5,'Bond Weight':1.e-5,'Torsions':[],'Torsion Weight':1.e-5}) 4795 if 'Cycles' not in RMCPdict: 4796 RMCPdict['Cycles'] = 1 4797 if 'min Contact' not in RMCPdict: 4798 RMCPdict['min Contact'] = 1.5 4739 4799 #end patches 4740 4800 4741 4801 generalData = data['General'] 4802 cx,ct,cs,cia = generalData['AtomPtrs'] 4803 atomData = data['Atoms'] 4804 atNames = [atom[ct-1] for atom in atomData] 4805 ifP1 = False 4806 if generalData['SGData']['SpGrp'] == 'P 1': 4807 ifP1 = True 4742 4808 ifBox = False 4743 4809 if 'macromolecular' in generalData['Type']: … … 4747 4813 lineSizer.Add(wx.StaticText(G2frame.FRMC,label=' Big box dimensions, %s:'%Angstr),0,WACV) 4748 4814 lineSizer.Add(GetBoxSizer(),0,WACV) 4749 el se:4815 elif ifP1: 4750 4816 lineSizer.Add(wx.StaticText(G2frame.FRMC,label=' Lattice multipliers:'),0,WACV) 4751 4817 lineSizer.Add(GetSuperSizer(),0,WACV) … … 4756 4822 lineSizer.Add(wx.StaticText(G2frame.FRMC,label=' Num. atoms per molecule '),0,WACV) 4757 4823 lineSizer.Add(G2G.ValidatedTxtCtrl(G2frame.FRMC,RMCPdict,'Natoms',min=1,size=[40,25]),0,WACV) 4824 else: 4825 lineSizer.Add(wx.StaticText(G2frame.FRMC,label=' Starting phase symmetry must be P 1; transform structure first')) 4758 4826 mainSizer.Add(lineSizer,0,WACV) 4759 4827 if ifBox: … … 4771 4839 molecSizer.Add(makePDB,0,WACV) 4772 4840 mainSizer.Add(molecSizer,0,WACV) 4773 el se:4841 elif ifP1: 4774 4842 makePDB = wx.Button(G2frame.FRMC,label='Make big box PDB') 4775 4843 makePDB.Bind(wx.EVT_BUTTON,OnMakePDB) 4776 mainSizer.Add(makePDB,0,WACV) 4844 mainSizer.Add(makePDB,0,WACV) 4845 else: #Abort because starting phase symmetry isn't P 1 4846 SetPhaseWindow(G2frame.FRMC,mainSizer) 4847 return 4777 4848 4778 4849 G2G.HorizontalLine(mainSizer,G2frame.FRMC) 4779 4850 mainSizer.Add(wx.StaticText(G2frame.FRMC,label=' fullrmc run file preparation:'),0,WACV) 4851 resLine = wx.BoxSizer(wx.HORIZONTAL) 4780 4852 restart = wx.CheckBox(G2frame.FRMC,label=' Restart fullrmc Engine? (will clear old result!) ') 4781 4853 restart.SetValue(RMCPdict['ReStart'][0]) 4782 4854 restart.Bind(wx.EVT_CHECKBOX,OnReStart) 4783 mainSizer.Add(restart,0,WACV) 4855 resLine.Add(restart,0,WACV) 4856 resLine.Add(wx.StaticText(G2frame.FRMC,label=' Computation cycles: '),0,WACV) 4857 resLine.Add(G2G.ValidatedTxtCtrl(G2frame.FRMC,RMCPdict,'Cycles',min=1,size=[60,25]),0,WACV) 4858 mainSizer.Add(resLine,0,WACV) 4784 4859 4785 4860 G2G.HorizontalLine(mainSizer,G2frame.FRMC) … … 4801 4876 distBox.Add(wx.StaticText(G2frame.FRMC,label=' Distance constraints, weight: :'),0,WACV) 4802 4877 distBox.Add(G2G.ValidatedTxtCtrl(G2frame.FRMC,RMCPdict,'Bond Weight',min=0.,max=100.,size=(50,25)),0,WACV) 4878 distBox.Add(wx.StaticText(G2frame.FRMC,label=' min contact dist: '),0,WACV) 4879 distBox.Add(G2G.ValidatedTxtCtrl(G2frame.FRMC,RMCPdict,'min Contact',min=0.,max=4.,size=(50,25)),0,WACV) 4803 4880 mainSizer.Add(distBox,0,WACV) 4804 4881 mainSizer.Add(GetPairSizer(RMCPdict),0,WACV) … … 4814 4891 mainSizer.Add(GetAngleSizer(),0,WACV) 4815 4892 4893 torBox = wx.BoxSizer(wx.HORIZONTAL) 4894 torAdd = wx.Button(G2frame.FRMC,label='Add') 4895 torAdd.Bind(wx.EVT_BUTTON,OnAddTorsion) 4896 torBox.Add(torAdd,0,WACV) 4897 torBox.Add(wx.StaticText(G2frame.FRMC,label=' A-B-C-D torsion angle restraints, weight: '),0,WACV) 4898 torBox.Add(G2G.ValidatedTxtCtrl(G2frame.FRMC,RMCPdict,'Torsion Weight',min=0.,max=100.,size=(50,25)),0,WACV) 4899 mainSizer.Add(torBox,0,WACV) 4900 if len(RMCPdict['Torsions']): 4901 mainSizer.Add(GetTorsionSizer(),0,WACV) 4902 4816 4903 G2G.HorizontalLine(mainSizer,G2frame.FRMC) 4817 4904 mainSizer.Add(FileSizer(RMCPdict),0,WACV) … … 5220 5307 G2frame.OnFileSaveas(event) 5221 5308 if G2frame.RMCchoice == 'fullrmc': 5309 DisAglCtls = {} 5310 if 'DisAglCtls' in generalData: 5311 DisAglCtls = generalData['DisAglCtls'] 5312 dlg = G2G.DisAglDialog(G2frame,DisAglCtls,generalData,Reset=False) 5313 if dlg.ShowModal() == wx.ID_OK: 5314 DisAglCtls = dlg.GetData() 5315 if 'H' not in DisAglCtls['AtomTypes']: 5316 DisAglCtls['AtomTypes'].append('H') 5317 DisAglCtls['AngleRadii'].append(0.5) 5318 DisAglCtls['BondRadii'].append(0.5) 5319 dlg.Destroy() 5320 generalData['DisAglCtls'] = DisAglCtls 5222 5321 G2frame.dataWindow.FRMCDataEdit.Enable(G2G.wxID_RUNRMC,True) 5223 5322 RMCPdict = data['RMC']['fullrmc'] 5224 5323 fname = G2pwd.MakefullrmcRun(pName,data,RMCPdict) 5225 print('fullrmc file %s build completed'%fname) 5324 if fname is None: 5325 wx.MessageDialog(G2frame,' Big box pdb file is missing; fullrmc will not run','Missing pdb file',wx.OK).ShowModal() 5326 else: 5327 print('fullrmc file %s build completed'%fname) 5226 5328 else: 5227 5329 G2frame.dataWindow.FRMCDataEdit.Enable(G2G.wxID_RUNRMC,True) … … 5290 5392 # TBD - remove filedialog & use defined run.py file name here 5291 5393 rname = pName+'-run.py' 5292 dlg = wx.FileDialog(G2frame, 'Choose fullrmc python file to execute', G2G.GetImportPath(G2frame),5293 wildcard='fullrmc python file (*.py)|*.py',style=wx.FD_CHANGE_DIR)5294 try:5295 if dlg.ShowModal() == wx.ID_OK:5296 rname = dlg.GetPath()5297 else:5298 return5299 finally:5300 dlg.Destroy()5394 # dlg = wx.FileDialog(G2frame, 'Choose fullrmc python file to execute', G2G.GetImportPath(G2frame), 5395 # wildcard='fullrmc python file (*.py)|*.py',style=wx.FD_CHANGE_DIR) 5396 # try: 5397 # if dlg.ShowModal() == wx.ID_OK: 5398 # rname = dlg.GetPath() 5399 # else: 5400 # return 5401 # finally: 5402 # dlg.Destroy() 5301 5403 import subprocess as sb 5302 5404 batch = open('fullrmc.bat','w') … … 5413 5515 if 'total' not in rdfDict: 5414 5516 print('No data yet - wait for a save') 5517 ENGINE.close() 5415 5518 if Proc is not None: 5416 5519 Proc.resume() … … 5466 5569 G2plt.PlotBarGraph(G2frame,bondAngs,Xname=r'%s Angle, deg'%Aname,Title='%s Bond angles for %s'%(Aname,pName), 5467 5570 PlotName='%s Angles for %s'%(Aname,pName),maxBins=20) 5468 elif ' ImproperAngleConstraint' in sitem:5571 elif 'DihedralAngleConstraint' in sitem: 5469 5572 impangles = 180.*item.get_constraint_value()['angles']/np.pi 5470 5573 impangleList = item.anglesList[:4] … … 5476 5579 for Aname in impangleSet: 5477 5580 impAngs = [angle[1] for angle in impAngles if angle[0]==Aname] 5478 G2plt.PlotBarGraph(G2frame,impAngs,Xname=r'%s $ Improper Angle, deg$'%Aname,Title='%s Improperangles for %s'%(Aname,pName),5479 PlotName='%s ImproperAngles for %s'%(Aname,pName),maxBins=20)5581 G2plt.PlotBarGraph(G2frame,impAngs,Xname=r'%s $Dihedral Angle, deg$'%Aname,Title='%s Dihedral angles for %s'%(Aname,pName), 5582 PlotName='%s Dihedral Angles for %s'%(Aname,pName),maxBins=20) 5480 5583 elif 'AtomicCoordinationNumber' in sitem or 'InterMolecular' in sitem: 5481 5584 print(sitem+' not plotted') -
trunk/GSASIIplot.py
r4408 r4415 290 290 fil.write(line+'\n') 291 291 292 def MPLsubplots(figure, nrows=1, ncols=1, sharex=False, sharey=False,293 squeeze=True, subplot_kw=None, gridspec_kw=None):294 """295 Add a set of subplots to this figure.296 297 This is a copy of Figure.figure.subplots from matplotlib.figure.py.298 Included here because this appears only in later versions of299 matplotlib. When v2.2 is standard, this should be removed from GSAS-II.300 301 :param int nrows, ncols: default: 1302 Number of rows/cols of the subplot grid.303 :param bool/str sharex, sharey: True/False or {'none', 'all', 'row', 'col'}, default: False304 305 Controls sharing of properties among x (`sharex`) or y (`sharey`)306 axes:292 # def MPLsubplots(figure, nrows=1, ncols=1, sharex=False, sharey=False, 293 # squeeze=True, subplot_kw=None, gridspec_kw=None): 294 # """ 295 # Add a set of subplots to this figure. 296 297 # This is a copy of Figure.figure.subplots from matplotlib.figure.py. 298 # Included here because this appears only in later versions of 299 # matplotlib. When v2.2 is standard, this should be removed from GSAS-II. 300 301 # :param int nrows, ncols: default: 1 302 # Number of rows/cols of the subplot grid. 303 # :param bool/str sharex, sharey: True/False or {'none', 'all', 'row', 'col'}, default: False 304 305 # Controls sharing of properties among x (`sharex`) or y (`sharey`) 306 # axes: 307 307 308 - True or 'all': x- or y-axis will be shared among all309 subplots.310 - False or 'none': each subplot x- or y-axis will be311 independent.312 - 'row': each subplot row will share an x- or y-axis.313 - 'col': each subplot column will share an x- or y-axis.308 # - True or 'all': x- or y-axis will be shared among all 309 # subplots. 310 # - False or 'none': each subplot x- or y-axis will be 311 # independent. 312 # - 'row': each subplot row will share an x- or y-axis. 313 # - 'col': each subplot column will share an x- or y-axis. 314 314 315 When subplots have a shared x-axis along a column, only the x tick316 labels of the bottom subplot are visible. Similarly, when317 subplots have a shared y-axis along a row, only the y tick labels318 of the first column subplot are visible.319 :param bool squeeze: default: True320 321 - If True, extra dimensions are squeezed out from the returned322 axis object:315 # When subplots have a shared x-axis along a column, only the x tick 316 # labels of the bottom subplot are visible. Similarly, when 317 # subplots have a shared y-axis along a row, only the y tick labels 318 # of the first column subplot are visible. 319 # :param bool squeeze: default: True 320 321 # - If True, extra dimensions are squeezed out from the returned 322 # axis object: 323 323 324 - if only one subplot is constructed (nrows=ncols=1), the325 resulting single Axes object is returned as a scalar.326 - for Nx1 or 1xN subplots, the returned object is a 1D numpy327 object array of Axes objects are returned as numpy 1D328 arrays.329 - for NxM, subplots with N>1 and M>1 are returned as a 2D330 arrays.324 # - if only one subplot is constructed (nrows=ncols=1), the 325 # resulting single Axes object is returned as a scalar. 326 # - for Nx1 or 1xN subplots, the returned object is a 1D numpy 327 # object array of Axes objects are returned as numpy 1D 328 # arrays. 329 # - for NxM, subplots with N>1 and M>1 are returned as a 2D 330 # arrays. 331 331 332 - If False, no squeezing at all is done: the returned Axes object333 is always a 2D array containing Axes instances, even if it ends334 up being 1x1.332 # - If False, no squeezing at all is done: the returned Axes object 333 # is always a 2D array containing Axes instances, even if it ends 334 # up being 1x1. 335 335 336 :param dict subplot_kw: default: {}337 Dict with keywords passed to the338 :meth:`matplotlib.figure.Figure.add_subplot` call used to create339 each subplots.340 :param dict gridspec_kw: default: {}341 Dict with keywords passed to the342 :class:`matplotlib.gridspec.GridSpec` constructor used to create343 the grid the subplots are placed on.336 # :param dict subplot_kw: default: {} 337 # Dict with keywords passed to the 338 # :meth:`matplotlib.figure.Figure.add_subplot` call used to create 339 # each subplots. 340 # :param dict gridspec_kw: default: {} 341 # Dict with keywords passed to the 342 # :class:`matplotlib.gridspec.GridSpec` constructor used to create 343 # the grid the subplots are placed on. 344 344 345 :returns: A single Axes object or array of Axes objects with346 the added axes. The dimensions of the resulting array can be347 controlled with the squeeze keyword, see above.345 # :returns: A single Axes object or array of Axes objects with 346 # the added axes. The dimensions of the resulting array can be 347 # controlled with the squeeze keyword, see above. 348 348 349 See also: pyplot.subplots: pyplot API; docstring includes examples.350 351 """352 353 # for backwards compatibility354 if isinstance(sharex, bool):355 sharex = "all" if sharex else "none"356 if isinstance(sharey, bool):357 sharey = "all" if sharey else "none"358 share_values = ["all", "row", "col", "none"]359 if sharex not in share_values:360 # This check was added because it is very easy to type361 # `subplots(1, 2, 1)` when `subplot(1, 2, 1)` was intended.362 # In most cases, no error will ever occur, but mysterious behavior363 # will result because what was intended to be the subplot index is364 # instead treated as a bool for sharex.365 if isinstance(sharex, int):366 warnings.warn(367 "sharex argument to subplots() was an integer. "368 "Did you intend to use subplot() (without 's')?")369 370 raise ValueError("sharex [%s] must be one of %s" %371 (sharex, share_values))372 if sharey not in share_values:373 raise ValueError("sharey [%s] must be one of %s" %374 (sharey, share_values))375 if subplot_kw is None:376 subplot_kw = {}377 if gridspec_kw is None:378 gridspec_kw = {}379 380 # if figure.get_constrained_layout():381 # gs = GridSpec(nrows, ncols, figure=figure, **gridspec_kw)382 # else:383 # # this should turn constrained_layout off if we don't want it384 # gs = GridSpec(nrows, ncols, figure=None, **gridspec_kw)385 gs = mpl.gridspec.GridSpec(nrows, ncols, **gridspec_kw)386 387 # Create array to hold all axes.388 axarr = np.empty((nrows, ncols), dtype=object)389 for row in range(nrows):390 for col in range(ncols):391 shared_with = {"none": None, "all": axarr[0, 0],392 "row": axarr[row, 0], "col": axarr[0, col]}393 subplot_kw["sharex"] = shared_with[sharex]394 subplot_kw["sharey"] = shared_with[sharey]395 axarr[row, col] = figure.add_subplot(gs[row, col], **subplot_kw)396 397 # turn off redundant tick labeling398 if sharex in ["col", "all"]:399 # turn off all but the bottom row400 for ax in axarr[:-1, :].flat:401 ax.xaxis.set_tick_params(which='both',402 labelbottom=False, labeltop=False)403 ax.xaxis.offsetText.set_visible(False)404 if sharey in ["row", "all"]:405 # turn off all but the first column406 for ax in axarr[:, 1:].flat:407 ax.yaxis.set_tick_params(which='both',408 labelleft=False, labelright=False)409 ax.yaxis.offsetText.set_visible(False)410 411 if squeeze:412 # Discarding unneeded dimensions that equal 1. If we only have one413 # subplot, just return it instead of a 1-element array.414 return axarr.item() if axarr.size == 1 else axarr.squeeze()415 else:416 # Returned axis array will be always 2-d, even if nrows=ncols=1.417 return axarr349 # See also: pyplot.subplots: pyplot API; docstring includes examples. 350 351 # """ 352 353 # # for backwards compatibility 354 # if isinstance(sharex, bool): 355 # sharex = "all" if sharex else "none" 356 # if isinstance(sharey, bool): 357 # sharey = "all" if sharey else "none" 358 # share_values = ["all", "row", "col", "none"] 359 # if sharex not in share_values: 360 # # This check was added because it is very easy to type 361 # # `subplots(1, 2, 1)` when `subplot(1, 2, 1)` was intended. 362 # # In most cases, no error will ever occur, but mysterious behavior 363 # # will result because what was intended to be the subplot index is 364 # # instead treated as a bool for sharex. 365 # if isinstance(sharex, int): 366 # warnings.warn( 367 # "sharex argument to subplots() was an integer. " 368 # "Did you intend to use subplot() (without 's')?") 369 370 # raise ValueError("sharex [%s] must be one of %s" % 371 # (sharex, share_values)) 372 # if sharey not in share_values: 373 # raise ValueError("sharey [%s] must be one of %s" % 374 # (sharey, share_values)) 375 # if subplot_kw is None: 376 # subplot_kw = {} 377 # if gridspec_kw is None: 378 # gridspec_kw = {} 379 380 # # if figure.get_constrained_layout(): 381 # # gs = GridSpec(nrows, ncols, figure=figure, **gridspec_kw) 382 # # else: 383 # # # this should turn constrained_layout off if we don't want it 384 # # gs = GridSpec(nrows, ncols, figure=None, **gridspec_kw) 385 # gs = mpl.gridspec.GridSpec(nrows, ncols, **gridspec_kw) 386 387 # # Create array to hold all axes. 388 # axarr = np.empty((nrows, ncols), dtype=object) 389 # for row in range(nrows): 390 # for col in range(ncols): 391 # shared_with = {"none": None, "all": axarr[0, 0], 392 # "row": axarr[row, 0], "col": axarr[0, col]} 393 # subplot_kw["sharex"] = shared_with[sharex] 394 # subplot_kw["sharey"] = shared_with[sharey] 395 # axarr[row, col] = figure.add_subplot(gs[row, col], **subplot_kw) 396 397 # # turn off redundant tick labeling 398 # if sharex in ["col", "all"]: 399 # # turn off all but the bottom row 400 # for ax in axarr[:-1, :].flat: 401 # ax.xaxis.set_tick_params(which='both', 402 # labelbottom=False, labeltop=False) 403 # ax.xaxis.offsetText.set_visible(False) 404 # if sharey in ["row", "all"]: 405 # # turn off all but the first column 406 # for ax in axarr[:, 1:].flat: 407 # ax.yaxis.set_tick_params(which='both', 408 # labelleft=False, labelright=False) 409 # ax.yaxis.offsetText.set_visible(False) 410 411 # if squeeze: 412 # # Discarding unneeded dimensions that equal 1. If we only have one 413 # # subplot, just return it instead of a 1-element array. 414 # return axarr.item() if axarr.size == 1 else axarr.squeeze() 415 # else: 416 # # Returned axis array will be always 2-d, even if nrows=ncols=1. 417 # return axarr 418 418 419 419 class _tabPlotWin(wx.Panel): … … 2999 2999 Plot.set_visible(False) #hide old plot frame, will get replaced below 3000 3000 GS_kw = {'height_ratios':[4, 1],} 3001 try:3002 3003 except AttributeError: # figure.Figure.subplots added in MPL 2.23004 Plot,Plot1 = MPLsubplots(Page.figure, 2, 1, sharex=True, gridspec_kw=GS_kw)3001 # try: 3002 Plot,Plot1 = Page.figure.subplots(2,1,sharex=True,gridspec_kw=GS_kw) 3003 # except AttributeError: # figure.Figure.subplots added in MPL 2.2 3004 # Plot,Plot1 = MPLsubplots(Page.figure, 2, 1, sharex=True, gridspec_kw=GS_kw) 3005 3005 Plot1.set_ylabel(r'$\mathsf{\Delta(I)/\sigma(I)}$',fontsize=16) 3006 3006 Plot1.set_xlabel(xLabel,fontsize=16) … … 7642 7642 Plot.set_visible(False) 7643 7643 GS_kw = {'width_ratios':[1,2],} 7644 try:7645 7646 except AttributeError: # figure.Figure.subplots added in MPL 2.27647 Plot1,Plot = MPLsubplots(Page.figure, 1,2, gridspec_kw=GS_kw)7644 # try: 7645 Plot1,Plot = Page.figure.subplots(1,2,gridspec_kw=GS_kw) 7646 # except AttributeError: # figure.Figure.subplots added in MPL 2.2 7647 # Plot1,Plot = MPLsubplots(Page.figure, 1,2, gridspec_kw=GS_kw) 7648 7648 Plot1.set_title('Line scan at azm= %6.1f'%Data['linescan'][1]) 7649 7649 Plot1.set_xlabel(r'$\mathsf{2\Theta}$',fontsize=12) -
trunk/GSASIIpwd.py
r4405 r4415 18 18 import time 19 19 import os 20 import os.path 20 21 import subprocess as subp 21 22 import copy … … 2462 2463 return fname 2463 2464 2465 def FindBonds(Phase,RMCPdict): 2466 generalData = Phase['General'] 2467 cx,ct,cs,cia = generalData['AtomPtrs'] 2468 atomData = Phase['Atoms'] 2469 Res = 'RMC' 2470 if 'macro' in generalData['Type']: 2471 Res = atomData[0][ct-3] 2472 AtDict = {atom[ct-1]:atom[ct] for atom in atomData} 2473 Pairs = RMCPdict['Pairs'] #dict! 2474 BondList = [] 2475 notNames = [] 2476 for FrstName in AtDict: 2477 nbrs = G2mth.FindAllNeighbors(Phase,FrstName,list(AtDict.keys()),notName=notNames,Short=True)[0] 2478 Atyp1 = AtDict[FrstName] 2479 for nbr in nbrs: 2480 Atyp2 = AtDict[nbr[0]] 2481 try: 2482 bndData = Pairs[' %s-%s'%(Atyp1,Atyp2)][1:] 2483 except KeyError: 2484 bndData = Pairs[' %s-%s'%(Atyp2,Atyp1)][1:] 2485 if any(bndData): 2486 if bndData[0] <= nbr[1] <= bndData[1]: 2487 bondStr = str((FrstName,nbr[0])+tuple(bndData))+',\n' 2488 revbondStr = str((nbr[0],FrstName)+tuple(bndData))+',\n' 2489 if bondStr not in BondList and revbondStr not in BondList: 2490 BondList.append(bondStr) 2491 notNames.append(FrstName) 2492 return Res,BondList 2493 2494 def FindAngles(Phase,RMCPdict): 2495 generalData = Phase['General'] 2496 Cell = generalData['Cell'][1:7] 2497 Amat = G2lat.cell2AB(Cell)[0] 2498 cx,ct,cs,cia = generalData['AtomPtrs'] 2499 atomData = Phase['Atoms'] 2500 AtLookup = G2mth.FillAtomLookUp(atomData,cia+8) 2501 AtDict = {atom[ct-1]:atom[ct] for atom in atomData} 2502 Angles = RMCPdict['Angles'] 2503 AngDict = {'%s-%s-%s'%(angle[0],angle[1],angle[2]):angle[3:] for angle in Angles} 2504 AngleList = [] 2505 for MidName in AtDict: 2506 nbrs,nbrIds = G2mth.FindAllNeighbors(Phase,MidName,list(AtDict.keys()),Short=True) 2507 if len(nbrs) < 2: #need 2 neighbors to make an angle 2508 continue 2509 Atyp2 = AtDict[MidName] 2510 for i,nbr1 in enumerate(nbrs): 2511 Atyp1 = AtDict[nbr1[0]] 2512 for j,nbr3 in enumerate(nbrs[i+1:]): 2513 Atyp3 = AtDict[nbr3[0]] 2514 IdList = [nbrIds[1][i],nbrIds[0],nbrIds[1][i+j+1]] 2515 try: 2516 angData = AngDict['%s-%s-%s'%(Atyp1,Atyp2,Atyp3)] 2517 except KeyError: 2518 try: 2519 angData = AngDict['%s-%s-%s'%(Atyp3,Atyp2,Atyp1)] 2520 except KeyError: 2521 continue 2522 XYZ = np.array(G2mth.GetAtomItemsById(atomData,AtLookup,IdList,cx,numItems=3)) 2523 calAngle = G2mth.getRestAngle(XYZ,Amat) 2524 if angData[0] < calAngle < angData[1]: 2525 AngleList.append(str((MidName,nbr1[0],nbr3[0])+tuple(angData))+',\n') 2526 return AngleList 2527 2528 def GetSqConvolution(XY,d): 2529 2530 n = XY.shape[1] 2531 snew = np.zeros(n) 2532 dq = np.zeros(n) 2533 sold = XY[1] 2534 q = XY[0] 2535 dq[1:] = np.diff(q) 2536 dq[0] = dq[1] 2537 2538 for j in range(n): 2539 for i in range(n): 2540 b = abs(q[i]-q[j]) 2541 t = q[i]+q[j] 2542 if j == i: 2543 snew[j] += q[i]*sold[i]*(d-np.sin(t*d)/t)*dq[i] 2544 else: 2545 snew[j] += q[i]*sold[i]*(np.sin(b*d)/b-np.sin(t*d)/t)*dq[i] 2546 snew[j] /= np.pi*q[j] 2547 2548 snew[0] = snew[1] 2549 return snew 2550 2551 def GetMaxSphere(pdbName): 2552 try: 2553 pFil = open(pdbName,'r') 2554 except FileNotFoundError: 2555 return None 2556 while True: 2557 line = pFil.readline() 2558 if 'Boundary' in line: 2559 line = line.split()[3:] 2560 G = np.array([float(item) for item in line]) 2561 G = np.reshape(G,(3,3))**2 2562 G = nl.inv(G) 2563 pFil.close() 2564 break 2565 dspaces = [0.5/np.sqrt(G2lat.calc_rDsq2(H,G)) for H in np.eye(3)] 2566 return min(dspaces) 2567 2464 2568 def MakefullrmcRun(pName,Phase,RMCPdict): 2569 Res,BondList = FindBonds(Phase,RMCPdict) 2570 AngleList = FindAngles(Phase,RMCPdict) 2571 rmin = RMCPdict['min Contact'] 2572 rmax = GetMaxSphere(RMCPdict['atomPDB']) 2573 if rmax is None: 2574 return None 2465 2575 rname = pName+'-run.py' 2576 restart = '%s_restart.pdb'%pName 2466 2577 Files = RMCPdict['files'] 2578 wtDict = {} 2467 2579 rundata = '' 2468 2580 rundata += '#### fullrmc %s file; edit by hand if you so choose #####\n'%rname … … 2470 2582 # fullrmc imports (all that are potentially useful) 2471 2583 import numpy as np 2584 from fullrmc.sincConvolution import sincConvolution 2472 2585 from fullrmc.Globals import LOGGER 2473 2586 from fullrmc.Engine import Engine 2474 2587 from fullrmc.Constraints.PairDistributionConstraints import PairDistributionConstraint 2475 2588 from fullrmc.Constraints.PairCorrelationConstraints import PairCorrelationConstraint 2476 from fullrmc.Constraints.StructureFactorConstraints import StructureFactorConstraint2589 from fullrmc.Constraints.StructureFactorConstraints import ReducedStructureFactorConstraint 2477 2590 from fullrmc.Constraints.DistanceConstraints import InterMolecularDistanceConstraint 2478 2591 from fullrmc.Constraints.BondConstraints import BondConstraint 2479 2592 from fullrmc.Constraints.AngleConstraints import BondsAngleConstraint 2480 from fullrmc.Constraints. ImproperAngleConstraints import ImproperAngleConstraint2593 from fullrmc.Constraints.DihedralAngleConstraints import DihedralAngleConstraint 2481 2594 from fullrmc.Core.MoveGenerator import MoveGeneratorCollector 2482 2595 from fullrmc.Core.GroupSelector import RecursiveGroupSelector … … 2488 2601 from fullrmc.Core.Collection import get_principal_axis 2489 2602 # engine setup\n''' 2490 rundata += 'LOGGER.set_log_file_basename( %s)\n'%pName2603 rundata += 'LOGGER.set_log_file_basename("%s")\n'%pName 2491 2604 rundata += 'engineFileName = "%s.rmc"\n'%pName 2492 2605 rundata += 'ENGINE = Engine(path=None)\n' 2493 2606 rundata += 'if not ENGINE.is_engine(engineFileName):\n' 2494 # create engine 2607 rundata += '# create engine & set atomic (pdb) model\n' 2495 2608 rundata += ' ENGINE = Engine(path=engineFileName)\n' 2496 rundata += ' ENGINE.set_pdb( %s)\n'%RMCPdict['atomPDB']2497 ## create experimental constraints 2609 rundata += ' ENGINE.set_pdb("%s")\n'%RMCPdict['atomPDB'] 2610 rundata += '# create experimental constraints must restart to change these\n' 2498 2611 for File in Files: 2499 2612 filDat = RMCPdict['files'][File] … … 2503 2616 sfwt = 'xrays' 2504 2617 if 'G(r)' in File: 2505 rundata += ' GofR = PairDistributionConstraint(experimentalData=%s, weighting="%s")\n'%(filDat[0],sfwt) 2506 rundata += ' GofR.set_variance_squared(%f)\n'%filDat[1] 2618 rundata += ' RGR = np.loadtxt("%s").T\n'%filDat[0] 2619 if filDat[3]: 2620 rundata += ' RGR[1] *= RGR[0]\n' 2621 rundata += ' GofR = PairDistributionConstraint(experimentalData=RGR.T, weighting="%s")\n'%sfwt 2507 2622 rundata += ' ENGINE.add_constraints([GofR])\n' 2623 wtDict['Pair'] = filDat[1] 2508 2624 else: 2509 rundata += ' FofQ = StructureFactorConstraint(experimentalData=%s, weighting="%s")\n'%(filDat[0],sfwt) 2510 rundata += ' FofQ.set_variance_squared(%f)\n'%filDat[1] 2625 rundata += ' SOQ = np.loadtxt("%s").T\n'%filDat[0] 2626 if filDat[3]: 2627 rundata += ' SOQ[1] = sincConvolution(SOQ,%.3f)\n'%rmax 2628 rundata += ' FofQ = ReducedStructureFactorConstraint(experimentalData=SOQ.T, weighting="%s")\n'%sfwt 2511 2629 rundata += ' ENGINE.add_constraints([FofQ])\n' 2630 wtDict['Struct'] = filDat[1] 2631 rundata += ' ENGINE.add_constraints(InterMolecularDistanceConstraint())\n' 2632 if len(BondList): 2633 rundata += ' B_CONSTRAINT = BondConstraint()\n' 2634 rundata += ' ENGINE.add_constraints(B_CONSTRAINT)\n' 2635 if len(AngleList): 2636 rundata += ' A_CONSTRAINT = BondsAngleConstraint()\n' 2637 rundata += ' ENGINE.add_constraints(A_CONSTRAINT)\n' 2638 if len(RMCPdict['Torsions']): 2639 rundata += ' T_CONSTRAINT = DihedralAngleConstraint()\n' 2640 rundata += ' ENGINE.add_constraints(T_CONSTRAINT)\n' 2512 2641 rundata += ' ENGINE.save()\n' 2513 2514 2515 2516 2642 rundata += 'else:\n' 2517 2643 rundata += ' ENGINE = ENGINE.load(path=engineFileName)\n' 2518 2644 rundata += '#fill & change constraints - can be done without restart\n' 2645 rundata += 'Constraints = ENGINE.constraints\n' 2646 rundata += 'for constraint in Constraints:\n' 2647 rundata += ' strcons = str(type(constraint))\n' 2648 if len(BondList): 2649 rundata += ' if "BondConstraint" in strcons:\n' 2650 rundata += ' constraint.set_variance_squared(%f)\n'%RMCPdict['Bond Weight'] 2651 rundata += ' constraint.create_bonds_by_definition(bondsDefinition={"%s":[\n'%Res 2652 for bond in BondList: 2653 rundata += ' %s'%bond 2654 rundata += ' ]})\n' 2655 if len(AngleList): 2656 rundata += ' elif "BondsAngleConstraint" in strcons:\n' 2657 rundata += ' constraint.set_variance_squared(%f)\n'%RMCPdict['Angle Weight'] 2658 rundata += ' constraint.create_angles_by_definition(anglesDefinition={"%s":[\n'%Res 2659 for angle in AngleList: 2660 rundata += ' %s'%angle 2661 rundata += ' ]})\n' 2662 if len(RMCPdict['Torsions']): 2663 rundata += ' elif "DihedralAngleConstraint" in strcons:\n' 2664 rundata += ' constraint.set_variance_squared(%f)\n'%RMCPdict['Torsion Weight'] 2665 rundata += ' constraint.create_angles_by_definition(anglesDefinition={"%s":[\n'%Res 2666 for torsion in RMCPdict['Torsions']: 2667 rundata += ' %s\n'%str(tuple(torsion)) 2668 rundata += ' ]})\n' 2669 rundata += ' elif "InterMolecular" in strcons:\n' 2670 rundata += ' constraint.set_default_distance(%f)\n'%RMCPdict['min Contact'] 2671 rundata += ' elif "PairDistribution" in strcons:\n' 2672 rundata += ' constraint.set_variance_squared(%f)\n'%wtDict['Pair'] 2673 rundata += ' constraint.set_limits((%.3f,%.3f))\n'%(rmin,rmax) 2674 if RMCPdict['FitScale']: 2675 rundata += ' constraint.set_adjust_scale_factor((10, 0.01, 100.))\n' 2676 rundata += ' elif "StructureFactor" in strcons:\n' 2677 rundata += ' constraint.set_variance_squared(%f)\n'%wtDict['Struct'] 2678 if RMCPdict['FitScale']: 2679 rundata += ' constraint.set_adjust_scale_factor((10, 0.01, 100.))\n' 2680 rundata += 'ENGINE.set_groups_as_atoms()\n' 2681 if len(RMCPdict['Swaps']): 2682 print(RMCPdict['Swaps']) 2683 2684 # allElements = ENGINE.allElements 2685 # niSwapList = [[idx] for idx in range(len(allElements)) if allElements[idx]=='ni'] 2686 # tiSwapList = [[idx] for idx in range(len(allElements)) if allElements[idx]=='ti'] 2687 # # create swap generator 2688 # toNiSG = SwapPositionsGenerator(swapList=niSwapList) 2689 # toTiSG = SwapPositionsGenerator(swapList=tiSwapList) 2690 2691 2692 rundata += 'ENGINE.run(restartPdb="%s",numberOfSteps=%d, saveFrequency=1000)\n'%(restart,RMCPdict['Cycles']) 2693 rundata += 'ENGINE.save()\n' 2694 rundata += '#setup runs for fullrmc\n' 2695 2696 2697 2698 2699 2700 2701 2519 2702 2520 2703 rfile = open(rname,'w') … … 2523 2706 2524 2707 return rname 2525 2708 2526 2709 2527 2710 def MakefullrmcPDB(Name,Phase,RMCPdict): … … 2534 2717 newPhase['General']['SGData'] = G2spc.SpcGroup('P 1')[1] 2535 2718 newPhase['General']['Cell'][1:] = G2lat.TransformCell(Cell,Trans.T) 2536 newPhase,Atcodes = G2lat.TransformPhase(Phase,newPhase,Trans,np.zeros(3),np.zeros(3),ifMag=False )2719 newPhase,Atcodes = G2lat.TransformPhase(Phase,newPhase,Trans,np.zeros(3),np.zeros(3),ifMag=False,Force=False) 2537 2720 Atoms = newPhase['Atoms'] 2538 2721 XYZ = np.array([atom[3:6] for atom in Atoms]).T … … 2542 2725 fname = Name+'_cbb.pdb' 2543 2726 fl = open(fname,'w') 2544 fl.write('REMARK this file is generated using GSASII\n')2545 2727 fl.write('REMARK Boundary Conditions:%6.2f 0.0 0.0 0.0%7.2f 0.0 0.0 0.0%7.2f\n'%( 2546 2728 Cell[0],Cell[1],Cell[2])) 2547 fl.write('CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f P 1 1\n'%(2548 Cell[0],Cell[1],Cell[2],Cell[3],Cell[4],Cell[5]))2549 2729 fl.write('ORIGX1 1.000000 0.000000 0.000000 0.00000\n') 2550 2730 fl.write('ORIGX2 0.000000 1.000000 0.000000 0.00000\n') 2551 2731 fl.write('ORIGX3 0.000000 0.000000 1.000000 0.00000\n') 2732 fl.write('CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f P 1 1\n'%( 2733 Cell[0],Cell[1],Cell[2],Cell[3],Cell[4],Cell[5])) 2552 2734 2553 2735 Natm = np.core.defchararray.count(np.array(Atcodes),'+') … … 2557 2739 NPM = RMCPdict['Natoms'] 2558 2740 for iat,atom in enumerate(Atoms): 2559 XYZ = np.inner(A,np.array(atom[3:6])-XYZptp) #shift origin to middle & make Cartesian 2560 fl.write('ATOM %5d %-4s RMC%6d%12.3f%8.3f%8.3f 1.00 0.00 % -2s\n'%(2741 XYZ = np.inner(A,np.array(atom[3:6])-XYZptp) #shift origin to middle & make Cartesian;residue = 'RMC' 2742 fl.write('ATOM %5d %-4s RMC%6d%12.3f%8.3f%8.3f 1.00 0.00 %2s\n'%( 2561 2743 1+nat%NPM,atom[0],1+nat//NPM,XYZ[0],XYZ[1],XYZ[2],atom[1].lower())) 2562 2744 nat += 1 … … 2566 2748 if atom[1] == atm: 2567 2749 XYZ = np.inner(A,np.array(atom[3:6])-XYZptp) #shift origin to middle & make Cartesian 2568 fl.write('ATOM %5d %-4s RMC%6d%12.3f%8.3f%8.3f 1.00 0.00 % -2s\n'%(2750 fl.write('ATOM %5d %-4s RMC%6d%12.3f%8.3f%8.3f 1.00 0.00 %2s\n'%( 2569 2751 1+nat,atom[0],1+nat,XYZ[0],XYZ[1],XYZ[2],atom[1].lower())) 2570 2752 nat += 1 … … 3712 3894 reflDict[hash('%5d%5d%5d'%(ref[0],ref[1],ref[2]))] = iref 3713 3895 fbaName = os.path.splitext(prfName)[0]+'.fba' 3714 try: # patch for FileNotFoundError not in Python 2.7 3715 FileNotFoundError 3716 except NameError: 3717 FileNotFoundError = Exception 3718 try: 3896 if os.path.isfile(fbaName): 3719 3897 fba = open(fbaName,'r') 3720 e xcept FileNotFoundError:3898 else: 3721 3899 return False 3722 3900 fba.readline() -
trunk/exports/G2export_PDB.py
r3245 r4415 141 141 'LEU','LYS','MET','PHE','PRO','SER','THR','TRP','TYR','VAL','MSE'] 142 142 seq = 0 143 notProt = True 143 144 for atom in Atoms: 144 145 if atom[ct-3] in AA3letter and int(atom[ct-4]) != seq: 146 notProt = False 145 147 if atom[ct-2] not in seqList: 146 148 seqList[atom[ct-2]] = [] … … 172 174 Biso = atom[cia+1]*8.*np.pi**2 173 175 xyz = np.inner(A,np.array(atom[cx:cx+3])) 174 if atom[ct-3] in AA3letter :176 if atom[ct-3] in AA3letter or notProt: 175 177 self.Write(fmt.format('ATOM ',iatom,atom[ct-1],atom[ct-3].strip(), \ 176 178 atom[ct-2].strip(),atom[ct-4].rjust(4),xyz[0],xyz[1],xyz[2],atom[cx+3], \ -
trunk/imports/G2phase.py
r4213 r4415 59 59 # return False 60 60 for i,l in enumerate(fp): 61 if l.startswith('ATOM') :61 if l.startswith('ATOM') or l.startswith('HETATM'): 62 62 fp.close() 63 63 return True … … 79 79 Phase = {} 80 80 Title = os.path.basename(filename) 81 RES = Title[:3] 81 82 82 83 Compnd = '' … … 88 89 cell = None 89 90 Dummy = True 91 Anum = 0 90 92 while S: 91 93 self.errors = 'Error reading at line '+str(line) … … 134 136 cell = [20.0,20.0,20.0,90.,90.,90.] 135 137 Volume = G2lat.calc_V(G2lat.cell2A(cell)) 136 AA,AB = G2lat.cell2AB(cell) 138 AA,AB = G2lat.cell2AB(cell) 139 Anum = 1 137 140 XYZ = [float(S[31:39]),float(S[39:47]),float(S[47:55])] 138 141 XYZ = np.inner(AB,XYZ) … … 143 146 if Dummy and S[12:17].strip() == 'CA': 144 147 Type = 'C' 145 Atom = [S[22:27].strip(),S[17:20].upper(),S[20:22], 146 S[12:17].strip(),Type.strip().capitalize(),'',XYZ[0],XYZ[1],XYZ[2], 148 Aname = S[12:17].strip() 149 if Anum: 150 Aname += '%d'%Anum 151 if S[17:20].upper() != 'UNL': 152 RES = S[17:20].upper() 153 Atom = [S[22:27].strip(),RES,S[20:22], 154 Aname,Type.strip().capitalize(),'',XYZ[0],XYZ[1],XYZ[2], 147 155 float(S[55:61]),SytSym,Mult,'I',Uiso,0,0,0,0,0,0] 148 156 if S[16] in [' ','A','B']: … … 150 158 Atom.append(ran.randint(0,sys.maxsize)) 151 159 Atoms.append(Atom) 160 if Anum: 161 Anum += 1 152 162 elif 'ANISOU' in S[:6]: 153 163 Uij = S[30:72].split()
Note: See TracChangeset
for help on using the changeset viewer.