source: trunk/GSASIIlattice.py @ 1244

Last change on this file since 1244 was 1075, checked in by vondreele, 12 years ago

implement new March-Dollase term in MC/SA

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 57.3 KB
Line 
1# -*- coding: utf-8 -*-
2'''
3*GSASIIlattice: Unit cells*
4---------------------------
5
6Perform lattice-related computations
7
8Note that *g* is the reciprocal lattice tensor, and *G* is its inverse,
9:math:`G = g^{-1}`, where
10
11  .. math::
12
13   G = \\left( \\begin{matrix}
14   a^2 & a b\\cos\gamma & a c\\cos\\beta \\\\
15   a b\\cos\\gamma & b^2 & b c \cos\\alpha \\\\
16   a c\\cos\\beta &  b c \\cos\\alpha & c^2
17   \\end{matrix}\\right)
18
19The "*A* tensor" terms are defined as
20:math:`A = (\\begin{matrix} G_{11} & G_{22} & G_{33} & 2G_{12} & 2G_{13} & 2G_{23}\\end{matrix})` and *A* can be used in this fashion:
21:math:`d^* = \sqrt {A_1 h^2 + A_2 k^2 + A_3 l^2 + A_4 hk + A_5 hl + A_6 kl}`, where
22*d* is the d-spacing, and :math:`d^*` is the reciprocal lattice spacing,
23:math:`Q = 2 \\pi d^* = 2 \\pi / d`
24'''
25########### SVN repository information ###################
26# $Date: 2013-10-02 20:42:53 +0000 (Wed, 02 Oct 2013) $
27# $Author: vondreele $
28# $Revision: 1075 $
29# $URL: trunk/GSASIIlattice.py $
30# $Id: GSASIIlattice.py 1075 2013-10-02 20:42:53Z vondreele $
31########### SVN repository information ###################
32import math
33import numpy as np
34import numpy.linalg as nl
35import GSASIIpath
36GSASIIpath.SetVersionNumber("$Revision: 1075 $")
37# trig functions in degrees
38sind = lambda x: np.sin(x*np.pi/180.)
39asind = lambda x: 180.*np.arcsin(x)/np.pi
40tand = lambda x: np.tan(x*np.pi/180.)
41atand = lambda x: 180.*np.arctan(x)/np.pi
42atan2d = lambda y,x: 180.*np.arctan2(y,x)/np.pi
43cosd = lambda x: np.cos(x*np.pi/180.)
44acosd = lambda x: 180.*np.arccos(x)/np.pi
45rdsq2d = lambda x,p: round(1.0/np.sqrt(x),p)
46
47def sec2HMS(sec):
48    """Convert time in sec to H:M:S string
49   
50    :param sec: time in seconds
51    :return: H:M:S string (to nearest 100th second)
52   
53    """
54    H = int(sec/3600)
55    M = int(sec/60-H*60)
56    S = sec-3600*H-60*M
57    return '%d:%2d:%.2f'%(H,M,S)
58   
59def rotdMat(angle,axis=0):
60    """Prepare rotation matrix for angle in degrees about axis(=0,1,2)
61
62    :param angle: angle in degrees
63    :param axis:  axis (0,1,2 = x,y,z) about which for the rotation
64    :return: rotation matrix - 3x3 numpy array
65
66    """
67    if axis == 2:
68        return np.array([[cosd(angle),-sind(angle),0],[sind(angle),cosd(angle),0],[0,0,1]])
69    elif axis == 1:
70        return np.array([[cosd(angle),0,-sind(angle)],[0,1,0],[sind(angle),0,cosd(angle)]])
71    else:
72        return np.array([[1,0,0],[0,cosd(angle),-sind(angle)],[0,sind(angle),cosd(angle)]])
73       
74def rotdMat4(angle,axis=0):
75    """Prepare rotation matrix for angle in degrees about axis(=0,1,2) with scaling for OpenGL
76
77    :param angle: angle in degrees
78    :param axis:  axis (0,1,2 = x,y,z) about which for the rotation
79    :return: rotation matrix - 4x4 numpy array (last row/column for openGL scaling)
80
81    """
82    Mat = rotdMat(angle,axis)
83    return np.concatenate((np.concatenate((Mat,[[0],[0],[0]]),axis=1),[[0,0,0,1],]),axis=0)
84   
85def fillgmat(cell):
86    """Compute lattice metric tensor from unit cell constants
87
88    :param cell: tuple with a,b,c,alpha, beta, gamma (degrees)
89    :return: 3x3 numpy array
90
91    """
92    a,b,c,alp,bet,gam = cell
93    g = np.array([
94        [a*a,  a*b*cosd(gam),  a*c*cosd(bet)],
95        [a*b*cosd(gam),  b*b,  b*c*cosd(alp)],
96        [a*c*cosd(bet) ,b*c*cosd(alp),   c*c]])
97    return g
98           
99def cell2Gmat(cell):
100    """Compute real and reciprocal lattice metric tensor from unit cell constants
101
102    :param cell: tuple with a,b,c,alpha, beta, gamma (degrees)
103    :return: reciprocal (G) & real (g) metric tensors (list of two numpy 3x3 arrays)
104
105    """
106    g = fillgmat(cell)
107    G = nl.inv(g)       
108    return G,g
109
110def A2Gmat(A,inverse=True):
111    """Fill real & reciprocal metric tensor (G) from A.
112
113    :param A: reciprocal metric tensor elements as [G11,G22,G33,2*G12,2*G13,2*G23]
114    :param bool inverse: if True return both G and g; else just G
115    :return: reciprocal (G) & real (g) metric tensors (list of two numpy 3x3 arrays)
116
117    """
118    G = np.zeros(shape=(3,3))
119    G = [
120        [A[0],  A[3]/2.,  A[4]/2.], 
121        [A[3]/2.,A[1],    A[5]/2.], 
122        [A[4]/2.,A[5]/2.,    A[2]]]
123    if inverse:
124        g = nl.inv(G)
125        return G,g
126    else:
127        return G
128
129def Gmat2A(G):
130    """Extract A from reciprocal metric tensor (G)
131
132    :param G: reciprocal maetric tensor (3x3 numpy array
133    :return: A = [G11,G22,G33,2*G12,2*G13,2*G23]
134
135    """
136    return [G[0][0],G[1][1],G[2][2],2.*G[0][1],2.*G[0][2],2.*G[1][2]]
137   
138def cell2A(cell):
139    """Obtain A = [G11,G22,G33,2*G12,2*G13,2*G23] from lattice parameters
140
141    :param cell: [a,b,c,alpha,beta,gamma] (degrees)
142    :return: G reciprocal metric tensor as 3x3 numpy array
143
144    """
145    G,g = cell2Gmat(cell)
146    return Gmat2A(G)
147
148def A2cell(A):
149    """Compute unit cell constants from A
150
151    :param A: [G11,G22,G33,2*G12,2*G13,2*G23] G - reciprocal metric tensor
152    :return: a,b,c,alpha, beta, gamma (degrees) - lattice parameters
153
154    """
155    G,g = A2Gmat(A)
156    return Gmat2cell(g)
157
158def Gmat2cell(g):
159    """Compute real/reciprocal lattice parameters from real/reciprocal metric tensor (g/G)
160    The math works the same either way.
161
162    :param g (or G): real (or reciprocal) metric tensor 3x3 array
163    :return: a,b,c,alpha, beta, gamma (degrees) (or a*,b*,c*,alpha*,beta*,gamma* degrees)
164
165    """
166    oldset = np.seterr('raise')
167    a = np.sqrt(max(0,g[0][0]))
168    b = np.sqrt(max(0,g[1][1]))
169    c = np.sqrt(max(0,g[2][2]))
170    alp = acosd(g[2][1]/(b*c))
171    bet = acosd(g[2][0]/(a*c))
172    gam = acosd(g[0][1]/(a*b))
173    np.seterr(**oldset)
174    return a,b,c,alp,bet,gam
175
176def invcell2Gmat(invcell):
177    """Compute real and reciprocal lattice metric tensor from reciprocal
178       unit cell constants
179       
180    :param invcell: [a*,b*,c*,alpha*, beta*, gamma*] (degrees)
181    :return: reciprocal (G) & real (g) metric tensors (list of two 3x3 arrays)
182
183    """
184    G = fillgmat(invcell)
185    g = nl.inv(G)
186    return G,g
187       
188def calc_rVsq(A):
189    """Compute the square of the reciprocal lattice volume (1/V**2) from A'
190
191    """
192    G,g = A2Gmat(A)
193    rVsq = nl.det(G)
194    if rVsq < 0:
195        return 1
196    return rVsq
197   
198def calc_rV(A):
199    """Compute the reciprocal lattice volume (V*) from A
200    """
201    return np.sqrt(calc_rVsq(A))
202   
203def calc_V(A):
204    """Compute the real lattice volume (V) from A
205    """
206    return 1./calc_rV(A)
207
208def A2invcell(A):
209    """Compute reciprocal unit cell constants from A
210    returns tuple with a*,b*,c*,alpha*, beta*, gamma* (degrees)
211    """
212    G,g = A2Gmat(A)
213    return Gmat2cell(G)
214   
215def Gmat2AB(G):
216    """Computes orthogonalization matrix from reciprocal metric tensor G
217
218    :returns: tuple of two 3x3 numpy arrays (A,B)
219
220       * A for crystal to Cartesian transformations A*x = np.inner(A,x) = X
221       * B (= inverse of A) for Cartesian to crystal transformation B*X = np.inner(B,X) = x
222
223    """
224    cellstar = Gmat2cell(G)
225    g = nl.inv(G)
226    cell = Gmat2cell(g)
227    A = np.zeros(shape=(3,3))
228    # from Giacovazzo (Fundamentals 2nd Ed.) p.75
229    A[0][0] = cell[0]                # a
230    A[0][1] = cell[1]*cosd(cell[5])  # b cos(gamma)
231    A[0][2] = cell[2]*cosd(cell[4])  # c cos(beta)
232    A[1][1] = cell[1]*sind(cell[5])  # b sin(gamma)
233    A[1][2] = -cell[2]*cosd(cellstar[3])*sind(cell[4]) # - c cos(alpha*) sin(beta)
234    A[2][2] = 1/cellstar[2]         # 1/c*
235    B = nl.inv(A)
236    return A,B
237   
238
239def cell2AB(cell):
240    """Computes orthogonalization matrix from unit cell constants
241
242    :param tuple cell: a,b,c, alpha, beta, gamma (degrees)
243    :returns: tuple of two 3x3 numpy arrays (A,B)
244       A for crystal to Cartesian transformations A*x = np.inner(A,x) = X
245       B (= inverse of A) for Cartesian to crystal transformation B*X = np.inner(B,X) = x
246    """
247    G,g = cell2Gmat(cell) 
248    cellstar = Gmat2cell(G)
249    A = np.zeros(shape=(3,3))
250    # from Giacovazzo (Fundamentals 2nd Ed.) p.75
251    A[0][0] = cell[0]                # a
252    A[0][1] = cell[1]*cosd(cell[5])  # b cos(gamma)
253    A[0][2] = cell[2]*cosd(cell[4])  # c cos(beta)
254    A[1][1] = cell[1]*sind(cell[5])  # b sin(gamma)
255    A[1][2] = -cell[2]*cosd(cellstar[3])*sind(cell[4]) # - c cos(alpha*) sin(beta)
256    A[2][2] = 1/cellstar[2]         # 1/c*
257    B = nl.inv(A)
258    return A,B
259   
260def U6toUij(U6):
261    """Fill matrix (Uij) from U6 = [U11,U22,U33,U12,U13,U23]
262    NB: there is a non numpy version in GSASIIspc: U2Uij
263
264    :param list U6: 6 terms of u11,u22,...
265    :returns:
266        Uij - numpy [3][3] array of uij
267    """
268    U = np.array([
269        [U6[0],  U6[3],  U6[4]], 
270        [U6[3],  U6[1],  U6[5]], 
271        [U6[4],  U6[5],  U6[2]]])
272    return U
273
274def UijtoU6(U):
275    """Fill vector [U11,U22,U33,U12,U13,U23] from Uij
276    NB: there is a non numpy version in GSASIIspc: Uij2U
277    """
278    U6 = np.array([U[0][0],U[1][1],U[2][2],U[0][1],U[0][2],U[1][2]])
279    return U6
280
281def Uij2betaij(Uij,G):
282    """
283    Convert Uij to beta-ij tensors -- stub for eventual completion
284   
285    :param Uij: numpy array [Uij]
286    :param G: reciprocal metric tensor
287    :returns: beta-ij - numpy array [beta-ij]
288    """
289    pass
290   
291def cell2GS(cell):
292    ''' returns Uij to betaij conversion matrix'''
293    G,g = cell2Gmat(cell)
294    GS = G
295    GS[0][1] = GS[1][0] = math.sqrt(GS[0][0]*GS[1][1])
296    GS[0][2] = GS[2][0] = math.sqrt(GS[0][0]*GS[2][2])
297    GS[1][2] = GS[2][1] = math.sqrt(GS[1][1]*GS[2][2])
298    return GS   
299   
300def Uij2Ueqv(Uij,GS,Amat):
301    ''' returns 1/3 trace of diagonalized U matrix'''
302    U = np.multiply(U6toUij(Uij),GS)
303    U = np.inner(Amat,np.inner(U,Amat).T)
304    E,R = nl.eigh(U)
305    return np.sum(E)/3.
306       
307def CosAngle(U,V,G):
308    """ calculate cos of angle between U & V in generalized coordinates
309    defined by metric tensor G
310
311    :param U: 3-vectors assume numpy arrays, can be multiple reflections as (N,3) array
312    :param V: 3-vectors assume numpy arrays, only as (3) vector
313    :param G: metric tensor for U & V defined space assume numpy array
314    :returns:
315        cos(phi)
316    """
317    u = (U.T/np.sqrt(np.sum(np.inner(U,G)*U,axis=1))).T
318    v = V/np.sqrt(np.inner(V,np.inner(G,V)))
319    cosP = np.inner(u,np.inner(G,v))
320    return cosP
321   
322def CosSinAngle(U,V,G):
323    """ calculate sin & cos of angle between U & V in generalized coordinates
324    defined by metric tensor G
325
326    :param U: 3-vectors assume numpy arrays
327    :param V: 3-vectors assume numpy arrays
328    :param G: metric tensor for U & V defined space assume numpy array
329    :returns:
330        cos(phi) & sin(phi)
331    """
332    u = U/np.sqrt(np.inner(U,np.inner(G,U)))
333    v = V/np.sqrt(np.inner(V,np.inner(G,V)))
334    cosP = np.inner(u,np.inner(G,v))
335    sinP = np.sqrt(max(0.0,1.0-cosP**2))
336    return cosP,sinP
337   
338def criticalEllipse(prob):
339    """
340    Calculate critical values for probability ellipsoids from probability
341    """
342    if not ( 0.01 <= prob < 1.0):
343        return 1.54 
344    coeff = np.array([6.44988E-09,4.16479E-07,1.11172E-05,1.58767E-04,0.00130554,
345        0.00604091,0.0114921,-0.040301,-0.6337203,1.311582])
346    llpr = math.log(-math.log(prob))
347    return np.polyval(coeff,llpr)
348   
349def CellBlock(nCells):
350    """
351    Generate block of unit cells n*n*n on a side; [0,0,0] centered, n = 2*nCells+1
352    currently only works for nCells = 0 or 1 (not >1)
353    """
354    if nCells:
355        N = 2*nCells+1
356        N2 = N*N
357        N3 = N*N*N
358        cellArray = []
359        A = np.array(range(N3))
360        cellGen = np.array([A/N2-1,A/N%N-1,A%N-1]).T
361        for cell in cellGen:
362            cellArray.append(cell)
363        return cellArray
364    else:
365        return [0,0,0]
366       
367def CellAbsorption(ElList,Volume):
368    '''Compute unit cell absorption
369
370    :param dict ElList: dictionary of element contents including mu and
371      number of atoms be cell
372    :param float Volume: unit cell volume
373    :returns: mu-total/Volume
374    '''
375    muT = 0
376    for El in ElList:
377        muT += ElList[El]['mu']*ElList[El]['FormulaNo']
378    return muT/Volume
379   
380#Permutations and Combinations
381# Four routines: combinations,uniqueCombinations, selections & permutations
382#These taken from Python Cookbook, 2nd Edition. 19.15 p724-726
383#   
384def _combinators(_handle, items, n):
385    """ factored-out common structure of all following combinators """
386    if n==0:
387        yield [ ]
388        return
389    for i, item in enumerate(items):
390        this_one = [ item ]
391        for cc in _combinators(_handle, _handle(items, i), n-1):
392            yield this_one + cc
393def combinations(items, n):
394    """ take n distinct items, order matters """
395    def skipIthItem(items, i):
396        return items[:i] + items[i+1:]
397    return _combinators(skipIthItem, items, n)
398def uniqueCombinations(items, n):
399    """ take n distinct items, order is irrelevant """
400    def afterIthItem(items, i):
401        return items[i+1:]
402    return _combinators(afterIthItem, items, n)
403def selections(items, n):
404    """ take n (not necessarily distinct) items, order matters """
405    def keepAllItems(items, i):
406        return items
407    return _combinators(keepAllItems, items, n)
408def permutations(items):
409    """ take all items, order matters """
410    return combinations(items, len(items))
411
412#reflection generation routines
413#for these: H = [h,k,l]; A is as used in calc_rDsq; G - inv metric tensor, g - metric tensor;
414#           cell - a,b,c,alp,bet,gam in A & deg
415   
416def calc_rDsq(H,A):
417    'needs doc string'
418    rdsq = H[0]*H[0]*A[0]+H[1]*H[1]*A[1]+H[2]*H[2]*A[2]+H[0]*H[1]*A[3]+H[0]*H[2]*A[4]+H[1]*H[2]*A[5]
419    return rdsq
420   
421def calc_rDsq2(H,G):
422    'needs doc string'
423    return np.inner(H,np.inner(G,H))
424   
425def calc_rDsqZ(H,A,Z,tth,lam):
426    'needs doc string'
427    rpd = np.pi/180.
428    rdsq = calc_rDsq(H,A)+Z*sind(tth)*2.0*rpd/lam**2
429    return rdsq
430       
431def MaxIndex(dmin,A):
432    'needs doc string'
433    Hmax = [0,0,0]
434    try:
435        cell = A2cell(A)
436    except:
437        cell = [1,1,1,90,90,90]
438    for i in range(3):
439        Hmax[i] = int(round(cell[i]/dmin))
440    return Hmax
441   
442def sortHKLd(HKLd,ifreverse,ifdup):
443    '''needs doc string
444
445    :param HKLd: a list of [h,k,l,d,...];
446    :param ifreverse: True for largest d first
447    :param ifdup: True if duplicate d-spacings allowed
448    '''
449    T = []
450    for i,H in enumerate(HKLd):
451        if ifdup:
452            T.append((H[3],i))
453        else:
454            T.append(H[3])           
455    D = dict(zip(T,HKLd))
456    T.sort()
457    if ifreverse:
458        T.reverse()
459    X = []
460    okey = ''
461    for key in T: 
462        if key != okey: X.append(D[key])    #remove duplicate d-spacings
463        okey = key
464    return X
465   
466def SwapIndx(Axis,H):
467    'needs doc string'
468    if Axis in [1,-1]:
469        return H
470    elif Axis in [2,-3]:
471        return [H[1],H[2],H[0]]
472    else:
473        return [H[2],H[0],H[1]]
474       
475def Rh2Hx(Rh):
476    'needs doc string'
477    Hx = [0,0,0]
478    Hx[0] = Rh[0]-Rh[1]
479    Hx[1] = Rh[1]-Rh[2]
480    Hx[2] = np.sum(Rh)
481    return Hx
482   
483def Hx2Rh(Hx):
484    'needs doc string'
485    Rh = [0,0,0]
486    itk = -Hx[0]+Hx[1]+Hx[2]
487    if itk%3 != 0:
488        return 0        #error - not rhombohedral reflection
489    else:
490        Rh[1] = itk/3
491        Rh[0] = Rh[1]+Hx[0]
492        Rh[2] = Rh[1]-Hx[1]
493        if Rh[0] < 0:
494            for i in range(3):
495                Rh[i] = -Rh[i]
496        return Rh
497       
498def CentCheck(Cent,H):
499    'needs doc string'
500    h,k,l = H
501    if Cent == 'A' and (k+l)%2:
502        return False
503    elif Cent == 'B' and (h+l)%2:
504        return False
505    elif Cent == 'C' and (h+k)%2:
506        return False
507    elif Cent == 'I' and (h+k+l)%2:
508        return False
509    elif Cent == 'F' and ((h+k)%2 or (h+l)%2 or (k+l)%2):
510        return False
511    elif Cent == 'R' and (-h+k+l)%3:
512        return False
513    else:
514        return True
515                                   
516def GetBraviasNum(center,system):
517    """Determine the Bravais lattice number, as used in GenHBravais
518   
519    :param center: one of: 'P', 'C', 'I', 'F', 'R' (see SGLatt from GSASIIspc.SpcGroup)
520    :param system: one of 'cubic', 'hexagonal', 'tetragonal', 'orthorhombic', 'trigonal' (for R)
521      'monoclinic', 'triclinic' (see SGSys from GSASIIspc.SpcGroup)
522    :return: a number between 0 and 13
523      or throws a ValueError exception if the combination of center, system is not found (i.e. non-standard)
524
525    """
526    if center.upper() == 'F' and system.lower() == 'cubic':
527        return 0
528    elif center.upper() == 'I' and system.lower() == 'cubic':
529        return 1
530    elif center.upper() == 'P' and system.lower() == 'cubic':
531        return 2
532    elif center.upper() == 'R' and system.lower() == 'trigonal':
533        return 3
534    elif center.upper() == 'P' and system.lower() == 'hexagonal':
535        return 4
536    elif center.upper() == 'I' and system.lower() == 'tetragonal':
537        return 5
538    elif center.upper() == 'P' and system.lower() == 'tetragonal':
539        return 6
540    elif center.upper() == 'F' and system.lower() == 'orthorhombic':
541        return 7
542    elif center.upper() == 'I' and system.lower() == 'orthorhombic':
543        return 8
544    elif center.upper() == 'C' and system.lower() == 'orthorhombic':
545        return 9
546    elif center.upper() == 'P' and system.lower() == 'orthorhombic':
547        return 10
548    elif center.upper() == 'C' and system.lower() == 'monoclinic':
549        return 11
550    elif center.upper() == 'P' and system.lower() == 'monoclinic':
551        return 12
552    elif center.upper() == 'P' and system.lower() == 'triclinic':
553        return 13
554    raise ValueError,'non-standard Bravais lattice center=%s, cell=%s' % (center,system)
555
556def GenHBravais(dmin,Bravais,A):
557    """Generate the positionally unique powder diffraction reflections
558     
559    :param dmin: minimum d-spacing in A
560    :param Bravais: lattice type (see GetBraviasNum). Bravais is one of::
561             0 F cubic
562             1 I cubic
563             2 P cubic
564             3 R hexagonal (trigonal not rhombohedral)
565             4 P hexagonal
566             5 I tetragonal
567             6 P tetragonal
568             7 F orthorhombic
569             8 I orthorhombic
570             9 C orthorhombic
571             10 P orthorhombic
572             11 C monoclinic
573             12 P monoclinic
574             13 P triclinic
575           
576    :param A: reciprocal metric tensor elements as [G11,G22,G33,2*G12,2*G13,2*G23]
577    :return: HKL unique d list of [h,k,l,d,-1] sorted with largest d first
578           
579    """
580    import math
581    if Bravais in [9,11]:
582        Cent = 'C'
583    elif Bravais in [1,5,8]:
584        Cent = 'I'
585    elif Bravais in [0,7]:
586        Cent = 'F'
587    elif Bravais in [3]:
588        Cent = 'R'
589    else:
590        Cent = 'P'
591    Hmax = MaxIndex(dmin,A)
592    dminsq = 1./(dmin**2)
593    HKL = []
594    if Bravais == 13:                       #triclinic
595        for l in range(-Hmax[2],Hmax[2]+1):
596            for k in range(-Hmax[1],Hmax[1]+1):
597                hmin = 0
598                if (k < 0): hmin = 1
599                if (k ==0 and l < 0): hmin = 1
600                for h in range(hmin,Hmax[0]+1):
601                    H=[h,k,l]
602                    rdsq = calc_rDsq(H,A)
603                    if 0 < rdsq <= dminsq:
604                        HKL.append([h,k,l,rdsq2d(rdsq,6),-1])
605    elif Bravais in [11,12]:                #monoclinic - b unique
606        Hmax = SwapIndx(2,Hmax)
607        for h in range(Hmax[0]+1):
608            for k in range(-Hmax[1],Hmax[1]+1):
609                lmin = 0
610                if k < 0:lmin = 1
611                for l in range(lmin,Hmax[2]+1):
612                    [h,k,l] = SwapIndx(-2,[h,k,l])
613                    H = []
614                    if CentCheck(Cent,[h,k,l]): H=[h,k,l]
615                    if H:
616                        rdsq = calc_rDsq(H,A)
617                        if 0 < rdsq <= dminsq:
618                            HKL.append([h,k,l,rdsq2d(rdsq,6),-1])
619                    [h,k,l] = SwapIndx(2,[h,k,l])
620    elif Bravais in [7,8,9,10]:            #orthorhombic
621        for h in range(Hmax[0]+1):
622            for k in range(Hmax[1]+1):
623                for l in range(Hmax[2]+1):
624                    H = []
625                    if CentCheck(Cent,[h,k,l]): H=[h,k,l]
626                    if H:
627                        rdsq = calc_rDsq(H,A)
628                        if 0 < rdsq <= dminsq:
629                            HKL.append([h,k,l,rdsq2d(rdsq,6),-1])
630    elif Bravais in [5,6]:                  #tetragonal
631        for l in range(Hmax[2]+1):
632            for k in range(Hmax[1]+1):
633                for h in range(k,Hmax[0]+1):
634                    H = []
635                    if CentCheck(Cent,[h,k,l]): H=[h,k,l]
636                    if H:
637                        rdsq = calc_rDsq(H,A)
638                        if 0 < rdsq <= dminsq:
639                            HKL.append([h,k,l,rdsq2d(rdsq,6),-1])
640    elif Bravais in [3,4]:
641        lmin = 0
642        if Bravais == 3: lmin = -Hmax[2]                  #hexagonal/trigonal
643        for l in range(lmin,Hmax[2]+1):
644            for k in range(Hmax[1]+1):
645                hmin = k
646                if l < 0: hmin += 1
647                for h in range(hmin,Hmax[0]+1):
648                    H = []
649                    if CentCheck(Cent,[h,k,l]): H=[h,k,l]
650                    if H:
651                        rdsq = calc_rDsq(H,A)
652                        if 0 < rdsq <= dminsq:
653                            HKL.append([h,k,l,rdsq2d(rdsq,6),-1])
654
655    else:                                   #cubic
656        for l in range(Hmax[2]+1):
657            for k in range(l,Hmax[1]+1):
658                for h in range(k,Hmax[0]+1):
659                    H = []
660                    if CentCheck(Cent,[h,k,l]): H=[h,k,l]
661                    if H:
662                        rdsq = calc_rDsq(H,A)
663                        if 0 < rdsq <= dminsq:
664                            HKL.append([h,k,l,rdsq2d(rdsq,6),-1])
665    return sortHKLd(HKL,True,False)
666   
667def getHKLmax(dmin,SGData,A):
668    'finds maximum allowed hkl for given A within dmin'
669    SGLaue = SGData['SGLaue']
670    if SGLaue in ['3R','3mR']:        #Rhombohedral axes
671        Hmax = [0,0,0]
672        cell = A2cell(A)
673        aHx = cell[0]*math.sqrt(2.0*(1.0-cosd(cell[3])))
674        cHx = cell[0]*math.sqrt(3.0*(1.0+2.0*cosd(cell[3])))
675        Hmax[0] = Hmax[1] = int(round(aHx/dmin))
676        Hmax[2] = int(round(cHx/dmin))
677        #print Hmax,aHx,cHx
678    else:                           # all others
679        Hmax = MaxIndex(dmin,A)
680    return Hmax
681   
682def GenHLaue(dmin,SGData,A):
683    """Generate the crystallographically unique powder diffraction reflections
684    for a lattice and Bravais type
685   
686    :param dmin: minimum d-spacing
687    :param SGData: space group dictionary with at least
688   
689        * 'SGLaue': Laue group symbol: one of '-1','2/m','mmm','4/m','6/m','4/mmm','6/mmm', '3m1', '31m', '3', '3R', '3mR', 'm3', 'm3m'
690        * 'SGLatt': lattice centering: one of 'P','A','B','C','I','F'
691        * 'SGUniq': code for unique monoclinic axis one of 'a','b','c' (only if 'SGLaue' is '2/m') otherwise an empty string
692       
693    :param A: reciprocal metric tensor elements as [G11,G22,G33,2*G12,2*G13,2*G23]
694    :return: HKL = list of [h,k,l,d] sorted with largest d first and is unique
695            part of reciprocal space ignoring anomalous dispersion
696           
697    """
698    import math
699    SGLaue = SGData['SGLaue']
700    SGLatt = SGData['SGLatt']
701    SGUniq = SGData['SGUniq']
702    #finds maximum allowed hkl for given A within dmin
703    Hmax = getHKLmax(dmin,SGData,A)
704       
705    dminsq = 1./(dmin**2)
706    HKL = []
707    if SGLaue == '-1':                       #triclinic
708        for l in range(-Hmax[2],Hmax[2]+1):
709            for k in range(-Hmax[1],Hmax[1]+1):
710                hmin = 0
711                if (k < 0) or (k ==0 and l < 0): hmin = 1
712                for h in range(hmin,Hmax[0]+1):
713                    H = []
714                    if CentCheck(SGLatt,[h,k,l]): H=[h,k,l]
715                    if H:
716                        rdsq = calc_rDsq(H,A)
717                        if 0 < rdsq <= dminsq:
718                            HKL.append([h,k,l,1/math.sqrt(rdsq)])
719    elif SGLaue == '2/m':                #monoclinic
720        axisnum = 1 + ['a','b','c'].index(SGUniq)
721        Hmax = SwapIndx(axisnum,Hmax)
722        for h in range(Hmax[0]+1):
723            for k in range(-Hmax[1],Hmax[1]+1):
724                lmin = 0
725                if k < 0:lmin = 1
726                for l in range(lmin,Hmax[2]+1):
727                    [h,k,l] = SwapIndx(-axisnum,[h,k,l])
728                    H = []
729                    if CentCheck(SGLatt,[h,k,l]): H=[h,k,l]
730                    if H:
731                        rdsq = calc_rDsq(H,A)
732                        if 0 < rdsq <= dminsq:
733                            HKL.append([h,k,l,1/math.sqrt(rdsq)])
734                    [h,k,l] = SwapIndx(axisnum,[h,k,l])
735    elif SGLaue in ['mmm','4/m','6/m']:            #orthorhombic
736        for l in range(Hmax[2]+1):
737            for h in range(Hmax[0]+1):
738                kmin = 1
739                if SGLaue == 'mmm' or h ==0: kmin = 0
740                for k in range(kmin,Hmax[1]+1):
741                    H = []
742                    if CentCheck(SGLatt,[h,k,l]): H=[h,k,l]
743                    if H:
744                        rdsq = calc_rDsq(H,A)
745                        if 0 < rdsq <= dminsq:
746                            HKL.append([h,k,l,1/math.sqrt(rdsq)])
747    elif SGLaue in ['4/mmm','6/mmm']:                  #tetragonal & hexagonal
748        for l in range(Hmax[2]+1):
749            for h in range(Hmax[0]+1):
750                for k in range(h+1):
751                    H = []
752                    if CentCheck(SGLatt,[h,k,l]): H=[h,k,l]
753                    if H:
754                        rdsq = calc_rDsq(H,A)
755                        if 0 < rdsq <= dminsq:
756                            HKL.append([h,k,l,1/math.sqrt(rdsq)])
757    elif SGLaue in ['3m1','31m','3','3R','3mR']:                  #trigonals
758        for l in range(-Hmax[2],Hmax[2]+1):
759            hmin = 0
760            if l < 0: hmin = 1
761            for h in range(hmin,Hmax[0]+1):
762                if SGLaue in ['3R','3']:
763                    kmax = h
764                    kmin = -int((h-1.)/2.)
765                else:
766                    kmin = 0
767                    kmax = h
768                    if SGLaue in ['3m1','3mR'] and l < 0: kmax = h-1
769                    if SGLaue == '31m' and l < 0: kmin = 1
770                for k in range(kmin,kmax+1):
771                    H = []
772                    if CentCheck(SGLatt,[h,k,l]): H=[h,k,l]
773                    if SGLaue in ['3R','3mR']:
774                        H = Hx2Rh(H)
775                    if H:
776                        rdsq = calc_rDsq(H,A)
777                        if 0 < rdsq <= dminsq:
778                            HKL.append([H[0],H[1],H[2],1/math.sqrt(rdsq)])
779    else:                                   #cubic
780        for h in range(Hmax[0]+1):
781            for k in range(h+1):
782                lmin = 0
783                lmax = k
784                if SGLaue =='m3':
785                    lmax = h-1
786                    if h == k: lmax += 1
787                for l in range(lmin,lmax+1):
788                    H = []
789                    if CentCheck(SGLatt,[h,k,l]): H=[h,k,l]
790                    if H:
791                        rdsq = calc_rDsq(H,A)
792                        if 0 < rdsq <= dminsq:
793                            HKL.append([h,k,l,1/math.sqrt(rdsq)])
794    return sortHKLd(HKL,True,True)
795
796#Spherical harmonics routines
797def OdfChk(SGLaue,L,M):
798    'needs doc string'
799    if not L%2 and abs(M) <= L:
800        if SGLaue == '0':                      #cylindrical symmetry
801            if M == 0: return True
802        elif SGLaue == '-1':
803            return True
804        elif SGLaue == '2/m':
805            if not abs(M)%2: return True
806        elif SGLaue == 'mmm':
807            if not abs(M)%2 and M >= 0: return True
808        elif SGLaue == '4/m':
809            if not abs(M)%4: return True
810        elif SGLaue == '4/mmm':
811            if not abs(M)%4 and M >= 0: return True
812        elif SGLaue in ['3R','3']:
813            if not abs(M)%3: return True
814        elif SGLaue in ['3mR','3m1','31m']:
815            if not abs(M)%3 and M >= 0: return True
816        elif SGLaue == '6/m':
817            if not abs(M)%6: return True
818        elif SGLaue == '6/mmm':
819            if not abs(M)%6 and M >= 0: return True
820        elif SGLaue == 'm3':
821            if M > 0:
822                if L%12 == 2:
823                    if M <= L/12: return True
824                else:
825                    if M <= L/12+1: return True
826        elif SGLaue == 'm3m':
827            if M > 0:
828                if L%12 == 2:
829                    if M <= L/12: return True
830                else:
831                    if M <= L/12+1: return True
832    return False
833       
834def GenSHCoeff(SGLaue,SamSym,L,IfLMN=True):
835    'needs doc string'
836    coeffNames = []
837    for iord in [2*i+2 for i in range(L/2)]:
838        for m in [i-iord for i in range(2*iord+1)]:
839            if OdfChk(SamSym,iord,m):
840                for n in [i-iord for i in range(2*iord+1)]:
841                    if OdfChk(SGLaue,iord,n):
842                        if IfLMN:
843                            coeffNames.append('C(%d,%d,%d)'%(iord,m,n))
844                        else:
845                            coeffNames.append('C(%d,%d)'%(iord,n))
846    return coeffNames
847   
848def CrsAng(H,cell,SGData):
849    'needs doc string'
850    a,b,c,al,be,ga = cell
851    SQ3 = 1.732050807569
852    H1 = np.array([1,0,0])
853    H2 = np.array([0,1,0])
854    H3 = np.array([0,0,1])
855    H4 = np.array([1,1,1])
856    G,g = cell2Gmat(cell)
857    Laue = SGData['SGLaue']
858    Naxis = SGData['SGUniq']
859    DH = np.inner(H,np.inner(G,H))
860    if Laue == '2/m':
861        if Naxis == 'a':
862            DR = np.inner(H1,np.inner(G,H1))
863            DHR = np.inner(H,np.inner(G,H1))
864        elif Naxis == 'b':
865            DR = np.inner(H2,np.inner(G,H2))
866            DHR = np.inner(H,np.inner(G,H2))
867        else:
868            DR = np.inner(H3,np.inner(G,H3))
869            DHR = np.inner(H,np.inner(G,H3))
870    elif Laue in ['R3','R3m']:
871        DR = np.inner(H4,np.inner(G,H4))
872        DHR = np.inner(H,np.inner(G,H4))
873       
874    else:
875        DR = np.inner(H3,np.inner(G,H3))
876        DHR = np.inner(H,np.inner(G,H3))
877    DHR /= np.sqrt(DR*DH)
878    phi = np.where(DHR <= 1.0,acosd(DHR),0.0)
879    if Laue == '-1':
880        BA = H[1]*a/(b-H[0]*cosd(ga))
881        BB = H[0]*sind(ga)**2
882    elif Laue == '2/m':
883        if Naxis == 'a':
884            BA = H[2]*b/(c-H[1]*cosd(al))
885            BB = H[1]*sind(al)**2
886        elif Naxis == 'b':
887            BA = H[0]*c/(a-H[2]*cosd(be))
888            BB = H[2]*sind(be)**2
889        else:
890            BA = H[1]*a/(b-H[0]*cosd(ga))
891            BB = H[0]*sind(ga)**2
892    elif Laue in ['mmm','4/m','4/mmm']:
893        BA = H[1]*a
894        BB = H[0]*b
895   
896    elif Laue in ['3R','3mR']:
897        BA = H[0]+H[1]-2.0*H[2]
898        BB = SQ3*(H[0]-H[1])
899    elif Laue in ['m3','m3m']:
900        BA = H[1]
901        BB = H[0]
902    else:
903        BA = H[0]+2.0*H[1]
904        BB = SQ3*H[0]
905    beta = atan2d(BA,BB)
906    return phi,beta
907   
908def SamAng(Tth,Gangls,Sangl,IFCoup):
909    """Compute sample orientation angles vs laboratory coord. system
910
911    :param Tth:        Signed theta                                   
912    :param Gangls:     Sample goniometer angles phi,chi,omega,azmuth 
913    :param Sangl:      Sample angle zeros om-0, chi-0, phi-0         
914    :param IFCoup:     True if omega & 2-theta coupled in CW scan
915    :returns: 
916        psi,gam:    Sample odf angles                             
917        dPSdA,dGMdA:    Angle zero derivatives
918    """                         
919   
920    rpd = math.pi/180.
921    if IFCoup:
922        GSomeg = sind(Gangls[2]+Tth)
923        GComeg = cosd(Gangls[2]+Tth)
924    else:
925        GSomeg = sind(Gangls[2])
926        GComeg = cosd(Gangls[2])
927    GSTth = sind(Tth)
928    GCTth = cosd(Tth)     
929    GSazm = sind(Gangls[3])
930    GCazm = cosd(Gangls[3])
931    GSchi = sind(Gangls[1])
932    GCchi = cosd(Gangls[1])
933    GSphi = sind(Gangls[0]+Sangl[2])
934    GCphi = cosd(Gangls[0]+Sangl[2])
935    SSomeg = sind(Sangl[0])
936    SComeg = cosd(Sangl[0])
937    SSchi = sind(Sangl[1])
938    SCchi = cosd(Sangl[1])
939    AT = -GSTth*GComeg+GCTth*GCazm*GSomeg
940    BT = GSTth*GSomeg+GCTth*GCazm*GComeg
941    CT = -GCTth*GSazm*GSchi
942    DT = -GCTth*GSazm*GCchi
943   
944    BC1 = -AT*GSphi+(CT+BT*GCchi)*GCphi
945    BC2 = DT-BT*GSchi
946    BC3 = AT*GCphi+(CT+BT*GCchi)*GSphi
947     
948    BC = BC1*SComeg*SCchi+BC2*SComeg*SSchi-BC3*SSomeg     
949    psi = acosd(BC)
950   
951    BD = 1.0-BC**2
952    if BD > 0.:
953        C = rpd/math.sqrt(BD)
954    else:
955        C = 0.
956    dPSdA = [-C*(-BC1*SSomeg*SCchi-BC2*SSomeg*SSchi-BC3*SComeg),
957        -C*(-BC1*SComeg*SSchi+BC2*SComeg*SCchi),
958        -C*(-BC1*SSomeg-BC3*SComeg*SCchi)]
959     
960    BA = -BC1*SSchi+BC2*SCchi
961    BB = BC1*SSomeg*SCchi+BC2*SSomeg*SSchi+BC3*SComeg
962    gam = atan2d(BB,BA)
963
964    BD = (BA**2+BB**2)/rpd
965
966    dBAdO = 0
967    dBAdC = -BC1*SCchi-BC2*SSchi
968    dBAdF = BC3*SSchi
969   
970    dBBdO = BC1*SComeg*SCchi+BC2*SComeg*SSchi-BC3*SSomeg
971    dBBdC = -BC1*SSomeg*SSchi+BC2*SSomeg*SCchi
972    dBBdF = BC1*SComeg-BC3*SSomeg*SCchi
973   
974    if BD > 0.:
975        dGMdA = [(BA*dBBdO-BB*dBAdO)/BD,(BA*dBBdC-BB*dBAdC)/BD,(BA*dBBdF-BB*dBAdF)/BD]
976    else:
977        dGMdA = [0.0,0.0,0.0]
978
979       
980    return psi,gam,dPSdA,dGMdA
981
982BOH = {
983'L=2':[[],[],[]],
984'L=4':[[0.30469720,0.36418281],[],[]],
985'L=6':[[-0.14104740,0.52775103],[],[]],
986'L=8':[[0.28646862,0.21545346,0.32826995],[],[]],
987'L=10':[[-0.16413497,0.33078546,0.39371345],[],[]],
988'L=12':[[0.26141975,0.27266871,0.03277460,0.32589402],
989    [0.09298802,-0.23773812,0.49446631,0.0],[]],
990'L=14':[[-0.17557309,0.25821932,0.27709173,0.33645360],[],[]],
991'L=16':[[0.24370673,0.29873515,0.06447688,0.00377,0.32574495],
992    [0.12039646,-0.25330128,0.23950998,0.40962508,0.0],[]],
993'L=18':[[-0.16914245,0.17017340,0.34598142,0.07433932,0.32696037],
994    [-0.06901768,0.16006562,-0.24743528,0.47110273,0.0],[]],
995'L=20':[[0.23067026,0.31151832,0.09287682,0.01089683,0.00037564,0.32573563],
996    [0.13615420,-0.25048007,0.12882081,0.28642879,0.34620433,0.0],[]],
997'L=22':[[-0.16109560,0.10244188,0.36285175,0.13377513,0.01314399,0.32585583],
998    [-0.09620055,0.20244115,-0.22389483,0.17928946,0.42017231,0.0],[]],
999'L=24':[[0.22050742,0.31770654,0.11661736,0.02049853,0.00150861,0.00003426,0.32573505],
1000    [0.13651722,-0.21386648,0.00522051,0.33939435,0.10837396,0.32914497,0.0],
1001    [0.05378596,-0.11945819,0.16272298,-0.26449730,0.44923956,0.0,0.0]],
1002'L=26':[[-0.15435003,0.05261630,0.35524646,0.18578869,0.03259103,0.00186197,0.32574594],
1003    [-0.11306511,0.22072681,-0.18706142,0.05439948,0.28122966,0.35634355,0.0],[]],
1004'L=28':[[0.21225019,0.32031716,0.13604702,0.03132468,0.00362703,0.00018294,0.00000294,0.32573501],
1005    [0.13219496,-0.17206256,-0.08742608,0.32671661,0.17973107,0.02567515,0.32619598,0.0],
1006    [0.07989184,-0.16735346,0.18839770,-0.20705337,0.12926808,0.42715602,0.0,0.0]],
1007'L=30':[[-0.14878368,0.01524973,0.33628434,0.22632587,0.05790047,0.00609812,0.00022898,0.32573594],
1008    [-0.11721726,0.20915005,-0.11723436,-0.07815329,0.31318947,0.13655742,0.33241385,0.0],
1009    [-0.04297703,0.09317876,-0.11831248,0.17355132,-0.28164031,0.42719361,0.0,0.0]],
1010'L=32':[[0.20533892,0.32087437,0.15187897,0.04249238,0.00670516,0.00054977,0.00002018,0.00000024,0.32573501],
1011    [0.12775091,-0.13523423,-0.14935701,0.28227378,0.23670434,0.05661270,0.00469819,0.32578978,0.0],
1012    [0.09703829,-0.19373733,0.18610682,-0.14407046,0.00220535,0.26897090,0.36633402,0.0,0.0]],
1013'L=34':[[-0.14409234,-0.01343681,0.31248977,0.25557722,0.08571889,0.01351208,0.00095792,0.00002550,0.32573508],
1014    [-0.11527834,0.18472133,-0.04403280,-0.16908618,0.27227021,0.21086614,0.04041752,0.32688152,0.0],
1015    [-0.06773139,0.14120811,-0.15835721,0.18357456,-0.19364673,0.08377174,0.43116318,0.0,0.0]]
1016}
1017
1018Lnorm = lambda L: 4.*np.pi/(2.0*L+1.)
1019
1020def GetKcl(L,N,SGLaue,phi,beta):
1021    'needs doc string'
1022    import pytexture as ptx
1023    RSQ2PI = 0.3989422804014
1024    SQ2 = 1.414213562373
1025    if SGLaue in ['m3','m3m']:
1026        Kcl = 0.0
1027        for j in range(0,L+1,4):
1028            im = j/4+1
1029            pcrs,dum = ptx.pyplmpsi(L,j,1,phi)
1030            Kcl += BOH['L='+str(L)][N-1][im-1]*pcrs*cosd(j*beta)       
1031    else:
1032        pcrs,dum = ptx.pyplmpsi(L,N,1,phi)
1033        pcrs *= RSQ2PI
1034        if N:
1035            pcrs *= SQ2
1036        if SGLaue in ['mmm','4/mmm','6/mmm','R3mR','3m1','31m']:
1037            if SGLaue in ['3mR','3m1','31m']: 
1038                if N%6 == 3:
1039                    Kcl = pcrs*sind(N*beta)
1040                else:
1041                    Kcl = pcrs*cosd(N*beta)
1042            else:
1043                Kcl = pcrs*cosd(N*beta)
1044        else:
1045            Kcl = pcrs*(cosd(N*beta)+sind(N*beta))
1046    return Kcl
1047   
1048def GetKsl(L,M,SamSym,psi,gam):
1049    'needs doc string'
1050    import pytexture as ptx
1051    RSQPI = 0.5641895835478
1052    SQ2 = 1.414213562373
1053    psrs,dpdps = ptx.pyplmpsi(L,M,1,psi)
1054    psrs *= RSQPI
1055    dpdps *= RSQPI
1056    if M == 0:
1057        psrs /= SQ2
1058        dpdps /= SQ2
1059    if SamSym in ['mmm',]:
1060        dum = cosd(M*gam)
1061        Ksl = psrs*dum
1062        dKsdp = dpdps*dum
1063        dKsdg = -psrs*M*sind(M*gam)
1064    else:
1065        dum = cosd(M*gam)+sind(M*gam)
1066        Ksl = psrs*dum
1067        dKsdp = dpdps*dum
1068        dKsdg = psrs*M*(-sind(M*gam)+cosd(M*gam))
1069    return Ksl,dKsdp,dKsdg
1070   
1071def GetKclKsl(L,N,SGLaue,psi,phi,beta):
1072    """
1073    This is used for spherical harmonics description of preferred orientation;
1074        cylindrical symmetry only (M=0) and no sample angle derivatives returned
1075    """
1076    import pytexture as ptx
1077    RSQ2PI = 0.3989422804014
1078    SQ2 = 1.414213562373
1079    Ksl,x = ptx.pyplmpsi(L,0,1,psi)
1080    Ksl *= RSQ2PI
1081    if SGLaue in ['m3','m3m']:
1082        Kcl = 0.0
1083        for j in range(0,L+1,4):
1084            im = j/4+1
1085            pcrs,dum = ptx.pyplmpsi(L,j,1,phi)
1086            Kcl += BOH['L='+str(L)][N-1][im-1]*pcrs*cosd(j*beta)       
1087    else:
1088        pcrs,dum = ptx.pyplmpsi(L,N,1,phi)
1089        pcrs *= RSQ2PI
1090        if N:
1091            pcrs *= SQ2
1092        if SGLaue in ['mmm','4/mmm','6/mmm','R3mR','3m1','31m']:
1093            if SGLaue in ['3mR','3m1','31m']: 
1094                if N%6 == 3:
1095                    Kcl = pcrs*sind(N*beta)
1096                else:
1097                    Kcl = pcrs*cosd(N*beta)
1098            else:
1099                Kcl = pcrs*cosd(N*beta)
1100        else:
1101            Kcl = pcrs*(cosd(N*beta)+sind(N*beta))
1102    return Kcl*Ksl,Lnorm(L)
1103   
1104def Glnh(Start,SHCoef,psi,gam,SamSym):
1105    'needs doc string'
1106    import pytexture as ptx
1107    RSQPI = 0.5641895835478
1108    SQ2 = 1.414213562373
1109
1110    if Start:
1111        ptx.pyqlmninit()
1112        Start = False
1113    Fln = np.zeros(len(SHCoef))
1114    for i,term in enumerate(SHCoef):
1115        l,m,n = eval(term.strip('C'))
1116        pcrs,dum = ptx.pyplmpsi(l,m,1,psi)
1117        pcrs *= RSQPI
1118        if m == 0:
1119            pcrs /= SQ2
1120        if SamSym in ['mmm',]:
1121            Ksl = pcrs*cosd(m*gam)
1122        else:
1123            Ksl = pcrs*(cosd(m*gam)+sind(m*gam))
1124        Fln[i] = SHCoef[term]*Ksl*Lnorm(l)
1125    ODFln = dict(zip(SHCoef.keys(),list(zip(SHCoef.values(),Fln))))
1126    return ODFln
1127
1128def Flnh(Start,SHCoef,phi,beta,SGData):
1129    'needs doc string'
1130    import pytexture as ptx
1131   
1132    FORPI = 12.5663706143592
1133    RSQPI = 0.5641895835478
1134    SQ2 = 1.414213562373
1135
1136    if Start:
1137        ptx.pyqlmninit()
1138        Start = False
1139    Fln = np.zeros(len(SHCoef))
1140    for i,term in enumerate(SHCoef):
1141        l,m,n = eval(term.strip('C'))
1142        if SGData['SGLaue'] in ['m3','m3m']:
1143            Kcl = 0.0
1144            for j in range(0,l+1,4):
1145                im = j/4+1
1146                pcrs,dum = ptx.pyplmpsi(l,j,1,phi)
1147                Kcl += BOH['L='+str(l)][n-1][im-1]*pcrs*cosd(j*beta)       
1148        else:                #all but cubic
1149            pcrs,dum = ptx.pyplmpsi(l,n,1,phi)
1150            pcrs *= RSQPI
1151            if n == 0:
1152                pcrs /= SQ2
1153            if SGData['SGLaue'] in ['mmm','4/mmm','6/mmm','R3mR','3m1','31m']:
1154               if SGData['SGLaue'] in ['3mR','3m1','31m']: 
1155                   if n%6 == 3:
1156                       Kcl = pcrs*sind(n*beta)
1157                   else:
1158                       Kcl = pcrs*cosd(n*beta)
1159               else:
1160                   Kcl = pcrs*cosd(n*beta)
1161            else:
1162                Kcl = pcrs*(cosd(n*beta)+sind(n*beta))
1163        Fln[i] = SHCoef[term]*Kcl*Lnorm(l)
1164    ODFln = dict(zip(SHCoef.keys(),list(zip(SHCoef.values(),Fln))))
1165    return ODFln
1166   
1167def polfcal(ODFln,SamSym,psi,gam):
1168    'needs doc string'
1169    import pytexture as ptx
1170    RSQPI = 0.5641895835478
1171    SQ2 = 1.414213562373
1172    PolVal = np.ones_like(gam)
1173    for term in ODFln:
1174        if abs(ODFln[term][1]) > 1.e-3:
1175            l,m,n = eval(term.strip('C'))
1176            psrs,dum = ptx.pyplmpsi(l,m,len(psi),psi)
1177            if SamSym in ['-1','2/m']:
1178                if m != 0:
1179                    Ksl = RSQPI*psrs*(cosd(m*gam)+sind(m*gam))
1180                else:
1181                    Ksl = RSQPI*psrs/SQ2
1182            else:
1183                if m != 0:
1184                    Ksl = RSQPI*psrs*cosd(m*gam)
1185                else:
1186                    Ksl = RSQPI*psrs/SQ2
1187            PolVal += ODFln[term][1]*Ksl
1188    return PolVal
1189   
1190def invpolfcal(ODFln,SGData,phi,beta):
1191    'needs doc string'
1192    import pytexture as ptx
1193   
1194    FORPI = 12.5663706143592
1195    RSQPI = 0.5641895835478
1196    SQ2 = 1.414213562373
1197
1198    invPolVal = np.ones_like(beta)
1199    for term in ODFln:
1200        if abs(ODFln[term][1]) > 1.e-3:
1201            l,m,n = eval(term.strip('C'))
1202            if SGData['SGLaue'] in ['m3','m3m']:
1203                Kcl = 0.0
1204                for j in range(0,l+1,4):
1205                    im = j/4+1
1206                    pcrs,dum = ptx.pyplmpsi(l,j,len(beta),phi)
1207                    Kcl += BOH['L='+str(l)][n-1][im-1]*pcrs*cosd(j*beta)       
1208            else:                #all but cubic
1209                pcrs,dum = ptx.pyplmpsi(l,n,len(beta),phi)
1210                pcrs *= RSQPI
1211                if n == 0:
1212                    pcrs /= SQ2
1213                if SGData['SGLaue'] in ['mmm','4/mmm','6/mmm','R3mR','3m1','31m']:
1214                   if SGData['SGLaue'] in ['3mR','3m1','31m']: 
1215                       if n%6 == 3:
1216                           Kcl = pcrs*sind(n*beta)
1217                       else:
1218                           Kcl = pcrs*cosd(n*beta)
1219                   else:
1220                       Kcl = pcrs*cosd(n*beta)
1221                else:
1222                    Kcl = pcrs*(cosd(n*beta)+sind(n*beta))
1223            invPolVal += ODFln[term][1]*Kcl
1224    return invPolVal
1225   
1226   
1227def textureIndex(SHCoef):
1228    'needs doc string'
1229    Tindx = 1.0
1230    for term in SHCoef:
1231        l = eval(term.strip('C'))[0]
1232        Tindx += SHCoef[term]**2/(2.0*l+1.)
1233    return Tindx
1234   
1235# self-test materials follow.
1236selftestlist = []
1237'''Defines a list of self-tests'''
1238selftestquiet = True
1239def _ReportTest():
1240    'Report name and doc string of current routine when ``selftestquiet`` is False'
1241    if not selftestquiet:
1242        import inspect
1243        caller = inspect.stack()[1][3]
1244        doc = eval(caller).__doc__
1245        if doc is not None:
1246            print('testing '+__file__+' with '+caller+' ('+doc+')')
1247        else:
1248            print('testing '+__file__()+" with "+caller)
1249NeedTestData = True
1250def TestData():
1251    array = np.array
1252    global NeedTestData
1253    NeedTestData = False
1254    global CellTestData
1255    # output from uctbx computed on platform darwin on 2010-05-28
1256    CellTestData = [
1257# cell, g, G, cell*, V, V*
1258  [(4, 4, 4, 90, 90, 90), 
1259   array([[  1.60000000e+01,   9.79717439e-16,   9.79717439e-16],
1260       [  9.79717439e-16,   1.60000000e+01,   9.79717439e-16],
1261       [  9.79717439e-16,   9.79717439e-16,   1.60000000e+01]]), array([[  6.25000000e-02,   3.82702125e-18,   3.82702125e-18],
1262       [  3.82702125e-18,   6.25000000e-02,   3.82702125e-18],
1263       [  3.82702125e-18,   3.82702125e-18,   6.25000000e-02]]), (0.25, 0.25, 0.25, 90.0, 90.0, 90.0), 64.0, 0.015625],
1264# cell, g, G, cell*, V, V*
1265  [(4.0999999999999996, 5.2000000000000002, 6.2999999999999998, 100, 80, 130), 
1266   array([[ 16.81      , -13.70423184,   4.48533243],
1267       [-13.70423184,  27.04      ,  -5.6887143 ],
1268       [  4.48533243,  -5.6887143 ,  39.69      ]]), array([[ 0.10206349,  0.05083339, -0.00424823],
1269       [ 0.05083339,  0.06344997,  0.00334956],
1270       [-0.00424823,  0.00334956,  0.02615544]]), (0.31947376387537696, 0.25189277536327803, 0.16172643497798223, 85.283666420376008, 94.716333579624006, 50.825714168082683), 100.98576357983838, 0.0099023858863968445],
1271# cell, g, G, cell*, V, V*
1272  [(3.5, 3.5, 6, 90, 90, 120), 
1273   array([[  1.22500000e+01,  -6.12500000e+00,   1.28587914e-15],
1274       [ -6.12500000e+00,   1.22500000e+01,   1.28587914e-15],
1275       [  1.28587914e-15,   1.28587914e-15,   3.60000000e+01]]), array([[  1.08843537e-01,   5.44217687e-02,   3.36690552e-18],
1276       [  5.44217687e-02,   1.08843537e-01,   3.36690552e-18],
1277       [  3.36690552e-18,   3.36690552e-18,   2.77777778e-02]]), (0.32991443953692895, 0.32991443953692895, 0.16666666666666669, 90.0, 90.0, 60.000000000000021), 63.652867178156257, 0.015710211406520427],
1278  ]
1279    global CoordTestData
1280    CoordTestData = [
1281# cell, ((frac, ortho),...)
1282  ((4,4,4,90,90,90,), [
1283 ((0.10000000000000001, 0.0, 0.0),(0.40000000000000002, 0.0, 0.0)),
1284 ((0.0, 0.10000000000000001, 0.0),(2.4492935982947065e-17, 0.40000000000000002, 0.0)),
1285 ((0.0, 0.0, 0.10000000000000001),(2.4492935982947065e-17, -2.4492935982947065e-17, 0.40000000000000002)),
1286 ((0.10000000000000001, 0.20000000000000001, 0.29999999999999999),(0.40000000000000013, 0.79999999999999993, 1.2)),
1287 ((0.20000000000000001, 0.29999999999999999, 0.10000000000000001),(0.80000000000000016, 1.2, 0.40000000000000002)),
1288 ((0.29999999999999999, 0.20000000000000001, 0.10000000000000001),(1.2, 0.80000000000000004, 0.40000000000000002)),
1289 ((0.5, 0.5, 0.5),(2.0, 1.9999999999999998, 2.0)),
1290]),
1291# cell, ((frac, ortho),...)
1292  ((4.1,5.2,6.3,100,80,130,), [
1293 ((0.10000000000000001, 0.0, 0.0),(0.40999999999999998, 0.0, 0.0)),
1294 ((0.0, 0.10000000000000001, 0.0),(-0.33424955703700043, 0.39834311042186865, 0.0)),
1295 ((0.0, 0.0, 0.10000000000000001),(0.10939835193016617, -0.051013289294572106, 0.6183281045774256)),
1296 ((0.10000000000000001, 0.20000000000000001, 0.29999999999999999),(0.069695941716497567, 0.64364635296002093, 1.8549843137322766)),
1297 ((0.20000000000000001, 0.29999999999999999, 0.10000000000000001),(-0.073350319180835066, 1.1440160419710339, 0.6183281045774256)),
1298 ((0.29999999999999999, 0.20000000000000001, 0.10000000000000001),(0.67089923785616512, 0.74567293154916525, 0.6183281045774256)),
1299 ((0.5, 0.5, 0.5),(0.92574397446582857, 1.7366491056364828, 3.0916405228871278)),
1300]),
1301# cell, ((frac, ortho),...)
1302  ((3.5,3.5,6,90,90,120,), [
1303 ((0.10000000000000001, 0.0, 0.0),(0.35000000000000003, 0.0, 0.0)),
1304 ((0.0, 0.10000000000000001, 0.0),(-0.17499999999999993, 0.3031088913245536, 0.0)),
1305 ((0.0, 0.0, 0.10000000000000001),(3.6739403974420595e-17, -3.6739403974420595e-17, 0.60000000000000009)),
1306 ((0.10000000000000001, 0.20000000000000001, 0.29999999999999999),(2.7675166561703527e-16, 0.60621778264910708, 1.7999999999999998)),
1307 ((0.20000000000000001, 0.29999999999999999, 0.10000000000000001),(0.17500000000000041, 0.90932667397366063, 0.60000000000000009)),
1308 ((0.29999999999999999, 0.20000000000000001, 0.10000000000000001),(0.70000000000000018, 0.6062177826491072, 0.60000000000000009)),
1309 ((0.5, 0.5, 0.5),(0.87500000000000067, 1.5155444566227676, 3.0)),
1310]),
1311]
1312    global LaueTestData             #generated by GSAS
1313    LaueTestData = {
1314    'R 3 m':[(4.,4.,6.,90.,90.,120.),((1,0,1,6),(1,0,-2,6),(0,0,3,2),(1,1,0,6),(2,0,-1,6),(2,0,2,6),
1315        (1,1,3,12),(1,0,4,6),(2,1,1,12),(2,1,-2,12),(3,0,0,6),(1,0,-5,6),(2,0,-4,6),(3,0,-3,6),(3,0,3,6),
1316        (0,0,6,2),(2,2,0,6),(2,1,4,12),(2,0,5,6),(3,1,-1,12),(3,1,2,12),(1,1,6,12),(2,2,3,12),(2,1,-5,12))],
1317    'R 3':[(4.,4.,6.,90.,90.,120.),((1,0,1,6),(1,0,-2,6),(0,0,3,2),(1,1,0,6),(2,0,-1,6),(2,0,2,6),(1,1,3,6),
1318        (1,1,-3,6),(1,0,4,6),(3,-1,1,6),(2,1,1,6),(3,-1,-2,6),(2,1,-2,6),(3,0,0,6),(1,0,-5,6),(2,0,-4,6),
1319        (2,2,0,6),(3,0,3,6),(3,0,-3,6),(0,0,6,2),(3,-1,4,6),(2,0,5,6),(2,1,4,6),(4,-1,-1,6),(3,1,-1,6),
1320        (3,1,2,6),(4,-1,2,6),(2,2,-3,6),(1,1,-6,6),(1,1,6,6),(2,2,3,6),(2,1,-5,6),(3,-1,-5,6))],
1321    'P 3':[(4.,4.,6.,90.,90.,120.),((0,0,1,2),(1,0,0,6),(1,0,1,6),(0,0,2,2),(1,0,-1,6),(1,0,2,6),(1,0,-2,6),
1322        (1,1,0,6),(0,0,3,2),(1,1,1,6),(1,1,-1,6),(1,0,3,6),(1,0,-3,6),(2,0,0,6),(2,0,-1,6),(1,1,-2,6),
1323        (1,1,2,6),(2,0,1,6),(2,0,-2,6),(2,0,2,6),(0,0,4,2),(1,1,-3,6),(1,1,3,6),(1,0,-4,6),(1,0,4,6),
1324        (2,0,-3,6),(2,1,0,6),(2,0,3,6),(3,-1,0,6),(2,1,1,6),(3,-1,-1,6),(2,1,-1,6),(3,-1,1,6),(1,1,4,6),
1325        (3,-1,2,6),(3,-1,-2,6),(1,1,-4,6),(0,0,5,2),(2,1,2,6),(2,1,-2,6),(3,0,0,6),(3,0,1,6),(2,0,4,6),
1326        (2,0,-4,6),(3,0,-1,6),(1,0,-5,6),(1,0,5,6),(3,-1,-3,6),(2,1,-3,6),(2,1,3,6),(3,-1,3,6),(3,0,-2,6),
1327        (3,0,2,6),(1,1,5,6),(1,1,-5,6),(2,2,0,6),(3,0,3,6),(3,0,-3,6),(0,0,6,2),(2,0,-5,6),(2,1,-4,6),
1328        (2,2,-1,6),(3,-1,-4,6),(2,2,1,6),(3,-1,4,6),(2,1,4,6),(2,0,5,6),(1,0,-6,6),(1,0,6,6),(4,-1,0,6),
1329        (3,1,0,6),(3,1,-1,6),(3,1,1,6),(4,-1,-1,6),(2,2,2,6),(4,-1,1,6),(2,2,-2,6),(3,1,2,6),(3,1,-2,6),
1330        (3,0,4,6),(3,0,-4,6),(4,-1,-2,6),(4,-1,2,6),(2,2,-3,6),(1,1,6,6),(1,1,-6,6),(2,2,3,6),(3,-1,5,6),
1331        (2,1,5,6),(2,1,-5,6),(3,-1,-5,6))],
1332    'P 3 m 1':[(4.,4.,6.,90.,90.,120.),((0,0,1,2),(1,0,0,6),(1,0,-1,6),(1,0,1,6),(0,0,2,2),(1,0,-2,6),
1333        (1,0,2,6),(1,1,0,6),(0,0,3,2),(1,1,1,12),(1,0,-3,6),(1,0,3,6),(2,0,0,6),(1,1,2,12),(2,0,1,6),
1334        (2,0,-1,6),(0,0,4,2),(2,0,-2,6),(2,0,2,6),(1,1,3,12),(1,0,-4,6),(1,0,4,6),(2,0,3,6),(2,1,0,12),
1335        (2,0,-3,6),(2,1,1,12),(2,1,-1,12),(1,1,4,12),(2,1,2,12),(0,0,5,2),(2,1,-2,12),(3,0,0,6),(1,0,-5,6),
1336        (3,0,1,6),(3,0,-1,6),(1,0,5,6),(2,0,4,6),(2,0,-4,6),(2,1,3,12),(2,1,-3,12),(3,0,-2,6),(3,0,2,6),
1337        (1,1,5,12),(3,0,-3,6),(0,0,6,2),(2,2,0,6),(3,0,3,6),(2,1,4,12),(2,2,1,12),(2,0,5,6),(2,1,-4,12),
1338        (2,0,-5,6),(1,0,-6,6),(1,0,6,6),(3,1,0,12),(3,1,-1,12),(3,1,1,12),(2,2,2,12),(3,1,2,12),
1339        (3,0,4,6),(3,1,-2,12),(3,0,-4,6),(1,1,6,12),(2,2,3,12))],
1340    'P 3 1 m':[(4.,4.,6.,90.,90.,120.),((0,0,1,2),(1,0,0,6),(0,0,2,2),(1,0,1,12),(1,0,2,12),(1,1,0,6),
1341        (0,0,3,2),(1,1,-1,6),(1,1,1,6),(1,0,3,12),(2,0,0,6),(2,0,1,12),(1,1,2,6),(1,1,-2,6),(2,0,2,12),
1342        (0,0,4,2),(1,1,-3,6),(1,1,3,6),(1,0,4,12),(2,1,0,12),(2,0,3,12),(2,1,1,12),(2,1,-1,12),(1,1,-4,6),
1343        (1,1,4,6),(0,0,5,2),(2,1,-2,12),(2,1,2,12),(3,0,0,6),(1,0,5,12),(2,0,4,12),(3,0,1,12),(2,1,-3,12),
1344        (2,1,3,12),(3,0,2,12),(1,1,5,6),(1,1,-5,6),(3,0,3,12),(0,0,6,2),(2,2,0,6),(2,1,-4,12),(2,0,5,12),
1345        (2,2,-1,6),(2,2,1,6),(2,1,4,12),(3,1,0,12),(1,0,6,12),(2,2,2,6),(3,1,-1,12),(2,2,-2,6),(3,1,1,12),
1346        (3,1,-2,12),(3,0,4,12),(3,1,2,12),(1,1,-6,6),(2,2,3,6),(2,2,-3,6),(1,1,6,6))],
1347    }
1348   
1349    global FLnhTestData
1350    FLnhTestData = [{
1351    'C(4,0,0)': (0.965, 0.42760447),
1352    'C(2,0,0)': (1.0122, -0.80233610),
1353    'C(2,0,2)': (0.0061, 8.37491546E-03),
1354    'C(6,0,4)': (-0.0898, 4.37985696E-02),
1355    'C(6,0,6)': (-0.1369, -9.04081762E-02),
1356    'C(6,0,0)': (0.5935, -0.18234928),
1357    'C(4,0,4)': (0.1872, 0.16358127),
1358    'C(6,0,2)': (0.6193, 0.27573633),
1359    'C(4,0,2)': (-0.1897, 0.12530720)},[1,0,0]]
1360def test0():
1361    if NeedTestData: TestData()
1362    msg = 'test cell2Gmat, fillgmat, Gmat2cell'
1363    for (cell, tg, tG, trcell, tV, trV) in CellTestData:
1364        G, g = cell2Gmat(cell)
1365        assert np.allclose(G,tG),msg
1366        assert np.allclose(g,tg),msg
1367        tcell = Gmat2cell(g)
1368        assert np.allclose(cell,tcell),msg
1369        tcell = Gmat2cell(G)
1370        assert np.allclose(tcell,trcell),msg
1371selftestlist.append(test0)
1372
1373def test1():
1374    'test cell2A and A2Gmat'
1375    _ReportTest()
1376    if NeedTestData: TestData()
1377    msg = 'test cell2A and A2Gmat'
1378    for (cell, tg, tG, trcell, tV, trV) in CellTestData:
1379        G, g = A2Gmat(cell2A(cell))
1380        assert np.allclose(G,tG),msg
1381        assert np.allclose(g,tg),msg
1382selftestlist.append(test1)
1383
1384def test2():
1385    'test Gmat2A, A2cell, A2Gmat, Gmat2cell'
1386    _ReportTest()
1387    if NeedTestData: TestData()
1388    msg = 'test Gmat2A, A2cell, A2Gmat, Gmat2cell'
1389    for (cell, tg, tG, trcell, tV, trV) in CellTestData:
1390        G, g = cell2Gmat(cell)
1391        tcell = A2cell(Gmat2A(G))
1392        assert np.allclose(cell,tcell),msg
1393selftestlist.append(test2)
1394
1395def test3():
1396    'test invcell2Gmat'
1397    _ReportTest()
1398    if NeedTestData: TestData()
1399    msg = 'test invcell2Gmat'
1400    for (cell, tg, tG, trcell, tV, trV) in CellTestData:
1401        G, g = invcell2Gmat(trcell)
1402        assert np.allclose(G,tG),msg
1403        assert np.allclose(g,tg),msg
1404selftestlist.append(test3)
1405
1406def test4():
1407    'test calc_rVsq, calc_rV, calc_V'
1408    _ReportTest()
1409    if NeedTestData: TestData()
1410    msg = 'test calc_rVsq, calc_rV, calc_V'
1411    for (cell, tg, tG, trcell, tV, trV) in CellTestData:
1412        assert np.allclose(calc_rV(cell2A(cell)),trV), msg
1413        assert np.allclose(calc_V(cell2A(cell)),tV), msg
1414selftestlist.append(test4)
1415
1416def test5():
1417    'test A2invcell'
1418    _ReportTest()
1419    if NeedTestData: TestData()
1420    msg = 'test A2invcell'
1421    for (cell, tg, tG, trcell, tV, trV) in CellTestData:
1422        rcell = A2invcell(cell2A(cell))
1423        assert np.allclose(rcell,trcell),msg
1424selftestlist.append(test5)
1425
1426def test6():
1427    'test cell2AB'
1428    _ReportTest()
1429    if NeedTestData: TestData()
1430    msg = 'test cell2AB'
1431    for (cell,coordlist) in CoordTestData:
1432        A,B = cell2AB(cell)
1433        for (frac,ortho) in coordlist:
1434            to = np.inner(A,frac)
1435            tf = np.inner(B,to)
1436            assert np.allclose(ortho,to), msg
1437            assert np.allclose(frac,tf), msg
1438            to = np.sum(A*frac,axis=1)
1439            tf = np.sum(B*to,axis=1)
1440            assert np.allclose(ortho,to), msg
1441            assert np.allclose(frac,tf), msg
1442selftestlist.append(test6)
1443
1444def test7():
1445    'test GetBraviasNum(...) and GenHBravais(...)'
1446    _ReportTest()
1447    import os.path
1448    import sys
1449    import GSASIIspc as spc
1450    testdir = os.path.join(os.path.split(os.path.abspath( __file__ ))[0],'testinp')
1451    if os.path.exists(testdir):
1452        if testdir not in sys.path: sys.path.insert(0,testdir)
1453    import sgtbxlattinp
1454    derror = 1e-4
1455    def indexmatch(hklin, hkllist, system):
1456        for hklref in hkllist:
1457            hklref = list(hklref)
1458            # these permutations are far from complete, but are sufficient to
1459            # allow the test to complete
1460            if system == 'cubic':
1461                permlist = [(1,2,3),(1,3,2),(2,1,3),(2,3,1),(3,1,2),(3,2,1),]
1462            elif system == 'monoclinic':
1463                permlist = [(1,2,3),(-1,2,-3)]
1464            else:
1465                permlist = [(1,2,3)]
1466
1467            for perm in permlist:
1468                hkl = [abs(i) * hklin[abs(i)-1] / i for i in perm]
1469                if hkl == hklref: return True
1470                if [-i for i in hkl] == hklref: return True
1471        else:
1472            return False
1473
1474    for key in sgtbxlattinp.sgtbx7:
1475        spdict = spc.SpcGroup(key)
1476        cell = sgtbxlattinp.sgtbx7[key][0]
1477        system = spdict[1]['SGSys']
1478        center = spdict[1]['SGLatt']
1479
1480        bravcode = GetBraviasNum(center, system)
1481
1482        g2list = GenHBravais(sgtbxlattinp.dmin, bravcode, cell2A(cell))
1483
1484        assert len(sgtbxlattinp.sgtbx7[key][1]) == len(g2list), 'Reflection lists differ for %s' % key
1485        for h,k,l,d,num in g2list:
1486            for hkllist,dref in sgtbxlattinp.sgtbx7[key][1]: 
1487                if abs(d-dref) < derror:
1488                    if indexmatch((h,k,l,), hkllist, system):
1489                        break
1490            else:
1491                assert 0,'No match for %s at %s (%s)' % ((h,k,l),d,key)
1492selftestlist.append(test7)
1493
1494def test8():
1495    'test GenHLaue'
1496    _ReportTest()
1497    import GSASIIspc as spc
1498    import sgtbxlattinp
1499    derror = 1e-4
1500    dmin = sgtbxlattinp.dmin
1501
1502    def indexmatch(hklin, hklref, system, axis):
1503        # these permutations are far from complete, but are sufficient to
1504        # allow the test to complete
1505        if system == 'cubic':
1506            permlist = [(1,2,3),(1,3,2),(2,1,3),(2,3,1),(3,1,2),(3,2,1),]
1507        elif system == 'monoclinic' and axis=='b':
1508            permlist = [(1,2,3),(-1,2,-3)]
1509        elif system == 'monoclinic' and axis=='a':
1510            permlist = [(1,2,3),(1,-2,-3)]
1511        elif system == 'monoclinic' and axis=='c':
1512            permlist = [(1,2,3),(-1,-2,3)]
1513        elif system == 'trigonal':
1514            permlist = [(1,2,3),(2,1,3),(-1,-2,3),(-2,-1,3)]
1515        elif system == 'rhombohedral':
1516            permlist = [(1,2,3),(2,3,1),(3,1,2)]
1517        else:
1518            permlist = [(1,2,3)]
1519
1520        hklref = list(hklref)
1521        for perm in permlist:
1522            hkl = [abs(i) * hklin[abs(i)-1] / i for i in perm]
1523            if hkl == hklref: return True
1524            if [-i for i in hkl] == hklref: return True
1525        return False
1526
1527    for key in sgtbxlattinp.sgtbx8:
1528        spdict = spc.SpcGroup(key)[1]
1529        cell = sgtbxlattinp.sgtbx8[key][0]
1530        center = spdict['SGLatt']
1531        Laue = spdict['SGLaue']
1532        Axis = spdict['SGUniq']
1533        system = spdict['SGSys']
1534
1535        g2list = GenHLaue(dmin,spdict,cell2A(cell))
1536        #if len(g2list) != len(sgtbxlattinp.sgtbx8[key][1]):
1537        #    print 'failed',key,':' ,len(g2list),'vs',len(sgtbxlattinp.sgtbx8[key][1])
1538        #    print 'GSAS-II:'
1539        #    for h,k,l,d in g2list: print '  ',(h,k,l),d
1540        #    print 'SGTBX:'
1541        #    for hkllist,dref in sgtbxlattinp.sgtbx8[key][1]: print '  ',hkllist,dref
1542        assert len(g2list) == len(sgtbxlattinp.sgtbx8[key][1]), (
1543            'Reflection lists differ for %s' % key
1544            )
1545        #match = True
1546        for h,k,l,d in g2list:
1547            for hkllist,dref in sgtbxlattinp.sgtbx8[key][1]: 
1548                if abs(d-dref) < derror:
1549                    if indexmatch((h,k,l,), hkllist, system, Axis): break
1550            else:
1551                assert 0,'No match for %s at %s (%s)' % ((h,k,l),d,key)
1552                #match = False
1553        #if not match:
1554            #for hkllist,dref in sgtbxlattinp.sgtbx8[key][1]: print '  ',hkllist,dref
1555            #print center, Laue, Axis, system
1556selftestlist.append(test8)
1557           
1558def test9():
1559    'test GenHLaue'
1560    _ReportTest()
1561    import GSASIIspc as G2spc
1562    if NeedTestData: TestData()
1563    for spc in LaueTestData:
1564        data = LaueTestData[spc]
1565        cell = data[0]
1566        hklm = np.array(data[1])
1567        H = hklm[-1][:3]
1568        hklO = hklm.T[:3].T
1569        A = cell2A(cell)
1570        dmin = 1./np.sqrt(calc_rDsq(H,A))
1571        SGData = G2spc.SpcGroup(spc)[1]
1572        hkls = np.array(GenHLaue(dmin,SGData,A))
1573        hklN = hkls.T[:3].T
1574        #print spc,hklO.shape,hklN.shape
1575        err = True
1576        for H in hklO:
1577            if H not in hklN:
1578                print H,' missing from hkl from GSASII'
1579                err = False
1580        assert(err)
1581selftestlist.append(test9)
1582       
1583       
1584   
1585
1586if __name__ == '__main__':
1587    # run self-tests
1588    selftestquiet = False
1589    for test in selftestlist:
1590        test()
1591    print "OK"
Note: See TracBrowser for help on using the repository browser.