This repository has been archived by the owner on Sep 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
GSASIIstrIO.py
4452 lines (4237 loc) · 204 KB
/
GSASIIstrIO.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
########### SVN repository information ###################
# $Date: 2023-12-16 09:25:27 -0600 (Sat, 16 Dec 2023) $
# $Author: vondreele $
# $Revision: 5707 $
# $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/GSASIIstrIO.py $
# $Id: GSASIIstrIO.py 5707 2023-12-16 15:25:27Z vondreele $
########### SVN repository information ###################
'''
:mod:`GSASIIstrIO` routines, used for refinement to
read from GPX files and print to the .LST file.
Used for refinements and in G2scriptable.
This file should not contain any wxpython references as this
must be used in non-GUI settings.
'''
from __future__ import division, print_function
import platform
import re
import os
import os.path as ospath
import time
import math
import random as rand
import copy
if '2' in platform.python_version_tuple()[0]:
import cPickle
else:
import pickle as cPickle
import numpy as np
import numpy.ma as ma
import GSASIIpath
GSASIIpath.SetVersionNumber("$Revision: 5707 $")
import GSASIIElem as G2el
import GSASIIlattice as G2lat
import GSASIIspc as G2spc
import GSASIIobj as G2obj
import GSASIImapvars as G2mv
import GSASIImath as G2mth
import GSASIIstrMath as G2stMth
import GSASIIfiles as G2fil
sind = lambda x: np.sin(x*np.pi/180.)
cosd = lambda x: np.cos(x*np.pi/180.)
tand = lambda x: np.tan(x*np.pi/180.)
asind = lambda x: 180.*np.arcsin(x)/np.pi
acosd = lambda x: 180.*np.arccos(x)/np.pi
atan2d = lambda y,x: 180.*np.arctan2(y,x)/np.pi
ateln2 = 8.0*math.log(2.0)
#===============================================================================
# Support for GPX file reading
#===============================================================================
def cPickleLoad(fp):
if '2' in platform.python_version_tuple()[0]:
return cPickle.load(fp)
else:
return cPickle.load(fp,encoding='latin-1')
gpxIndex = {}; gpxNamelist = []; gpxSize = -1
'''Global variables used in :func:`IndexGPX` to see if file has changed
(gpxSize) and to index where to find each 1st-level tree item in the file.
'''
def GetFullGPX(GPXfile):
''' Returns complete contents of GSASII gpx file.
Used in :func:`GSASIIscriptable.LoadDictFromProjFile`.
:param str GPXfile: full .gpx file name
:returns: Project,nameList, where
* Project (dict) is a representation of gpx file following the GSAS-II
tree structure for each item: key = tree name (e.g. 'Controls',
'Restraints', etc.), data is dict
* nameList (list) has names of main tree entries & subentries used to reconstruct project file
'''
return IndexGPX(GPXfile,read=True)
def IndexGPX(GPXfile,read=False):
'''Create an index to a GPX file, optionally the file into memory.
The byte size of the GPX file is saved. If this routine is called
again, and if this size does not change, indexing is not repeated
since it is assumed the file has not changed (this can be overriden
by setting read=True).
:param str GPXfile: full .gpx file name
:returns: Project,nameList if read=, where
* Project (dict) is a representation of gpx file following the GSAS-II
tree structure for each item: key = tree name (e.g. 'Controls',
'Restraints', etc.), data is dict
* nameList (list) has names of main tree entries & subentries used to reconstruct project file
'''
global gpxSize
if gpxSize == os.path.getsize(GPXfile) and not read:
return
global gpxIndex
gpxIndex = {}
global gpxNamelist
gpxNamelist = []
if GSASIIpath.GetConfigValue('debug'): print("DBG: Indexing GPX file")
gpxSize = os.path.getsize(GPXfile)
fp = open(GPXfile,'rb')
Project = {}
try:
while True:
pos = fp.tell()
data = cPickleLoad(fp)
datum = data[0]
gpxIndex[datum[0]] = pos
if read: Project[datum[0]] = {'data':datum[1]}
gpxNamelist.append([datum[0],])
for datus in data[1:]:
if read: Project[datum[0]][datus[0]] = datus[1]
gpxNamelist[-1].append(datus[0])
# print('project load successful')
except EOFError:
pass
except Exception as msg:
G2fil.G2Print('Read Error:',msg)
raise Exception("Error reading file "+str(GPXfile)+". This is not a GSAS-II .gpx file")
finally:
fp.close()
if read: return Project,gpxNamelist
def GetControls(GPXfile):
''' Returns dictionary of control items found in GSASII gpx file
:param str GPXfile: full .gpx file name
:return: dictionary of control items
'''
Controls = copy.deepcopy(G2obj.DefaultControls)
IndexGPX(GPXfile)
pos = gpxIndex.get('Controls')
if pos is None:
G2fil.G2Print('Warning: Controls not found in gpx file {}'.format(GPXfile))
return Controls
fp = open(GPXfile,'rb')
fp.seek(pos)
datum = cPickleLoad(fp)[0]
fp.close()
Controls.update(datum[1])
return Controls
def ReadConstraints(GPXfile, seqHist=None):
'''Read the constraints from the GPX file and interpret them
called in :func:`ReadCheckConstraints`, :func:`GSASIIstrMain.Refine`
and :func:`GSASIIstrMain.SeqRefine`.
'''
IndexGPX(GPXfile)
fl = open(GPXfile,'rb')
pos = gpxIndex.get('Constraints')
if pos is None:
raise Exception("No constraints in GPX file")
fl.seek(pos)
ConstraintsItem = cPickleLoad(fl)[0]
seqmode = 'use-all'
if seqHist is not None:
seqmode = ConstraintsItem[1].get('_seqmode','wildcards-only')
fl.close()
constList = []
for item in ConstraintsItem[1]:
if item.startswith('_'): continue
constList += ConstraintsItem[1][item]
constrDict,fixedList,ignored = G2mv.ProcessConstraints(constList,seqmode,seqHist)
#if ignored:
# G2fil.G2Print ('Warning: {} Constraints were rejected. Was a constrained phase, histogram or atom deleted?'.format(ignored))
return constrDict,fixedList
def ReadCheckConstraints(GPXfile, seqHist=None,Histograms=None,Phases=None):
'''Load constraints and related info and return any error or warning messages
This is done from the GPX file rather than the tree.
:param str GPXfile: specifies the path to a .gpx file.
:param str seqHist: specifies a histogram to be loaded for
a sequential refinement. If None (default) all are loaded.
:param dict Histograms: output from :func:`GetUsedHistogramsAndPhases`,
can optionally be supplied to save time for sequential refinements
:param dict Phases: output from :func:`GetUsedHistogramsAndPhases`, can
optionally be supplied to save time for sequential refinements
'''
G2mv.InitVars() # init constraints
# get variables
if Histograms is None or Phases is None:
Histograms,Phases = GetUsedHistogramsAndPhases(GPXfile)
if not Phases:
return 'Error: No phases or no histograms in phases!',''
if not Histograms:
return 'Error: no diffraction data',''
if seqHist:
Histograms = {seqHist:Histograms[seqHist]} # sequential fit: only need one histogram
hId = Histograms[seqHist]['hId']
else:
hId = None
constrDict,fixedList = ReadConstraints(GPXfile, hId) # load user constraints from file (uses ProcessConstraints)
parmDict = {}
# generate symmetry constraints to check for conflicts
rigidbodyDict = GetRigidBodies(GPXfile)
rbIds = rigidbodyDict.get('RBIds',{'Vector':[],'Residue':[],'Spin':[]})
rbVary,rbDict = GetRigidBodyModels(rigidbodyDict,Print=False)
parmDict.update(rbDict)
(Natoms, atomIndx, phaseVary,phaseDict, pawleyLookup,FFtables,EFtables,ORBtables,BLtables,MFtables,maxSSwave) = \
GetPhaseData(Phases,RestraintDict=None,seqHistName=seqHist,rbIds=rbIds,Print=False) # generates atom symmetry constraints
parmDict.update(phaseDict)
hapVary,hapDict,controlDict = GetHistogramPhaseData(Phases,Histograms,Print=False,resetRefList=False)
parmDict.update(hapDict)
histVary,histDict,controlDict = GetHistogramData(Histograms,Print=False)
parmDict.update(histDict)
varyList = rbVary+phaseVary+hapVary+histVary
msg = G2mv.EvaluateMultipliers(constrDict,phaseDict,hapDict,histDict)
if msg:
return 'Unable to interpret multiplier(s): '+msg,''
errmsg,warnmsg,groups,parmlist = G2mv.GenerateConstraints(varyList,constrDict,fixedList,parmDict,seqHistNum=hId)
G2mv.Map2Dict(parmDict,varyList) # changes varyList
return errmsg, warnmsg
def makeTwinFrConstr(Phases,Histograms,hapVary):
TwConstr = []
TwFixed = []
for Phase in Phases:
pId = Phases[Phase]['pId']
for Histogram in Phases[Phase]['Histograms']:
try:
hId = Histograms[Histogram]['hId']
phfx = '%d:%d:'%(pId,hId)
if phfx+'TwinFr:0' in hapVary:
TwFixed.append('1.0') #constraint value
nTwin = len(Phases[Phase]['Histograms'][Histogram]['Twins'])
TwConstr.append({phfx+'TwinFr:'+str(i):'1.0' for i in range(nTwin)})
except KeyError: #unused histograms?
pass
return TwConstr,TwFixed
def GetRestraints(GPXfile):
'''Read the restraints from the GPX file.
Throws an exception if not found in the .GPX file
'''
IndexGPX(GPXfile)
fl = open(GPXfile,'rb')
pos = gpxIndex.get('Restraints')
if pos is None:
raise Exception("No Restraints in GPX file")
fl.seek(pos)
datum = cPickleLoad(fl)[0]
fl.close()
return datum[1]
def GetRigidBodies(GPXfile):
'''Read the rigid body models from the GPX file
'''
IndexGPX(GPXfile)
fl = open(GPXfile,'rb')
pos = gpxIndex.get('Rigid bodies')
if pos is None:
raise Exception("No Rigid bodies in GPX file")
fl.seek(pos)
datum = cPickleLoad(fl)[0]
fl.close()
return datum[1]
def GetFprime(controlDict,Histograms):
'Needs a doc string'
FFtables = controlDict['FFtables']
if not FFtables:
return
histoList = list(Histograms.keys())
histoList.sort()
for histogram in histoList:
if histogram[:4] in ['PWDR','HKLF']:
Histogram = Histograms[histogram]
hId = Histogram['hId']
hfx = ':%d:'%(hId)
if 'E' in controlDict[hfx+'histType']:
for El in FFtables:
FFtables[El][hfx+'FP'] = 0.
FFtables[El][hfx+'FPP'] = 0.
elif 'X' in controlDict[hfx+'histType']:
keV = controlDict[hfx+'keV']
for El in FFtables:
Orbs = G2el.GetXsectionCoeff(El.split('+')[0].split('-')[0])
FP,FPP,Mu = G2el.FPcalc(Orbs, keV)
FFtables[El][hfx+'FP'] = FP
FFtables[El][hfx+'FPP'] = FPP
def PrintFprime(FFtables,pfx,pFile):
pFile.write('\n Resonant form factors:(ref: D.T. Cromer & D.A. Liberman (1981), Acta Cryst. A37, 267-268.)\n')
Elstr = ' Element:'
FPstr = " f' :"
FPPstr = ' f" :'
for El in FFtables:
if 'Q' not in El:
Elstr += ' %8s'%(El)
FPstr += ' %8.3f'%(FFtables[El][pfx+'FP'])
FPPstr += ' %8.3f'%(FFtables[El][pfx+'FPP'])
pFile.write(Elstr+'\n')
pFile.write(FPstr+'\n')
pFile.write(FPPstr+'\n')
def PrintBlength(BLtables,wave,pFile):
pFile.write('\n Resonant neutron scattering lengths:\n')
Elstr = ' Element:'
FPstr = " b' :"
FPPstr = ' b" :'
for El in BLtables:
if 'Q' not in El:
BP,BPP = G2el.BlenResCW([El,],BLtables,wave)
Elstr += ' %8s'%(El)
FPstr += ' %8.3f'%(BP)
FPPstr += ' %8.3f'%(BPP)
pFile.write(Elstr+'\n')
pFile.write(FPstr+'\n')
pFile.write(FPPstr+'\n')
def PrintISOmodes(pFile,Phases,parmDict,sigDict):
'''Prints the values for the ISODISTORT modes into the project's
.lst file after a refinement.
'''
for phase in Phases:
if 'ISODISTORT' not in Phases[phase]: continue
data = Phases[phase]
ISO = data['ISODISTORT']
atNames = [atom[0] for atom in data['Atoms']]
if 'G2VarList' in ISO:
deltaList = []
notfound = []
for gv,Ilbl in zip(ISO['G2VarList'],ISO['IsoVarList']):
dvar = gv.varname()
var = dvar.replace('::dA','::A')
atnum = atNames.index(Ilbl[:Ilbl.rfind('_')])
v = Ilbl[Ilbl.rfind('_')+1:]
pval = ISO['G2parentCoords'][atnum][['dx','dy','dz'].index(v)]
if var in parmDict:
cval = parmDict[var]
else:
notfound.append(var)
continue
deltaList.append(cval-pval)
if notfound:
msg = 'PrintISOmodes warning: Atom parameters '
for i,v in enumerate(notfound):
if i == len(notfound)-1:
msg += ' & '
elif i != 0:
msg += ', '
msg += v
print(msg,'not found')
print(' skipping computation for modes:')
for i,j in zip(ISO['IsoModeList'],ISO['G2ModeList']):
print(' ',i,'({})'.format(j))
continue
modeVals = np.inner(ISO['Var2ModeMatrix'],deltaList)
pFile.write('\n ISODISTORT Displacive Modes for phase {}\n'.format(data['General'].get('Name','')))
l = str(max([len(i) for i in ISO['IsoModeList']])+3)
fmt = ' {:'+l+'}{}'
for varid,[var,val,norm,G2mode] in enumerate(zip(
ISO['IsoModeList'],modeVals,ISO['NormList'],ISO['G2ModeList'] )):
try:
value = G2mth.ValEsd(val/norm,-0.001)
item = str(G2mode).replace('::','::nv-')
if item in sigDict:
ISO['modeDispl'][varid] = val/norm
value = G2mth.ValEsd(val/norm,sigDict[item]/norm)
except TypeError:
value = '?'
pFile.write(fmt.format(var,value)+'\n')
if 'G2OccVarList' in ISO: #untested - probably wrong
deltaOccList = []
notfound = []
for gv,Ilbl in zip(ISO['G2OccVarList'],ISO['OccVarList']):
var = gv.varname()
albl = Ilbl[:Ilbl.rfind('_')]
pval = ISO['BaseOcc'][albl]
if var in parmDict:
cval = parmDict[var]
else:
notfound.append(var)
continue
deltaOccList.append(cval-pval)
if notfound:
msg = 'PrintISOmodes warning: Atom parameters '
for i,v in enumerate(notfound):
if i == len(notfound)-1:
msg += ' & '
elif i != 0:
msg += ', '
msg += v
print(msg,'not found')
print(' skipping computation for modes:')
for i,j in zip(ISO['OccVarList'],ISO['G2OccVarList']):
print(' ',i,'({})'.format(j))
continue
modeOccVals = np.inner(ISO['Var2OccMatrix'],deltaOccList)
pFile.write('\n ISODISTORT Occupancy Modes for phase {}\n'.format(data['General'].get('Name','')))
l = str(max([len(i) for i in ISO['OccModeList']])+3)
fmt = ' {:'+l+'}{}'
for var,val,norm,G2mode in zip(
ISO['OccModeList'],modeOccVals,ISO['OccNormList'],ISO['G2OccModeList'] ):
try:
value = G2fil.FormatSigFigs(val/norm)
if str(G2mode) in sigDict:
value = G2mth.ValEsd(val/norm,sigDict[str(G2mode)]/norm)
except TypeError:
value = '?'
pFile.write(fmt.format(var,value)+'\n')
def PrintIndependentVars(parmDict,varyList,sigDict,PrintAll=False,pFile=None):
'''Print the values and uncertainties on the independent parameters'''
printlist = []
mvs = G2mv.GetIndependentVars()
for i,name in enumerate(mvs):
if PrintAll or name in varyList:
sig = sigDict.get(name)
printlist.append([name,parmDict[name],sig])
if len(printlist) == 0: return
s1 = ''
s2 = ''
s3 = ''
pFile.write(130*'-'+'\n')
pFile.write("Parameters generated by constraints\n")
printlist.append(3*[None])
for name,val,esd in printlist:
if len(s1) > 120 or name is None:
pFile.write(''+'\n')
pFile.write(s1+'\n')
pFile.write(s2+'\n')
pFile.write(s3+'\n')
s1 = ''
if name is None: break
if s1 == "":
s1 = ' name :'
s2 = ' value :'
s3 = ' sig : '
wdt = len(name)+1
s1 += ('%15s' % (name)).rjust(wdt)
s2 += ('%15.5f' % (val)).center(wdt)
if esd is None:
s3 += ('%15s' % ('n/a')).center(wdt)
else:
s3 += fmtESD(name,sigDict,'f',15,5).center(wdt)
def GetPhaseNames(GPXfile):
''' Returns a list of phase names found under 'Phases' in GSASII gpx file
:param str GPXfile: full .gpx file name
:return: list of phase names
'''
IndexGPX(GPXfile)
fl = open(GPXfile,'rb')
pos = gpxIndex.get('Phases')
if pos is None:
raise Exception("No Phases in GPX file")
fl.seek(pos)
data = cPickleLoad(fl)
fl.close()
return [datus[0] for datus in data[1:]]
def GetAllPhaseData(GPXfile,PhaseName):
''' Returns the entire dictionary for PhaseName from GSASII gpx file
:param str GPXfile: full .gpx file name
:param str PhaseName: phase name
:return: phase dictionary or None if PhaseName is not present
'''
IndexGPX(GPXfile)
fl = open(GPXfile,'rb')
pos = gpxIndex.get('Phases')
if pos is None:
raise Exception("No Phases in GPX file")
fl.seek(pos)
data = cPickleLoad(fl)
fl.close()
for datus in data[1:]:
if datus[0] == PhaseName:
return datus[1]
def GetHistograms(GPXfile,hNames):
""" Returns a dictionary of histograms found in GSASII gpx file
:param str GPXfile: full .gpx file name
:param str hNames: list of histogram names
:return: dictionary of histograms (types = PWDR & HKLF)
"""
IndexGPX(GPXfile)
fl = open(GPXfile,'rb')
Histograms = {}
for hist in hNames:
pos = gpxIndex.get(hist)
if pos is None:
raise Exception("Histogram {} not found in GPX file".format(hist))
fl.seek(pos)
data = cPickleLoad(fl)
datum = data[0]
if 'PWDR' in hist[:4]:
PWDRdata = {}
PWDRdata.update(datum[1][0]) #weight factor
PWDRdata['Data'] = ma.array(ma.getdata(datum[1][1])) #masked powder data arrays/clear previous masks
PWDRdata[data[2][0]] = data[2][1] #Limits & excluded regions (if any)
PWDRdata[data[3][0]] = data[3][1] #Background
PWDRdata[data[4][0]] = data[4][1] #Instrument parameters
PWDRdata[data[5][0]] = data[5][1] #Sample parameters
try:
PWDRdata[data[9][0]] = data[9][1] #Reflection lists might be missing
except IndexError:
PWDRdata['Reflection Lists'] = {}
PWDRdata['Residuals'] = {}
Histograms[hist] = PWDRdata
elif 'HKLF' in hist[:4]:
HKLFdata = {}
HKLFdata.update(datum[1][0]) #weight factor
#patch
if 'list' in str(type(datum[1][1])):
#if isinstance(datum[1][1],list):
RefData = {'RefList':[],'FF':{}}
for ref in datum[1][1]:
RefData['RefList'].append(ref[:11]+[ref[13],])
RefData['RefList'] = np.array(RefData['RefList'])
datum[1][1] = RefData
#end patch
datum[1][1]['FF'] = {}
HKLFdata['Data'] = datum[1][1]
HKLFdata['Instrument Parameters'] = dict(data)['Instrument Parameters']
HKLFdata['Reflection Lists'] = None
HKLFdata['Residuals'] = {}
Histograms[hist] = HKLFdata
fl.close()
return Histograms
def GetHistogramNames(GPXfile,hTypes):
""" Returns a list of histogram names found in a GSAS-II .gpx file that
match specifed histogram types. Names are returned in the order they
appear in the file.
:param str GPXfile: full .gpx file name
:param str hTypes: list of histogram types
:return: list of histogram names (types = PWDR & HKLF)
"""
IndexGPX(GPXfile)
return [n[0] for n in gpxNamelist if n[0][:4] in hTypes]
def GetUsedHistogramsAndPhases(GPXfile):
''' Returns all histograms that are found in any phase
and any phase that uses a histogram. This also
assigns numbers to used phases and histograms by the
order they appear in the file.
:param str GPXfile: full .gpx file name
:returns: (Histograms,Phases)
* Histograms = dictionary of histograms as {name:data,...}
* Phases = dictionary of phases that use histograms
'''
phaseNames = GetPhaseNames(GPXfile)
histoList = GetHistogramNames(GPXfile,['PWDR','HKLF'])
allHistograms = GetHistograms(GPXfile,histoList)
phaseData = {}
for name in phaseNames:
phaseData[name] = GetAllPhaseData(GPXfile,name)
Histograms = {}
Phases = {}
for phase in phaseData:
Phase = phaseData[phase]
if Phase['General']['Type'] == 'faulted': continue #don't use faulted phases!
if Phase['Histograms']:
for hist in Phase['Histograms']:
if 'Use' not in Phase['Histograms'][hist]: #patch
Phase['Histograms'][hist]['Use'] = True
if Phase['Histograms'][hist]['Use'] and phase not in Phases:
pId = phaseNames.index(phase)
Phase['pId'] = pId
Phases[phase] = Phase
if hist not in Histograms and Phase['Histograms'][hist]['Use']:
try:
Histograms[hist] = allHistograms[hist]
hId = histoList.index(hist)
Histograms[hist]['hId'] = hId
except KeyError: # would happen if a referenced histogram were
# renamed or deleted
G2fil.G2Print('Warning: For phase "'+phase+
'" unresolved reference to histogram "'+hist+'"')
# load the fix background info into the histograms
for hist in Histograms:
if 'Background' not in Histograms[hist]: continue
fixedBkg = Histograms[hist]['Background'][1].get('background PWDR')
if fixedBkg:
if not fixedBkg[0]: continue
# patch: add refinement flag, if needed
if len(fixedBkg) == 2: fixedBkg += [False]
h = Histograms[hist]['Background'][1]
try:
Limits = Histograms[hist]['Limits'][1]
x = Histograms[hist]['Data'][0]
xB = np.searchsorted(x,Limits[0])
xF = np.searchsorted(x,Limits[1])+1
h['fixback'] = allHistograms[fixedBkg[0]]['Data'][1][xB:xF]
except KeyError: # would happen if a referenced histogram were renamed or deleted
G2fil.G2Print('Warning: For hist "{}" unresolved background reference to hist "{}"'
.format(hist,fixedBkg[0]))
G2obj.IndexAllIds(Histograms=Histograms,Phases=Phases)
return Histograms,Phases
def getBackupName(GPXfile,makeBack):
'''
Get the name for the backup .gpx file name
:param str GPXfile: full .gpx file name
:param bool makeBack: if True the name of a new file is returned, if
False the name of the last file that exists is returned
:returns: the name of a backup file
'''
GPXpath,GPXname = ospath.split(GPXfile)
if GPXpath == '': GPXpath = '.'
Name = ospath.splitext(GPXname)[0]
files = os.listdir(GPXpath)
last = 0
for name in files:
name = name.split('.')
if len(name) == 3 and name[0] == Name and 'bak' in name[1]:
if makeBack:
last = max(last,int(name[1].strip('bak'))+1)
else:
last = max(last,int(name[1].strip('bak')))
GPXback = ospath.join(GPXpath,ospath.splitext(GPXname)[0]+'.bak'+str(last)+'.gpx')
return GPXback
def GPXBackup(GPXfile,makeBack=True):
'''
makes a backup of the specified .gpx file
:param str GPXfile: full .gpx file name
:param bool makeBack: if True (default), the backup is written to
a new file; if False, the last backup is overwritten
:returns: the name of the backup file that was written
'''
import distutils.file_util as dfu
GPXback = getBackupName(GPXfile,makeBack)
tries = 0
while True:
try:
dfu.copy_file(GPXfile,GPXback)
break
except:
tries += 1
if tries > 10:
return GPXfile #failed!
time.sleep(1) #just wait a second!
return GPXback
def SetUsedHistogramsAndPhases(GPXfile,Histograms,Phases,RigidBodies,CovData,parmFrozenList,makeBack=True):
''' Updates gpxfile from all histograms that are found in any phase
and any phase that used a histogram. Also updates rigid body definitions.
This is used for non-sequential fits, but not for sequential fitting.
:param str GPXfile: full .gpx file name
:param dict Histograms: dictionary of histograms as {name:data,...}
:param dict Phases: dictionary of phases that use histograms
:param dict RigidBodies: dictionary of rigid bodies
:param dict CovData: dictionary of refined variables, varyList, & covariance matrix
:param list parmFrozenList: list of parameters (as str) that are frozen
due to limits; converted to :class:`GSASIIobj.G2VarObj` objects.
:param bool makeBack: True if new backup of .gpx file is to be made; else
use the last one made
'''
import distutils.file_util as dfu
GPXback = GPXBackup(GPXfile,makeBack)
G2fil.G2Print ('Read from file:'+GPXback)
G2fil.G2Print ('Save to file :'+GPXfile)
infile = open(GPXback,'rb')
outfile = open(GPXfile,'wb')
while True:
try:
data = cPickleLoad(infile)
except EOFError:
break
datum = data[0]
# print 'read: ',datum[0]
if datum[0] == 'Phases':
for iphase in range(len(data)):
if data[iphase][0] in Phases:
phaseName = data[iphase][0]
data[iphase][1].update(Phases[phaseName])
elif datum[0] == 'Covariance':
data[0][1] = CovData
elif datum[0] == 'Rigid bodies':
data[0][1] = RigidBodies
elif datum[0] == 'Controls':
Controls = data[0][1]
if 'parmFrozen' not in Controls:
Controls['parmFrozen'] = {}
Controls['parmFrozen']['FrozenList'] = [i if type(i) is G2obj.G2VarObj
else G2obj.G2VarObj(i) for i in parmFrozenList]
try:
histogram = Histograms[datum[0]]
# print 'found ',datum[0]
data[0][1][1] = histogram['Data']
data[0][1][0].update(histogram['Residuals'])
for datus in data[1:]:
# print ' read: ',datus[0]
if datus[0] in ['Instrument Parameters','Sample Parameters','Reflection Lists']:
datus[1] = histogram[datus[0]]
if datus[0] == 'Background': # remove fixed background from file
d1 = {key:histogram['Background'][1][key]
for key in histogram['Background'][1]
if not key.startswith('_fixed')}
datus[1] = copy.deepcopy(histogram['Background'])
datus[1][1] = d1
except KeyError:
pass
try:
cPickle.dump(data,outfile,1)
except AttributeError:
G2fil.G2Print ('ERROR - bad data in least squares result')
infile.close()
outfile.close()
dfu.copy_file(GPXback,GPXfile)
G2fil.G2Print ('GPX file save failed - old version retained',mode='error')
return
infile.close()
outfile.close()
G2fil.G2Print ('GPX file save successful')
def GetSeqResult(GPXfile):
'''
Returns the sequential results table information from a GPX file.
Called at the beginning of :meth:`GSASIIstrMain.SeqRefine`
:param str GPXfile: full .gpx file name
:returns: a dict containing the sequential results table
'''
IndexGPX(GPXfile)
pos = gpxIndex.get('Sequential results')
if pos is None:
return {}
fl = open(GPXfile,'rb')
fl.seek(pos)
datum = cPickleLoad(fl)[0]
fl.close()
return datum[1]
def SetupSeqSavePhases(GPXfile):
'''Initialize the files used to save intermediate results from
sequential fits.
'''
IndexGPX(GPXfile)
# load initial Phase results from GPX
fl = open(GPXfile,'rb')
pos = gpxIndex.get('Phases')
if pos is None:
raise Exception("No Phases in GPX file")
fl.seek(pos)
data = cPickleLoad(fl)
fl.close()
# create GPX-like file to store latest Phase info; init with start vals
GPXphase = os.path.splitext(GPXfile)[0]+'.seqPhase'
fp = open(GPXphase,'wb')
cPickle.dump(data,fp,1)
fp.close()
# create empty file for histogram info
GPXhist = os.path.splitext(GPXfile)[0]+'.seqHist'
fp = open(GPXhist,'wb')
fp.close()
def SaveUpdatedHistogramsAndPhases(GPXfile,Histograms,Phases,RigidBodies,CovData,parmFrozen):
'''
Save phase and histogram information into "pseudo-gpx" files. The phase
information is overwritten each time this is called, but histogram information is
appended after each sequential step.
:param str GPXfile: full .gpx file name
:param dict Histograms: dictionary of histograms as {name:data,...}
:param dict Phases: dictionary of phases that use histograms
:param dict RigidBodies: dictionary of rigid bodies
:param dict CovData: dictionary of refined variables, varyList, & covariance matrix
:param dict parmFrozen: dict with frozen parameters for all phases
and histograms (specified as str values)
'''
GPXphase = os.path.splitext(GPXfile)[0]+'.seqPhase'
fp = open(GPXphase,'rb')
data = cPickleLoad(fp) # first block in file should be Phases
if data[0][0] != 'Phases':
raise Exception('Unexpected block in {} file. How did this happen?'
.format(GPXphase))
fp.close()
# update previous phase info
for datum in data[1:]:
if datum[0] in Phases:
datum[1].update(Phases[datum[0]])
# save latest Phase/refinement info
fp = open(GPXphase,'wb')
cPickle.dump(data,fp,1)
cPickle.dump([['Covariance',CovData]],fp,1)
cPickle.dump([['Rigid bodies',RigidBodies]],fp,1)
cPickle.dump([['parmFrozen',parmFrozen]],fp,1)
fp.close()
# create an entry that looks like a PWDR tree item
for key in Histograms:
if key.startswith('PWDR '):
break
else:
raise Exception('No PWDR entry in Histogram dict!')
histname = key
hist = copy.deepcopy(Histograms[key])
xfer_dict = {'Index Peak List': [[], []],
'Comments': [],
'Unit Cells List': [],
'Peak List': {'peaks': [], 'sigDict': {}},
}
histData = hist['Data']
del hist['Data']
for key in ('Limits','Background','Instrument Parameters',
'Sample Parameters','Reflection Lists'):
xfer_dict[key] = hist[key]
if key == 'Background': # remove fixed background from file
xfer_dict['Background'][1] = {k:hist['Background'][1][k]
for k in hist['Background'][1]
if not k.startswith('_fixed')}
del hist[key]
# xform into a gpx-type entry
data = []
data.append([histname,[hist,histData,histname]])
for key in ['Comments','Limits','Background','Instrument Parameters',
'Sample Parameters','Peak List','Index Peak List',
'Unit Cells List','Reflection Lists']:
data.append([key,xfer_dict[key]])
# append histogram to histogram info
GPXhist = os.path.splitext(GPXfile)[0]+'.seqHist'
fp = open(GPXhist,'ab')
cPickle.dump(data,fp,1)
fp.close()
return
def SetSeqResult(GPXfile,Histograms,SeqResult):
'''
Places the sequential results information into a GPX file
after a refinement has been completed.
Called at the end of :meth:`GSASIIstrMain.SeqRefine`
:param str GPXfile: full .gpx file name
'''
GPXback = GPXBackup(GPXfile)
G2fil.G2Print ('Read from file:'+GPXback)
G2fil.G2Print ('Save to file :'+GPXfile)
GPXphase = os.path.splitext(GPXfile)[0]+'.seqPhase'
fp = open(GPXphase,'rb')
data = cPickleLoad(fp) # first block in file should be Phases
if data[0][0] != 'Phases':
raise Exception('Unexpected block in {} file. How did this happen?'.format(GPXphase))
Phases = {}
for name,vals in data[1:]:
Phases[name] = vals
name,CovData = cPickleLoad(fp)[0] # 2nd block in file should be Covariance
name,RigidBodies = cPickleLoad(fp)[0] # 3rd block in file should be Rigid Bodies
name,parmFrozenDict = cPickleLoad(fp)[0] # 4th block in file should be frozen parameters
fp.close()
GPXhist = os.path.splitext(GPXfile)[0]+'.seqHist'
hist = open(GPXhist,'rb')
# build an index to the GPXhist file
histIndex = {}
while True:
loc = hist.tell()
try:
datum = cPickleLoad(hist)[0]
except EOFError:
break
histIndex[datum[0]] = loc
infile = open(GPXback,'rb')
outfile = open(GPXfile,'wb')
while True:
try:
data = cPickleLoad(infile)
except EOFError:
break
datum = data[0]
if datum[0] == 'Sequential results':
data[0][1] = SeqResult
elif datum[0] == 'Phases':
for pdata in data[1:]:
if pdata[0] in Phases:
pdata[1].update(Phases[pdata[0]])
elif datum[0] == 'Covariance':
data[0][1] = CovData
elif datum[0] == 'Rigid bodies':
data[0][1] = RigidBodies
elif datum[0] == 'Controls': # reset the Copy Next flag after a sequential fit
Controls = data[0][1]
Controls['Copy2Next'] = False
for key in parmFrozenDict:
Controls['parmFrozen'][key] = [
i if type(i) is G2obj.G2VarObj
else G2obj.G2VarObj(i)
for i in parmFrozenDict[key]]
elif datum[0] in histIndex:
hist.seek(histIndex[datum[0]])
hdata = cPickleLoad(hist)
if data[0][0] != hdata[0][0]:
G2fil.G2Print('Error! Updating {} with {}'.format(data[0][0],hdata[0][0]))
data[0] = hdata[0]
xferItems = ['Background','Instrument Parameters','Sample Parameters','Reflection Lists']
hItems = {name:j+1 for j,(name,val) in enumerate(hdata[1:]) if name in xferItems}
for j,(name,val) in enumerate(data[1:]):
if name not in xferItems: continue
data[j+1][1] = hdata[hItems[name]][1]
cPickle.dump(data,outfile,1)
hist.close()
infile.close()
outfile.close()
# clean up tmp files
try:
os.remove(GPXphase)
except:
G2fil.G2Print('Warning: unable to delete {}'.format(GPXphase))
try:
os.remove(GPXhist)
except:
G2fil.G2Print('Warning: unable to delete {}'.format(GPXhist))
G2fil.G2Print ('GPX file merge completed')
#==============================================================================
# Refinement routines
#==============================================================================
def ShowBanner(pFile=None):
'Print authorship, copyright and citation notice'
pFile.write(80*'*'+'\n')
pFile.write(' General Structure Analysis System-II Crystal Structure Refinement\n')
pFile.write(' by Robert B. Von Dreele & Brian H. Toby\n')
pFile.write(' Argonne National Laboratory(C), 2010\n')
pFile.write(' This product includes software developed by the UChicago Argonne, LLC,\n')
pFile.write(' as Operator of Argonne National Laboratory.\n')
pFile.write(' Please cite:\n')
pFile.write(' B.H. Toby & R.B. Von Dreele, J. Appl. Cryst. 46, 544-549 (2013)\n')
pFile.write(80*'*'+'\n')
def ShowControls(Controls,pFile=None,SeqRef=False,preFrozenCount=0):
'Print controls information'
pFile.write(' Least squares controls:\n')
pFile.write(' Refinement type: %s\n'%Controls['deriv type'])
if 'Hessian' in Controls['deriv type']:
pFile.write(' Maximum number of cycles: %d\n'%Controls['max cyc'])
else:
pFile.write(' Minimum delta-M/M for convergence: %.2g\n'%(Controls['min dM/M']))
pFile.write(' Regularize hydrogens (if any): %s\n'%Controls.get('HatomFix',False))
pFile.write(' Initial shift factor: %.3f\n'%(Controls['shift factor']))
if SeqRef:
pFile.write(' Sequential refinement controls:\n')
pFile.write(' Copy of histogram results to next: %s\n'%(Controls['Copy2Next']))
pFile.write(' Process histograms in reverse order: %s\n'%(Controls['Reverse Seq']))
if preFrozenCount:
pFile.write('\n Starting refinement with {} Frozen variables\n\n'.format(preFrozenCount))
def GetPawleyConstr(SGLaue,PawleyRef,im,pawleyVary):
'needs a doc string'
# if SGLaue in ['-1','2/m','mmm']:
# return #no Pawley symmetry required constraints
eqvDict = {}
for i,varyI in enumerate(pawleyVary):
eqvDict[varyI] = []
refI = int(varyI.split(':')[-1])
ih,ik,il = PawleyRef[refI][:3]
dspI = PawleyRef[refI][4+im]
for varyJ in pawleyVary[i+1:]:
refJ = int(varyJ.split(':')[-1])
jh,jk,jl = PawleyRef[refJ][:3]
dspJ = PawleyRef[refJ][4+im]
if SGLaue in ['4/m','4/mmm']:
isum = ih**2+ik**2
jsum = jh**2+jk**2
if abs(il) == abs(jl) and isum == jsum:
eqvDict[varyI].append(varyJ)
elif SGLaue in ['3R','3mR']:
isum = ih**2+ik**2+il**2
jsum = jh**2+jk**2+jl**2
isum2 = ih*ik+ih*il+ik*il
jsum2 = jh*jk+jh*jl+jk*jl
if isum == jsum and isum2 == jsum2:
eqvDict[varyI].append(varyJ)
elif SGLaue in ['3','3m1','31m','6/m','6/mmm']:
isum = ih**2+ik**2+ih*ik
jsum = jh**2+jk**2+jh*jk
if abs(il) == abs(jl) and isum == jsum:
eqvDict[varyI].append(varyJ)
elif SGLaue in ['m3','m3m']:
isum = ih**2+ik**2+il**2
jsum = jh**2+jk**2+jl**2
if isum == jsum: