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
/
GSASIIlattice.py
3335 lines (3076 loc) · 141 KB
/
GSASIIlattice.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-11-30 08:10:11 -0600 (Thu, 30 Nov 2023) $
# $Author: vondreele $
# $Revision: 5702 $
# $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/GSASIIlattice.py $
# $Id: GSASIIlattice.py 5702 2023-11-30 14:10:11Z vondreele $
########### SVN repository information ###################
'''
:mod:`GSASIIlattice` Classes & routines follow
'''
from __future__ import division, print_function
import math
import time
import copy
import sys
import random as ran
import numpy as np
import numpy.linalg as nl
import scipy.special as spsp
import GSASIIpath
import GSASIImath as G2mth
import GSASIIspc as G2spc
import GSASIIElem as G2elem
GSASIIpath.SetVersionNumber("$Revision: 5702 $")
# trig functions in degrees
sind = lambda x: np.sin(x*np.pi/180.)
asind = lambda x: 180.*np.arcsin(x)/np.pi
tand = lambda x: np.tan(x*np.pi/180.)
atand = lambda x: 180.*np.arctan(x)/np.pi
atan2d = lambda y,x: 180.*np.arctan2(y,x)/np.pi
cosd = lambda x: np.cos(x*np.pi/180.)
acosd = lambda x: 180.*np.arccos(x)/np.pi
rdsq2d = lambda x,p: round(1.0/np.sqrt(x),p)
try: # fails on doc build
rpd = np.pi/180.
RSQ2PI = 1./np.sqrt(2.*np.pi)
SQ2 = np.sqrt(2.)
RSQPI = 1./np.sqrt(np.pi)
R2pisq = 1./(2.*np.pi**2)
Forpi = 4.0*np.pi
except TypeError:
pass
nxs = np.newaxis
def sec2HMS(sec):
"""Convert time in sec to H:M:S string
:param sec: time in seconds
:return: H:M:S string (to nearest 100th second)
"""
H = int(sec//3600)
M = int(sec//60-H*60)
S = sec-3600*H-60*M
return '%d:%2d:%.2f'%(H,M,S)
def rotdMat(angle,axis=0):
"""Prepare rotation matrix for angle in degrees about axis(=0,1,2)
:param angle: angle in degrees
:param axis: axis (0,1,2 = x,y,z) about which for the rotation
:return: rotation matrix - 3x3 numpy array
"""
if axis == 2:
return np.array([[cosd(angle),-sind(angle),0],[sind(angle),cosd(angle),0],[0,0,1]])
elif axis == 1:
return np.array([[cosd(angle),0,-sind(angle)],[0,1,0],[sind(angle),0,cosd(angle)]])
else:
return np.array([[1,0,0],[0,cosd(angle),-sind(angle)],[0,sind(angle),cosd(angle)]])
def rotdMat4(angle,axis=0):
"""Prepare rotation matrix for angle in degrees about axis(=0,1,2) with scaling for OpenGL
:param angle: angle in degrees
:param axis: axis (0,1,2 = x,y,z) about which for the rotation
:return: rotation matrix - 4x4 numpy array (last row/column for openGL scaling)
"""
Mat = rotdMat(angle,axis)
return np.concatenate((np.concatenate((Mat,[[0],[0],[0]]),axis=1),[[0,0,0,1],]),axis=0)
def fillgmat(cell):
"""Compute lattice metric tensor from unit cell constants
:param cell: tuple with a,b,c,alpha, beta, gamma (degrees)
:return: 3x3 numpy array
"""
a,b,c,alp,bet,gam = cell
g = np.array([
[a*a, a*b*cosd(gam), a*c*cosd(bet)],
[a*b*cosd(gam), b*b, b*c*cosd(alp)],
[a*c*cosd(bet) ,b*c*cosd(alp), c*c]])
return g
def cell2Gmat(cell):
"""Compute real and reciprocal lattice metric tensor from unit cell constants
:param cell: tuple with a,b,c,alpha, beta, gamma (degrees)
:return: reciprocal (G) & real (g) metric tensors (list of two numpy 3x3 arrays)
"""
g = fillgmat(cell)
G = nl.inv(g)
return G,g
def A2Gmat(A,inverse=True):
"""Fill real & reciprocal metric tensor (G) from A.
:param A: reciprocal metric tensor elements as [G11,G22,G33,2*G12,2*G13,2*G23]
:param bool inverse: if True return both G and g; else just G
:return: reciprocal (G) & real (g) metric tensors (list of two numpy 3x3 arrays)
"""
G = np.array([
[A[0], A[3]/2., A[4]/2.],
[A[3]/2.,A[1], A[5]/2.],
[A[4]/2.,A[5]/2., A[2]]])
if inverse:
g = nl.inv(G)
return G,g
else:
return G
def Gmat2A(G):
"""Extract A from reciprocal metric tensor (G)
:param G: reciprocal metric tensor (3x3 numpy array)
:return: A = [G11,G22,G33,2*G12,2*G13,2*G23]
"""
return [G[0][0],G[1][1],G[2][2],2.*G[0][1],2.*G[0][2],2.*G[1][2]]
def cell2A(cell):
"""Obtain A = [G11,G22,G33,2*G12,2*G13,2*G23] from lattice parameters
:param cell: [a,b,c,alpha,beta,gamma] (degrees)
:return: G reciprocal metric tensor as 3x3 numpy array
"""
G,g = cell2Gmat(cell)
return Gmat2A(G)
def A2cell(A):
"""Compute unit cell constants from A
:param A: [G11,G22,G33,2*G12,2*G13,2*G23] G - reciprocal metric tensor
:return: a,b,c,alpha, beta, gamma (degrees) - lattice parameters
"""
G,g = A2Gmat(A)
return Gmat2cell(g)
def Gmat2cell(g):
"""Compute real/reciprocal lattice parameters from real/reciprocal metric tensor (g/G)
The math works the same either way.
:param g (or G): real (or reciprocal) metric tensor 3x3 array
:return: a,b,c,alpha, beta, gamma (degrees) (or a*,b*,c*,alpha*,beta*,gamma* degrees)
"""
oldset = np.seterr('raise')
a = np.sqrt(max(0,g[0][0]))
b = np.sqrt(max(0,g[1][1]))
c = np.sqrt(max(0,g[2][2]))
alp = acosd(g[2][1]/(b*c))
bet = acosd(g[2][0]/(a*c))
gam = acosd(g[0][1]/(a*b))
np.seterr(**oldset)
return a,b,c,alp,bet,gam
def invcell2Gmat(invcell):
"""Compute real and reciprocal lattice metric tensor from reciprocal
unit cell constants
:param invcell: [a*,b*,c*,alpha*, beta*, gamma*] (degrees)
:return: reciprocal (G) & real (g) metric tensors (list of two 3x3 arrays)
"""
G = fillgmat(invcell)
g = nl.inv(G)
return G,g
def cellDijFill(pfx,phfx,SGData,parmDict):
'''Returns the filled-out reciprocal cell (A) terms
from the parameter dictionaries corrected for Dij.
:param str pfx: parameter prefix ("n::", where n is a phase number)
:param dict SGdata: a symmetry object
:param dict parmDict: a dictionary of parameters
:returns: A,sigA where each is a list of six terms with the A terms
'''
if pfx+'D11' not in parmDict:
return None
if SGData['SGLaue'] in ['-1',]:
A = [parmDict[pfx+'A0']+parmDict[phfx+'D11'],parmDict[pfx+'A1']+parmDict[phfx+'D22'],
parmDict[pfx+'A2']+parmDict[phfx+'D33'],
parmDict[pfx+'A3']+parmDict[phfx+'D12'],parmDict[pfx+'A4']+parmDict[phfx+'D13'],
parmDict[pfx+'A5']+parmDict[phfx+'D23']]
elif SGData['SGLaue'] in ['2/m',]:
if SGData['SGUniq'] == 'a':
A = [parmDict[pfx+'A0']+parmDict[phfx+'D11'],parmDict[pfx+'A1']+parmDict[phfx+'D22'],
parmDict[pfx+'A2']+parmDict[phfx+'D33'],0,0,parmDict[pfx+'A5']+parmDict[phfx+'D23']]
elif SGData['SGUniq'] == 'b':
A = [parmDict[pfx+'A0']+parmDict[phfx+'D11'],parmDict[pfx+'A1']+parmDict[phfx+'D22'],
parmDict[pfx+'A2']+parmDict[phfx+'D33'],0,parmDict[pfx+'A4']+parmDict[phfx+'D13'],0]
else:
A = [parmDict[pfx+'A0']+parmDict[phfx+'D11'],parmDict[pfx+'A1']+parmDict[phfx+'D22'],
parmDict[pfx+'A2']+parmDict[phfx+'D33'],parmDict[pfx+'A3']+parmDict[phfx+'D12'],0,0]
elif SGData['SGLaue'] in ['mmm',]:
A = [parmDict[pfx+'A0']+parmDict[phfx+'D11'],parmDict[pfx+'A1']+parmDict[phfx+'D22'],
parmDict[pfx+'A2']+parmDict[phfx+'D33'],0,0,0]
elif SGData['SGLaue'] in ['4/m','4/mmm']:
A = [parmDict[pfx+'A0']+parmDict[phfx+'D11'],parmDict[pfx+'A0']+parmDict[phfx+'D11'],
parmDict[pfx+'A2']+parmDict[phfx+'D33'],0,0,0]
elif SGData['SGLaue'] in ['6/m','6/mmm','3m1', '31m', '3']:
A = [parmDict[pfx+'A0']+parmDict[phfx+'D11'],parmDict[pfx+'A0']+parmDict[phfx+'D11'],
parmDict[pfx+'A2']+parmDict[phfx+'D33'],parmDict[pfx+'A0']+parmDict[phfx+'D11'],0,0]
elif SGData['SGLaue'] in ['3R', '3mR']:
A = [parmDict[pfx+'A0']+parmDict[phfx+'D11'],parmDict[pfx+'A0']+parmDict[phfx+'D11'],
parmDict[pfx+'A0']+parmDict[phfx+'D11'],
parmDict[pfx+'A3']+parmDict[phfx+'D23'],parmDict[pfx+'A3']+parmDict[phfx+'D23'],
parmDict[pfx+'A3']+parmDict[phfx+'D23']]
elif SGData['SGLaue'] in ['m3m','m3']:
A = [parmDict[pfx+'A0']+parmDict[phfx+'D11'],parmDict[pfx+'A0']+parmDict[phfx+'D11'],
parmDict[pfx+'A0']+parmDict[phfx+'D11'],0,0,0]
return A
def CellDijCorr(Cell,SGData,Data,hist):
'''Returns the cell corrected for Dij values.
:param list Cell: lattice parameters
:param dict SGdata: a symmetry object
:param dict Data: phase data structure; contains set of Dij values
:param str hist: histogram name
:returns: cell corrected for Dij values
'''
A = cell2A(Cell)
Dij = Data[hist]['HStrain'][0]
newA = AplusDij(A,Dij,SGData)
return A2cell(newA)
def AplusDij(A,Dij,SGData):
''' returns the A corrected by Dij
:param list A: reciprocal metric terms A0-A5
:param array Dij: unique Dij values as stored in Hstrain
:param dict SGdata: a symmetry object
:returns list newA: A corrected by Dij
'''
if SGData['SGLaue'] in ['-1',]:
newA = [A[0]+Dij[0],A[1]+Dij[1],A[2]+Dij[2],A[3]+Dij[3],A[4]+Dij[4],A[5]+Dij[5]]
elif SGData['SGLaue'] in ['2/m',]:
if SGData['SGUniq'] == 'a':
newA = [A[0]+Dij[0],A[1]+Dij[1],A[2]+Dij[2],0,0,A[5]+Dij[3]]
elif SGData['SGUniq'] == 'b':
newA = [A[0]+Dij[0],A[1]+Dij[1],A[2]+Dij[2],0,A[4]+Dij[3],0]
else:
newA = [A[0]+Dij[0],A[1]+Dij[1],A[2]+Dij[2],A[3]+Dij[3],0,0]
elif SGData['SGLaue'] in ['mmm',]:
newA = [A[0]+Dij[0],A[1]+Dij[1],A[2]+Dij[2],0,0,0]
elif SGData['SGLaue'] in ['4/m','4/mmm']:
newA = [A[0]+Dij[0],A[0]+Dij[0],A[2]+Dij[1],0,0,0]
elif SGData['SGLaue'] in ['6/m','6/mmm','3m1', '31m', '3']:
newA = [A[0]+Dij[0],A[0]+Dij[0],A[2]+Dij[1],A[0]+Dij[0],0,0]
elif SGData['SGLaue'] in ['3R', '3mR']:
newA = [A[0]+Dij[0],A[0]+Dij[0],A[0]+Dij[0],A[3]+Dij[1],A[3]+Dij[1],A[3]+Dij[1]]
elif SGData['SGLaue'] in ['m3m','m3']:
newA = [A[0]+Dij[0],A[0]+Dij[0],A[0]+Dij[0],0,0,0]
return newA
def prodMGMT(G,Mat):
'''Transform metric tensor by matrix
:param G: array metric tensor
:param Mat: array transformation matrix
:return: array new metric tensor
'''
return np.inner(np.inner(Mat,G),Mat) #right
# return np.inner(Mat,np.inner(Mat,G)) #right
# return np.inner(np.inner(G,Mat).T,Mat) #right
# return np.inner(Mat,np.inner(G,Mat).T) #right
def TransformCell(cell,Trans):
'''Transform lattice parameters by matrix
:param cell: list a,b,c,alpha,beta,gamma,(volume)
:param Trans: array transformation matrix
:return: array transformed a,b,c,alpha,beta,gamma,volume
'''
newCell = np.zeros(7)
g = cell2Gmat(cell)[1]
newg = prodMGMT(g,Trans)
newCell[:6] = Gmat2cell(newg)
newCell[6] = calc_V(cell2A(newCell[:6]))
return newCell
# code to generate lattice constraint relationships between two phases
# (chemical & magnetic) related by a transformation matrix.
def symInner(M1,M2):
'''Compute inner product of two square matrices with symbolic processing
Use dot product because sympy does not define an inner product primitive
This requires that M1 & M2 be two sympy objects, as created in
GenerateCellConstraints().
Note that this is only used to do the symbolic math needed to generate
cell relationships. It is not used normally in GSAS-II.
'''
import sympy as sym
prodOuter = []
for i in range(3):
prod = []
for j in range(3):
prod.append(M1[i,:].dot(M2[j,:]))
prodOuter.append(prod)
return sym.Matrix(prodOuter)
def GenerateCellConstraints():
'''Generate unit cell constraints for transforming one set of A tensor
values to another using symbolic math (requires the sympy package)
Note that this is only used to do the symbolic math needed to generate
cell relationships. It is not used normally in GSAS-II.
'''
import sympy as sym
# define A tensor for starting cell
A0, A1, A2, A3, A4, A5 = sym.symbols('A0, A1, A2, A3, A4, A5')
G = sym.Matrix([ [A0, A3/2., A4/2.],
[A3/2., A1, A5/2.],
[A4/2., A5/2., A2 ]] )
# define transformation matrix
T00, T10, T20, T01, T11, T21, T02, T12, T22 = sym.symbols(
'T00, T10, T20, T01, T11, T21, T02, T12, T22')
Tr = sym.Matrix([ [T00, T10, T20], [T01, T11, T21], [T02, T12, T22],])
# apply transform
newG = symInner(symInner(Tr,G),Tr).expand()
# define A tensor for converted cell
return [newG[0,0],newG[1,1],newG[2,2],2.*newG[0,1],2.*newG[0,2],2.*newG[1,2]]
def subVals(expr,A,T):
'''Evaluate the symbolic expressions by substituting for A0-A5 & Tij
This can be used on the cell relationships created in
:func:`GenerateCellConstraints` like this::
Trans = np.array([ [2/3, 4/3, 1/3], [-1, 0, 0], [-1/3, -2/3, 1/3] ])
T = np.linalg.inv(Trans).T
print([subVals(i,Aold,T) for i in GenerateCellConstraints()])
:param list expr: a list of sympy expressions.
:param list A: This is the A* tensor as defined above.
:param np.array T: a 3x3 transformation matrix where,
Trans = np.array([ [2/3, 4/3, 1/3], [-1, 0, 0], [-1/3, -2/3, 1/3] ])
(for a' = 2/3a + 4/3b + 1/3c; b' = -a; c' = -1/3, -2/3, 1/3)
then T = np.linalg.inv(Trans).T
Note that this is only used to do the symbolic math needed to generate
cell relationships. It is not used normally in GSAS-II.
'''
import sympy as sym
A0, A1, A2, A3, A4, A5 = sym.symbols('A0, A1, A2, A3, A4, A5')
# transformation matrix
T00, T10, T20, T01, T11, T21, T02, T12, T22 = sym.symbols(
'T00, T10, T20, T01, T11, T21, T02, T12, T22')
vals = dict(zip([T00, T10, T20, T01, T11, T21, T02, T12, T22],T.ravel()))
vals.update(dict(zip([A0, A1, A2, A3, A4, A5],A)))
return float(expr.subs(vals))
# some sample test code using the routines above follows::
# Trans = np.array([ [2/3, 4/3, 1/3], [-1, 0, 0], [-1/3, -2/3, 1/3] ])
# Mat = np.linalg.inv(Trans).T
# Aold = [0.05259986634758891, 0.05259986634758891, 0.005290771904550856, 0.052599866347588925, 0, 0]
# Anew = [0.018440738491448085, 0.03944989976069168, 0.034313054205100654, 0, -0.00513684555559103, 0]
# cellConstr = G2lat.GenerateCellConstraints()
# calcA = [G2lat.subVals(i,Aold,Mat) for i in cellConstr]
# print('original xform A',Anew)
# print('calculated xfrom A',calcA)
# print('input')
# print(' old cell',G2lat.A2cell(Aold))
# print(' new cell',G2lat.A2cell(Anew))
# print('derived results')
# print(' from eq.',G2lat.A2cell(calcA))
# print(' diffs ',np.array(G2lat.A2cell(calcA)) - G2lat.A2cell(Anew))
def fmtCellConstraints(cellConstr):
'''Format the cell relationships created in :func:`GenerateCellConstraints`
in a format that can be used to generate constraints.
Use::
cXforms = G2lat.fmtCellConstraints(G2lat.GenerateCellConstraints())
Note that this is only used to do the symbolic math needed to generate
cell relationships. It is not used normally in GSAS-II.
'''
import re
import sympy as sym
A3, A4, A5 = sym.symbols('A3, A4, A5')
consDict = {}
for num,cons in enumerate(cellConstr):
cons = str(cons.factor(A3,A4,A5,deep=True).simplify())
cons = re.sub('T([0-2]?)([0-2]?)',r'T[\2,\1]',cons) # Tij to T[j,i]
l = []
for i in str(cons).split('+'):
if ')' in i:
l[-1] += ' + ' + i.strip()
else:
l.append(i.strip())
print("\nA'{} = ".format(num),str(cons))
consDict[num] = l
return consDict
cellXformRelations = {0: ['1.0*A0*T[0,0]**2',
'1.0*A1*T[0,1]**2',
'1.0*A2*T[0,2]**2',
'1.0*A3*T[0,0]*T[0,1]',
'1.0*A4*T[0,0]*T[0,2]',
'1.0*A5*T[0,1]*T[0,2]'],
1: ['1.0*A0*T[1,0]**2',
'1.0*A1*T[1,1]**2',
'1.0*A2*T[1,2]**2',
'1.0*A3*T[1,0]*T[1,1]',
'1.0*A4*T[1,0]*T[1,2]',
'1.0*A5*T[1,1]*T[1,2]'],
2: ['1.0*A0*T[2,0]**2',
'1.0*A1*T[2,1]**2',
'1.0*A2*T[2,2]**2',
'1.0*A3*T[2,0]*T[2,1]',
'1.0*A4*T[2,0]*T[2,2]',
'1.0*A5*T[2,1]*T[2,2]'],
3: ['2.0*A0*T[0,0]*T[1,0]',
'2.0*A1*T[0,1]*T[1,1]',
'2.0*A2*T[0,2]*T[1,2]',
'1.0*A3*(T[0,0]*T[1,1] + T[1,0]*T[0,1])',
'1.0*A4*(T[0,0]*T[1,2] + T[1,0]*T[0,2])',
'1.0*A5*(T[0,1]*T[1,2] + T[1,1]*T[0,2])'],
4: ['2.0*A0*T[0,0]*T[2,0]',
'2.0*A1*T[0,1]*T[2,1]',
'2.0*A2*T[0,2]*T[2,2]',
'1.0*A3*(T[0,0]*T[2,1] + T[2,0]*T[0,1])',
'1.0*A4*(T[0,0]*T[2,2] + T[2,0]*T[0,2])',
'1.0*A5*(T[0,1]*T[2,2] + T[2,1]*T[0,2])'],
5: ['2.0*A0*T[1,0]*T[2,0]',
'2.0*A1*T[1,1]*T[2,1]',
'2.0*A2*T[1,2]*T[2,2]',
'1.0*A3*(T[1,0]*T[2,1] + T[2,0]*T[1,1])',
'1.0*A4*(T[1,0]*T[2,2] + T[2,0]*T[1,2])',
'1.0*A5*(T[1,1]*T[2,2] + T[2,1]*T[1,2])']}
'''cellXformRelations provide the constraints on newA[i] values for a new
cell generated from oldA[i] values.
'''
# cellXformRelations values were generated using::
# from GSASIIlattice import fmtCellConstraints,GenerateCellConstraints
# cellXformRelations = fmtCellConstraints(GenerateCellConstraints())
def GenCellConstraints(Trans,origPhase,newPhase,origA,oSGLaue,nSGLaue,debug=False):
'''Generate the constraints between two unit cells constants for a phase transformed
by matrix Trans.
:param np.array Trans: a 3x3 direct cell transformation matrix where,
Trans = np.array([ [2/3, 4/3, 1/3], [-1, 0, 0], [-1/3, -2/3, 1/3] ])
(for a' = 2/3a + 4/3b + 1/3c; b' = -a; c' = -1/3, -2/3, 1/3)
:param int origPhase: phase id (pId) for original phase
:param int newPhase: phase id for the transformed phase to be constrained from
original phase
:param list origA: reciprocal cell ("A*") tensor (used for debug only)
:param dict oSGLaue: space group info for original phase
:param dict nSGLaue: space group info for transformed phase
:param bool debug: If true, the constraint input is used to compute and print A*
and from that the direct cell for the transformed phase.
'''
import GSASIIobj as G2obj
T = Mat = np.linalg.inv(Trans).T
Anew = []
constrList = []
uniqueAnew = cellUnique(nSGLaue)
zeroAorig = cellZeros(oSGLaue)
for i in range(6):
constr = [[-1.0,G2obj.G2VarObj('{}::A{}'.format(newPhase,i))]]
mult = []
for j,item in enumerate(cellXformRelations[i]):
const, aTerm, tTerm = item.split('*',2)
const = float(const) * eval(tTerm)
mult.append(const)
# skip over A terms that are required to be zero
if zeroAorig[int(aTerm[1])]: continue # only add non-zero terms
# ignore terms where either the Transform contribution is zero [= abs() < 1e-8]
# If the multiplier term is zero I don't think this accidental
# but since it will not change there is no reason to include that
# term in any case
if abs(const) < 1e-8: continue
constr.append([const,G2obj.G2VarObj('{}::{}'.format(origPhase,aTerm))])
if i in uniqueAnew:
constrList.append(constr + [0.0,None,'c'])
if debug: Anew.append(np.dot(origA,mult))
if debug:
print('xformed A* ',Anew)
print('xformed cell',A2cell(Anew))
return constrList
def cellUnique(SGData):
'''Returns the indices for the unique A tensor terms
based on the Laue class.
Any terms that are determined from others or are zero are not included.
:param dict SGdata: a symmetry object
:returns: a list of 0 to 6 terms with indices of the unique A terms
'''
if SGData['SGLaue'] in ['-1',]:
return [0,1,2,3,4,5]
elif SGData['SGLaue'] in ['2/m',]:
if SGData['SGUniq'] == 'a':
return [0,1,2,5]
elif SGData['SGUniq'] == 'b':
return [0,1,2,4]
else:
return [0,1,2,3]
elif SGData['SGLaue'] in ['mmm',]:
return [0,1,2]
elif SGData['SGLaue'] in ['4/m','4/mmm']:
return [0,2]
elif SGData['SGLaue'] in ['6/m','6/mmm','3m1', '31m', '3']:
return [0,2]
elif SGData['SGLaue'] in ['3R', '3mR']:
return [0,3]
elif SGData['SGLaue'] in ['m3m','m3']:
return [0,]
def cellZeros(SGData):
'''Returns a list with the A terms required to be zero based on Laue symmetry
:param dict SGdata: a symmetry object
:returns: A list of six terms where the values are True if the
A term must be zero, False otherwise.
'''
if SGData['SGLaue'] in ['-1',]:
return 6*[False]
elif SGData['SGLaue'] in ['2/m',]:
if SGData['SGUniq'] == 'a':
return [False,False,False,True,True,False]
elif SGData['SGUniq'] == 'b':
return [False,False,False,True,False,True]
else:
return [False,False,False,False,True,True]
elif SGData['SGLaue'] in ['mmm',]:
return [False,False,False,True,True,True]
elif SGData['SGLaue'] in ['4/m','4/mmm']:
return [False,False,False,True,True,True]
elif SGData['SGLaue'] in ['6/m','6/mmm','3m1', '31m', '3']:
return [False,False,False,False,True,True]
elif SGData['SGLaue'] in ['3R', '3mR']:
return 6*[False]
elif SGData['SGLaue'] in ['m3m','m3']:
return [False,False,False,True,True,True]
def TransformXYZ(XYZ,Trans,Vec):
return np.inner(XYZ,Trans)+Vec
def TransformU6(U6,Trans):
Uij = np.inner(Trans,np.inner(U6toUij(U6),Trans).T)/nl.det(Trans)
return UijtoU6(Uij)
def ExpandCell(Atoms,atCodes,cx,Trans):
Unit = [int(max(abs(np.array(unit)))-1) for unit in Trans.T]
nUnit = (Unit[0]+1)*(Unit[1]+1)*(Unit[2]+1)
Ugrid = np.mgrid[0:Unit[0]+1,0:Unit[1]+1,0:Unit[2]+1]
Ugrid = np.reshape(Ugrid,(3,nUnit)).T
Codes = copy.deepcopy(atCodes)
newAtoms = copy.deepcopy(Atoms)
for unit in Ugrid[1:]:
moreAtoms = copy.deepcopy(Atoms)
for atom in moreAtoms:
atom[cx:cx+3] += unit
newAtoms += moreAtoms
codes = copy.deepcopy(atCodes)
moreCodes = [code+'+%d,%d,%d'%(unit[0],unit[1],unit[2]) for code in codes]
Codes += moreCodes
return newAtoms,Codes
def TransformPhase(oldPhase,newPhase,Trans,Uvec,Vvec,ifMag,Force=True):
'''Transform atoms from oldPhase to newPhase
M' is inv(M)
does X' = M(X-U)+V transformation for coordinates and U' = MUM/det(M)
for anisotropic thermal parameters
:param oldPhase: dict G2 phase info for old phase
:param newPhase: dict G2 phase info for new phase; with new cell & space group
atoms are from oldPhase & will be transformed
:param Trans: lattice transformation matrix M
:param Uvec: array parent coordinates transformation vector U
:param Vvec: array child coordinate transformation vector V
:param ifMag: bool True if convert to magnetic phase;
if True all nonmagnetic atoms will be removed
:return: newPhase dict modified G2 phase info
:return: atCodes list atom transformation codes
'''
cx,ct,cs,cia = oldPhase['General']['AtomPtrs']
cm = 0
if oldPhase['General']['Type'] == 'magnetic':
cm = cx+4
oAmat,oBmat = cell2AB(oldPhase['General']['Cell'][1:7])
nAmat,nBmat = cell2AB(newPhase['General']['Cell'][1:7])
SGData = newPhase['General']['SGData']
invTrans = nl.inv(Trans)
newAtoms,atCodes = FillUnitCell(oldPhase,Force)
newAtoms,atCodes = ExpandCell(newAtoms,atCodes,cx,Trans)
if ifMag:
cia += 3
cs += 3
newPhase['General']['Type'] = 'magnetic'
newPhase['General']['AtomPtrs'] = [cx,ct,cs,cia]
magAtoms = []
magatCodes = []
Landeg = 2.0
for iat,atom in enumerate(newAtoms):
if len(G2elem.GetMFtable([atom[ct],],[Landeg,])):
magAtoms.append(atom[:cx+4]+[0.,0.,0.]+atom[cx+4:])
magatCodes.append(atCodes[iat])
newAtoms = magAtoms
atCodes = magatCodes
newPhase['Draw Atoms'] = []
for atom in newAtoms:
xyz = TransformXYZ(atom[cx:cx+3]+Uvec,invTrans.T,Vvec)
if Force:
xyz = np.around(xyz,6)%1.
atom[cx:cx+3] = xyz
if atom[cia] == 'A':
atom[cia+2:cia+8] = TransformU6(atom[cia+2:cia+8],Trans)
atom[cs:cs+2] = G2spc.SytSym(atom[cx:cx+3],SGData)[:2]
atom[cia+8] = ran.randint(0,sys.maxsize)
if cm:
mag = np.sqrt(np.sum(np.array(atom[cm:cm+3])**2))
if mag:
mom = np.inner(np.array(atom[cm:cm+3]),oBmat)
mom = np.inner(mom,invTrans)
mom = np.inner(mom,nAmat)
mom /= np.sqrt(np.sum(mom**2))
atom[cm:cm+3] = mom*mag
newPhase['Atoms'] = newAtoms
if SGData['SpGrp'] != 'P 1':
newPhase['Atoms'],atCodes = GetUnique(newPhase,atCodes)
newPhase['Drawing'] = []
newPhase['ranId'] = ran.randint(0,sys.maxsize)
return newPhase,atCodes
def FindNonstandard(controls,Phase):
'''
Find nonstandard setting of magnetic cell that aligns with parent nuclear cell
:param controls: list unit cell indexing controls
:param Phase: dict new magnetic phase data (NB:not G2 phase construction); modified here
:return: None
'''
abc = np.eye(3)
cba = np.rot90(np.eye(3))
cba[1,1] *= -1 #makes c-ba
Mats = {'abc':abc,'cab':np.roll(abc,2,1),'bca':np.roll(abc,1,1),
'acb':np.roll(cba,1,1),'bac':np.roll(cba,2,1),'cba':cba} #ok
BNS = {'A':{'abc':'A','cab':'C','bca':'B','acb':'A','bac':'B','cba':'C'},
'B':{'abc':'B','cab':'A','bca':'C','acb':'C','bac':'A','cba':'B'},
'C':{'abc':'C','cab':'B','bca':'A','acb':'B','bac':'C','cba':'A'},
'a':{'abc':'a','cab':'c','bca':'b','acb':'a','bac':'b','cba':'c'}, #Ok
'b':{'abc':'b','cab':'a','bca':'c','acb':'c','bac':'a','cba':'b'},
'c':{'abc':'c','cab':'b','bca':'a','acb':'b','bac':'c','cba':'a'},
'S':{'abc':'S','cab':'S','bca':'S','acb':'S','bac':'S','cba':'S'},
'I':{'abc':'I','cab':'I','bca':'I','acb':'I','bac':'I','cba':'I'},
}
Trans = Phase['Trans']
Uvec = Phase['Uvec']
SGData = Phase['SGData']
MSG = SGData.get('MagSpGrp',SGData['SpGrp']).split(' ',1)
MSG[0] += ' '
bns = ''
if '_' in MSG[0]:
bns = MSG[0][2]
spn = SGData.get('SGSpin',[])
if 'ortho' in SGData['SGSys']:
lattSym = G2spc.getlattSym(Trans)
SpGrp = SGData['SpGrp']
NTrans = np.inner(Mats[lattSym].T,Trans.T) #ok
if len(spn): spn[1:4] = np.inner(np.abs(nl.inv(Mats[lattSym])),spn[1:4]) #ok
SGsym = G2spc.getlattSym(nl.inv(Mats[lattSym]))
if lattSym != 'abc':
NSG = G2spc.altSettingOrtho[SpGrp][SGsym].replace("'",'').split(' ')
if ' '.join(NSG) in ['P 2 21 2',]:
Uvec[1] += .25
elif ' '.join(NSG) in ['P 21 2 2',]:
Uvec[0] += .25
elif ' '.join(NSG) in ['P 2 2 21',]:
Uvec[2] += .25
Bns = ''
if bns:
Bns = BNS[bns][lattSym]
NSG[0] += '_'+Bns+' '
elif len(spn):
for ifld in [1,2,3]:
if spn[ifld] < 0:
NSG[ifld] += "'"
Nresult = [''.join(NSG)+' ',Bns]
return Nresult,Uvec,NTrans
else:
return None
elif 'mono' in SGData['SGSys']: # and not 'P_A' in Phase['Name']: #skip the one that doesn't work
newcell = TransformCell(controls[6:12],Trans)
MatsA = np.array([[1.,0.,0.],[0.,1.,0.],[1.,0,1.]])
MatsB = np.array([[1.,0.,0.],[0.,1.,0.],[-1.,0,1.]])
if not 70. < newcell[4] < 110.:
MSG[1] = MSG[1].replace('c','n')
MSG[0] = MSG[0].replace('C_c','C_B').replace('P_A','P ')
if '_' in MSG[0]:
bns = MSG[0][2]
if newcell[4] > 110.:
if newcell[2] > newcell[0]:
Mats = MatsA
else:
MSG[1] = MSG[1].replace('n','c')
MSG[0] = MSG[0].replace('C ','I ')
Mats = MatsA.T
elif newcell[4] < 70.:
if newcell[2] > newcell[0]:
Mats = MatsB
else:
MSG[1] = MSG[1].replace('n','c')
MSG[0] = MSG[0].replace('C ','I ')
Mats = MatsB.T
Nresult = [' '.join(MSG)+' ',bns]
NTrans = np.inner(Mats,Trans.T)
return Nresult,Uvec,NTrans
return None
def makeBilbaoPhase(result,uvec,trans,ifMag=False):
phase = {}
phase['Name'] = result[0].strip()
phase['Uvec'] = uvec
phase['Trans'] = trans
phase['Keep'] = False
phase['Use'] = False
phase['aType'] = ''
SpGp = result[0].replace("'",'')
SpGrp = G2spc.StandardizeSpcName(SpGp)
phase['SGData'] = G2spc.SpcGroup(SpGrp)[1]
if ifMag:
BNSlatt = phase['SGData']['SGLatt']
if not result[1]:
MSpGrp = G2spc.SplitMagSpSG(result[0])
phase['SGData']['SGSpin'] = G2spc.GetSGSpin(phase['SGData'],MSpGrp)
phase['SGData']['GenSym'],phase['SGData']['GenFlg'],BNSsym = G2spc.GetGenSym(phase['SGData'])
if result[1]:
BNSlatt += '_'+result[1]
if 'P_S' in BNSlatt: BNSlatt = 'P_c' #triclinic fix
phase['SGData']['BNSlattsym'] = [BNSlatt,BNSsym[BNSlatt]]
G2spc.ApplyBNSlatt(phase['SGData'],phase['SGData']['BNSlattsym'])
phase['SGData']['SpnFlp'] = G2spc.GenMagOps(phase['SGData'])[1]
phase['SGData']['MagSpGrp'] = G2spc.MagSGSym(phase['SGData'])
return phase
def FillUnitCell(Phase,Force=True):
Atoms = copy.deepcopy(Phase['Atoms'])
atomData = []
atCodes = []
SGData = Phase['General']['SGData']
SpnFlp = SGData.get('SpnFlp',[])
Amat,Bmat = cell2AB(Phase['General']['Cell'][1:7])
cx,ct,cs,cia = Phase['General']['AtomPtrs']
cm = 0
if Phase['General']['Type'] == 'magnetic':
cm = cx+4
for iat,atom in enumerate(Atoms):
XYZ = np.array(atom[cx:cx+3])
xyz = XYZ
cellj = np.zeros(3,dtype=np.int32)
if Force:
xyz,cellj = G2spc.MoveToUnitCell(xyz)
if atom[cia] == 'A':
Uij = atom[cia+2:cia+8]
result = G2spc.GenAtom(xyz,SGData,False,Uij,Force)
for item in result:
item = list(item)
item[2] += cellj
# if item[0][2] >= .95: item[0][2] -= 1.
atom[cx:cx+3] = item[0]
atom[cia+2:cia+8] = item[1]
if cm:
Opr = abs(item[2])%100
M = SGData['SGOps'][Opr-1][0]
opNum = G2spc.GetOpNum(item[2],SGData)
mom = np.inner(np.array(atom[cm:cm+3]),Bmat)
atom[cm:cm+3] = np.inner(np.inner(mom,M),Amat)*nl.det(M)*SpnFlp[opNum-1]
atCodes.append('%d:%s'%(iat,str(item[2])))
atomData.append(atom[:cia+9]) #not SS stuff
else:
result = G2spc.GenAtom(xyz,SGData,False,Move=Force)
for item in result:
item = list(item)
item[2] += cellj
# if item[0][2] >= .95: item[0][2] -= 1.
atom[cx:cx+3] = item[0]
if cm:
Opr = abs(item[1])%100
M = SGData['SGOps'][Opr-1][0]
opNum = G2spc.GetOpNum(item[1],SGData)
mom = np.inner(np.array(atom[cm:cm+3]),Bmat)
atom[cm:cm+3] = np.inner(np.inner(mom,M),Amat)*nl.det(M)*SpnFlp[opNum-1]
atCodes.append('%d:%s'%(iat,str(item[1])))
atomData.append(atom[:cia+9]) #not SS stuff
return atomData,atCodes
def GetUnique(Phase,atCodes):
def noDuplicate(xyzA,XYZ):
if True in [np.allclose(xyzA%1.,xyzB%1.,atol=0.0002) for xyzB in XYZ]:
return False
return True
cx,ct = Phase['General']['AtomPtrs'][:2]
SGData = Phase['General']['SGData']
Atoms = Phase['Atoms']
Ind = len(Atoms)
newAtoms = []
newAtCodes = []
Indx = {}
XYZ = {}
for ind in range(Ind):
XYZ[ind] = np.array(Atoms[ind][cx:cx+3])%1.
Indx[ind] = True
for ind in range(Ind):
if Indx[ind]:
xyz = XYZ[ind]
for jnd in range(Ind):
if Atoms[ind][ct-1] == Atoms[jnd][ct-1]:
if ind != jnd and Indx[jnd]:
Equiv = G2spc.GenAtom(XYZ[jnd],SGData,Move=True)
xyzs = np.array([equiv[0] for equiv in Equiv])
Indx[jnd] = noDuplicate(xyz,xyzs)
Ind = []
for ind in Indx:
if Indx[ind]:
newAtoms.append(Atoms[ind])
newAtCodes.append(atCodes[ind])
return newAtoms,newAtCodes
def calc_rVsq(A):
"""Compute the square of the reciprocal lattice volume (1/V**2) from A'
"""
G,g = A2Gmat(A)
rVsq = nl.det(G)
if rVsq < 0:
return 1
return rVsq
def calc_rV(A):
"""Compute the reciprocal lattice volume (V*) from A
"""
return np.sqrt(calc_rVsq(A))
def calc_V(A):
"""Compute the real lattice volume (V) from A
"""
return 1./calc_rV(A)
def A2invcell(A):
"""Compute reciprocal unit cell constants from A
returns tuple with a*,b*,c*,alpha*, beta*, gamma* (degrees)
"""
G,g = A2Gmat(A)
return Gmat2cell(G)
def Gmat2AB(G):
"""Computes orthogonalization matrix from reciprocal metric tensor G
:returns: tuple of two 3x3 numpy arrays (A,B)
* A for crystal to Cartesian transformations (A*x = np.inner(A,x) = X)
* B (= inverse of A) for Cartesian to crystal transformation (B*X = np.inner(B,X) = x)
"""
# cellstar = Gmat2cell(G)
g = nl.inv(G)
cell = Gmat2cell(g)
# A = np.zeros(shape=(3,3))
return cell2AB(cell)
# # from Giacovazzo (Fundamentals 2nd Ed.) p.75
# A[0][0] = cell[0] # a
# A[0][1] = cell[1]*cosd(cell[5]) # b cos(gamma)
# A[0][2] = cell[2]*cosd(cell[4]) # c cos(beta)
# A[1][1] = cell[1]*sind(cell[5]) # b sin(gamma)
# A[1][2] = -cell[2]*cosd(cellstar[3])*sind(cell[4]) # - c cos(alpha*) sin(beta)
# A[2][2] = 1./cellstar[2] # 1/c*
# B = nl.inv(A)
# return A,B
def cell2AB(cell,alt=False):
"""Computes orthogonalization matrix from unit cell constants
:param tuple cell: a,b,c, alpha, beta, gamma (degrees)
:returns: tuple of two 3x3 numpy arrays (A,B)
A for crystal to Cartesian transformations A*x = np.inner(A,x) = X
B (= inverse of A) for Cartesian to crystal transformation B*X = np.inner(B,X) = x
both rounded to 12 places (typically zero terms = +/-10e-6 otherwise)
"""
G,g = cell2Gmat(cell)
cellstar = Gmat2cell(G)
A = np.zeros(shape=(3,3))
if alt: #as used in RMCProfile!!
A[0][0] = 1./cellstar[0]
A[0][1] = cell[0]*cosd(cell[5])*sind(cell[3])
A[0][2] = cell[0]*cosd(cell[4])
A[1][1] = cell[1]*sind(cell[3])
A[1][2] = cell[1]*cosd(cell[3])
A[2][2] = cell[2]
A = np.around(A,12)
B = nl.inv(A)
return A,B
# from Giacovazzo (Fundamentals 2nd Ed.) p.75
A[0][0] = cell[0] # a
A[0][1] = cell[1]*cosd(cell[5]) # b cos(gamma)
A[0][2] = cell[2]*cosd(cell[4]) # c cos(beta)
A[1][1] = cell[1]*sind(cell[5]) # b sin(gamma)
A[1][2] = -cell[2]*cosd(cellstar[3])*sind(cell[4]) # - c cos(alpha*) sin(beta)
A[2][2] = 1./cellstar[2] # 1/c*
A = np.around(A,12)
B = nl.inv(A)
return A,B
def HKL2SpAng(H,cell,SGData):
"""Computes spherical coords for hkls; view along 001
:param array H: arrays of hkl
:param tuple cell: a,b,c, alpha, beta, gamma (degrees)
:param dict SGData: space group dictionary
:returns: arrays of r,phi,psi (radius,inclination,azimuth) about 001
"""
A,B = cell2AB(cell)
xH = np.inner(B.T,H)
r = np.sqrt(np.sum(xH**2,axis=0))
phi = acosd(xH[2]/r)
psi = atan2d(xH[1],xH[0])
phi = np.where(phi>90.,180.-phi,phi)
return r,phi,psi
def U6toUij(U6):
"""Fill matrix (Uij) from U6 = [U11,U22,U33,U12,U13,U23]
NB: there is a non numpy version in GSASIIspc: U2Uij
:param list U6: 6 terms of u11,u22,...
:returns:
Uij - numpy [3][3] array of uij
"""
U = np.array([
[U6[0], U6[3], U6[4]],
[U6[3], U6[1], U6[5]],
[U6[4], U6[5], U6[2]]])
return U
def UijtoU6(U):
"""Fill vector [U11,U22,U33,U12,U13,U23] from Uij
NB: there is a non numpy version in GSASIIspc: Uij2U
"""
U6 = np.array([U[0][0],U[1][1],U[2][2],U[0][1],U[0][2],U[1][2]])
return U6
def betaij2Uij(betaij,G):
"""
Convert beta-ij to Uij tensors
:param beta-ij - numpy array [beta-ij]
:param G: reciprocal metric tensor
:returns: Uij: numpy array [Uij]
"""
ast = np.sqrt(np.diag(G)) #a*, b*, c*
Mast = np.multiply.outer(ast,ast)
return R2pisq*UijtoU6(U6toUij(betaij)/Mast)
def Uij2betaij(Uij,G):
"""
Convert Uij to beta-ij tensors -- stub for eventual completion
:param Uij: numpy array [Uij]
:param G: reciprocal metric tensor
:returns: beta-ij - numpy array [beta-ij]
"""
pass