1 | # -*- coding: utf-8 -*- |
---|
2 | ########### SVN repository information ################### |
---|
3 | # $Date: 2015-10-30 21:02:02 +0000 (Fri, 30 Oct 2015) $ |
---|
4 | # $Author: vondreele $ |
---|
5 | # $Revision: 2038 $ |
---|
6 | # $URL: trunk/imports/G2phase_CIF.py $ |
---|
7 | # $Id: G2phase_CIF.py 2038 2015-10-30 21:02:02Z vondreele $ |
---|
8 | ########### SVN repository information ################### |
---|
9 | ''' |
---|
10 | *Module G2phase_CIF: Coordinates from CIF* |
---|
11 | ------------------------------------------ |
---|
12 | |
---|
13 | Parses a CIF using PyCifRW from James Hester and pulls out the |
---|
14 | structural information. |
---|
15 | |
---|
16 | If a CIF generated by ISODISTORT is encountered, extra information is |
---|
17 | added to the phase entry and constraints are generated. |
---|
18 | |
---|
19 | ''' |
---|
20 | # Routines to import Phase information from CIF files |
---|
21 | import sys |
---|
22 | import random as ran |
---|
23 | import numpy as np |
---|
24 | import re |
---|
25 | import GSASIIIO as G2IO |
---|
26 | import GSASIIobj as G2obj |
---|
27 | import GSASIIspc as G2spc |
---|
28 | import GSASIIElem as G2elem |
---|
29 | import GSASIIlattice as G2lat |
---|
30 | import GSASIIpy3 as G2p3 |
---|
31 | import GSASIIpath |
---|
32 | GSASIIpath.SetVersionNumber("$Revision: 2038 $") |
---|
33 | import CifFile as cif # PyCifRW from James Hester |
---|
34 | |
---|
35 | class CIFPhaseReader(G2IO.ImportPhase): |
---|
36 | 'Implements a phase importer from a possibly multi-block CIF file' |
---|
37 | def __init__(self): |
---|
38 | super(self.__class__,self).__init__( # fancy way to say ImportPhase.__init__ |
---|
39 | extensionlist=('.CIF','.cif','.txt'), |
---|
40 | strictExtension=False, |
---|
41 | formatName = 'CIF', |
---|
42 | longFormatName = 'Crystallographic Information File import' |
---|
43 | ) |
---|
44 | |
---|
45 | def ContentsValidator(self, filepointer): |
---|
46 | return self.CIFValidator(filepointer) |
---|
47 | |
---|
48 | def Reader(self,filename,filepointer, ParentFrame=None, usedRanIdList=[], **unused): |
---|
49 | self.isodistort_warnings = '' |
---|
50 | self.Phase = G2IO.SetNewPhase(Name='new phase',SGData=G2IO.P1SGData) # create a new empty phase dict |
---|
51 | # make sure the ranId is really unique! |
---|
52 | while self.Phase['ranId'] in usedRanIdList: |
---|
53 | self.Phase['ranId'] = ran.randint(0,sys.maxint) |
---|
54 | returnstat = False |
---|
55 | cellitems = ( |
---|
56 | '_cell_length_a','_cell_length_b','_cell_length_c', |
---|
57 | '_cell_angle_alpha','_cell_angle_beta','_cell_angle_gamma',) |
---|
58 | cellwaveitems = ( |
---|
59 | '_cell_wave_vector_seq_id', |
---|
60 | '_cell_wave_vector_x','_cell_wave_vector_y','_cell_wave_vector_z') |
---|
61 | reqitems = ( |
---|
62 | '_atom_site_fract_x', |
---|
63 | '_atom_site_fract_y', |
---|
64 | '_atom_site_fract_z', |
---|
65 | ) |
---|
66 | phasenamefields = ( |
---|
67 | '_chemical_name_common', |
---|
68 | '_pd_phase_name', |
---|
69 | '_chemical_formula_sum' |
---|
70 | ) |
---|
71 | try: |
---|
72 | self.ShowBusy() # this can take a while |
---|
73 | try: |
---|
74 | cf = G2IO.ReadCIF(filename) |
---|
75 | except Exception as detail: |
---|
76 | self.errors = "Parse or reading of file failed in pyCifRW; check syntax of file in enCIFer or CheckCIF" |
---|
77 | return False |
---|
78 | finally: |
---|
79 | self.DoneBusy() |
---|
80 | # scan blocks for structural info |
---|
81 | self.errors = 'Error during scan of blocks for datasets' |
---|
82 | str_blklist = [] |
---|
83 | for blk in cf.keys(): |
---|
84 | for r in reqitems+cellitems: |
---|
85 | if r not in cf[blk].keys(): |
---|
86 | break |
---|
87 | else: |
---|
88 | str_blklist.append(blk) |
---|
89 | if not str_blklist: |
---|
90 | selblk = None # no block to choose |
---|
91 | elif len(str_blklist) == 1: # only one choice |
---|
92 | selblk = 0 |
---|
93 | else: # choose from options |
---|
94 | choice = [] |
---|
95 | for blknm in str_blklist: |
---|
96 | choice.append('') |
---|
97 | # accumumlate some info about this phase |
---|
98 | choice[-1] += blknm + ': ' |
---|
99 | for i in phasenamefields: # get a name for the phase |
---|
100 | name = cf[blknm].get(i).strip() |
---|
101 | if name is None or name == '?' or name == '.': |
---|
102 | continue |
---|
103 | else: |
---|
104 | choice[-1] += name.strip()[:20] + ', ' |
---|
105 | break |
---|
106 | na = len(cf[blknm].get("_atom_site_fract_x")) |
---|
107 | if na == 1: |
---|
108 | choice[-1] += '1 atom' |
---|
109 | else: |
---|
110 | choice[-1] += ('%d' % nd) + ' atoms' |
---|
111 | choice[-1] += ', cell: ' |
---|
112 | fmt = "%.2f," |
---|
113 | for i,key in enumerate(cellitems): |
---|
114 | if i == 3: fmt = "%.f," |
---|
115 | if i == 5: fmt = "%.f" |
---|
116 | choice[-1] += fmt % cif.get_number_with_esd( |
---|
117 | cf[blknm].get(key))[0] |
---|
118 | sg = cf[blknm].get("_symmetry_space_group_name_H-M",'') |
---|
119 | if not sg: sg = cf[blknm].get("_space_group_name_H-M_alt",'') |
---|
120 | if sg: choice[-1] += ', (' + sg.strip() + ')' |
---|
121 | selblk = self.PhaseSelector( |
---|
122 | choice, |
---|
123 | ParentFrame=ParentFrame, |
---|
124 | title= 'Select a phase from one the CIF data_ blocks below', |
---|
125 | size=(600,100) |
---|
126 | ) |
---|
127 | self.errors = 'Error during reading of selected block' |
---|
128 | if selblk is None: |
---|
129 | returnstat = False # no block selected or available |
---|
130 | else: |
---|
131 | blknm = str_blklist[selblk] |
---|
132 | blk = cf[str_blklist[selblk]] |
---|
133 | E = True |
---|
134 | Super = False |
---|
135 | SpGrp = blk.get("_symmetry_space_group_name_H-M",'') |
---|
136 | if not SpGrp: |
---|
137 | SpGrp = blk.get("_space_group_name_H-M_alt",'') |
---|
138 | if not SpGrp: |
---|
139 | sspgrp = blk.get("_space_group_ssg_name",'').split('(') |
---|
140 | SpGrp = sspgrp[0] |
---|
141 | SuperSg = '('+sspgrp[1].replace('\\','') |
---|
142 | Super = True |
---|
143 | SuperVec = [[0,0,.1],False,4] |
---|
144 | # try normalizing the space group, to see if we can pick the space group out of a table |
---|
145 | SpGrpNorm = G2spc.StandardizeSpcName(SpGrp) |
---|
146 | if SpGrpNorm: |
---|
147 | E,SGData = G2spc.SpcGroup(SpGrpNorm) |
---|
148 | # nope, try the space group "out of the Box" |
---|
149 | if E and SpGrp: |
---|
150 | E,SGData = G2spc.SpcGroup(SpGrp) |
---|
151 | if E: |
---|
152 | if not SpGrp: |
---|
153 | self.warnings += 'No space group name was found in the CIF.' |
---|
154 | self.warnings += '\nThe space group has been set to "P 1". ' |
---|
155 | self.warnings += "Change this in phase's General tab." |
---|
156 | else: |
---|
157 | self.warnings += 'ERROR in space group symbol '+SpGrp |
---|
158 | self.warnings += '\nThe space group has been set to "P 1". ' |
---|
159 | self.warnings += "Change this in phase's General tab." |
---|
160 | self.warnings += '\nAre there spaces separating axial fields?\n\nError msg: ' |
---|
161 | self.warnings += G2spc.SGErrors(E) |
---|
162 | SGData = G2IO.SGData # P 1 |
---|
163 | self.Phase['General']['SGData'] = SGData |
---|
164 | # cell parameters |
---|
165 | cell = [] |
---|
166 | for lbl in cellitems: |
---|
167 | cell.append(cif.get_number_with_esd(blk[lbl])[0]) |
---|
168 | Volume = G2lat.calc_V(G2lat.cell2A(cell)) |
---|
169 | self.Phase['General']['Cell'] = [False,]+cell+[Volume,] |
---|
170 | # read in atoms |
---|
171 | self.errors = 'Error during reading of atoms' |
---|
172 | atomlbllist = [] # table to look up atom IDs |
---|
173 | atomloop = blk.GetLoop('_atom_site_label') |
---|
174 | atomkeys = [i.lower() for i in atomloop.keys()] |
---|
175 | if not blk.get('_atom_site_type_symbol'): |
---|
176 | self.isodistort_warnings += '\natom types are missing. \n Check & revise atom types as needed' |
---|
177 | if blk.get('_atom_site_aniso_label'): |
---|
178 | anisoloop = blk.GetLoop('_atom_site_aniso_label') |
---|
179 | anisokeys = [i.lower() for i in anisoloop.keys()] |
---|
180 | anisolabels = blk.get('_atom_site_aniso_label') |
---|
181 | else: |
---|
182 | anisoloop = None |
---|
183 | anisokeys = [] |
---|
184 | anisolabels = [] |
---|
185 | self.Phase['Atoms'] = [] |
---|
186 | G2AtomDict = { '_atom_site_type_symbol' : 1, |
---|
187 | '_atom_site_label' : 0, |
---|
188 | '_atom_site_fract_x' : 3, |
---|
189 | '_atom_site_fract_y' : 4, |
---|
190 | '_atom_site_fract_z' : 5, |
---|
191 | '_atom_site_occupancy' : 6, |
---|
192 | '_atom_site_aniso_u_11' : 11, |
---|
193 | '_atom_site_aniso_u_22' : 12, |
---|
194 | '_atom_site_aniso_u_33' : 13, |
---|
195 | '_atom_site_aniso_u_12' : 14, |
---|
196 | '_atom_site_aniso_u_13' : 15, |
---|
197 | '_atom_site_aniso_u_23' : 16, } |
---|
198 | G2SSAtomDict = {'_atom_site_occ_Fourier_wave_vector_seq_id' : 1, |
---|
199 | '_atom_site_occ_Fourier_param_cos' : 2, |
---|
200 | '_atom_site_occ_Fourier_param_sin' : 3, |
---|
201 | '_atom_site_displace_Fourier_axis' : 2, |
---|
202 | '_atom_site_displace_Fourier_wave_vector_seq_id' : 3, |
---|
203 | '_atom_site_displace_Fourier_param_cos' : 5, |
---|
204 | '_atom_site_displace_Fourier_param_sin' : 4, |
---|
205 | '_atom_site_U_Fourier_tens_elem' : 7, |
---|
206 | '_atom_site_U_Fourier_wave_vector_seq_id' : 8, |
---|
207 | '_atom_site_U_Fourier_param_cos' : 9, |
---|
208 | '_atom_site_U_Fourier_param_sin' : 10, } |
---|
209 | |
---|
210 | |
---|
211 | |
---|
212 | ranIdlookup = {} |
---|
213 | for aitem in atomloop: |
---|
214 | atomlist = ['','','',0,0,0,1.0,'',0,'I',0.01,0,0,0,0,0,0,0] |
---|
215 | atomlist[-1] = ran.randint(0,sys.maxint) # add a random Id |
---|
216 | while atomlist[-1] in ranIdlookup: |
---|
217 | atomlist[-1] = ran.randint(0,sys.maxint) # make it unique |
---|
218 | for val,key in zip(aitem,atomkeys): |
---|
219 | col = G2AtomDict.get(key) |
---|
220 | if col >= 3: |
---|
221 | atomlist[col] = cif.get_number_with_esd(val)[0] |
---|
222 | if col >= 11: atomlist[9] = 'A' # if any Aniso term is defined, set flag |
---|
223 | elif col is not None: |
---|
224 | atomlist[col] = val |
---|
225 | elif key in ('_atom_site_thermal_displace_type', |
---|
226 | '_atom_site_adp_type'): #Iso or Aniso? |
---|
227 | if val.lower() == 'uani': |
---|
228 | atomlist[9] = 'A' |
---|
229 | elif key == '_atom_site_u_iso_or_equiv': |
---|
230 | uisoval =cif.get_number_with_esd(val)[0] |
---|
231 | if uisoval is not None: atomlist[10] = uisoval |
---|
232 | if not atomlist[1] and atomlist[0]: |
---|
233 | typ = atomlist[0].rstrip('0123456789-+') |
---|
234 | if G2elem.CheckElement(typ): |
---|
235 | atomlist[1] = typ |
---|
236 | if not atomlist[1]: |
---|
237 | atomlist[1] = 'Xe' |
---|
238 | self.warnings += ' Atom type '+typ+' not recognized; Xe assumed\n' |
---|
239 | if atomlist[0] in anisolabels: # does this atom have aniso values in separate loop? |
---|
240 | atomlist[9] = 'A' # set the aniso flag |
---|
241 | for val,key in zip( # load the values |
---|
242 | anisoloop.GetKeyedPacket('_atom_site_aniso_label',atomlist[0]), |
---|
243 | anisokeys): |
---|
244 | col = G2AtomDict.get(key) |
---|
245 | if col: |
---|
246 | atomlist[col] = cif.get_number_with_esd(val)[0] |
---|
247 | atomlist[7],atomlist[8] = G2spc.SytSym(atomlist[3:6],SGData) |
---|
248 | atomlist[1] = G2elem.FixValence(atomlist[1]) |
---|
249 | self.Phase['Atoms'].append(atomlist) |
---|
250 | ranIdlookup[atomlist[0]] = atomlist[-1] |
---|
251 | if atomlist[0] in atomlbllist: |
---|
252 | self.warnings += ' ERROR: repeated atom label: '+atomlist[0] |
---|
253 | else: |
---|
254 | atomlbllist.append(atomlist[0]) |
---|
255 | if len(atomlbllist) != len(self.Phase['Atoms']): |
---|
256 | self.isodistort_warnings += '\nRepeated atom labels prevents ISODISTORT decode' |
---|
257 | for lbl in phasenamefields: # get a name for the phase |
---|
258 | name = blk.get(lbl) |
---|
259 | if name is None: |
---|
260 | continue |
---|
261 | name = name.strip() |
---|
262 | if name == '?' or name == '.': |
---|
263 | continue |
---|
264 | else: |
---|
265 | break |
---|
266 | else: # no name found, use block name for lack of a better choice |
---|
267 | name = blknm |
---|
268 | self.Phase['General']['Name'] = name.strip()[:20] |
---|
269 | self.Phase['General']['Super'] = Super |
---|
270 | if Super: |
---|
271 | self.Phase['General']['Type'] = 'modulated' |
---|
272 | self.Phase['General']['SuperVec'] = SuperVec |
---|
273 | self.Phase['General']['SuperSg'] = SuperSg |
---|
274 | self.Phase['General']['SSGData'] = G2spc.SSpcGroup(SGData,SuperSg)[1] |
---|
275 | if not self.isodistort_warnings: |
---|
276 | if blk.get('_iso_displacivemode_label') or blk.get('_iso_occupancymode_label'): |
---|
277 | self.errors = "Error while processing ISODISTORT constraints" |
---|
278 | self.ISODISTORT_proc(blk,atomlbllist,ranIdlookup) |
---|
279 | else: |
---|
280 | self.warnings += self.isodistort_warnings |
---|
281 | returnstat = True |
---|
282 | except Exception as detail: |
---|
283 | self.errors += '\n '+str(detail) |
---|
284 | print 'CIF error:',detail # for testing |
---|
285 | print sys.exc_info()[0] # for testing |
---|
286 | import traceback |
---|
287 | print traceback.format_exc() |
---|
288 | returnstat = False |
---|
289 | return returnstat |
---|
290 | |
---|
291 | def ISODISTORT_proc(self,blk,atomlbllist,ranIdlookup): |
---|
292 | 'Process ISODISTORT items to create constraints etc.' |
---|
293 | varLookup = {'dx':'dAx','dy':'dAy','dz':'dAz','do':'Afrac'} |
---|
294 | 'Maps ISODISTORT parm names to GSAS-II names' |
---|
295 | #---------------------------------------------------------------------- |
---|
296 | # read in the ISODISTORT displacement modes |
---|
297 | #---------------------------------------------------------------------- |
---|
298 | self.Constraints = [] |
---|
299 | explaination = {} |
---|
300 | if blk.get('_iso_displacivemode_label'): |
---|
301 | modelist = [] |
---|
302 | shortmodelist = [] |
---|
303 | for lbl in blk.get('_iso_displacivemode_label'): |
---|
304 | modelist.append(lbl) |
---|
305 | # assume lbl is of form SSSSS[x,y,z]AAAA(a,b,...)BBBBB |
---|
306 | # where SSSSS is the parent spacegroup, [x,y,z] is a location |
---|
307 | regexp = re.match(r'.*?\[.*?\](.*?)\(.*?\)(.*)',lbl) |
---|
308 | # this extracts the AAAAA and BBBBB parts of the string |
---|
309 | if regexp: |
---|
310 | lbl = regexp.expand(r'\1\2') # parse succeeded, make a short version |
---|
311 | G2obj.MakeUniqueLabel(lbl,shortmodelist) # make unique and add to list |
---|
312 | # read in the coordinate offset variables names and map them to G2 names/objects |
---|
313 | coordVarLbl = [] |
---|
314 | G2varLbl = [] |
---|
315 | G2varObj = [] |
---|
316 | error = False |
---|
317 | for lbl in blk.get('_iso_deltacoordinate_label'): |
---|
318 | coordVarLbl.append(lbl) |
---|
319 | if '_' in lbl: |
---|
320 | albl = lbl[:lbl.rfind('_')] |
---|
321 | vlbl = lbl[lbl.rfind('_')+1:] |
---|
322 | else: |
---|
323 | self.warnings += ' ERROR: _iso_deltacoordinate_label not parsed: '+lbl |
---|
324 | error = True |
---|
325 | continue |
---|
326 | if albl not in atomlbllist: |
---|
327 | self.warnings += ' ERROR: _iso_deltacoordinate_label atom not found: '+lbl |
---|
328 | error = True |
---|
329 | continue |
---|
330 | else: |
---|
331 | anum = atomlbllist.index(albl) |
---|
332 | var = varLookup.get(vlbl) |
---|
333 | if not var: |
---|
334 | self.warnings += ' ERROR: _iso_deltacoordinate_label variable not found: '+lbl |
---|
335 | error = True |
---|
336 | continue |
---|
337 | G2varLbl.append('::'+var+':'+str(anum)) # variable name, less phase ID |
---|
338 | G2varObj.append(G2obj.G2VarObj( |
---|
339 | (self.Phase['ranId'],None,var,ranIdlookup[albl]) |
---|
340 | )) |
---|
341 | if error: |
---|
342 | raise Exception,"Error decoding variable labels" |
---|
343 | |
---|
344 | if len(G2varObj) != len(modelist): |
---|
345 | print "non-square input" |
---|
346 | raise Exception,"Rank of _iso_displacivemode != _iso_deltacoordinate" |
---|
347 | |
---|
348 | error = False |
---|
349 | ParentCoordinates = {} |
---|
350 | for lbl,exp in zip( |
---|
351 | blk.get('_iso_coordinate_label'), |
---|
352 | blk.get('_iso_coordinate_formula'), |
---|
353 | ): |
---|
354 | if '_' in lbl: |
---|
355 | albl = lbl[:lbl.rfind('_')] |
---|
356 | vlbl = lbl[lbl.rfind('_')+1:] |
---|
357 | else: |
---|
358 | self.warnings += ' ERROR: _iso_coordinate_label not parsed: '+lbl |
---|
359 | error = True |
---|
360 | continue |
---|
361 | if vlbl not in 'xyz' or len(vlbl) != 1: |
---|
362 | self.warnings += ' ERROR: _iso_coordinate_label coordinate not parsed: '+lbl |
---|
363 | error = True |
---|
364 | continue |
---|
365 | i = 'xyz'.index(vlbl) |
---|
366 | if not ParentCoordinates.get(albl): |
---|
367 | ParentCoordinates[albl] = [None,None,None] |
---|
368 | if '+' in exp: |
---|
369 | val = exp.split('+')[0].strip() |
---|
370 | val = G2p3.FormulaEval(val) |
---|
371 | if val is None: |
---|
372 | self.warnings += ' ERROR: _iso_coordinate_formula coordinate not interpreted: '+lbl |
---|
373 | error = True |
---|
374 | continue |
---|
375 | ParentCoordinates[albl][i] = val |
---|
376 | else: |
---|
377 | ParentCoordinates[albl][i] = G2p3.FormulaEval(exp) |
---|
378 | if error: |
---|
379 | print self.warnings |
---|
380 | raise Exception,"Error decoding variable labels" |
---|
381 | # get mapping of modes to atomic coordinate displacements |
---|
382 | displacivemodematrix = np.zeros((len(G2varObj),len(G2varObj))) |
---|
383 | for row,col,val in zip( |
---|
384 | blk.get('_iso_displacivemodematrix_row'), |
---|
385 | blk.get('_iso_displacivemodematrix_col'), |
---|
386 | blk.get('_iso_displacivemodematrix_value'),): |
---|
387 | displacivemodematrix[int(row)-1,int(col)-1] = float(val) |
---|
388 | # Invert to get mapping of atom displacements to modes |
---|
389 | displacivemodeInvmatrix = np.linalg.inv(displacivemodematrix) |
---|
390 | # create the constraints |
---|
391 | for i,row in enumerate(displacivemodeInvmatrix): |
---|
392 | constraint = [] |
---|
393 | for j,(lbl,k) in enumerate(zip(coordVarLbl,row)): |
---|
394 | if k == 0: continue |
---|
395 | constraint.append([k,G2varObj[j]]) |
---|
396 | constraint += [shortmodelist[i],False,'f'] |
---|
397 | self.Constraints.append(constraint) |
---|
398 | #---------------------------------------------------------------------- |
---|
399 | # save the ISODISTORT info for "mode analysis" |
---|
400 | if 'ISODISTORT' not in self.Phase: self.Phase['ISODISTORT'] = {} |
---|
401 | self.Phase['ISODISTORT'].update({ |
---|
402 | 'IsoModeList' : modelist, |
---|
403 | 'G2ModeList' : shortmodelist, |
---|
404 | 'IsoVarList' : coordVarLbl, |
---|
405 | 'G2VarList' : G2varObj, |
---|
406 | 'ParentStructure' : ParentCoordinates, |
---|
407 | 'Var2ModeMatrix' : displacivemodeInvmatrix, |
---|
408 | 'Mode2VarMatrix' : displacivemodematrix, |
---|
409 | }) |
---|
410 | # make explaination dictionary |
---|
411 | for mode,shortmode in zip(modelist,shortmodelist): |
---|
412 | explaination[shortmode] = "ISODISTORT full name "+str(mode) |
---|
413 | #---------------------------------------------------------------------- |
---|
414 | # now read in the ISODISTORT occupancy modes |
---|
415 | #---------------------------------------------------------------------- |
---|
416 | if blk.get('_iso_occupancymode_label'): |
---|
417 | modelist = [] |
---|
418 | shortmodelist = [] |
---|
419 | for lbl in blk.get('_iso_occupancymode_label'): |
---|
420 | modelist.append(lbl) |
---|
421 | # assume lbl is of form SSSSS[x,y,z]AAAA(a,b,...)BBBBB |
---|
422 | # where SSSSS is the parent spacegroup, [x,y,z] is a location |
---|
423 | regexp = re.match(r'.*?\[.*?\](.*?)\(.*?\)(.*)',lbl) |
---|
424 | # this extracts the AAAAA and BBBBB parts of the string |
---|
425 | if regexp: |
---|
426 | lbl = regexp.expand(r'\1\2') # parse succeeded, make a short version |
---|
427 | lbl = lbl.replace('order','o') |
---|
428 | G2obj.MakeUniqueLabel(lbl,shortmodelist) # make unique and add to list |
---|
429 | # read in the coordinate offset variables names and map them to G2 names/objects |
---|
430 | occVarLbl = [] |
---|
431 | G2varLbl = [] |
---|
432 | G2varObj = [] |
---|
433 | error = False |
---|
434 | for lbl in blk.get('_iso_deltaoccupancy_label'): |
---|
435 | occVarLbl.append(lbl) |
---|
436 | if '_' in lbl: |
---|
437 | albl = lbl[:lbl.rfind('_')] |
---|
438 | vlbl = lbl[lbl.rfind('_')+1:] |
---|
439 | else: |
---|
440 | self.warnings += ' ERROR: _iso_deltaoccupancy_label not parsed: '+lbl |
---|
441 | error = True |
---|
442 | continue |
---|
443 | if albl not in atomlbllist: |
---|
444 | self.warnings += ' ERROR: _iso_deltaoccupancy_label atom not found: '+lbl |
---|
445 | error = True |
---|
446 | continue |
---|
447 | else: |
---|
448 | anum = atomlbllist.index(albl) |
---|
449 | var = varLookup.get(vlbl) |
---|
450 | if not var: |
---|
451 | self.warnings += ' ERROR: _iso_deltaoccupancy_label variable not found: '+lbl |
---|
452 | error = True |
---|
453 | continue |
---|
454 | G2varLbl.append('::'+var+':'+str(anum)) # variable name, less phase ID |
---|
455 | G2varObj.append(G2obj.G2VarObj( |
---|
456 | (self.Phase['ranId'],None,var,ranIdlookup[albl]) |
---|
457 | )) |
---|
458 | if error: |
---|
459 | raise Exception,"Error decoding variable labels" |
---|
460 | |
---|
461 | if len(G2varObj) != len(modelist): |
---|
462 | print "non-square input" |
---|
463 | raise Exception,"Rank of _iso_occupancymode != _iso_deltaoccupancy" |
---|
464 | |
---|
465 | error = False |
---|
466 | ParentCoordinates = {} |
---|
467 | for lbl,exp in zip( |
---|
468 | blk.get('_iso_occupancy_label'), |
---|
469 | blk.get('_iso_occupancy_formula'), |
---|
470 | ): |
---|
471 | if '_' in lbl: |
---|
472 | albl = lbl[:lbl.rfind('_')] |
---|
473 | vlbl = lbl[lbl.rfind('_')+1:] |
---|
474 | else: |
---|
475 | self.warnings += ' ERROR: _iso_occupancy_label not parsed: '+lbl |
---|
476 | error = True |
---|
477 | continue |
---|
478 | if vlbl != 'occ': |
---|
479 | self.warnings += ' ERROR: _iso_occupancy_label coordinate not parsed: '+lbl |
---|
480 | error = True |
---|
481 | continue |
---|
482 | if '+' in exp: |
---|
483 | val = exp.split('+')[0].strip() |
---|
484 | val = G2p3.FormulaEval(val) |
---|
485 | if val is None: |
---|
486 | self.warnings += ' ERROR: _iso_occupancy_formula coordinate not interpreted: '+lbl |
---|
487 | error = True |
---|
488 | continue |
---|
489 | ParentCoordinates[albl] = val |
---|
490 | if error: |
---|
491 | raise Exception,"Error decoding occupancy labels" |
---|
492 | # get mapping of modes to atomic coordinate displacements |
---|
493 | occupancymodematrix = np.zeros((len(G2varObj),len(G2varObj))) |
---|
494 | for row,col,val in zip( |
---|
495 | blk.get('_iso_occupancymodematrix_row'), |
---|
496 | blk.get('_iso_occupancymodematrix_col'), |
---|
497 | blk.get('_iso_occupancymodematrix_value'),): |
---|
498 | occupancymodematrix[int(row)-1,int(col)-1] = float(val) |
---|
499 | # Invert to get mapping of atom displacements to modes |
---|
500 | occupancymodeInvmatrix = np.linalg.inv(occupancymodematrix) |
---|
501 | # create the constraints |
---|
502 | for i,row in enumerate(occupancymodeInvmatrix): |
---|
503 | constraint = [] |
---|
504 | for j,(lbl,k) in enumerate(zip(occVarLbl,row)): |
---|
505 | if k == 0: continue |
---|
506 | constraint.append([k,G2varObj[j]]) |
---|
507 | constraint += [shortmodelist[i],False,'f'] |
---|
508 | self.Constraints.append(constraint) |
---|
509 | #---------------------------------------------------------------------- |
---|
510 | # save the ISODISTORT info for "mode analysis" |
---|
511 | if 'ISODISTORT' not in self.Phase: self.Phase['ISODISTORT'] = {} |
---|
512 | self.Phase['ISODISTORT'].update({ |
---|
513 | 'OccModeList' : modelist, |
---|
514 | 'G2OccModeList' : shortmodelist, |
---|
515 | 'OccVarList' : occVarLbl, |
---|
516 | 'G2OccVarList' : G2varObj, |
---|
517 | 'BaseOcc' : ParentCoordinates, |
---|
518 | 'Var2OccMatrix' : occupancymodeInvmatrix, |
---|
519 | 'Occ2VarMatrix' : occupancymodematrix, |
---|
520 | }) |
---|
521 | # make explaination dictionary |
---|
522 | for mode,shortmode in zip(modelist,shortmodelist): |
---|
523 | explaination[shortmode] = "ISODISTORT full name "+str(mode) |
---|
524 | #---------------------------------------------------------------------- |
---|
525 | # done with read |
---|
526 | #---------------------------------------------------------------------- |
---|
527 | if explaination: self.Constraints.append(explaination) |
---|
528 | |
---|
529 | # # debug: show the mode var to mode relations |
---|
530 | # for i,row in enumerate(displacivemodeInvmatrix): |
---|
531 | # l = '' |
---|
532 | # for j,(lbl,k) in enumerate(zip(coordVarLbl,row)): |
---|
533 | # if k == 0: continue |
---|
534 | # if l: l += ' + ' |
---|
535 | # #l += lbl+' * '+str(k) |
---|
536 | # l += G2varLbl[j]+' * '+str(k) |
---|
537 | # print str(i) + ': '+shortmodelist[i]+' = '+l |
---|
538 | # print 70*'=' |
---|
539 | |
---|
540 | # # debug: Get the ISODISTORT offset values |
---|
541 | # coordVarDelta = {} |
---|
542 | # for lbl,val in zip( |
---|
543 | # blk.get('_iso_deltacoordinate_label'), |
---|
544 | # blk.get('_iso_deltacoordinate_value'),): |
---|
545 | # coordVarDelta[lbl] = float(val) |
---|
546 | # modeVarDelta = {} |
---|
547 | # for lbl,val in zip( |
---|
548 | # blk.get('_iso_displacivemode_label'), |
---|
549 | # blk.get('_iso_displacivemode_value'),): |
---|
550 | # modeVarDelta[lbl] = cif.get_number_with_esd(val)[0] |
---|
551 | |
---|
552 | # print 70*'=' |
---|
553 | # # compute the mode values from the reported coordinate deltas |
---|
554 | # for i,row in enumerate(displacivemodeInvmatrix): |
---|
555 | # l = '' |
---|
556 | # sl = '' |
---|
557 | # s = 0. |
---|
558 | # for lbl,k in zip(coordVarLbl,row): |
---|
559 | # if k == 0: continue |
---|
560 | # if l: l += ' + ' |
---|
561 | # l += lbl+' * '+str(k) |
---|
562 | # if sl: sl += ' + ' |
---|
563 | # sl += str(coordVarDelta[lbl])+' * '+str(k) |
---|
564 | # s += coordVarDelta[lbl] * k |
---|
565 | # print 'a'+str(i)+' = '+l |
---|
566 | # print '\t= '+sl |
---|
567 | # print modelist[i],shortmodelist[i],modeVarDelta[modelist[i]],s |
---|
568 | # print |
---|
569 | |
---|
570 | # print 70*'=' |
---|
571 | # # compute the coordinate displacements from the reported mode values |
---|
572 | # for i,lbl,row in zip(range(len(coordVarLbl)),coordVarLbl,displacivemodematrix): |
---|
573 | # l = '' |
---|
574 | # sl = '' |
---|
575 | # s = 0.0 |
---|
576 | # for j,k in enumerate(row): |
---|
577 | # if k == 0: continue |
---|
578 | # if l: l += ' + ' |
---|
579 | # l += 'a'+str(j+1)+' * '+str(k) |
---|
580 | # if sl: sl += ' + ' |
---|
581 | # sl += str(shortmodelist[j]) +' = '+ str(modeVarDelta[modelist[j]]) + ' * '+str(k) |
---|
582 | # s += modeVarDelta[modelist[j]] * k |
---|
583 | # print lbl+' = '+l |
---|
584 | # print '\t= '+sl |
---|
585 | # print lbl,G2varLbl[i],coordVarDelta[lbl],s |
---|
586 | # print |
---|
587 | |
---|
588 | # determine the coordinate delta values from deviations from the parent structure |
---|
589 | # for atmline in self.Phase['Atoms']: |
---|
590 | # lbl = atmline[0] |
---|
591 | # x,y,z = atmline[3:6] |
---|
592 | # if lbl not in ParentCoordinates: |
---|
593 | # print lbl,x,y,z |
---|
594 | # continue |
---|
595 | # px,py,pz = ParentCoordinates[lbl] |
---|
596 | # print lbl,x,y,z,x-px,y-py,z-pz |
---|