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
/
GSASIImath.py
6109 lines (5467 loc) · 233 KB
/
GSASIImath.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 -*-
#GSASIImath - major mathematics routines
########### SVN repository information ###################
# $Date: 2024-02-05 15:49:09 -0600 (Mon, 05 Feb 2024) $
# $Author: toby $
# $Revision: 5722 $
# $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/GSASIImath.py $
# $Id: GSASIImath.py 5722 2024-02-05 21:49:09Z toby $
########### SVN repository information ###################
'''
Routines defined in :mod:`GSASIImath` follow.
'''
from __future__ import division, print_function
import random as rn
import numpy as np
import numpy.linalg as nl
import numpy.ma as ma
import time
import math
import copy
import GSASIIpath
GSASIIpath.SetVersionNumber("$Revision: 5722 $")
import GSASIIElem as G2el
import GSASIIlattice as G2lat
import GSASIIspc as G2spc
import GSASIIpwd as G2pwd
import GSASIIobj as G2obj
import GSASIIfiles as G2fil
import numpy.fft as fft
import scipy.optimize as so
try:
import pypowder as pwd
except ImportError:
print ('pypowder is not available - profile calcs. not allowed')
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
atand = lambda x: 180.*np.arctan(x)/np.pi
atan2d = lambda y,x: 180.*np.arctan2(y,x)/np.pi
try: # fails on doc build
twopi = 2.0*np.pi
twopisq = 2.0*np.pi**2
_double_min = np.finfo(float).min
_double_max = np.finfo(float).max
except TypeError:
pass
nxs = np.newaxis
################################################################################
#### Hessian least-squares Levenberg-Marquardt routine
################################################################################
class G2NormException(Exception): pass
def pinv(a, rcond=1e-15 ):
'''
Compute the (Moore-Penrose) pseudo-inverse of a matrix.
Modified from numpy.linalg.pinv; assumes a is Hessian & returns no. zeros found
Calculate the generalized inverse of a matrix using its
singular-value decomposition (SVD) and including all
*large* singular values.
:param array a: (M, M) array_like - here assumed to be LS Hessian
Matrix to be pseudo-inverted.
:param float rcond: Cutoff for small singular values.
Singular values smaller (in modulus) than
`rcond` * largest_singular_value (again, in modulus)
are set to zero.
:returns: B : (M, M) ndarray
The pseudo-inverse of `a`
Raises: LinAlgError
If the SVD computation does not converge.
Notes:
The pseudo-inverse of a matrix A, denoted :math:`A^+`, is
defined as: "the matrix that 'solves' [the least-squares problem]
:math:`Ax = b`," i.e., if :math:`\\bar{x}` is said solution, then
:math:`A^+` is that matrix such that :math:`\\bar{x} = A^+b`.
It can be shown that if :math:`Q_1 \\Sigma Q_2^T = A` is the singular
value decomposition of A, then
:math:`A^+ = Q_2 \\Sigma^+ Q_1^T`, where :math:`Q_{1,2}` are
orthogonal matrices, :math:`\\Sigma` is a diagonal matrix consisting
of A's so-called singular values, (followed, typically, by
zeros), and then :math:`\\Sigma^+` is simply the diagonal matrix
consisting of the reciprocals of A's singular values
(again, followed by zeros). [1]
References:
.. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando, FL, Academic Press, Inc., 1980, pp. 139-142.
'''
u, s, vt = nl.svd(a)
cutoff = rcond*np.maximum.reduce(s)
s = np.where(s>cutoff,1./s,0.)
nzero = s.shape[0]-np.count_nonzero(s)
res = np.dot(vt.T,s[:,nxs]*u.T)
return res,nzero
def dropTerms(bad, hessian, indices, *vectors):
'''Remove the 'bad' terms from the Hessian and vector
:param tuple bad: a list of variable (row/column) numbers that should be
removed from the hessian and vector. Example: (0,3) removes the 1st and
4th column/row
:param np.array hessian: a square matrix of length n x n
:param np.array indices: the indices of the least-squares vector of length n
referenced to the initial variable list; as this routine is called
multiple times, more terms may be removed from this list
:param additional-args: various least-squares model values, length n
:returns: hessian, indices, vector0, vector1,... where the lengths are
now n' x n' and n', with n' = n - len(bad)
'''
out = [np.delete(np.delete(hessian,bad,1),bad,0),np.delete(indices,bad)]
for v in vectors:
out.append(np.delete(v,bad))
return out
def setHcorr(info,Amat,xtol,problem=False):
'''Find & report high correlation terms in covariance matrix
'''
Adiag = np.sqrt(np.diag(Amat))
if np.any(np.abs(Adiag) < 1.e-14): raise G2NormException # test for any hard singularities
Anorm = np.outer(Adiag,Adiag)
Amat = Amat/Anorm
Bmat,Nzeros = pinv(Amat,xtol) #Moore-Penrose inversion (via SVD) & count of zeros
Bmat = Bmat/Anorm
sig = np.sqrt(np.diag(Bmat))
xvar = np.outer(sig,np.ones_like(sig))
AcovUp = abs(np.triu(np.divide(np.divide(Bmat,xvar),xvar.T),1)) # elements above diagonal
if Nzeros or problem: # something is wrong, so report what is found
m = min(0.99,0.99*np.amax(AcovUp))
else:
m = max(0.95,0.99*np.amax(AcovUp))
info['Hcorr'] = [(i,j,AcovUp[i,j]) for i,j in zip(*np.where(AcovUp > m))]
return Bmat,Nzeros
def setSVDwarn(info,Amat,Nzeros,indices):
'''Find & report terms causing SVN zeros
'''
if Nzeros == 0: return
d = np.abs(np.diag(nl.qr(Amat)[1]))
svdsing = list(np.where(d < 1.e-14)[0])
if len(svdsing) < Nzeros: # try to get the Nzeros worst terms
svdsing = list(np.where(d <= sorted(d)[Nzeros-1])[0])
if not len(svdsing): # make sure at least the worst term is shown
svdsing = [np.argmin(d)]
info['SVDsing'] = [indices[i] for i in svdsing]
def HessianLSQ(func,x0,Hess,args=(),ftol=1.49012e-8,xtol=1.e-6, maxcyc=0,lamda=-3,Print=False,refPlotUpdate=None):
'''
Minimize the sum of squares of a function (:math:`f`) evaluated on a series of
values (y): :math:`\\sum_{y=0}^{N_{obs}} f(y,{args})`
where :math:`x = arg min(\\sum_{y=0}^{N_{obs}} (func(y)^2,axis=0))`
:param function func: callable method or function
should take at least one (possibly length N vector) argument and
returns M floating point numbers.
:param np.ndarray x0: The starting estimate for the minimization of length N
:param function Hess: callable method or function
A required function or method to compute the weighted vector and Hessian for func.
It must be a symmetric NxN array
:param tuple args: Any extra arguments to func are placed in this tuple.
:param float ftol: Relative error desired in the sum of squares.
:param float xtol: Relative tolerance of zeros in the SVD solution in nl.pinv.
:param int maxcyc: The maximum number of cycles of refinement to execute, if -1 refine
until other limits are met (ftol, xtol)
:param int lamda: initial Marquardt lambda=10**lamda
:param bool Print: True for printing results (residuals & times) by cycle
:returns: (x,cov_x,infodict) where
* x : ndarray
The solution (or the result of the last iteration for an unsuccessful
call).
* cov_x : ndarray
Uses the fjac and ipvt optional outputs to construct an
estimate of the jacobian around the solution. ``None`` if a
singular matrix encountered (indicates very flat curvature in
some direction). This matrix must be multiplied by the
residual standard deviation to get the covariance of the
parameter estimates -- see curve_fit.
* infodict : dict, a dictionary of optional outputs with the keys:
* 'fvec' : the function evaluated at the output
* 'num cyc':
* 'nfev': number of objective function evaluation calls
* 'lamMax':
* 'psing': list of variable variables that have been removed from the refinement
* 'SVD0': -1 for singlar matrix, -2 for objective function exception, Nzeroes = # of SVD 0's
* 'Hcorr': list entries (i,j,c) where i & j are of highly correlated variables & c is correlation coeff.
'''
ifConverged = False
deltaChi2 = -10.
x0 = np.array(x0, ndmin=1, dtype=np.float64) # make sure that x0 float 1-D
# array (in case any parameters were set to int)
n = len(x0)
if type(args) != type(()):
args = (args,)
dlg = None
if hasattr(args[-1],'Update'): dlg = args[-1]
if hasattr(dlg,'AdvanceCycle'): dlg.AdvanceCycle(-1)
icycle = 0
AmatAll = None # changed only if cycles > 0
lamMax = lam = 0 # start w/o Marquardt and add it in if needed
nfev = 0
if Print:
G2fil.G2Print(' Hessian Levenberg-Marquardt SVD refinement on %d variables:'%(n))
XvecAll = np.zeros(n)
try:
M2 = func(x0,*args)
except Exception as Msg:
if not hasattr(Msg,'msg'): Msg.msg = str(Msg)
G2fil.G2Print('\nouch #0 unable to evaluate initial objective function\nCheck for an invalid parameter value',mode='error')
G2fil.G2Print('Use Calculate/"View LS parms" to list all parameter values\n',mode='warn')
G2fil.G2Print('Error message: '+Msg.msg,mode='warn')
if GSASIIpath.GetConfigValue('debug'):
import traceback
print(traceback.format_exc())
raise G2obj.G2Exception('HessianLSQ -- ouch #0: look for invalid parameter (see console)')
chisq00 = np.sum(M2**2) # starting Chi**2
Nobs = len(M2)
if Print:
G2fil.G2Print('initial chi^2 %.5g with %d obs.'%(chisq00,Nobs))
if n == 0:
info = {'num cyc':0,'fvec':M2,'nfev':1,'lamMax':0,'psing':[],'SVD0':0}
info['msg'] = 'no variables: skipping refinement\n'
info.update({'Converged':True, 'DelChi2':0, 'Xvec':None, 'chisq0':chisq00})
return [x0,np.array([]),info]
indices = range(n)
while icycle < maxcyc:
M = M2
time0 = time.time()
nfev += 1
chisq0 = np.sum(M**2)
YvecAll,AmatAll = Hess(x0,*args) # compute hessian & vectors with all variables
Yvec = copy.copy(YvecAll)
Amat = copy.copy(AmatAll)
Xvec = copy.copy(XvecAll)
# we could remove vars that were dropped in previous cycles here (use indices), but for
# now let's reset them each cycle in case the singularities go away
indices = range(n)
Adiag = np.sqrt(np.diag(Amat))
psing = np.where(np.abs(Adiag) < 1.e-14)[0] # find any hard singularities
if len(psing):
G2fil.G2Print('ouch #1 dropping singularities for variable(s) #{}'.format(
psing), mode='warn')
Amat, indices, Xvec, Yvec, Adiag = dropTerms(psing,Amat, indices, Xvec, Yvec, Adiag)
Anorm = np.outer(Adiag,Adiag) # normalize matrix & vector
Yvec /= Adiag
Amat /= Anorm
chitol = ftol
maxdrop = 3 # max number of drop var attempts
loops = 0
while True: #--------- loop as we increase lamda and possibly drop terms
lamMax = max(lamMax,lam)
Amatlam = Amat*(1.+np.eye(Amat.shape[0])*lam)
try:
Nzeros = 1
Ainv,Nzeros = pinv(Amatlam,xtol) # Moore-Penrose SVD inversion
except nl.LinAlgError:
loops += 1
d = np.abs(np.diag(nl.qr(Amatlam)[1]))
psing = list(np.where(d < 1.e-14)[0])
if not len(psing): # make sure at least the worst term is removed
psing = [np.argmin(d)]
G2fil.G2Print('ouch #2 bad SVD inversion; dropping terms for for variable(s) #{}'.
format(psing), mode='warn')
Amat, indices, Xvec, Yvec, Adiag = dropTerms(psing,Amat, indices, Xvec, Yvec, Adiag)
if loops < maxdrop: continue # try again, same lam but fewer vars
G2fil.G2Print('giving up with ouch #2', mode='error')
info = {'num cyc':icycle,'fvec':M,'nfev':nfev,'lamMax':lamMax,'SVD0':Nzeros}
info['psing'] = [i for i in range(n) if i not in indices]
info['msg'] = 'SVD inversion failure\n'
return [x0,None,info]
Xvec = np.inner(Ainv,Yvec)/Adiag #solve for LS terms
XvecAll[indices] = Xvec # expand
try:
M2 = func(x0+XvecAll,*args)
except Exception as Msg:
if not hasattr(Msg,'msg'): Msg.msg = str(Msg)
G2fil.G2Print(Msg.msg,mode='warn')
loops += 1
d = np.abs(np.diag(nl.qr(Amatlam)[1]))
G2fil.G2Print('ouch #3 unable to evaluate objective function;',mode='error')
info = {'num cyc':icycle,'fvec':M,'nfev':nfev,'lamMax':lamMax,'SVD0':Nzeros}
info['psing'] = [i for i in range(n) if i not in indices]
try: # try to report highly correlated parameters from full Hessian
setHcorr(info,AmatAll,xtol,problem=True)
except nl.LinAlgError:
G2fil.G2Print('Warning: Hessian too ill-conditioned to get full covariance matrix')
except G2NormException:
G2fil.G2Print('Warning: Hessian normalization problem')
except Exception as Msg:
if not hasattr(Msg,'msg'): Msg.msg = str(Msg)
G2fil.G2Print('Error determining highly correlated vars',mode='warn')
G2fil.G2Print(Msg.msg,mode='warn')
info['msg'] = Msg.msg + '\n\n'
setSVDwarn(info,Amatlam,Nzeros,indices)
return [x0,None,info]
nfev += 1
chisq1 = np.sum(M2**2)
if chisq1 > chisq0*(1.+chitol): #TODO put Alan Coehlo's criteria for lambda here?
if lam == 0:
lam = 10.**lamda # set to initial Marquardt term
else:
lam *= 10.
if Print:
G2fil.G2Print(('divergence: chi^2 %.5g on %d obs. (%d SVD zeros)\n'+
'\tincreasing Marquardt lambda to %.1e')%(chisq1,Nobs,Nzeros,lam))
if lam > 10.:
G2fil.G2Print('ouch #4 stuck: chisq-new %.4g > chisq0 %.4g with lambda %.1g'%
(chisq1,chisq0,lam), mode='warn')
if GSASIIpath.GetConfigValue('debug'):
print('Cycle %d: %.2fs' % (icycle,time.time()-time0))
try: # report highly correlated parameters from full Hessian, if we can
info = {'num cyc':icycle,'fvec':M,'nfev':nfev,'lamMax':lamMax,
'Converged':False, 'DelChi2':deltaChi2, 'Xvec':XvecAll,
'chisq0':chisq00, 'Ouch#4':True}
info['psing'] = [i for i in range(n) if i not in indices]
Bmat,Nzeros = setHcorr(info,AmatAll,xtol,problem=True)
info['SVD0'] = Nzeros
setSVDwarn(info,Amatlam,Nzeros,indices)
return [x0,Bmat,info]
except Exception as Msg:
if not hasattr(Msg,'msg'): Msg.msg = str(Msg)
G2fil.G2Print('Error determining highly correlated vars',mode='warn')
G2fil.G2Print(Msg.msg,mode='warn')
maxcyc = -1 # no more cycles
break
chitol *= 2
else: # refinement succeeded
x0 += XvecAll
lam /= 10. # drop lam on next cycle
break
# complete current cycle
if hasattr(dlg,'AdvanceCycle'): dlg.AdvanceCycle(icycle)
deltaChi2 = (chisq0-chisq1)/chisq0
if Print:
if n-len(indices):
G2fil.G2Print(
'Cycle %d: %.2fs Chi2: %.5g; Obs: %d; Lam: %.3g Del: %.3g; drop=%d, SVD=%d'%
(icycle,time.time()-time0,chisq1,Nobs,lamMax,deltaChi2,n-len(indices),Nzeros))
else:
G2fil.G2Print(
'Cycle %d: %.2fs, Chi**2: %.5g for %d obs., Lambda: %.3g, Delta: %.3g, SVD=%d'%
(icycle,time.time()-time0,chisq1,Nobs,lamMax,deltaChi2,Nzeros))
Histograms = args[0][0]
if refPlotUpdate is not None: refPlotUpdate(Histograms,icycle) # update plot
if deltaChi2 < ftol:
ifConverged = True
if Print:
G2fil.G2Print("converged")
break
icycle += 1
#----------------------- refinement complete, compute Covariance matrix w/o Levenberg-Marquardt
nfev += 1
try:
if icycle == 0: # no parameter changes, skip recalc
M = M2
else:
M = func(x0,*args)
except Exception as Msg:
if not hasattr(Msg,'msg'): Msg.msg = str(Msg)
G2fil.G2Print(Msg.msg,mode='warn')
G2fil.G2Print('ouch #5 final objective function re-eval failed',mode='error')
psing = [i for i in range(n) if i not in indices]
info = {'num cyc':icycle,'fvec':M2,'nfev':nfev,'lamMax':lamMax,'psing':psing,'SVD0':-2}
info['msg'] = Msg.msg + '\n'
setSVDwarn(info,Amatlam,Nzeros,indices)
return [x0,None,info]
chisqf = np.sum(M**2) # ending chi**2
if not maxcyc: #zero cycle calc exit here
info = {'num cyc':0,'fvec':M,'nfev':0,'lamMax':0,'SVD0':0,
'Converged':True, 'DelChi2':0., 'Xvec':XvecAll, 'chisq0':chisqf}
return [x0,None,info]
psing_prev = [i for i in range(n) if i not in indices] # save dropped vars
if AmatAll is None: # Save some time and use Hessian from the last refinement cycle
Yvec,Amat = Hess(x0,*args)
else:
Yvec = copy.copy(YvecAll)
Amat = copy.copy(AmatAll)
indices = range(n)
info = {}
try: # report highly correlated parameters from full Hessian, if we can
Bmat,Nzeros = setHcorr(info,Amat,xtol,problem=False)
info.update({'num cyc':icycle,'fvec':M,'nfev':nfev,'lamMax':lamMax,'SVD0':Nzeros,'psing':psing_prev,
'Converged':ifConverged, 'DelChi2':deltaChi2, 'chisq0':chisq00})
if icycle > 0: info.update({'Xvec':XvecAll})
setSVDwarn(info,Amat,Nzeros,indices)
# expand Bmat by filling with zeros if columns have been dropped
if len(psing_prev):
ins = [j-i for i,j in enumerate(psing_prev)]
Bmat = np.insert(np.insert(Bmat,ins,0,1),ins,0,0)
return [x0,Bmat,info]
except nl.LinAlgError:
G2fil.G2Print('Warning: Hessian too ill-conditioned to get full covariance matrix')
except G2NormException:
G2fil.G2Print('Warning: Hessian normalization problem')
except Exception as Msg:
if not hasattr(Msg,'msg'): Msg.msg = str(Msg)
G2fil.G2Print('Error determining highly correlated vars',mode='warn')
G2fil.G2Print(Msg.msg,mode='warn')
# matrix above inversion failed, drop previously removed variables & try again
Amat, indices, Yvec = dropTerms(psing_prev, Amat, indices, Yvec)
Adiag = np.sqrt(np.diag(Amat))
Anorm = np.outer(Adiag,Adiag)
Amat = Amat/Anorm
try:
Bmat,Nzeros = pinv(Amat,xtol) #Moore-Penrose inversion (via SVD) & count of zeros
Bmat = Bmat/Anorm
except nl.LinAlgError: # this is unexpected. How did we get this far with a singular matrix?
G2fil.G2Print('ouch #6 linear algebra error in making final v-cov matrix', mode='error')
psing = list(np.where(np.abs(np.diag(nl.qr(Amat)[1])) < 1.e-14)[0])
if not len(psing): # make sure at least the worst term is flagged
d = np.abs(np.diag(nl.qr(Amat)[1]))
psing = [np.argmin(d)]
Amat, indices, Yvec = dropTerms(psing, Amat, indices, Yvec)
info = {'num cyc':icycle,'fvec':M,'nfev':nfev,'lamMax':lamMax,'SVD0':-1,'Xvec':None, 'chisq0':chisqf}
info['psing'] = [i for i in range(n) if i not in indices]
return [x0,None,info]
# expand Bmat by filling with zeros if columns have been dropped
psing = [i for i in range(n) if i not in indices]
if len(psing):
ins = [j-i for i,j in enumerate(psing)]
Bmat = np.insert(np.insert(Bmat,ins,0,1),ins,0,0)
info.update({'num cyc':icycle,'fvec':M,'nfev':nfev,'lamMax':lamMax,'SVD0':Nzeros,
'Converged':ifConverged, 'DelChi2':deltaChi2, 'Xvec':XvecAll, 'chisq0':chisq00})
info['psing'] = [i for i in range(n) if i not in indices]
setSVDwarn(info,Amat,Nzeros,indices)
return [x0,Bmat,info]
def HessianSVD(func,x0,Hess,args=(),ftol=1.49012e-8,xtol=1.e-6, maxcyc=0,lamda=-3,Print=False,refPlotUpdate=None):
'''
Minimize the sum of squares of a function (:math:`f`) evaluated on a series of
values (y): :math:`\\sum_{y=0}^{N_{obs}} f(y,{args})`
where :math:`x = arg min(\\sum_{y=0}^{N_{obs}} (func(y)^2,axis=0))`
:param function func: callable method or function
should take at least one (possibly length N vector) argument and
returns M floating point numbers.
:param np.ndarray x0: The starting estimate for the minimization of length N
:param function Hess: callable method or function
A required function or method to compute the weighted vector and Hessian for func.
It must be a symmetric NxN array
:param tuple args: Any extra arguments to func are placed in this tuple.
:param float ftol: Relative error desired in the sum of squares.
:param float xtol: Relative tolerance of zeros in the SVD solution in nl.pinv.
:param int maxcyc: The maximum number of cycles of refinement to execute, if -1 refine
until other limits are met (ftol, xtol)
:param bool Print: True for printing results (residuals & times) by cycle
:returns: (x,cov_x,infodict) where
* x : ndarray
The solution (or the result of the last iteration for an unsuccessful
call).
* cov_x : ndarray
Uses the fjac and ipvt optional outputs to construct an
estimate of the jacobian around the solution. ``None`` if a
singular matrix encountered (indicates very flat curvature in
some direction). This matrix must be multiplied by the
residual standard deviation to get the covariance of the
parameter estimates -- see curve_fit.
* infodict : dict
a dictionary of optional outputs with the keys:
* 'fvec' : the function evaluated at the output
* 'num cyc':
* 'nfev':
* 'lamMax':0.
* 'psing':
* 'SVD0':
'''
ifConverged = False
deltaChi2 = -10.
x0 = np.array(x0, ndmin=1) #might be redundant?
n = len(x0)
if type(args) != type(()):
args = (args,)
icycle = 0
nfev = 0
if Print:
G2fil.G2Print(' Hessian SVD refinement on %d variables:'%(n))
chisq00 = None
while icycle < maxcyc:
time0 = time.time()
M = func(x0,*args)
nfev += 1
chisq0 = np.sum(M**2)
if chisq00 is None: chisq00 = chisq0
Yvec,Amat = Hess(x0,*args)
Adiag = np.sqrt(np.diag(Amat))
psing = np.where(np.abs(Adiag) < 1.e-14,True,False)
if np.any(psing): #hard singularity in matrix
return [x0,None,{'num cyc':icycle,'fvec':M,'nfev':nfev,'lamMax':0.,'psing':psing,'SVD0':-1}]
Anorm = np.outer(Adiag,Adiag)
Yvec /= Adiag
Amat /= Anorm
if Print:
G2fil.G2Print('initial chi^2 %.5g'%(chisq0))
try:
Ainv,Nzeros = pinv(Amat,xtol) #do Moore-Penrose inversion (via SVD)
except nl.LinAlgError:
G2fil.G2Print('ouch #1 bad SVD inversion; change parameterization', mode='warn')
psing = list(np.where(np.abs(np.diag(nl.qr(Amat)[1])) < 1.e-14)[0])
return [x0,None,{'num cyc':icycle,'fvec':M,'nfev':nfev,'lamMax':0.,'psing':psing,'SVD0':-1}]
Xvec = np.inner(Ainv,Yvec) #solve
Xvec /= Adiag
M2 = func(x0+Xvec,*args)
nfev += 1
chisq1 = np.sum(M2**2)
deltaChi2 = (chisq0-chisq1)/chisq0
if Print:
G2fil.G2Print(' Cycle: %d, Time: %.2fs, Chi**2: %.5g, Delta: %.3g'%(
icycle,time.time()-time0,chisq1,deltaChi2))
Histograms = args[0][0]
if refPlotUpdate is not None: refPlotUpdate(Histograms,icycle) # update plot
if deltaChi2 < ftol:
ifConverged = True
if Print: G2fil.G2Print("converged")
break
icycle += 1
M = func(x0,*args)
nfev += 1
Yvec,Amat = Hess(x0,*args)
Adiag = np.sqrt(np.diag(Amat))
Anorm = np.outer(Adiag,Adiag)
Amat = Amat/Anorm
try:
Bmat,Nzero = pinv(Amat,xtol) #Moore-Penrose inversion (via SVD) & count of zeros
G2fil.G2Print('Found %d SVD zeros'%(Nzero), mode='warn')
# Bmat = nl.inv(Amatlam); Nzeros = 0
Bmat = Bmat/Anorm
return [x0,Bmat,{'num cyc':icycle,'fvec':M,'nfev':nfev,'lamMax':0.,'psing':[],
'SVD0':Nzero,'Converged': ifConverged, 'DelChi2':deltaChi2,
'chisq0':chisq00}]
except nl.LinAlgError:
G2fil.G2Print('ouch #2 linear algebra error in making v-cov matrix', mode='error')
psing = []
if maxcyc:
psing = list(np.where(np.diag(nl.qr(Amat)[1]) < 1.e-14)[0])
return [x0,None,{'num cyc':icycle,'fvec':M,'nfev':nfev,'lamMax':0.,'psing':psing,'SVD0':-1,
'chisq0':chisq00}]
def getVCov(varyNames,varyList,covMatrix):
'''obtain variance-covariance terms for a set of variables. NB: the varyList
and covMatrix were saved by the last least squares refinement so they must match.
:param list varyNames: variable names to find v-cov matric for
:param list varyList: full list of all variables in v-cov matrix
:param nparray covMatrix: full variance-covariance matrix from the last
least squares refinement
:returns: nparray vcov: variance-covariance matrix for the variables given
in varyNames
'''
vcov = np.zeros((len(varyNames),len(varyNames)))
for i1,name1 in enumerate(varyNames):
for i2,name2 in enumerate(varyNames):
try:
vcov[i1][i2] = covMatrix[varyList.index(name1)][varyList.index(name2)]
except ValueError:
vcov[i1][i2] = 0.0
# if i1 == i2:
# vcov[i1][i2] = 1e-20
# else:
# vcov[i1][i2] = 0.0
return vcov
################################################################################
#### Atom manipulations
################################################################################
def getAtomPtrs(data,draw=False):
''' get atom data pointers cx,ct,cs,cia in Atoms or Draw Atoms lists
NB:may not match column numbers in displayed table
param: dict: data phase data structure
draw: boolean True if Draw Atoms list pointers are required
return: cx,ct,cs,cia pointers to atom xyz, type, site sym, uiso/aniso flag
'''
if draw:
return data['Drawing']['atomPtrs']
else:
return data['General']['AtomPtrs']
def FindMolecule(ind,generalData,atomData): #uses numpy & masks - very fast even for proteins!
def getNeighbors(atom,radius):
Dx = UAtoms-np.array(atom[cx:cx+3])
dist = ma.masked_less(np.sqrt(np.sum(np.inner(Amat,Dx)**2,axis=0)),0.5) #gets rid of disorder "bonds" < 0.5A
sumR = Radii+radius
return set(ma.nonzero(ma.masked_greater(dist-factor*sumR,0.))[0]) #get indices of bonded atoms
import numpy.ma as ma
indices = (-1,0,1)
Units = np.array([[h,k,l] for h in indices for k in indices for l in indices],dtype='f')
cx,ct,cs,ci = generalData['AtomPtrs']
DisAglCtls = generalData['DisAglCtls']
SGData = generalData['SGData']
Amat,Bmat = G2lat.cell2AB(generalData['Cell'][1:7])
radii = DisAglCtls['BondRadii']
atomTypes = DisAglCtls['AtomTypes']
factor = DisAglCtls['Factors'][0]
unit = np.zeros(3)
try:
indH = atomTypes.index('H')
radii[indH] = 0.5
except:
pass
nAtom = len(atomData)
Indx = list(range(nAtom))
UAtoms = []
Radii = []
for atom in atomData:
UAtoms.append(np.array(atom[cx:cx+3]))
Radii.append(radii[atomTypes.index(atom[ct])])
UAtoms = np.array(UAtoms)
Radii = np.array(Radii)
for nOp,Op in enumerate(SGData['SGOps'][1:]):
UAtoms = np.concatenate((UAtoms,(np.inner(Op[0],UAtoms[:nAtom]).T+Op[1])))
Radii = np.concatenate((Radii,Radii[:nAtom]))
Indx += Indx[:nAtom]
for icen,cen in enumerate(SGData['SGCen'][1:]):
UAtoms = np.concatenate((UAtoms,(UAtoms+cen)))
Radii = np.concatenate((Radii,Radii))
Indx += Indx[:nAtom]
if SGData['SGInv']:
UAtoms = np.concatenate((UAtoms,-UAtoms))
Radii = np.concatenate((Radii,Radii))
Indx += Indx
UAtoms %= 1.
mAtoms = len(UAtoms)
for unit in Units:
if np.any(unit): #skip origin cell
UAtoms = np.concatenate((UAtoms,UAtoms[:mAtoms]+unit))
Radii = np.concatenate((Radii,Radii[:mAtoms]))
Indx += Indx[:mAtoms]
UAtoms = np.array(UAtoms)
Radii = np.array(Radii)
newAtoms = [atomData[ind],]
atomData[ind] = None
radius = Radii[ind]
IndB = getNeighbors(newAtoms[-1],radius)
while True:
if not len(IndB):
break
indb = IndB.pop()
if atomData[Indx[indb]] == None:
continue
while True:
try:
jndb = IndB.index(indb)
IndB.remove(jndb)
except:
break
newAtom = copy.copy(atomData[Indx[indb]])
newAtom[cx:cx+3] = UAtoms[indb] #NB: thermal Uij, etc. not transformed!
newAtoms.append(newAtom)
atomData[Indx[indb]] = None
IndB = set(list(IndB)+list(getNeighbors(newAtoms[-1],radius)))
if len(IndB) > nAtom:
return 'Assemble molecule cannot be used on extended structures'
for atom in atomData:
if atom != None:
newAtoms.append(atom)
return newAtoms
def FindAtomIndexByIDs(atomData,loc,IDs,Draw=True):
'''finds the set of atom array indices for a list of atom IDs. Will search
either the Atom table or the drawAtom table.
:param list atomData: Atom or drawAtom table containting coordinates, etc.
:param int loc: location of atom id in atomData record
:param list IDs: atom IDs to be found
:param bool Draw: True if drawAtom table to be searched; False if Atom table
is searched
:returns: list indx: atom (or drawAtom) indices
'''
indx = []
for i,atom in enumerate(atomData):
if Draw and atom[loc] in IDs:
indx.append(i)
elif atom[loc] in IDs:
indx.append(i)
return indx
def FillAtomLookUp(atomData,indx):
'''create a dictionary of atom indexes with atom IDs as keys
:param list atomData: Atom table to be used
:param int indx: pointer to position of atom id in atom record (typically cia+8)
:returns: dict atomLookUp: dictionary of atom indexes with atom IDs as keys
'''
return {atom[indx]:iatm for iatm,atom in enumerate(atomData)}
def DrawAtomsReplaceByID(data,loc,atom,ID):
'''Replace all atoms in drawing array with an ID matching the specified value'''
atomData = data['Drawing']['Atoms']
indx = FindAtomIndexByIDs(atomData,loc,[ID,])
for ind in indx:
atomData[ind] = MakeDrawAtom(data,atom,atomData[ind])
def MakeDrawAtom(data,atom,oldatom=None):
'needs a description'
AA3letter = ['ALA','ARG','ASN','ASP','CYS','GLN','GLU','GLY','HIS','ILE',
'LEU','LYS','MET','PHE','PRO','SER','THR','TRP','TYR','VAL','MSE','HOH','WAT','UNK']
AA1letter = ['A','R','N','D','C','Q','E','G','H','I',
'L','K','M','F','P','S','T','W','Y','V','M',' ',' ',' ']
generalData = data['General']
Amat,Bmat = G2lat.cell2AB(generalData['Cell'][1:7])
SGData = generalData['SGData']
deftype = G2obj.validateAtomDrawType(GSASIIpath.GetConfigValue('DrawAtoms_default'),generalData)
if generalData['Type'] in ['nuclear','faulted',]:
if oldatom:
opr = oldatom[5]
if atom[9] == 'A':
X,U = G2spc.ApplyStringOps(opr,SGData,atom[3:6],atom[11:17])
atomInfo = [atom[:2]+list(X)+oldatom[5:9]+atom[9:11]+list(U)+oldatom[17:]][0]
else:
X = G2spc.ApplyStringOps(opr,SGData,atom[3:6])
atomInfo = [atom[:2]+list(X)+oldatom[5:9]+atom[9:]+oldatom[17:]][0]
else:
atomInfo = [atom[:2]+atom[3:6]+['1',]+[deftype]+
['',]+[[255,255,255],]+atom[9:]+[[],[]]][0]
ct,cs = [1,8] #type & color
elif generalData['Type'] == 'magnetic':
if oldatom:
opr = oldatom[8]
mom = np.array(atom[7:10])
if generalData['Super']:
SSGData = generalData['SSGData']
Mom = G2spc.ApplyStringOpsMom(opr,SGData,SSGData,mom)
else:
Mom = G2spc.ApplyStringOpsMom(opr,SGData,None,mom)
if atom[12] == 'A':
X,U = G2spc.ApplyStringOps(opr,SGData,atom[3:6],atom[14:20])
atomInfo = [atom[:2]+list(X)+list(Mom)+oldatom[8:12]+atom[12:14]+list(U)+oldatom[20:]][0]
else:
X = G2spc.ApplyStringOps(opr,SGData,atom[3:6])
atomInfo = [atom[:2]+list(X)+list(Mom)+oldatom[8:12]+atom[12:]+oldatom[20:]][0]
else:
atomInfo = [atom[:2]+atom[3:6]+atom[7:10]+['1',]+[deftype]+
['',]+[[255,255,255],]+atom[12:]+[[],[]]][0]
ct,cs = [1,11] #type & color
elif generalData['Type'] == 'macromolecular':
try:
oneLetter = AA3letter.index(atom[1])
except ValueError:
oneLetter = -1
atomInfo = [[atom[1].strip()+atom[0],]+
[AA1letter[oneLetter]+atom[0],]+atom[2:5]+
atom[6:9]+['1',]+[deftype]+['',]+[[255,255,255],]+atom[12:]+[[],[]]][0]
ct,cs = [4,11] #type & color
atNum = generalData['AtomTypes'].index(atom[ct])
atomInfo[cs] = list(generalData['Color'][atNum])
return atomInfo
def GetAtomsById(atomData,atomLookUp,IdList):
'''gets a list of atoms from Atom table that match a set of atom IDs
:param list atomData: Atom table to be used
:param dict atomLookUp: dictionary of atom indexes with atom IDs as keys
:param list IdList: atom IDs to be found
:returns: list atoms: list of atoms found
'''
atoms = []
for Id in IdList:
if Id < 0:
continue
atoms.append(atomData[atomLookUp[Id]])
return atoms
def GetAtomItemsById(atomData,atomLookUp,IdList,itemLoc,numItems=1):
'''gets atom parameters for atoms using atom IDs
:param list atomData: Atom table to be used
:param dict atomLookUp: dictionary of atom indexes with atom IDs as keys
:param list IdList: atom IDs to be found
:param int itemLoc: pointer to desired 1st item in an atom table entry
:param int numItems: number of items to be retrieved
:returns: type name: description
'''
Items = []
if not isinstance(IdList,list):
IdList = [IdList,]
for Id in IdList:
if Id < 0:
continue
if numItems == 1:
Items.append(atomData[atomLookUp[Id]][itemLoc])
else:
Items.append(atomData[atomLookUp[Id]][itemLoc:itemLoc+numItems])
return Items
def GetAtomCoordsByID(pId,parmDict,AtLookup,indx):
'''default doc string
:param type name: description
:returns: type name: description
'''
pfx = [str(pId)+'::A'+i+':' for i in ['x','y','z']]
dpfx = [str(pId)+'::dA'+i+':' for i in ['x','y','z']]
XYZ = []
for ind in indx:
names = [pfx[i]+str(AtLookup[ind]) for i in range(3)]
dnames = [dpfx[i]+str(AtLookup[ind]) for i in range(3)]
XYZ.append([parmDict[name]+parmDict[dname] for name,dname in zip(names,dnames)])
return XYZ
def GetAtomFracByID(pId,parmDict,AtLookup,indx):
'''default doc string
:param type name: description
:returns: type name: description
'''
pfx = str(pId)+'::Afrac:'
Frac = []
for ind in indx:
name = pfx+str(AtLookup[ind])
Frac.append(parmDict[name])
return Frac
# for Atom in Atoms:
# XYZ = Atom[cx:cx+3]
# if 'A' in Atom[cia]:
# U6 = Atom[cia+2:cia+8]
def GetAtomMomsByID(pId,parmDict,AtLookup,indx):
'''default doc string
:param type name: description
:returns: type name: description
'''
pfx = [str(pId)+'::A'+i+':' for i in ['Mx','My','Mz']]
Mom = []
for ind in indx:
names = [pfx[i]+str(AtLookup[ind]) for i in range(3)]
Mom.append([parmDict[name] for name in names])
return Mom
def ApplySeqData(data,seqData,PF2=False):
'''Applies result from seq. refinement to drawing atom positions & Uijs
:param dict data: GSAS-II phase data structure
:param dict seqData: GSAS-II sequential refinement results structure
:param bool PF2: if True then seqData is from a sequential run of PDFfit2
:returns: list drawAtoms: revised Draw Atoms list
'''
cx,ct,cs,cia = getAtomPtrs(data)
drawingData = data['Drawing']
dcx,dct,dcs,dci = getAtomPtrs(data,True)
atoms = data['Atoms']
drawAtoms = drawingData['Atoms']
parmDict = copy.deepcopy(seqData['parmDict'])
if PF2:
PDFData = data['RMC']['PDFfit']
SGData = data['General']['SGData']
AtmConstr = PDFData['AtomConstr']
for ia,atom in enumerate(atoms):
atxyz = atom[cx:cx+3]
for ix in [0,1,2]:
item = AtmConstr[ia][ix+2]
if '@' in item:
Ids = [itm[:2] for itm in item.split('@')[1:]]
for Id in Ids:
item = item.replace('@'+Id,str(parmDict[Id][0]))
atxyz[ix] = eval(item)
if '@' in AtmConstr[ia][6]:
itm = AtmConstr[ia][6].split('@')[:2][1]
atuij = np.array([parmDict[itm][0],parmDict[itm][0],parmDict[itm][0],0.0,0.0,0.0])
indx = FindAtomIndexByIDs(drawAtoms,dci,[atom[cia+8],],True)
for ind in indx:
drawatom = drawAtoms[ind]
opr = drawatom[dcs-1]
#how do I handle Sfrac? - fade the atoms?
X,U = G2spc.ApplyStringOps(opr,SGData,atxyz,atuij)
drawatom[dcx:dcx+3] = X
drawatom[dci-6:dci] = U
else:
SGData = data['General']['SGData']
pId = data['pId']
pfx = '%d::'%(pId)
for ia,atom in enumerate(atoms):
dxyz = np.array([parmDict[pfx+'dAx:'+str(ia)],parmDict[pfx+'dAy:'+str(ia)],parmDict[pfx+'dAz:'+str(ia)]])
if atom[cia] == 'A':
atuij = np.array([parmDict[pfx+'AU11:'+str(ia)],parmDict[pfx+'AU22:'+str(ia)],parmDict[pfx+'AU33:'+str(ia)],
parmDict[pfx+'AU12:'+str(ia)],parmDict[pfx+'AU13:'+str(ia)],parmDict[pfx+'AU23:'+str(ia)]])
else:
atuiso = parmDict[pfx+'AUiso:'+str(ia)]
atxyz = G2spc.MoveToUnitCell(np.array(atom[cx:cx+3])+dxyz)[0]
indx = FindAtomIndexByIDs(drawAtoms,dci,[atom[cia+8],],True)
for ind in indx:
drawatom = drawAtoms[ind]
opr = drawatom[dcs-1]
#how do I handle Sfrac? - fade the atoms?
if atom[cia] == 'A':
X,U = G2spc.ApplyStringOps(opr,SGData,atxyz,atuij)
drawatom[dcx:dcx+3] = X
drawatom[dci-6:dci] = U
else:
X = G2spc.ApplyStringOps(opr,SGData,atxyz)
drawatom[dcx:dcx+3] = X
drawatom[dci-7] = atuiso
return drawAtoms
def FindOctahedron(results):
Octahedron = np.array([[1.,0,0],[0,1.,0],[0,0,1.],[-1.,0,0],[0,-1.,0],[0,0,-1.]])
Polygon = np.array([result[3] for result in results])
Dists = np.array([np.sqrt(np.sum(axis**2)) for axis in Polygon])
bond = np.mean(Dists)
std = np.std(Dists)
Norms = Polygon/Dists[:,nxs]
Tilts = acosd(np.dot(Norms,Octahedron[0]))
iAng = np.argmin(Tilts)
Qavec = np.cross(Norms[iAng],Octahedron[0])
QA = AVdeg2Q(Tilts[iAng],Qavec)
newNorms = prodQVQ(QA,Norms)
Rots = acosd(np.dot(newNorms,Octahedron[1]))
jAng = np.argmin(Rots)
Qbvec = np.cross(Norms[jAng],Octahedron[1])
QB = AVdeg2Q(Rots[jAng],Qbvec)
QQ = prodQQ(QA,QB)
newNorms = prodQVQ(QQ,Norms)
dispVecs = np.array([norm[:,nxs]-Octahedron.T for norm in newNorms])
disp = np.sqrt(np.sum(dispVecs**2,axis=1))
dispids = np.argmin(disp,axis=1)
vecDisp = np.array([dispVecs[i,:,dispid] for i,dispid in enumerate(dispids)])
Disps = np.array([disp[i,dispid] for i,dispid in enumerate(dispids)])
meanDisp = np.mean(Disps)
stdDisp = np.std(Disps)
A,V = Q2AVdeg(QQ)
return bond,std,meanDisp,stdDisp,A,V,vecDisp
def FindTetrahedron(results):
Tetrahedron = np.array([[1.,1,1],[1,-1,-1],[-1,1,-1],[-1,-1,1]])/np.sqrt(3.)
Polygon = np.array([result[3] for result in results])
Dists = np.array([np.sqrt(np.sum(axis**2)) for axis in Polygon])
bond = np.mean(Dists)
std = np.std(Dists)
Norms = Polygon/Dists[:,nxs]
Tilts = acosd(np.dot(Norms,Tetrahedron[0]))
iAng = np.argmin(Tilts)
Qavec = np.cross(Norms[iAng],Tetrahedron[0])
QA = AVdeg2Q(Tilts[iAng],Qavec)
newNorms = prodQVQ(QA,Norms)
Rots = acosd(np.dot(newNorms,Tetrahedron[1]))
jAng = np.argmin(Rots)
Qbvec = np.cross(Norms[jAng],Tetrahedron[1])
QB = AVdeg2Q(Rots[jAng],Qbvec)
QQ = prodQQ(QA,QB)
newNorms = prodQVQ(QQ,Norms)
dispVecs = np.array([norm[:,nxs]-Tetrahedron.T for norm in newNorms])
disp = np.sqrt(np.sum(dispVecs**2,axis=1))
dispids = np.argmin(disp,axis=1)
vecDisp = np.array([dispVecs[i,:,dispid] for i,dispid in enumerate(dispids)])
Disps = np.array([disp[i,dispid] for i,dispid in enumerate(dispids)])
meanDisp = np.mean(Disps)
stdDisp = np.std(Disps)
A,V = Q2AVdeg(QQ)
return bond,std,meanDisp,stdDisp,A,V,vecDisp
def FindNeighbors(phase,FrstName,AtNames,notName=''):
General = phase['General']
cx,ct,cs,cia = getAtomPtrs(phase)
Atoms = phase['Atoms']
atNames = [atom[ct-1] for atom in Atoms]
Cell = General['Cell'][1:7]
Amat,Bmat = G2lat.cell2AB(Cell)