source: trunk/GSASIIlattice.py @ 1445

Last change on this file since 1445 was 1445, checked in by vondreele, 9 years ago

add error bars to calibration plot
disable Autosearch if peaks already picked
implement cell refine for TOF data - isn't quite right yet
implement tool tip on calibration plot to show position for each peak

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