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
/
Copy pathGSASIIstrMain.py
1520 lines (1459 loc) · 69.8 KB
/
GSASIIstrMain.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: 2024-02-21 22:58:44 -0600 (Wed, 21 Feb 2024) $
# $Author: toby $
# $Revision: 5737 $
# $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/GSASIIstrMain.py $
# $Id: GSASIIstrMain.py 5737 2024-02-22 04:58:44Z toby $
########### SVN repository information ###################
'''
:mod:`GSASIIstrMain` routines, used for refinement are found below.
'''
from __future__ import division, print_function
import platform
import sys
import os.path as ospath
import time
import math
import copy
if '2' in platform.python_version_tuple()[0]:
import cPickle
else:
import pickle as cPickle
import numpy as np
import numpy.linalg as nl
import scipy.optimize as so
import GSASIIpath
GSASIIpath.SetBinaryPath()
GSASIIpath.SetVersionNumber("$Revision: 5737 $")
import GSASIIlattice as G2lat
import GSASIIspc as G2spc
import GSASIImapvars as G2mv
import GSASIImath as G2mth
import GSASIIstrIO as G2stIO
import GSASIIstrMath as G2stMth
import GSASIIobj as G2obj
import GSASIIfiles as G2fil
import GSASIIElem as G2elem
import GSASIIscriptable as G2sc
import atmdata
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)
DEBUG = True
#PhFrExtPOSig = None
def ReportProblems(result,Rvals,varyList):
'''Create a message based results from the refinement
'''
#report on SVD 0's and highly correlated variables
msg = ''
# process singular variables; all vars go to console, first 10 to
# dialog window
psing = result[2].get('psing',[])
if len(psing):
if msg: msg += '\n'
m = 'Error: {} Parameter(s) dropped:'.format(len(psing))
msg += m
G2fil.G2Print(m, mode='warn')
m = ''
for i,val in enumerate(psing):
if i == 0:
msg += '\n{}'.format(varyList[val])
m = ' {}'.format(varyList[val])
else:
if len(m) > 70:
G2fil.G2Print(m, mode='warn')
m = ' '
else:
m += ', '
m += '{}'.format(varyList[val])
if i == 10:
msg += ', {}... see console for full list'.format(varyList[val])
elif i > 10:
pass
else:
msg += ', {}'.format(varyList[val])
if m: G2fil.G2Print(m, mode='warn')
SVD0 = result[2].get('SVD0',0)
if SVD0 == 1:
msg += 'Warning: Soft (SVD) singularity in the Hessian'
elif SVD0 > 0:
msg += 'Warning: {} soft (SVD) Hessian singularities'.format(SVD0)
SVDsing = result[2].get('SVDsing',[])
if len(SVDsing):
if msg: msg += '\n'
m = 'SVD problem(s) likely from:'
msg += m
G2fil.G2Print(m, mode='warn')
m = ''
for i,val in enumerate(SVDsing):
if i == 0:
msg += '\n{}'.format(varyList[val])
m = ' {}'.format(varyList[val])
else:
if len(m) > 70:
G2fil.G2Print(m, mode='warn')
m = ' '
else:
m += ', '
m += '{}'.format(varyList[val])
if i == 10:
msg += ', {}... see console for full list'.format(varyList[val])
elif i > 10:
pass
else:
msg += ', {}'.format(varyList[val])
if m: G2fil.G2Print(m, mode='warn')
#report on highly correlated variables
Hcorr = result[2].get('Hcorr',[])
if len(Hcorr) > 0:
if msg: msg += '\n'
m = 'Note highly correlated parameters:'
G2fil.G2Print(m, mode='warn')
msg += m
elif SVD0 > 0:
if msg: msg += '\n'
m = 'Check covariance matrix for parameter correlation'
G2fil.G2Print(m, mode='warn')
msg += m
for i,(v1,v2,corr) in enumerate(Hcorr):
if corr > .95:
stars = '**'
else:
stars = ' '
m = ' {} {} and {} (@{:.2f}%)'.format(
stars,varyList[v1],varyList[v2],100.*corr)
G2fil.G2Print(m, mode='warn')
if i == 5:
msg += '\n' + m
msg += '\n ... check console for more'
elif i < 5:
msg += '\n' + m
if msg:
if 'msg' not in Rvals: Rvals['msg'] = ''
Rvals['msg'] += msg
def IgnoredLatticePrms(Phases):
ignore = []
copydict = {}
for p in Phases:
pfx = str(Phases[p]['pId']) + '::'
laue = Phases[p]['General']['SGData']['SGLaue']
axis = Phases[p]['General']['SGData']['SGUniq']
if laue in ['-1',]:
pass
elif laue in ['2/m',]:
if axis == 'a':
ignore += [pfx+'A4',pfx+'A5']
elif axis == 'b':
ignore += [pfx+'A3',pfx+'A5']
else:
ignore += [pfx+'A3',pfx+'A4']
elif laue in ['mmm',]:
ignore += [pfx+'A3',pfx+'A4',pfx+'A5']
elif laue in ['4/m','4/mmm']:
ignore += [pfx+'A1',pfx+'A3',pfx+'A4',pfx+'A5']
copydict[pfx+'A0':[pfx+'A1']]
elif laue in ['6/m','6/mmm','3m1', '31m', '3']:
ignore += [pfx+'A1',pfx+'A3',pfx+'A4',pfx+'A5']
copydict[pfx+'A0'] = [pfx+'A1',pfx+'A3']
elif laue in ['3R', '3mR']:
ignore += [pfx+'A1',pfx+'A2',pfx+'A4',pfx+'A5']
copydict[pfx+'A0'] = [pfx+'A1',pfx+'A2']
copydict[pfx+'A3'] = [pfx+'A4',pfx+'A5']
elif laue in ['m3m','m3']:
ignore += [pfx+'A1',pfx+'A2',pfx+'A3',pfx+'A4',pfx+'A5']
copydict[pfx+'A0'] = [pfx+'A1',pfx+'A2']
return ignore,copydict
def AllPrmDerivs(Controls,Histograms,Phases,restraintDict,rigidbodyDict,
parmDict,varyList,calcControls,pawleyLookup,symHold,dlg=None):
'''Computes the derivative of the fitting function (total Chi**2) with
respect to every parameter in the parameter dictionary (parmDict)
by applying shift below the parameter value as well as above.
:returns: a dict with the derivatives keyed by variable number.
Derivatives are a list with three values: evaluated over
v-d to v; v-d to v+d; v to v+d where v is the current value for the
variable and d is a small delta value chosen for that variable type.
'''
import re
rms = lambda y: np.sqrt(np.mean(y**2))
G2mv.Map2Dict(parmDict,varyList)
begin = time.time()
seqList = Controls.get('Seq Data',[])
hId = '*'
if seqList:
hId = str(Histograms[seqList[0]]['hId'])
# values = np.array(G2stMth.Dict2Values(parmDict, varyList))
# if np.any(np.isnan(values)):
# raise G2obj.G2Exception('ERROR - nan found in LS parameters - use Calculate/View LS parms to locate')
latIgnoreLst,latCopyDict = IgnoredLatticePrms(Phases)
HistoPhases = [Histograms,Phases,restraintDict,rigidbodyDict]
origDiffs = G2stMth.errRefine([],HistoPhases,parmDict,[],calcControls,pawleyLookup,None)
chiStart = rms(origDiffs)
origParms = copy.deepcopy(parmDict)
#print('after 1st calc',time.time()-begin)
derivCalcs = {}
if dlg: dlg.SetRange(len(origParms))
for i,prm in enumerate(origParms):
if dlg:
if not dlg.Update(i)[0]:
return None
parmDict = copy.deepcopy(origParms)
p,h,nam = prm.split(':')[:3]
if 'UVmat' in nam:
continue
if hId != '*' and h != '' and h != hId: continue
if (type(parmDict[prm]) is bool or type(parmDict[prm]) is str or
type(parmDict[prm]) is int): continue
if type(parmDict[prm]) is not float and type(parmDict[prm]) is not np.float64:
print('*** unexpected type for ',prm,parmDict[prm],type(parmDict[prm]))
continue
if prm in latIgnoreLst: continue # remove unvaried lattice params
if re.match(r'\d:\d:D[012][012]',prm): continue # don't need Dij terms
if nam in ['Vol','Gonio. radius']: continue
if nam.startswith('dA') and nam[2] in ['x','y','z']: continue
delta = max(abs(parmDict[prm])*0.0001,1e-6)
if nam in ['Shift','DisplaceX','DisplaceY',]:
delta = 0.1
elif nam.startswith('AUiso'):
delta = 1e-5
if nam[0] == 'A' and nam[1] in ['x','y','z']:
dprm = prm.replace('::A','::dA')
if dprm in symHold: continue # held by symmetry
delta = 1e-6
if nam in ['A0','A1','A2','A3','A4','A5'] and 'PWDR' not in Histograms.keys():
continue
else:
dprm = prm
#print('***',prm,type(parmDict[prm]))
#origVal = parmDict[dprm]
parmDict[dprm] -= delta
G2mv.Dict2Map(parmDict)
if dprm in latCopyDict: # apply contraints on lattice parameters
for i in latCopyDict:
parmDict[i] = parmDict[dprm]
#for i in parmDict:
# if origParms[i] != parmDict[i]: print('changed',i,origParms[i],parmDict[i])
chiLow = rms(G2stMth.errRefine([],HistoPhases,parmDict,[],calcControls,pawleyLookup,None))
parmDict[dprm] += 2*delta
G2mv.Dict2Map(parmDict)
if dprm in latCopyDict: # apply contraints on lattice parameters
for i in latCopyDict:
parmDict[i] = parmDict[dprm]
#for i in parmDict:
# if origParms[i] != parmDict[i]: print('changed',i,origParms[i],parmDict[i])
chiHigh = rms(G2stMth.errRefine([],HistoPhases,parmDict,[],calcControls,pawleyLookup,None))
#print('===>',prm,parmDict[dprm],delta)
#print(chiLow,chiStart,chiHigh)
#print((chiLow-chiStart)/delta,0.5*(chiLow-chiHigh)/delta,(chiStart-chiHigh)/delta)
derivCalcs[prm] = ((chiLow-chiStart)/delta,0.5*(chiLow-chiHigh)/delta,(chiStart-chiHigh)/delta)
print('derivative computation time',time.time()-begin)
return derivCalcs
def RefineCore(Controls,Histograms,Phases,restraintDict,rigidbodyDict,parmDict,varyList,
calcControls,pawleyLookup,ifSeq,printFile,dlg,refPlotUpdate=None):
'''Core optimization routines, shared between SeqRefine and Refine
:returns: 5-tuple of ifOk (bool), Rvals (dict), result, covMatrix, sig
'''
#patch (added Oct 2020) convert variable names for parm limits to G2VarObj
G2sc.patchControls(Controls)
# end patch
# print 'current',varyList
# for item in parmDict: print item,parmDict[item] ######### show dict just before refinement
ifPrint = True
if ifSeq:
ifPrint = False
Rvals = {}
chisq0 = None
Lastshft = None
while True:
G2mv.Map2Dict(parmDict,varyList)
begin = time.time()
values = np.array(G2stMth.Dict2Values(parmDict, varyList))
if np.any(np.isnan(values)):
raise G2obj.G2Exception('ERROR - nan found in LS parameters - use Calculate/View LS parms to locate')
# test code to compute GOF and save for external repeat
#args = ([Histograms,Phases,restraintDict,rigidbodyDict],parmDict,varyList,calcControls,pawleyLookup,dlg)
#print '*** before fit chi**2',np.sum(G2stMth.errRefine(values,*args)**2)
#fl = open('beforeFit.cpickle','wb')
#cPickle.dump(values,fl,1)
#cPickle.dump(args[:-1],fl,1)
#fl.close()
Ftol = Controls['min dM/M']
Xtol = Controls['SVDtol']
Factor = Controls['shift factor']
if 'Jacobian' in Controls['deriv type']:
maxCyc = Controls.get('max cyc',1)
result = so.leastsq(G2stMth.errRefine,values,Dfun=G2stMth.dervRefine,full_output=True,
ftol=Ftol,col_deriv=True,factor=Factor,
args=([Histograms,Phases,restraintDict,rigidbodyDict],parmDict,varyList,calcControls,pawleyLookup,dlg))
ncyc = int(result[2]['nfev']/2)
result[2]['num cyc'] = ncyc
if refPlotUpdate is not None: refPlotUpdate(Histograms) # update plot after completion
elif 'analytic Hessian' in Controls['deriv type']:
Lamda = Controls.get('Marquardt',-3)
maxCyc = Controls['max cyc']
result = G2mth.HessianLSQ(G2stMth.errRefine,values,Hess=G2stMth.HessRefine,ftol=Ftol,xtol=Xtol,maxcyc=maxCyc,Print=ifPrint,lamda=Lamda,
args=([Histograms,Phases,restraintDict,rigidbodyDict],parmDict,varyList,calcControls,pawleyLookup,dlg),
refPlotUpdate=refPlotUpdate)
ncyc = result[2]['num cyc']+1
Rvals['lamMax'] = result[2]['lamMax']
if 'Ouch#4' in result[2]:
Rvals['Aborted'] = True
if 'msg' in result[2]:
Rvals['msg'] = result[2]['msg']
Controls['Marquardt'] = -3 #reset to default
if 'chisq0' in result[2] and chisq0 is None:
chisq0 = result[2]['chisq0']
elif 'Hessian SVD' in Controls['deriv type']:
maxCyc = Controls['max cyc']
result = G2mth.HessianSVD(G2stMth.errRefine,values,Hess=G2stMth.HessRefine,ftol=Ftol,xtol=Xtol,maxcyc=maxCyc,Print=ifPrint,
args=([Histograms,Phases,restraintDict,rigidbodyDict],parmDict,varyList,calcControls,pawleyLookup,dlg),
refPlotUpdate=refPlotUpdate)
if result[1] is None:
IfOK = False
covMatrix = []
sig = len(varyList)*[None,]
break
ncyc = result[2]['num cyc']+1
if 'chisq0' in result[2] and chisq0 is None:
chisq0 = result[2]['chisq0']
else: #'numeric'
maxCyc = Controls.get('max cyc',1)
result = so.leastsq(G2stMth.errRefine,values,full_output=True,ftol=Ftol,epsfcn=1.e-8,factor=Factor,
args=([Histograms,Phases,restraintDict,rigidbodyDict],parmDict,varyList,calcControls,pawleyLookup,dlg))
ncyc = 1
result[2]['num cyc'] = ncyc
if len(varyList):
ncyc = int(result[2]['nfev']/len(varyList))
if refPlotUpdate is not None: refPlotUpdate(Histograms) # update plot
#table = dict(zip(varyList,zip(values,result[0],(result[0]-values))))
#for item in table: print(item,table[item]) #useful debug - are things shifting?
runtime = time.time()-begin
Rvals['SVD0'] = result[2].get('SVD0',0)
Rvals['converged'] = result[2].get('Converged')
Rvals['DelChi2'] = result[2].get('DelChi2',-1.)
Rvals['chisq'] = np.sum(result[2]['fvec']**2)
G2stMth.Values2Dict(parmDict, varyList, result[0])
G2mv.Dict2Map(parmDict)
Rvals['Nobs'] = Histograms['Nobs']
Rvals['Nvars'] = len(varyList)
Rvals['RestraintSum'] = Histograms.get('RestraintSum',0.)
Rvals['RestraintTerms'] = Histograms.get('RestraintTerms',0)
Rvals['Rwp'] = np.sqrt(Rvals['chisq']/Histograms['sumwYo'])*100. #to %
Rvals['GOF'] = np.sqrt(Rvals['chisq']/(Histograms['Nobs']+Rvals['RestraintTerms']-len(varyList)))
printFile.write(' Number of function calls: %d No. of observations: %d No. of parameters: %d User rejected: %d Sp. gp. extinct: %d\n'% \
(result[2]['nfev'],Histograms['Nobs'],len(varyList),Histograms['Nrej'],Histograms['Next']))
if ncyc:
printFile.write(' Refinement time = %8.3fs, %8.3fs/cycle, for %d cycles\n'%(runtime,runtime/ncyc,ncyc))
printFile.write(' wR = %7.2f%%, chi**2 = %12.6g, GOF = %6.2f\n'%(Rvals['Rwp'],Rvals['chisq'],Rvals['GOF']))
sig = len(varyList)*[None,]
if 'None' in str(type(result[1])) and ifSeq: #this bails out of a sequential refinement on singular matrix
IfOK = False
covMatrix = []
G2fil.G2Print ('Warning: **** Refinement failed - singular matrix ****')
if 'Hessian' in Controls['deriv type']:
num = len(varyList)-1
# BHT -- I am not sure if this works correctly:
for i,val in enumerate(np.flipud(result[2]['psing'])):
if val:
G2fil.G2Print('Bad parameter: '+varyList[num-i],mode='warn')
else:
Ipvt = result[2]['ipvt']
for i,ipvt in enumerate(Ipvt):
if not np.sum(result[2]['fjac'],axis=1)[i]:
G2fil.G2Print('Bad parameter: '+varyList[ipvt-1],mode='warn')
break
IfOK = True
if not len(varyList) or not maxCyc:
covMatrix = []
break
try:
covMatrix = result[1]*Rvals['GOF']**2
sig = np.sqrt(np.diag(covMatrix))
Lastshft = result[0]-values #NOT last shift since values is starting set before current refinement
#table = dict(zip(varyList,zip(values,result[0],Lastshft,Lastshft/sig)))
#for item in table: print(item,table[item]) #useful debug
Rvals['Max shft/sig'] = np.max(np.nan_to_num(Lastshft/sig))
if np.any(np.isnan(sig)) or not sig.shape:
G2fil.G2Print ('*** Least squares aborted - some invalid esds possible ***',mode='error')
else:
print('Maximum shift/esd = {:.3f} for all cycles'.format(Rvals['Max shft/sig']))
# report on refinement issues. Result in Rvals['msg']
ReportProblems(result,Rvals,varyList)
break #refinement succeeded - finish up!
except TypeError:
# if we get here, no result[1] (covar matrix) was returned or other calc error: refinement failed
IfOK = False
if 'Hessian' in Controls['deriv type']:
SVD0 = result[2].get('SVD0')
if SVD0 == -1:
G2fil.G2Print ('**** Refinement failed - singular matrix ****',mode='error')
elif SVD0 == -2:
G2fil.G2Print ('**** Refinement failed - other problem ****',mode='error')
elif SVD0 > 0:
G2fil.G2Print ('**** Refinement failed with {} SVD singularities ****'.format(SVD0),mode='error')
else:
G2fil.G2Print ('**** Refinement failed ****',mode='error')
if result[1] is None:
IfOK = False
covMatrix = []
sig = len(varyList)*[None,]
# report on highly correlated variables
ReportProblems(result,Rvals,varyList)
# process singular variables
if dlg: break # refining interactively
else:
G2fil.G2Print ('**** Refinement failed - singular matrix ****',mode='error')
Ipvt = result[2]['ipvt']
for i,ipvt in enumerate(Ipvt):
if not np.sum(result[2]['fjac'],axis=1)[i]:
G2fil.G2Print ('Removing parameter: '+varyList[ipvt-1])
del(varyList[ipvt-1])
break
if IfOK:
if CheckLeBail(Phases): # only needed for LeBail extraction
G2stMth.errRefine([],[Histograms,Phases,restraintDict,rigidbodyDict],
parmDict,[],calcControls,pawleyLookup,dlg)
G2stMth.GetFobsSq(Histograms,Phases,parmDict,calcControls)
if chisq0 is not None:
Rvals['GOF0'] = np.sqrt(chisq0/(Histograms['Nobs']-len(varyList)))
return IfOK,Rvals,result,covMatrix,sig,Lastshft
def Refine(GPXfile,dlg=None,makeBack=True,refPlotUpdate=None,newLeBail=False,allDerivs=False):
'''Global refinement -- refines to minimize against all histograms.
This can be called in one of three ways, from :meth:`GSASIIdataGUI.GSASII.OnRefine` in an
interactive refinement, where dlg will be a wx.ProgressDialog, or non-interactively from
:meth:`GSASIIscriptable.G2Project.refine` or from :func:`do_refine`, where dlg will be None.
'''
import GSASIImpsubs as G2mp
G2mp.InitMP()
import pytexture as ptx
ptx.pyqlmninit() #initialize fortran arrays for spherical harmonics
if allDerivs:
printFile = open(ospath.splitext(GPXfile)[0]+'.junk','w')
else:
printFile = open(ospath.splitext(GPXfile)[0]+'.lst','w')
G2stIO.ShowBanner(printFile)
varyList = []
parmDict = {}
G2mv.InitVars()
Controls = G2stIO.GetControls(GPXfile)
Controls['newLeBail'] = newLeBail
G2stIO.ShowControls(Controls,printFile)
calcControls = {}
calcControls.update(Controls)
constrDict,fixedList = G2stIO.ReadConstraints(GPXfile)
restraintDict = G2stIO.GetRestraints(GPXfile)
Histograms,Phases = G2stIO.GetUsedHistogramsAndPhases(GPXfile)
if not Phases:
G2fil.G2Print (' *** ERROR - you have no phases to refine! ***')
G2fil.G2Print (' *** Refine aborted ***')
return False,{'msg':'No phases'}
if not Histograms:
G2fil.G2Print (' *** ERROR - you have no data to refine with! ***')
G2fil.G2Print (' *** Refine aborted ***')
return False,{'msg':'No data'}
rigidbodyDict = G2stIO.GetRigidBodies(GPXfile)
rbIds = rigidbodyDict.get('RBIds',{'Vector':[],'Residue':[]})
rbVary,rbDict = G2stIO.GetRigidBodyModels(rigidbodyDict,pFile=printFile)
symHold = None
if allDerivs: #============= develop partial derivative map
symHold = []
(Natoms,atomIndx,phaseVary,phaseDict,pawleyLookup,FFtables,EFtables,ORBtables,BLtables,MFtables,
maxSSwave) = G2stIO.GetPhaseData(Phases,restraintDict,rbIds,pFile=printFile,symHold=symHold)
calcControls['atomIndx'] = atomIndx
calcControls['Natoms'] = Natoms
calcControls['FFtables'] = FFtables
calcControls['EFtables'] = EFtables
calcControls['ORBtables'] = ORBtables
calcControls['BLtables'] = BLtables
calcControls['MFtables'] = MFtables
calcControls['maxSSwave'] = maxSSwave
hapVary,hapDict,controlDict = G2stIO.GetHistogramPhaseData(Phases,Histograms,Controls=calcControls,pFile=printFile)
TwConstr,TwFixed = G2stIO.makeTwinFrConstr(Phases,Histograms,hapVary)
constrDict += TwConstr
fixedList += TwFixed
calcControls.update(controlDict)
histVary,histDict,controlDict = G2stIO.GetHistogramData(Histograms,pFile=printFile)
calcControls.update(controlDict)
varyList = rbVary+phaseVary+hapVary+histVary
parmDict.update(rbDict)
parmDict.update(phaseDict)
parmDict.update(hapDict)
parmDict.update(histDict)
G2stIO.GetFprime(calcControls,Histograms)
# do constraint processing
varyListStart = tuple(varyList) # save the original varyList before dependent vars are removed
msg = G2mv.EvaluateMultipliers(constrDict,parmDict)
if allDerivs: #============= develop partial derivative map
varyListStart = varyList
varyList = None
if msg:
return False,{'msg':'Unable to interpret multiplier(s): '+msg}
try:
errmsg,warnmsg,groups,parmlist = G2mv.GenerateConstraints(varyList,constrDict,fixedList,parmDict)
G2mv.normParms(parmDict)
G2mv.Map2Dict(parmDict,varyList) # changes varyList
except G2mv.ConstraintException:
G2fil.G2Print (' *** ERROR - your constraints are internally inconsistent ***')
return False,{'msg':' Constraint error'}
# remove frozen vars from refinement
if 'parmFrozen' not in Controls:
Controls['parmFrozen'] = {}
if 'FrozenList' not in Controls['parmFrozen']:
Controls['parmFrozen']['FrozenList'] = []
if varyList is not None:
parmFrozenList = Controls['parmFrozen']['FrozenList']
frozenList = [i for i in varyList if i in parmFrozenList]
if len(frozenList) != 0:
varyList = [i for i in varyList if i not in parmFrozenList]
G2fil.G2Print(
'Frozen refined variables (due to exceeding limits)\n\t:{}'
.format(frozenList))
ifSeq = False
printFile.write('\n Refinement results:\n')
printFile.write(135*'-'+'\n')
Rvals = {}
G2mv.Dict2Map(parmDict) # impose constraints initially
if allDerivs: #============= develop partial derivative map
derivDict = AllPrmDerivs(Controls, Histograms, Phases, restraintDict,
rigidbodyDict, parmDict, varyList, calcControls,pawleyLookup,symHold,dlg)
printFile.close() #closes the .junk file
return derivDict,varyListStart
try:
covData = {}
IfOK,Rvals,result,covMatrix,sig,Lastshft = RefineCore(Controls,Histograms,Phases,restraintDict,
rigidbodyDict,parmDict,varyList,calcControls,pawleyLookup,ifSeq,printFile,dlg,
refPlotUpdate=refPlotUpdate)
if IfOK:
if len(covMatrix): #empty for zero cycle refinement
sigDict = dict(zip(varyList,sig))
newCellDict = G2stMth.GetNewCellParms(parmDict,varyList)
newAtomDict = G2stMth.ApplyXYZshifts(parmDict,varyList)
covData = {'variables':result[0],'varyList':varyList,'sig':sig,'Rvals':Rvals,
'varyListStart':varyListStart,'Lastshft':Lastshft,
'covMatrix':covMatrix,'title':GPXfile,'newAtomDict':newAtomDict,
'newCellDict':newCellDict,'freshCOV':True}
# add indirectly computed uncertainties into the esd dict
sigDict.update(G2mv.ComputeDepESD(covMatrix,varyList))
G2stIO.PrintIndependentVars(parmDict,varyList,sigDict,pFile=printFile)
G2stMth.ApplyRBModels(parmDict,Phases,rigidbodyDict,True)
G2stIO.SetRigidBodyModels(parmDict,sigDict,rigidbodyDict,printFile)
G2stIO.SetPhaseData(parmDict,sigDict,Phases,rbIds,covData,restraintDict,printFile)
G2stIO.SetISOmodes(parmDict,sigDict,Phases,printFile)
G2stIO.SetHistogramPhaseData(parmDict,sigDict,Phases,Histograms,calcControls,
pFile=printFile,covMatrix=covMatrix,varyList=varyList)
G2stIO.SetHistogramData(parmDict,sigDict,Histograms,calcControls,pFile=printFile)
# check for variables outside their allowed range, reset and freeze them
frozen = dropOOBvars(varyList,parmDict,sigDict,Controls,parmFrozenList)
# covData['depSig'] = G2stIO.PhFrExtPOSig # created in G2stIO.SetHistogramData, no longer used?
covData['depSigDict'] = {i:(parmDict[i],sigDict[i]) for i in parmDict if i in sigDict}
if len(frozen):
if 'msg' in Rvals:
Rvals['msg'] += '\n'
else:
Rvals['msg'] = ''
msg = ('Warning: {} variable(s) refined outside limits and were frozen ({} total frozen)'
.format(len(frozen),len(parmFrozenList))
)
G2fil.G2Print(msg)
Rvals['msg'] += msg
elif len(parmFrozenList):
if 'msg' in Rvals:
Rvals['msg'] += '\n'
else:
Rvals['msg'] = ''
msg = ('Note: a total of {} variable(s) are frozen due to refining outside limits'
.format(len(parmFrozenList))
)
G2fil.G2Print('Note: ',msg)
Rvals['msg'] += msg
G2stIO.SetUsedHistogramsAndPhases(GPXfile,Histograms,Phases,rigidbodyDict,covData,parmFrozenList,makeBack)
printFile.close()
G2fil.G2Print (' Refinement results are in file: '+ospath.splitext(GPXfile)[0]+'.lst')
G2fil.G2Print (' ***** Refinement successful *****')
else:
G2fil.G2Print ('****ERROR - Refinement failed',mode='error')
if 'msg' in Rvals:
G2fil.G2Print ('Note refinement problem:',mode='warn')
G2fil.G2Print (Rvals['msg'],mode='warn')
raise G2obj.G2Exception('**** ERROR: Refinement failed ****')
except G2obj.G2RefineCancel as Msg:
printFile.close()
G2fil.G2Print (' ***** Refinement stopped *****')
if not hasattr(Msg,'msg'): Msg.msg = str(Msg)
if 'msg' in Rvals:
Rvals['msg'] += '\n'
Rvals['msg'] += Msg.msg
if not dlg:
G2fil.G2Print ('Note refinement problem:',mode='warn')
G2fil.G2Print (Rvals['msg'],mode='warn')
else:
Rvals['msg'] = Msg.msg
return False,Rvals
# except G2obj.G2Exception as Msg: # cell metric error, others?
except Exception as Msg: # cell metric error, others?
if GSASIIpath.GetConfigValue('debug'):
import traceback
print(traceback.format_exc())
if not hasattr(Msg,'msg'): Msg.msg = str(Msg)
printFile.close()
G2fil.G2Print (' ***** Refinement error *****')
if 'msg' in Rvals:
Rvals['msg'] += '\n\n'
Rvals['msg'] += Msg.msg
if not dlg:
G2fil.G2Print ('Note refinement problem:',mode='warn')
G2fil.G2Print (Rvals['msg'],mode='warn')
else:
Rvals['msg'] = Msg.msg
return False,Rvals
#for testing purposes, create a file for testderiv
if GSASIIpath.GetConfigValue('debug'): # and IfOK:
#needs: values,HistoPhases,parmDict,varylist,calcControls,pawleyLookup
fl = open(ospath.splitext(GPXfile)[0]+'.testDeriv','wb')
cPickle.dump(result[0],fl,1)
cPickle.dump([Histograms,Phases,restraintDict,rigidbodyDict],fl,1)
cPickle.dump([constrDict,fixedList,G2mv.GetDependentVars()],fl,1)
cPickle.dump(parmDict,fl,1)
cPickle.dump(varyList,fl,1)
cPickle.dump(calcControls,fl,1)
cPickle.dump(pawleyLookup,fl,1)
fl.close()
if dlg:
return True,Rvals
elif 'msg' in Rvals:
G2fil.G2Print ('Reported from refinement:',mode='warn')
G2fil.G2Print (Rvals['msg'],mode='warn')
def CheckLeBail(Phases):
'''Check if there is a LeBail extraction in any histogram
:returns: True if there is at least one LeBail flag turned on, False otherwise
'''
for key in Phases:
phase = Phases[key]
for h in phase['Histograms']:
#phase['Histograms'][h]
if not phase['Histograms'][h]['Use']: continue
try:
if phase['Histograms'][h]['LeBail']:
return True
except KeyError: #HKLF & old gpx files
pass
return False
def DoNoFit(GPXfile,key):
'''Compute the diffraction pattern with no refinement of parameters.
TODO: At present, this will compute intensities all diffraction patterns
in the project, but this likely can be made faster by dropping
all the histograms except key from Histograms.
:param str GPXfile: G2 .gpx file name
:param str key: name of histogram to be computed
:returns: the computed diffraction pattern for the selected histogram
'''
import GSASIImpsubs as G2mp
G2mp.InitMP()
import pytexture as ptx
ptx.pyqlmninit() #initialize fortran arrays for spherical harmonics
parmDict = {}
Controls = G2stIO.GetControls(GPXfile)
calcControls = {}
calcControls.update(Controls)
constrDict,fixedList = G2stIO.ReadConstraints(GPXfile)
restraintDict = {}
Histograms,Phases = G2stIO.GetUsedHistogramsAndPhases(GPXfile)
if not Phases:
G2fil.G2Print (' *** ERROR - you have no phases to refine! ***')
return False,{'msg':'No phases'}
if not Histograms:
G2fil.G2Print (' *** ERROR - you have no data to refine with! ***')
return False,{'msg':'No data'}
if key not in Histograms:
print(f"Error: no histogram by name {key}")
return
#TODO: Histograms = {key:Histograms[key]}
rigidbodyDict = G2stIO.GetRigidBodies(GPXfile)
rbIds = rigidbodyDict.get('RBIds',{'Vector':[],'Residue':[]})
rbVary,rbDict = G2stIO.GetRigidBodyModels(rigidbodyDict,Print=False)
(Natoms,atomIndx,phaseVary,phaseDict,pawleyLookup,FFtables,EFtables,ORBtables,BLtables,MFtables,
maxSSwave) = G2stIO.GetPhaseData(Phases,restraintDict,rbIds,Print=False)
calcControls['atomIndx'] = atomIndx
calcControls['Natoms'] = Natoms
calcControls['FFtables'] = FFtables
calcControls['EFtables'] = EFtables
calcControls['ORBtables'] = ORBtables
calcControls['BLtables'] = BLtables
calcControls['MFtables'] = MFtables
calcControls['maxSSwave'] = maxSSwave
hapVary,hapDict,controlDict = G2stIO.GetHistogramPhaseData(Phases,Histograms,Controls=calcControls,Print=False)
calcControls.update(controlDict)
histVary,histDict,controlDict = G2stIO.GetHistogramData(Histograms,Print=False)
calcControls.update(controlDict)
parmDict.update(rbDict)
parmDict.update(phaseDict)
parmDict.update(hapDict)
parmDict.update(histDict)
G2stIO.GetFprime(calcControls,Histograms)
M = G2stMth.errRefine([],[Histograms,Phases,restraintDict,rigidbodyDict],parmDict,[],calcControls,pawleyLookup,None)
return Histograms[key]['Data'][3]
def DoLeBail(GPXfile,dlg=None,cycles=10,refPlotUpdate=None,seqList=None):
'''Fit LeBail intensities without changes to any other refined parameters.
This is a stripped-down version of :func:`Refine` that does not perform
any refinement cycles
:param str GPXfile: G2 .gpx file name
:param wx.ProgressDialog dlg: optional progress window to update.
Default is None, which means no calls are made to this.
:param int cycles: Number of LeBail cycles to perform
:param function refPlotUpdate: Optional routine used to plot results.
Default is None, which means no calls are made to this.
:param list seqList: List of histograms to be processed. Default
is None which means that all used histograms in .gpx file are processed.
'''
import GSASIImpsubs as G2mp
G2mp.InitMP()
import pytexture as ptx
ptx.pyqlmninit() #initialize fortran arrays for spherical harmonics
#varyList = []
parmDict = {}
Controls = G2stIO.GetControls(GPXfile)
calcControls = {}
calcControls.update(Controls)
constrDict,fixedList = G2stIO.ReadConstraints(GPXfile)
restraintDict = {}
Histograms_All,Phases = G2stIO.GetUsedHistogramsAndPhases(GPXfile)
if seqList:
Histograms = {i:Histograms_All[i] for i in seqList}
else:
Histograms = Histograms_All
if not Phases:
G2fil.G2Print (' *** ERROR - you have no phases to refine! ***')
return False,{'msg':'No phases'}
if not Histograms:
G2fil.G2Print (' *** ERROR - you have no data to refine with! ***')
return False,{'msg':'No data'}
if not CheckLeBail(Phases):
msg = 'Warning: There are no histograms with LeBail extraction enabled'
G2fil.G2Print ('*** '+msg+' ***')
return False,{'msg': msg}
rigidbodyDict = G2stIO.GetRigidBodies(GPXfile)
rbIds = rigidbodyDict.get('RBIds',{'Vector':[],'Residue':[]})
rbVary,rbDict = G2stIO.GetRigidBodyModels(rigidbodyDict,Print=False)
(Natoms,atomIndx,phaseVary,phaseDict,pawleyLookup,FFtables,EFtables,ORBtables,BLtables,MFtables,
maxSSwave) = G2stIO.GetPhaseData(Phases,restraintDict,rbIds,Print=False)
calcControls['atomIndx'] = atomIndx
calcControls['Natoms'] = Natoms
calcControls['FFtables'] = FFtables
calcControls['EFtables'] = EFtables
calcControls['ORBtables'] = ORBtables
calcControls['BLtables'] = BLtables
calcControls['MFtables'] = MFtables
calcControls['maxSSwave'] = maxSSwave
hapVary,hapDict,controlDict = G2stIO.GetHistogramPhaseData(Phases,Histograms,Controls=calcControls,Print=False)
calcControls.update(controlDict)
histVary,histDict,controlDict = G2stIO.GetHistogramData(Histograms,Print=False)
calcControls.update(controlDict)
parmDict.update(rbDict)
parmDict.update(phaseDict)
parmDict.update(hapDict)
parmDict.update(histDict)
G2stIO.GetFprime(calcControls,Histograms)
try:
for i in range(cycles):
M = G2stMth.errRefine([],[Histograms,Phases,restraintDict,rigidbodyDict],parmDict,[],calcControls,pawleyLookup,dlg)
G2stMth.GetFobsSq(Histograms,Phases,parmDict,calcControls)
if refPlotUpdate is not None: refPlotUpdate(Histograms,i)
Rvals = {}
Rvals['chisq'] = np.sum(M**2)
Rvals['Nobs'] = Histograms['Nobs']
Rvals['Rwp'] = np.sqrt(Rvals['chisq']/Histograms['sumwYo'])*100. #to %
Rvals['GOF'] = np.sqrt(Rvals['chisq']/(Histograms['Nobs'])) # no variables
covData = {'variables':0,'varyList':[],'sig':[],'Rvals':Rvals,'varyListStart':[],
'covMatrix':None,'title':GPXfile,'freshCOV':True} #np.zeros([0,0])?
# ?? 'newAtomDict':newAtomDict,'newCellDict':newCellDict,
G2stIO.SetUsedHistogramsAndPhases(GPXfile,Histograms,Phases,rigidbodyDict,covData,[],True)
G2fil.G2Print (' ***** LeBail fit completed *****')
return True,Rvals
except Exception as Msg:
G2fil.G2Print (' ***** LeBail fit error *****')
if not hasattr(Msg,'msg'): Msg.msg = str(Msg)
if GSASIIpath.GetConfigValue('debug'):
import traceback
print(traceback.format_exc())
return False,{'msg':Msg.msg}
def phaseCheck(phaseVary,Phases,histogram):
'''
Removes unused parameters from phase varylist if phase not in histogram
for seq refinement removes vars in "Fix FXU" and "FixedSeqVars" here
'''
NewVary = []
for phase in Phases:
if histogram not in Phases[phase]['Histograms']: continue
if Phases[phase]['Histograms'][histogram]['Use']:
pId = Phases[phase]['pId']
newVary = [item for item in phaseVary if item.split(':')[0] == str(pId)]
FixVals = Phases[phase]['Histograms'][histogram].get('Fix FXU',' ')
if 'F' in FixVals:
newVary = [item for item in newVary if not 'Afrac' in item]
if 'X' in FixVals:
newVary = [item for item in newVary if not 'dA' in item]
if 'U' in FixVals:
newVary = [item for item in newVary if not 'AU' in item]
if 'M' in FixVals:
newVary = [item for item in newVary if not 'AM' in item]
removeVars = Phases[phase]['Histograms'][histogram].get('FixedSeqVars',[])
newVary = [item for item in newVary if item not in removeVars]
NewVary += newVary
return NewVary
def SeqRefine(GPXfile,dlg,refPlotUpdate=None):
'''Perform a sequential refinement -- cycles through all selected histgrams,
one at a time
'''
import GSASIImpsubs as G2mp
G2mp.InitMP()
import pytexture as ptx
ptx.pyqlmninit() #initialize fortran arrays for spherical harmonics
msgs = {}
printFile = open(ospath.splitext(GPXfile)[0]+'.lst','w')
G2fil.G2Print ('Starting Sequential Refinement')
G2stIO.ShowBanner(printFile)
Controls = G2stIO.GetControls(GPXfile)
preFrozenCount = 0
for h in Controls['parmFrozen']:
if h == 'FrozenList':
continue
preFrozenCount += len(Controls['parmFrozen'][h])
G2stIO.ShowControls(Controls,printFile,SeqRef=True,preFrozenCount=preFrozenCount)
restraintDict = G2stIO.GetRestraints(GPXfile)
Histograms,Phases = G2stIO.GetUsedHistogramsAndPhases(GPXfile)
if not Phases:
G2fil.G2Print (' *** ERROR - you have no phases to refine! ***')
G2fil.G2Print (' *** Refine aborted ***')
return False,'No phases'
if not Histograms:
G2fil.G2Print (' *** ERROR - you have no data to refine with! ***')
G2fil.G2Print (' *** Refine aborted ***')
return False,'No data'
rigidbodyDict = G2stIO.GetRigidBodies(GPXfile)
rbIds = rigidbodyDict.get('RBIds',{'Vector':[],'Residue':[]})
rbVary,rbDict = G2stIO.GetRigidBodyModels(rigidbodyDict,pFile=printFile)
G2mv.InitVars()
(Natoms,atomIndx,phaseVary,phaseDict,pawleyLookup,FFtables,EFtables,BLtables,ORBtables,MFtables,maxSSwave) = \
G2stIO.GetPhaseData(Phases,restraintDict,rbIds,Print=False,pFile=printFile,seqHistName='All')
for item in phaseVary:
if '::A0' in item:
G2fil.G2Print ('**** WARNING - lattice parameters should not be refined in a sequential refinement ****')
G2fil.G2Print ('**** instead use the Dij parameters for each powder histogram ****')
return False,'Lattice parameter refinement error - see console message'
if '::C(' in item:
G2fil.G2Print ('**** WARNING - phase texture parameters should not be refined in a sequential refinement ****')
G2fil.G2Print ('**** instead use the C(L,N) parameters for each powder histogram ****')
return False,'Phase texture refinement error - see console message'
if 'Seq Data' in Controls:
histNames = Controls['Seq Data']
else: # patch from before Controls['Seq Data'] was implemented?
histNames = G2stIO.GetHistogramNames(GPXfile,['PWDR',])
if Controls.get('Reverse Seq'):
histNames.reverse()
SeqResult = G2stIO.GetSeqResult(GPXfile)
# SeqResult = {'SeqPseudoVars':{},'SeqParFitEqList':[]}
Histo = {}
NewparmDict = {}
G2stIO.SetupSeqSavePhases(GPXfile)
msgs['steepestNum'] = 0
msgs['maxshift/sigma'] = []
lasthist = ''
for ihst,histogram in enumerate(histNames):
if GSASIIpath.GetConfigValue('Show_timing'): t1 = time.time()
G2fil.G2Print('\nRefining with '+str(histogram))
G2mv.InitVars()
(Natoms,atomIndx,phaseVary,phaseDict,pawleyLookup,FFtables,EFtables,ORBtables,BLtables,MFtables,maxSSwave) = \
G2stIO.GetPhaseData(Phases,restraintDict,rbIds,Print=False,pFile=printFile,seqHistName=histogram)
ifPrint = False
if dlg:
dlg.SetTitle('Residual for histogram '+str(ihst))
calcControls = {}
calcControls['atomIndx'] = atomIndx
calcControls['Natoms'] = Natoms
calcControls['FFtables'] = FFtables
calcControls['EFtables'] = EFtables
calcControls['ORBtables'] = ORBtables
calcControls['BLtables'] = BLtables
calcControls['MFtables'] = MFtables
calcControls['maxSSwave'] = maxSSwave
if histogram not in Histograms:
G2fil.G2Print("Error: not found!")
raise G2obj.G2Exception("refining with invalid histogram {}".format(histogram))
hId = Histograms[histogram]['hId']
redphaseVary = phaseCheck(phaseVary,Phases,histogram)
Histo = {histogram:Histograms[histogram],}
hapVary,hapDict,controlDict = G2stIO.GetHistogramPhaseData(Phases,Histo,Controls=calcControls,Print=False)
calcControls.update(controlDict)
histVary,histDict,controlDict = G2stIO.GetHistogramData(Histo,False)
calcControls.update(controlDict)
varyList = rbVary+redphaseVary+hapVary+histVary
# if not ihst:
# save the initial vary list, but without histogram numbers on parameters
saveVaryList = varyList[:]
for i,item in enumerate(saveVaryList):
items = item.split(':')
if items[1]:
items[1] = ''
item = ':'.join(items)
saveVaryList[i] = item
if not ihst:
SeqResult['varyList'] = saveVaryList
else:
SeqResult['varyList'] = list(set(SeqResult['varyList']+saveVaryList))
parmDict = {}
parmDict.update(rbDict)
parmDict.update(phaseDict)
parmDict.update(hapDict)
parmDict.update(histDict)
if Controls['Copy2Next']: # update with parms from last histogram
#parmDict.update(NewparmDict) # don't use in case extra entries would cause a problem
for parm in NewparmDict:
if parm in parmDict:
parmDict[parm] = NewparmDict[parm]
for phase in Phases:
if Phases[phase]['Histograms'][histogram].get('LeBail',False) and lasthist:
oldFsqs = Histograms[lasthist]['Reflection Lists'][phase]['RefList'].T[8:10] #assume no superlattice!
newRefs = Histograms[histogram]['Reflection Lists'][phase]['RefList']
if len(newRefs) == len(oldFsqs.T):
newRefs.T[8:10] = copy.copy(oldFsqs)
# for i,ref in enumerate(newRefs):
# ref[8:10] = oldFsqs.T[i]
else:
print('ERROR - mismatch in reflection list length bewteen %s and %s; no copy done'%(lasthist,histogram))
####TBD: if LeBail copy reflections here?
elif histogram in SeqResult: # update phase from last seq ref
NewparmDict = SeqResult[histogram].get('parmDict',{})
for parm in NewparmDict:
if '::' in parm and parm in parmDict:
parmDict[parm] = NewparmDict[parm]
G2stIO.GetFprime(calcControls,Histo)
# do constraint processing (again, if called from GSASIIdataGUI.GSASII.OnSeqRefine)
constrDict,fixedList = G2stIO.ReadConstraints(GPXfile,seqHist=hId)
varyListStart = tuple(varyList) # save the original varyList before dependent vars are removed
msg = G2mv.EvaluateMultipliers(constrDict,phaseDict,hapDict,histDict)
if msg:
return False,'Unable to interpret multiplier(s): '+msg
try:
errmsg,warnmsg,groups,parmlist = G2mv.GenerateConstraints(varyList,constrDict,fixedList,parmDict,
seqHistNum=hId,raiseException=True)
constraintInfo = (groups,parmlist,constrDict,fixedList,ihst)
G2mv.normParms(parmDict)
G2mv.Map2Dict(parmDict,varyList) # changes varyList
except G2mv.ConstraintException:
G2fil.G2Print (' *** ERROR - your constraints are internally inconsistent for histogram {}***'.format(hId))
return False,' Constraint error'
if not ihst:
# first histogram to refine against
firstVaryList = []
for item in varyList:
items = item.split(':')
if items[1]:
items[1] = ''
item = ':'.join(items)
firstVaryList.append(item)
newVaryList = firstVaryList
else:
newVaryList = []
for item in varyList:
items = item.split(':')
if items[1]:
items[1] = ''
item = ':'.join(items)
newVaryList.append(item)
if newVaryList != firstVaryList and Controls['Copy2Next']:
# variable lists are expected to match between sequential refinements when Copy2Next is on
#print '**** ERROR - variable list for this histogram does not match previous'
#print ' Copy of variables is not possible'