source: trunk/GSASIIlattice.py @ 2218

Last change on this file since 2218 was 2218, checked in by vondreele, 7 years ago

work on cell transformations - fills new cell with unique atom set, deletes map (if any)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 90.8 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: 2016-04-18 16:26:02 +0000 (Mon, 18 Apr 2016) $
27# $Author: vondreele $
28# $Revision: 2218 $
29# $URL: trunk/GSASIIlattice.py $
30# $Id: GSASIIlattice.py 2218 2016-04-18 16:26:02Z vondreele $
31########### SVN repository information ###################
32import math
33import copy
34import sys
35import random as ran
36import numpy as np
37import numpy.linalg as nl
38import GSASIIpath
39import GSASIImath as G2mth
40import GSASIIspc as G2spc
41GSASIIpath.SetVersionNumber("$Revision: 2218 $")
42# trig functions in degrees
43sind = lambda x: np.sin(x*np.pi/180.)
44asind = lambda x: 180.*np.arcsin(x)/np.pi
45tand = lambda x: np.tan(x*np.pi/180.)
46atand = lambda x: 180.*np.arctan(x)/np.pi
47atan2d = lambda y,x: 180.*np.arctan2(y,x)/np.pi
48cosd = lambda x: np.cos(x*np.pi/180.)
49acosd = lambda x: 180.*np.arccos(x)/np.pi
50rdsq2d = lambda x,p: round(1.0/np.sqrt(x),p)
51rpd = np.pi/180.
52RSQ2PI = 1./np.sqrt(2.*np.pi)
53SQ2 = np.sqrt(2.)
54RSQPI = 1./np.sqrt(np.pi)
55R2pisq = 1./(2.*np.pi**2)
56nxs = np.newaxis
57
58def sec2HMS(sec):
59    """Convert time in sec to H:M:S string
60   
61    :param sec: time in seconds
62    :return: H:M:S string (to nearest 100th second)
63   
64    """
65    H = int(sec/3600)
66    M = int(sec/60-H*60)
67    S = sec-3600*H-60*M
68    return '%d:%2d:%.2f'%(H,M,S)
69   
70def rotdMat(angle,axis=0):
71    """Prepare rotation matrix for angle in degrees about axis(=0,1,2)
72
73    :param angle: angle in degrees
74    :param axis:  axis (0,1,2 = x,y,z) about which for the rotation
75    :return: rotation matrix - 3x3 numpy array
76
77    """
78    if axis == 2:
79        return np.array([[cosd(angle),-sind(angle),0],[sind(angle),cosd(angle),0],[0,0,1]])
80    elif axis == 1:
81        return np.array([[cosd(angle),0,-sind(angle)],[0,1,0],[sind(angle),0,cosd(angle)]])
82    else:
83        return np.array([[1,0,0],[0,cosd(angle),-sind(angle)],[0,sind(angle),cosd(angle)]])
84       
85def rotdMat4(angle,axis=0):
86    """Prepare rotation matrix for angle in degrees about axis(=0,1,2) with scaling for OpenGL
87
88    :param angle: angle in degrees
89    :param axis:  axis (0,1,2 = x,y,z) about which for the rotation
90    :return: rotation matrix - 4x4 numpy array (last row/column for openGL scaling)
91
92    """
93    Mat = rotdMat(angle,axis)
94    return np.concatenate((np.concatenate((Mat,[[0],[0],[0]]),axis=1),[[0,0,0,1],]),axis=0)
95   
96def fillgmat(cell):
97    """Compute lattice metric tensor from unit cell constants
98
99    :param cell: tuple with a,b,c,alpha, beta, gamma (degrees)
100    :return: 3x3 numpy array
101
102    """
103    a,b,c,alp,bet,gam = cell
104    g = np.array([
105        [a*a,  a*b*cosd(gam),  a*c*cosd(bet)],
106        [a*b*cosd(gam),  b*b,  b*c*cosd(alp)],
107        [a*c*cosd(bet) ,b*c*cosd(alp),   c*c]])
108    return g
109           
110def cell2Gmat(cell):
111    """Compute real and reciprocal lattice metric tensor from unit cell constants
112
113    :param cell: tuple with a,b,c,alpha, beta, gamma (degrees)
114    :return: reciprocal (G) & real (g) metric tensors (list of two numpy 3x3 arrays)
115
116    """
117    g = fillgmat(cell)
118    G = nl.inv(g)       
119    return G,g
120
121def A2Gmat(A,inverse=True):
122    """Fill real & reciprocal metric tensor (G) from A.
123
124    :param A: reciprocal metric tensor elements as [G11,G22,G33,2*G12,2*G13,2*G23]
125    :param bool inverse: if True return both G and g; else just G
126    :return: reciprocal (G) & real (g) metric tensors (list of two numpy 3x3 arrays)
127
128    """
129    G = np.zeros(shape=(3,3))
130    G = [
131        [A[0],  A[3]/2.,  A[4]/2.], 
132        [A[3]/2.,A[1],    A[5]/2.], 
133        [A[4]/2.,A[5]/2.,    A[2]]]
134    if inverse:
135        g = nl.inv(G)
136        return G,g
137    else:
138        return G
139
140def Gmat2A(G):
141    """Extract A from reciprocal metric tensor (G)
142
143    :param G: reciprocal maetric tensor (3x3 numpy array
144    :return: A = [G11,G22,G33,2*G12,2*G13,2*G23]
145
146    """
147    return [G[0][0],G[1][1],G[2][2],2.*G[0][1],2.*G[0][2],2.*G[1][2]]
148   
149def cell2A(cell):
150    """Obtain A = [G11,G22,G33,2*G12,2*G13,2*G23] from lattice parameters
151
152    :param cell: [a,b,c,alpha,beta,gamma] (degrees)
153    :return: G reciprocal metric tensor as 3x3 numpy array
154
155    """
156    G,g = cell2Gmat(cell)
157    return Gmat2A(G)
158
159def A2cell(A):
160    """Compute unit cell constants from A
161
162    :param A: [G11,G22,G33,2*G12,2*G13,2*G23] G - reciprocal metric tensor
163    :return: a,b,c,alpha, beta, gamma (degrees) - lattice parameters
164
165    """
166    G,g = A2Gmat(A)
167    return Gmat2cell(g)
168
169def Gmat2cell(g):
170    """Compute real/reciprocal lattice parameters from real/reciprocal metric tensor (g/G)
171    The math works the same either way.
172
173    :param g (or G): real (or reciprocal) metric tensor 3x3 array
174    :return: a,b,c,alpha, beta, gamma (degrees) (or a*,b*,c*,alpha*,beta*,gamma* degrees)
175
176    """
177    oldset = np.seterr('raise')
178    a = np.sqrt(max(0,g[0][0]))
179    b = np.sqrt(max(0,g[1][1]))
180    c = np.sqrt(max(0,g[2][2]))
181    alp = acosd(g[2][1]/(b*c))
182    bet = acosd(g[2][0]/(a*c))
183    gam = acosd(g[0][1]/(a*b))
184    np.seterr(**oldset)
185    return a,b,c,alp,bet,gam
186
187def invcell2Gmat(invcell):
188    """Compute real and reciprocal lattice metric tensor from reciprocal
189       unit cell constants
190       
191    :param invcell: [a*,b*,c*,alpha*, beta*, gamma*] (degrees)
192    :return: reciprocal (G) & real (g) metric tensors (list of two 3x3 arrays)
193
194    """
195    G = fillgmat(invcell)
196    g = nl.inv(G)
197    return G,g
198   
199def prodMGMT(G,Mat):
200    '''Transform metric tensor by matrix
201   
202    :param G: array metric tensor
203    :param Mat: array transformation matrix
204    :return: array new metric tensor
205   
206    '''
207    return np.inner(Mat,np.inner(G,Mat).T)
208   
209def TransformCell(cell,Trans):
210    '''Transform lattice parameters by matrix
211   
212    :param cell: list a,b,c,alpha,beta,gamma,(volume)
213    :param Trans: array transformation matrix
214    :return: array transformed a,b,c,alpha,beta,gamma,volume
215   
216    '''
217    newCell = np.zeros(7)
218    g = cell2Gmat(cell)[1]
219    newg = prodMGMT(g,Trans)
220    newCell[:6] = Gmat2cell(newg)
221    newCell[6] = calc_V(cell2A(newCell[:6]))
222    return newCell
223   
224def TransformXYZ(XYZ,Trans,Vec):
225    return np.inner(XYZ,Trans)+Vec
226   
227def TransformU6(U6,Trans):
228    Uij = np.inner(Trans,np.inner(U6toUij(U6),Trans))
229    return UijtoU6(Uij)
230   
231def TransformPhase(oldPhase,newPhase,Trans,Vec):
232    '''Transform atoms from oldPhase to newPhase by Trans & Vec
233   
234    :param oldPhase: dict G2 phase info for old phase
235    :param newPhase: dict G2 phase info for new phase; with new cell & space group
236            atoms are from oldPhase & will be transformed
237    :param Trans: array transformation matrix
238    :param Vec: array transformation vector
239    '''
240   
241    cx,ct,cs,cia = oldPhase['General']['AtomPtrs']
242    SGData = newPhase['General']['SGData']
243    invTrans = nl.inv(Trans)
244    newAtoms = FillUnitCell(oldPhase)
245    for atom in newAtoms:
246        atom[cx:cx+3] = TransformXYZ(atom[cx:cx+3],invTrans.T,Vec)
247        if atom[cia] == 'A':
248            atom[cia+2:cia+8] = TransformU6(atom[cia+2:cia+8],invTrans)
249        atom[cs:cs+2] = G2spc.SytSym(atom[cx:cx+3],SGData)
250        atom[cia+8] = ran.randint(0,sys.maxint)
251    newPhase['Atoms'] = newAtoms
252    newPhase['Atoms'] = GetUnique(newPhase)
253    newPhase['Drawing']['Atoms'] = []
254    return newPhase
255   
256def FillUnitCell(Phase):
257    Atoms = Phase['Atoms']
258    atomData = []
259    SGData = Phase['General']['SGData']
260    cx,ct,cs,cia = Phase['General']['AtomPtrs']
261    for atom in Atoms:
262        XYZ = np.array(atom[cx:cx+3])
263        if atom[cia] == 'A':
264            Uij = atom[cia+2:cia+8]
265            result = G2spc.GenAtom(XYZ,SGData,False,Uij,True)
266            for item in result:
267                if item[0][2] >= .95: item[0][2] -= 1.
268                atom[cx:cx+3] = item[0]
269                atom[cia+2:cia+8] = item[1]
270                atomData.append(atom[:cia+9])  #not SS stuff
271        else:
272            result = G2spc.GenAtom(XYZ,SGData,False,Move=True)
273            for item in result:
274                if item[0][2] >= .95: item[0][2] -= 1.
275                atom[cx:cx+3] = item[0]
276                atomData.append(atom[:cia+9])  #not SS stuff
277    return atomData
278       
279def GetUnique(Phase):
280   
281    def noDuplicate(xyzA,XYZ,Amat):
282        if True in [np.allclose(np.inner(Amat,xyzA),np.inner(Amat,xyzB),atol=0.05) for xyzB in XYZ]:
283            return False
284        return True
285
286    cx,ct,cs,cia = Phase['General']['AtomPtrs']
287    cell = Phase['General']['Cell'][1:7]
288    Amat,Bmat = cell2AB(cell)
289    SGData = Phase['General']['SGData']
290    Atoms = Phase['Atoms']
291    Ind = len(Atoms)
292    newAtoms = []
293    Indx = {}
294    XYZ = {}
295    for ind in range(Ind):
296        XYZ[ind] = np.array(Atoms[ind][cx:cx+3])
297        Indx[ind] = True
298    for ind in range(Ind):
299        if Indx[ind]:
300            xyz = XYZ[ind]
301            for jnd in range(Ind):
302                if ind != jnd and Indx[jnd]:                       
303                    Equiv = G2spc.GenAtom(XYZ[jnd],SGData,Move=True)
304                    xyzs = np.array([equiv[0] for equiv in Equiv])
305                    Indx[jnd] = noDuplicate(xyz,xyzs,Amat)
306    Ind = []
307    for ind in Indx:
308        if Indx[ind]:
309            newAtoms.append(Atoms[ind])
310    return newAtoms
311           
312def calc_rVsq(A):
313    """Compute the square of the reciprocal lattice volume (1/V**2) from A'
314
315    """
316    G,g = A2Gmat(A)
317    rVsq = nl.det(G)
318    if rVsq < 0:
319        return 1
320    return rVsq
321   
322def calc_rV(A):
323    """Compute the reciprocal lattice volume (V*) from A
324    """
325    return np.sqrt(calc_rVsq(A))
326   
327def calc_V(A):
328    """Compute the real lattice volume (V) from A
329    """
330    return 1./calc_rV(A)
331
332def A2invcell(A):
333    """Compute reciprocal unit cell constants from A
334    returns tuple with a*,b*,c*,alpha*, beta*, gamma* (degrees)
335    """
336    G,g = A2Gmat(A)
337    return Gmat2cell(G)
338   
339def Gmat2AB(G):
340    """Computes orthogonalization matrix from reciprocal metric tensor G
341
342    :returns: tuple of two 3x3 numpy arrays (A,B)
343
344       * A for crystal to Cartesian transformations A*x = np.inner(A,x) = X
345       * B (= inverse of A) for Cartesian to crystal transformation B*X = np.inner(B,X) = x
346
347    """
348    cellstar = Gmat2cell(G)
349    g = nl.inv(G)
350    cell = Gmat2cell(g)
351    A = np.zeros(shape=(3,3))
352    # from Giacovazzo (Fundamentals 2nd Ed.) p.75
353    A[0][0] = cell[0]                # a
354    A[0][1] = cell[1]*cosd(cell[5])  # b cos(gamma)
355    A[0][2] = cell[2]*cosd(cell[4])  # c cos(beta)
356    A[1][1] = cell[1]*sind(cell[5])  # b sin(gamma)
357    A[1][2] = -cell[2]*cosd(cellstar[3])*sind(cell[4]) # - c cos(alpha*) sin(beta)
358    A[2][2] = 1/cellstar[2]         # 1/c*
359    B = nl.inv(A)
360    return A,B
361   
362
363def cell2AB(cell):
364    """Computes orthogonalization matrix from unit cell constants
365
366    :param tuple cell: a,b,c, alpha, beta, gamma (degrees)
367    :returns: tuple of two 3x3 numpy arrays (A,B)
368       A for crystal to Cartesian transformations A*x = np.inner(A,x) = X
369       B (= inverse of A) for Cartesian to crystal transformation B*X = np.inner(B,X) = x
370    """
371    G,g = cell2Gmat(cell) 
372    cellstar = Gmat2cell(G)
373    A = np.zeros(shape=(3,3))
374    # from Giacovazzo (Fundamentals 2nd Ed.) p.75
375    A[0][0] = cell[0]                # a
376    A[0][1] = cell[1]*cosd(cell[5])  # b cos(gamma)
377    A[0][2] = cell[2]*cosd(cell[4])  # c cos(beta)
378    A[1][1] = cell[1]*sind(cell[5])  # b sin(gamma)
379    A[1][2] = -cell[2]*cosd(cellstar[3])*sind(cell[4]) # - c cos(alpha*) sin(beta)
380    A[2][2] = 1/cellstar[2]         # 1/c*
381    B = nl.inv(A)
382    return A,B
383   
384def U6toUij(U6):
385    """Fill matrix (Uij) from U6 = [U11,U22,U33,U12,U13,U23]
386    NB: there is a non numpy version in GSASIIspc: U2Uij
387
388    :param list U6: 6 terms of u11,u22,...
389    :returns:
390        Uij - numpy [3][3] array of uij
391    """
392    U = np.array([
393        [U6[0],  U6[3],  U6[4]], 
394        [U6[3],  U6[1],  U6[5]], 
395        [U6[4],  U6[5],  U6[2]]])
396    return U
397
398def UijtoU6(U):
399    """Fill vector [U11,U22,U33,U12,U13,U23] from Uij
400    NB: there is a non numpy version in GSASIIspc: Uij2U
401    """
402    U6 = np.array([U[0][0],U[1][1],U[2][2],U[0][1],U[0][2],U[1][2]])
403    return U6
404
405def betaij2Uij(betaij,G):
406    """
407    Convert beta-ij to Uij tensors
408   
409    :param beta-ij - numpy array [beta-ij]
410    :param G: reciprocal metric tensor
411    :returns: Uij: numpy array [Uij]
412    """
413    ast = np.sqrt(np.diag(G))   #a*, b*, c*
414    Mast = np.multiply.outer(ast,ast)   
415    return R2pisq*UijtoU6(U6toUij(betaij)/Mast)
416   
417def Uij2betaij(Uij,G):
418    """
419    Convert Uij to beta-ij tensors -- stub for eventual completion
420   
421    :param Uij: numpy array [Uij]
422    :param G: reciprocal metric tensor
423    :returns: beta-ij - numpy array [beta-ij]
424    """
425    pass
426   
427def cell2GS(cell):
428    ''' returns Uij to betaij conversion matrix'''
429    G,g = cell2Gmat(cell)
430    GS = G
431    GS[0][1] = GS[1][0] = math.sqrt(GS[0][0]*GS[1][1])
432    GS[0][2] = GS[2][0] = math.sqrt(GS[0][0]*GS[2][2])
433    GS[1][2] = GS[2][1] = math.sqrt(GS[1][1]*GS[2][2])
434    return GS   
435   
436def Uij2Ueqv(Uij,GS,Amat):
437    ''' returns 1/3 trace of diagonalized U matrix'''
438    U = np.multiply(U6toUij(Uij),GS)
439    U = np.inner(Amat,np.inner(U,Amat).T)
440    E,R = nl.eigh(U)
441    return np.sum(E)/3.
442       
443def CosAngle(U,V,G):
444    """ calculate cos of angle between U & V in generalized coordinates
445    defined by metric tensor G
446
447    :param U: 3-vectors assume numpy arrays, can be multiple reflections as (N,3) array
448    :param V: 3-vectors assume numpy arrays, only as (3) vector
449    :param G: metric tensor for U & V defined space assume numpy array
450    :returns:
451        cos(phi)
452    """
453    u = (U.T/np.sqrt(np.sum(np.inner(U,G)*U,axis=1))).T
454    v = V/np.sqrt(np.inner(V,np.inner(G,V)))
455    cosP = np.inner(u,np.inner(G,v))
456    return cosP
457   
458def CosSinAngle(U,V,G):
459    """ calculate sin & cos of angle between U & V in generalized coordinates
460    defined by metric tensor G
461
462    :param U: 3-vectors assume numpy arrays
463    :param V: 3-vectors assume numpy arrays
464    :param G: metric tensor for U & V defined space assume numpy array
465    :returns:
466        cos(phi) & sin(phi)
467    """
468    u = U/np.sqrt(np.inner(U,np.inner(G,U)))
469    v = V/np.sqrt(np.inner(V,np.inner(G,V)))
470    cosP = np.inner(u,np.inner(G,v))
471    sinP = np.sqrt(max(0.0,1.0-cosP**2))
472    return cosP,sinP
473   
474def criticalEllipse(prob):
475    """
476    Calculate critical values for probability ellipsoids from probability
477    """
478    if not ( 0.01 <= prob < 1.0):
479        return 1.54 
480    coeff = np.array([6.44988E-09,4.16479E-07,1.11172E-05,1.58767E-04,0.00130554,
481        0.00604091,0.0114921,-0.040301,-0.6337203,1.311582])
482    llpr = math.log(-math.log(prob))
483    return np.polyval(coeff,llpr)
484   
485def CellBlock(nCells):
486    """
487    Generate block of unit cells n*n*n on a side; [0,0,0] centered, n = 2*nCells+1
488    currently only works for nCells = 0 or 1 (not >1)
489    """
490    if nCells:
491        N = 2*nCells+1
492        N2 = N*N
493        N3 = N*N*N
494        cellArray = []
495        A = np.array(range(N3))
496        cellGen = np.array([A/N2-1,A/N%N-1,A%N-1]).T
497        for cell in cellGen:
498            cellArray.append(cell)
499        return cellArray
500    else:
501        return [0,0,0]
502       
503def CellAbsorption(ElList,Volume):
504    '''Compute unit cell absorption
505
506    :param dict ElList: dictionary of element contents including mu and
507      number of atoms be cell
508    :param float Volume: unit cell volume
509    :returns: mu-total/Volume
510    '''
511    muT = 0
512    for El in ElList:
513        muT += ElList[El]['mu']*ElList[El]['FormulaNo']
514    return muT/Volume
515   
516#Permutations and Combinations
517# Four routines: combinations,uniqueCombinations, selections & permutations
518#These taken from Python Cookbook, 2nd Edition. 19.15 p724-726
519#   
520def _combinators(_handle, items, n):
521    """ factored-out common structure of all following combinators """
522    if n==0:
523        yield [ ]
524        return
525    for i, item in enumerate(items):
526        this_one = [ item ]
527        for cc in _combinators(_handle, _handle(items, i), n-1):
528            yield this_one + cc
529def combinations(items, n):
530    """ take n distinct items, order matters """
531    def skipIthItem(items, i):
532        return items[:i] + items[i+1:]
533    return _combinators(skipIthItem, items, n)
534def uniqueCombinations(items, n):
535    """ take n distinct items, order is irrelevant """
536    def afterIthItem(items, i):
537        return items[i+1:]
538    return _combinators(afterIthItem, items, n)
539def selections(items, n):
540    """ take n (not necessarily distinct) items, order matters """
541    def keepAllItems(items, i):
542        return items
543    return _combinators(keepAllItems, items, n)
544def permutations(items):
545    """ take all items, order matters """
546    return combinations(items, len(items))
547
548#reflection generation routines
549#for these: H = [h,k,l]; A is as used in calc_rDsq; G - inv metric tensor, g - metric tensor;
550#           cell - a,b,c,alp,bet,gam in A & deg
551   
552def Pos2dsp(Inst,pos):
553    ''' convert powder pattern position (2-theta or TOF, musec) to d-spacing
554    '''
555    if 'C' in Inst['Type'][0] or 'PKS' in Inst['Type'][0]:
556        wave = G2mth.getWave(Inst)
557        return wave/(2.0*sind((pos-Inst.get('Zero',[0,0])[1])/2.0))
558    else:   #'T'OF - ignore difB
559        return TOF2dsp(Inst,pos)
560       
561def TOF2dsp(Inst,Pos):
562    ''' convert powder pattern TOF, musec to d-spacing by successive approximation
563    Pos can be numpy array
564    '''
565    def func(d,pos,Inst):       
566        return (pos-Inst['difA'][1]*d**2-Inst['Zero'][1]-Inst['difB'][1]/d)/Inst['difC'][1]
567    dsp0 = np.ones_like(Pos)
568    N = 0
569    while True:      #successive approximations
570        dsp = func(dsp0,Pos,Inst)
571        if np.allclose(dsp,dsp0,atol=0.000001):
572            return dsp
573        dsp0 = dsp
574        N += 1
575        if N > 10:
576            return dsp
577   
578def Dsp2pos(Inst,dsp):
579    ''' convert d-spacing to powder pattern position (2-theta or TOF, musec)
580    '''
581    if 'C' in Inst['Type'][0] or 'PKS' in Inst['Type'][0]:
582        wave = G2mth.getWave(Inst)
583        pos = 2.0*asind(wave/(2.*dsp))+Inst.get('Zero',[0,0])[1]             
584    else:   #'T'OF
585        pos = Inst['difC'][1]*dsp+Inst['Zero'][1]+Inst['difA'][1]*dsp**2+Inst.get('difB',[0,0,False])[1]/dsp
586    return pos
587   
588def getPeakPos(dataType,parmdict,dsp):
589    ''' convert d-spacing to powder pattern position (2-theta or TOF, musec)
590    '''
591    if 'C' in dataType:
592        pos = 2.0*asind(parmdict['Lam']/(2.*dsp))+parmdict['Zero']
593    else:   #'T'OF
594        pos = parmdict['difC']*dsp+parmdict['difA']*dsp**2+parmdict['difB']/dsp+parmdict['Zero']
595    return pos
596                   
597def calc_rDsq(H,A):
598    'needs doc string'
599    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]
600    return rdsq
601   
602def calc_rDsq2(H,G):
603    'needs doc string'
604    return np.inner(H,np.inner(G,H))
605   
606def calc_rDsqSS(H,A,vec):
607    'needs doc string'
608    rdsq = calc_rDsq(H[:3]+(H[3]*vec).T,A)
609    return rdsq
610       
611def calc_rDsqZ(H,A,Z,tth,lam):
612    'needs doc string'
613    rdsq = calc_rDsq(H,A)+Z*sind(tth)*2.0*rpd/lam**2
614    return rdsq
615       
616def calc_rDsqZSS(H,A,vec,Z,tth,lam):
617    'needs doc string'
618    rdsq = calc_rDsq(H[:3]+(H[3][:,np.newaxis]*vec).T,A)+Z*sind(tth)*2.0*rpd/lam**2
619    return rdsq
620       
621def calc_rDsqT(H,A,Z,tof,difC):
622    'needs doc string'
623    rdsq = calc_rDsq(H,A)+Z/difC
624    return rdsq
625       
626def calc_rDsqTSS(H,A,vec,Z,tof,difC):
627    'needs doc string'
628    rdsq = calc_rDsq(H[:3]+(H[3][:,np.newaxis]*vec).T,A)+Z/difC
629    return rdsq
630       
631def MaxIndex(dmin,A):
632    'needs doc string'
633    Hmax = [0,0,0]
634    try:
635        cell = A2cell(A)
636    except:
637        cell = [1,1,1,90,90,90]
638    for i in range(3):
639        Hmax[i] = int(round(cell[i]/dmin))
640    return Hmax
641   
642def transposeHKLF(transMat,Super,refList):
643    ''' Apply transformation matrix to hkl(m)
644    param: transmat: 3x3 or 4x4 array
645    param: Super: 0 or 1 for extra index
646    param: refList list of h,k,l,....
647    return: newRefs transformed list of h',k',l',,,
648    return: badRefs list of noninteger h',k',l'...
649    '''
650    newRefs = np.copy(refList)
651    badRefs = []
652    for H in newRefs:
653        newH = np.inner(transMat,H[:3+Super])
654        H[:3+Super] = np.rint(newH)
655        if not np.allclose(newH,H[:3+Super],atol=0.01):
656            badRefs.append(newH)
657    return newRefs,badRefs
658   
659def sortHKLd(HKLd,ifreverse,ifdup,ifSS=False):
660    '''sort reflection list on d-spacing; can sort in either order
661
662    :param HKLd: a list of [h,k,l,d,...];
663    :param ifreverse: True for largest d first
664    :param ifdup: True if duplicate d-spacings allowed
665    :return sorted reflection list
666    '''
667    T = []
668    N = 3
669    if ifSS:
670        N = 4
671    for i,H in enumerate(HKLd):
672        if ifdup:
673            T.append((H[N],i))
674        else:
675            T.append(H[N])           
676    D = dict(zip(T,HKLd))
677    T.sort()
678    if ifreverse:
679        T.reverse()
680    X = []
681    okey = ''
682    for key in T: 
683        if key != okey: X.append(D[key])    #remove duplicate d-spacings
684        okey = key
685    return X
686   
687def SwapIndx(Axis,H):
688    'needs doc string'
689    if Axis in [1,-1]:
690        return H
691    elif Axis in [2,-3]:
692        return [H[1],H[2],H[0]]
693    else:
694        return [H[2],H[0],H[1]]
695       
696def Rh2Hx(Rh):
697    'needs doc string'
698    Hx = [0,0,0]
699    Hx[0] = Rh[0]-Rh[1]
700    Hx[1] = Rh[1]-Rh[2]
701    Hx[2] = np.sum(Rh)
702    return Hx
703   
704def Hx2Rh(Hx):
705    'needs doc string'
706    Rh = [0,0,0]
707    itk = -Hx[0]+Hx[1]+Hx[2]
708    if itk%3 != 0:
709        return 0        #error - not rhombohedral reflection
710    else:
711        Rh[1] = itk/3
712        Rh[0] = Rh[1]+Hx[0]
713        Rh[2] = Rh[1]-Hx[1]
714        if Rh[0] < 0:
715            for i in range(3):
716                Rh[i] = -Rh[i]
717        return Rh
718       
719def CentCheck(Cent,H):
720    'needs doc string'
721    h,k,l = H
722    if Cent == 'A' and (k+l)%2:
723        return False
724    elif Cent == 'B' and (h+l)%2:
725        return False
726    elif Cent == 'C' and (h+k)%2:
727        return False
728    elif Cent == 'I' and (h+k+l)%2:
729        return False
730    elif Cent == 'F' and ((h+k)%2 or (h+l)%2 or (k+l)%2):
731        return False
732    elif Cent == 'R' and (-h+k+l)%3:
733        return False
734    else:
735        return True
736                                   
737def GetBraviasNum(center,system):
738    """Determine the Bravais lattice number, as used in GenHBravais
739   
740    :param center: one of: 'P', 'C', 'I', 'F', 'R' (see SGLatt from GSASIIspc.SpcGroup)
741    :param system: one of 'cubic', 'hexagonal', 'tetragonal', 'orthorhombic', 'trigonal' (for R)
742      'monoclinic', 'triclinic' (see SGSys from GSASIIspc.SpcGroup)
743    :return: a number between 0 and 13
744      or throws a ValueError exception if the combination of center, system is not found (i.e. non-standard)
745
746    """
747    if center.upper() == 'F' and system.lower() == 'cubic':
748        return 0
749    elif center.upper() == 'I' and system.lower() == 'cubic':
750        return 1
751    elif center.upper() == 'P' and system.lower() == 'cubic':
752        return 2
753    elif center.upper() == 'R' and system.lower() == 'trigonal':
754        return 3
755    elif center.upper() == 'P' and system.lower() == 'hexagonal':
756        return 4
757    elif center.upper() == 'I' and system.lower() == 'tetragonal':
758        return 5
759    elif center.upper() == 'P' and system.lower() == 'tetragonal':
760        return 6
761    elif center.upper() == 'F' and system.lower() == 'orthorhombic':
762        return 7
763    elif center.upper() == 'I' and system.lower() == 'orthorhombic':
764        return 8
765    elif center.upper() == 'C' and system.lower() == 'orthorhombic':
766        return 9
767    elif center.upper() == 'P' and system.lower() == 'orthorhombic':
768        return 10
769    elif center.upper() == 'C' and system.lower() == 'monoclinic':
770        return 11
771    elif center.upper() == 'P' and system.lower() == 'monoclinic':
772        return 12
773    elif center.upper() == 'P' and system.lower() == 'triclinic':
774        return 13
775    raise ValueError,'non-standard Bravais lattice center=%s, cell=%s' % (center,system)
776
777def GenHBravais(dmin,Bravais,A):
778    """Generate the positionally unique powder diffraction reflections
779     
780    :param dmin: minimum d-spacing in A
781    :param Bravais: lattice type (see GetBraviasNum). Bravais is one of::
782             0 F cubic
783             1 I cubic
784             2 P cubic
785             3 R hexagonal (trigonal not rhombohedral)
786             4 P hexagonal
787             5 I tetragonal
788             6 P tetragonal
789             7 F orthorhombic
790             8 I orthorhombic
791             9 C orthorhombic
792             10 P orthorhombic
793             11 C monoclinic
794             12 P monoclinic
795             13 P triclinic
796           
797    :param A: reciprocal metric tensor elements as [G11,G22,G33,2*G12,2*G13,2*G23]
798    :return: HKL unique d list of [h,k,l,d,-1] sorted with largest d first
799           
800    """
801    import math
802    if Bravais in [9,11]:
803        Cent = 'C'
804    elif Bravais in [1,5,8]:
805        Cent = 'I'
806    elif Bravais in [0,7]:
807        Cent = 'F'
808    elif Bravais in [3]:
809        Cent = 'R'
810    else:
811        Cent = 'P'
812    Hmax = MaxIndex(dmin,A)
813    dminsq = 1./(dmin**2)
814    HKL = []
815    if Bravais == 13:                       #triclinic
816        for l in range(-Hmax[2],Hmax[2]+1):
817            for k in range(-Hmax[1],Hmax[1]+1):
818                hmin = 0
819                if (k < 0): hmin = 1
820                if (k ==0 and l < 0): hmin = 1
821                for h in range(hmin,Hmax[0]+1):
822                    H=[h,k,l]
823                    rdsq = calc_rDsq(H,A)
824                    if 0 < rdsq <= dminsq:
825                        HKL.append([h,k,l,rdsq2d(rdsq,6),-1])
826    elif Bravais in [11,12]:                #monoclinic - b unique
827        Hmax = SwapIndx(2,Hmax)
828        for h in range(Hmax[0]+1):
829            for k in range(-Hmax[1],Hmax[1]+1):
830                lmin = 0
831                if k < 0:lmin = 1
832                for l in range(lmin,Hmax[2]+1):
833                    [h,k,l] = SwapIndx(-2,[h,k,l])
834                    H = []
835                    if CentCheck(Cent,[h,k,l]): H=[h,k,l]
836                    if H:
837                        rdsq = calc_rDsq(H,A)
838                        if 0 < rdsq <= dminsq:
839                            HKL.append([h,k,l,rdsq2d(rdsq,6),-1])
840                    [h,k,l] = SwapIndx(2,[h,k,l])
841    elif Bravais in [7,8,9,10]:            #orthorhombic
842        for h in range(Hmax[0]+1):
843            for k in range(Hmax[1]+1):
844                for l in range(Hmax[2]+1):
845                    H = []
846                    if CentCheck(Cent,[h,k,l]): H=[h,k,l]
847                    if H:
848                        rdsq = calc_rDsq(H,A)
849                        if 0 < rdsq <= dminsq:
850                            HKL.append([h,k,l,rdsq2d(rdsq,6),-1])
851    elif Bravais in [5,6]:                  #tetragonal
852        for l in range(Hmax[2]+1):
853            for k in range(Hmax[1]+1):
854                for h in range(k,Hmax[0]+1):
855                    H = []
856                    if CentCheck(Cent,[h,k,l]): H=[h,k,l]
857                    if H:
858                        rdsq = calc_rDsq(H,A)
859                        if 0 < rdsq <= dminsq:
860                            HKL.append([h,k,l,rdsq2d(rdsq,6),-1])
861    elif Bravais in [3,4]:
862        lmin = 0
863        if Bravais == 3: lmin = -Hmax[2]                  #hexagonal/trigonal
864        for l in range(lmin,Hmax[2]+1):
865            for k in range(Hmax[1]+1):
866                hmin = k
867                if l < 0: hmin += 1
868                for h in range(hmin,Hmax[0]+1):
869                    H = []
870                    if CentCheck(Cent,[h,k,l]): H=[h,k,l]
871                    if H:
872                        rdsq = calc_rDsq(H,A)
873                        if 0 < rdsq <= dminsq:
874                            HKL.append([h,k,l,rdsq2d(rdsq,6),-1])
875
876    else:                                   #cubic
877        for l in range(Hmax[2]+1):
878            for k in range(l,Hmax[1]+1):
879                for h in range(k,Hmax[0]+1):
880                    H = []
881                    if CentCheck(Cent,[h,k,l]): H=[h,k,l]
882                    if H:
883                        rdsq = calc_rDsq(H,A)
884                        if 0 < rdsq <= dminsq:
885                            HKL.append([h,k,l,rdsq2d(rdsq,6),-1])
886    return sortHKLd(HKL,True,False)
887   
888def getHKLmax(dmin,SGData,A):
889    'finds maximum allowed hkl for given A within dmin'
890    SGLaue = SGData['SGLaue']
891    if SGLaue in ['3R','3mR']:        #Rhombohedral axes
892        Hmax = [0,0,0]
893        cell = A2cell(A)
894        aHx = cell[0]*math.sqrt(2.0*(1.0-cosd(cell[3])))
895        cHx = cell[0]*math.sqrt(3.0*(1.0+2.0*cosd(cell[3])))
896        Hmax[0] = Hmax[1] = int(round(aHx/dmin))
897        Hmax[2] = int(round(cHx/dmin))
898        #print Hmax,aHx,cHx
899    else:                           # all others
900        Hmax = MaxIndex(dmin,A)
901    return Hmax
902   
903def GenHLaue(dmin,SGData,A):
904    """Generate the crystallographically unique powder diffraction reflections
905    for a lattice and Bravais type
906   
907    :param dmin: minimum d-spacing
908    :param SGData: space group dictionary with at least
909   
910        * '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'
911        * 'SGLatt': lattice centering: one of 'P','A','B','C','I','F'
912        * 'SGUniq': code for unique monoclinic axis one of 'a','b','c' (only if 'SGLaue' is '2/m') otherwise an empty string
913       
914    :param A: reciprocal metric tensor elements as [G11,G22,G33,2*G12,2*G13,2*G23]
915    :return: HKL = list of [h,k,l,d] sorted with largest d first and is unique
916            part of reciprocal space ignoring anomalous dispersion
917           
918    """
919    import math
920    SGLaue = SGData['SGLaue']
921    SGLatt = SGData['SGLatt']
922    SGUniq = SGData['SGUniq']
923    #finds maximum allowed hkl for given A within dmin
924    Hmax = getHKLmax(dmin,SGData,A)
925       
926    dminsq = 1./(dmin**2)
927    HKL = []
928    if SGLaue == '-1':                       #triclinic
929        for l in range(-Hmax[2],Hmax[2]+1):
930            for k in range(-Hmax[1],Hmax[1]+1):
931                hmin = 0
932                if (k < 0) or (k ==0 and l < 0): hmin = 1
933                for h in range(hmin,Hmax[0]+1):
934                    H = []
935                    if CentCheck(SGLatt,[h,k,l]): H=[h,k,l]
936                    if H:
937                        rdsq = calc_rDsq(H,A)
938                        if 0 < rdsq <= dminsq:
939                            HKL.append([h,k,l,1/math.sqrt(rdsq)])
940    elif SGLaue == '2/m':                #monoclinic
941        axisnum = 1 + ['a','b','c'].index(SGUniq)
942        Hmax = SwapIndx(axisnum,Hmax)
943        for h in range(Hmax[0]+1):
944            for k in range(-Hmax[1],Hmax[1]+1):
945                lmin = 0
946                if k < 0:lmin = 1
947                for l in range(lmin,Hmax[2]+1):
948                    [h,k,l] = SwapIndx(-axisnum,[h,k,l])
949                    H = []
950                    if CentCheck(SGLatt,[h,k,l]): H=[h,k,l]
951                    if H:
952                        rdsq = calc_rDsq(H,A)
953                        if 0 < rdsq <= dminsq:
954                            HKL.append([h,k,l,1/math.sqrt(rdsq)])
955                    [h,k,l] = SwapIndx(axisnum,[h,k,l])
956    elif SGLaue in ['mmm','4/m','6/m']:            #orthorhombic
957        for l in range(Hmax[2]+1):
958            for h in range(Hmax[0]+1):
959                kmin = 1
960                if SGLaue == 'mmm' or h ==0: kmin = 0
961                for k in range(kmin,Hmax[1]+1):
962                    H = []
963                    if CentCheck(SGLatt,[h,k,l]): H=[h,k,l]
964                    if H:
965                        rdsq = calc_rDsq(H,A)
966                        if 0 < rdsq <= dminsq:
967                            HKL.append([h,k,l,1/math.sqrt(rdsq)])
968    elif SGLaue in ['4/mmm','6/mmm']:                  #tetragonal & hexagonal
969        for l in range(Hmax[2]+1):
970            for h in range(Hmax[0]+1):
971                for k in range(h+1):
972                    H = []
973                    if CentCheck(SGLatt,[h,k,l]): H=[h,k,l]
974                    if H:
975                        rdsq = calc_rDsq(H,A)
976                        if 0 < rdsq <= dminsq:
977                            HKL.append([h,k,l,1/math.sqrt(rdsq)])
978    elif SGLaue in ['3m1','31m','3','3R','3mR']:                  #trigonals
979        for l in range(-Hmax[2],Hmax[2]+1):
980            hmin = 0
981            if l < 0: hmin = 1
982            for h in range(hmin,Hmax[0]+1):
983                if SGLaue in ['3R','3']:
984                    kmax = h
985                    kmin = -int((h-1.)/2.)
986                else:
987                    kmin = 0
988                    kmax = h
989                    if SGLaue in ['3m1','3mR'] and l < 0: kmax = h-1
990                    if SGLaue == '31m' and l < 0: kmin = 1
991                for k in range(kmin,kmax+1):
992                    H = []
993                    if CentCheck(SGLatt,[h,k,l]): H=[h,k,l]
994                    if SGLaue in ['3R','3mR']:
995                        H = Hx2Rh(H)
996                    if H:
997                        rdsq = calc_rDsq(H,A)
998                        if 0 < rdsq <= dminsq:
999                            HKL.append([H[0],H[1],H[2],1/math.sqrt(rdsq)])
1000    else:                                   #cubic
1001        for h in range(Hmax[0]+1):
1002            for k in range(h+1):
1003                lmin = 0
1004                lmax = k
1005                if SGLaue =='m3':
1006                    lmax = h-1
1007                    if h == k: lmax += 1
1008                for l in range(lmin,lmax+1):
1009                    H = []
1010                    if CentCheck(SGLatt,[h,k,l]): H=[h,k,l]
1011                    if H:
1012                        rdsq = calc_rDsq(H,A)
1013                        if 0 < rdsq <= dminsq:
1014                            HKL.append([h,k,l,1/math.sqrt(rdsq)])
1015    return sortHKLd(HKL,True,True)
1016   
1017def GenPfHKLs(nMax,SGData,A):   
1018    """Generate the unique pole figure reflections for a lattice and Bravais type.
1019    Min d-spacing=1.0A & no more than nMax returned
1020   
1021    :param nMax: maximum number of hkls returned
1022    :param SGData: space group dictionary with at least
1023   
1024        * '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'
1025        * 'SGLatt': lattice centering: one of 'P','A','B','C','I','F'
1026        * 'SGUniq': code for unique monoclinic axis one of 'a','b','c' (only if 'SGLaue' is '2/m') otherwise an empty string
1027       
1028    :param A: reciprocal metric tensor elements as [G11,G22,G33,2*G12,2*G13,2*G23]
1029    :return: HKL = list of 'h k l' strings sorted with largest d first; no duplicate zones
1030           
1031    """
1032    HKL = np.array(GenHLaue(1.0,SGData,A)).T[:3].T     #strip d-spacings
1033    N = min(nMax,len(HKL))
1034    return ['%d %d %d'%(h[0],h[1],h[2]) for h in HKL[:N]]       
1035
1036def GenSSHLaue(dmin,SGData,SSGData,Vec,maxH,A):
1037    'needs a doc string'
1038    HKLs = []
1039    vec = np.array(Vec)
1040    vstar = np.sqrt(calc_rDsq(vec,A))     #find extra needed for -n SS reflections
1041    dvec = 1./(maxH*vstar+1./dmin)
1042    HKL = GenHLaue(dvec,SGData,A)       
1043    SSdH = [vec*h for h in range(-maxH,maxH+1)]
1044    SSdH = dict(zip(range(-maxH,maxH+1),SSdH))
1045    for h,k,l,d in HKL:
1046        ext = G2spc.GenHKLf([h,k,l],SGData)[0]  #h,k,l must be integral values here
1047        if not ext and d >= dmin:
1048            HKLs.append([h,k,l,0,d])
1049        for dH in SSdH:
1050            if dH:
1051                DH = SSdH[dH]
1052                H = [h+DH[0],k+DH[1],l+DH[2]]
1053                d = 1/np.sqrt(calc_rDsq(H,A))
1054                if d >= dmin:
1055                    HKLM = np.array([h,k,l,dH])
1056                    if G2spc.checkSSLaue([h,k,l,dH],SGData,SSGData) and G2spc.checkSSextc(HKLM,SSGData):
1057                        HKLs.append([h,k,l,dH,d])   
1058    return HKLs
1059   
1060def LaueUnique2(SGData,refList):
1061    ''' Impose Laue symmetry on hkl
1062    :param SGData: space group data from 'P '+Laue
1063    :param HKLF: np.array([[h,k,l,...]]) reflection set to be converted
1064   
1065    :return: HKLF new reflection array with imposed Laue symmetry
1066    '''
1067    for ref in refList:
1068        H = ref[:3]
1069        Uniq = G2spc.GenHKLf(H,SGData)[2]
1070        Uniq = G2mth.sortArray(G2mth.sortArray(G2mth.sortArray(Uniq,2),1),0)
1071        ref[:3] = Uniq[-1]
1072    return refList
1073   
1074def LaueUnique(Laue,HKLF):
1075    ''' Impose Laue symmetry on hkl
1076    :param Laue: str Laue symbol
1077    centrosymmetric Laue groups
1078     ['-1','2/m','112/m','2/m11','mmm','-42m','-4m2','4/mmm','-3','-31m','-3m1',
1079     '6/m','6/mmm','m3','m3m']
1080     noncentrosymmetric Laue groups
1081     ['1','2','211','112','m','m11','11m','222','mm2','m2m','2mm',
1082     '4','-4','422','4mm','3','312','321','31m','3m1',
1083     '6','-6','622','6mm','-62m','-6m2','23','432','-43m']
1084    :param HKLF: np.array([[h,k,l,...]]) reflection set to be converted
1085   
1086    :return: HKLF new reflection array with imposed Laue symmetry
1087    '''
1088   
1089    HKLFT = HKLF.T
1090    mat41 = np.array([[0,1,0],[-1,0,0],[0,0,1]])    #hkl -> k,-h,l
1091    mat43 = np.array([[0,-1,0],[1,0,0],[0,0,1]])    #hkl -> -k,h,l
1092    mat4bar = np.array([[0,-1,0],[1,0,0],[0,0,-1]]) #hkl -> k,-h,-l
1093    mat31 = np.array([[-1,-1,0],[1,0,0],[0,0,1]])   #hkl -> ihl = -h-k,h,l
1094    mat32 = np.array([[0,1,0],[-1,-1,0],[0,0,1]])   #hkl -> kil = k,-h-k,l
1095    matd3 = np.array([[0,1,0],[0,0,1],[1,0,0]])     #hkl -> k,l,h
1096    matd3q = np.array([[0,0,-1],[-1,0,0],[0,1,0]])  #hkl -> -l,-h,k
1097    matd3t = np.array([[0,0,-1],[1,0,0],[0,-1,0]])  #hkl -> -l,h,-k
1098    matd3p = np.array([[0,1,0],[0,0,-1],[-1,0,0]])  #hkl -> k,-l,-h
1099    mat6 = np.array([[1,1,0],[-1,0,0],[0,0,1]])     #hkl -> h+k,-h,l really 65
1100    matdm = np.array([[0,1,0],[1,0,0],[0,0,1]])     #hkl -> k,h,l
1101    matdmt = np.array([[0,-1,0],[-1,0,0],[0,0,1]])    #hkl -> -k,-h,l
1102    matdmp = np.array([[-1,-1,0],[0,1,0],[0,0,1]])  #hkl -> -h-k,k,l
1103    matdmq = np.array([[-1,0,0],[1,1,0],[0,0,1]])   #hkl -> -h,h+k,l
1104    matkm = np.array([[-1,0,0],[1,1,0],[0,0,1]])    #hkl -> -h,h+k,l
1105    matkmp = np.array([[1,0,0],[-1,-1,0],[0,0,1]])  #hkl -> h,-h-k,l
1106    matd2 = np.array([[0,1,0],[1,0,0],[0,0,-1]])    #hkl -> k,h,-l
1107    matd2p = np.array([[-1,-1,0],[0,1,0],[0,0,-1]]) #hkl -> -h-k,k,-l
1108    matdm3 = np.array([[1,0,0],[0,0,1],[0,1,0]])    #hkl -> h,l,k
1109    mat2d43 = np.array([[0,1,0],[1,0,0],[0,0,1]])   #hkl -> k,-h,l
1110    math2 = np.array([[0,-1,0],[-1,0,0],[0,0,-1]])  #hkl -> -k,-h,-l
1111    matk2 = np.array([[-1,0,0],[1,1,0],[0,0,-1]])   #hkl -> -h,-i,-l
1112    #triclinic
1113    if Laue == '1': #ok
1114        pass
1115    elif Laue == '-1':  #ok
1116        HKLFT[:3] = np.where(HKLFT[0]<0,HKLFT[:3]*np.array([-1,-1,-1])[:,nxs],HKLFT[:3])
1117        HKLFT[:3] = np.where((HKLFT[0]==0)&(HKLFT[1]<0),HKLFT[:3]*np.array([-1,-1,-1])[:,nxs],HKLFT[:3])
1118        HKLFT[:3] = np.where((HKLFT[0]==0)&(HKLFT[2]<0),HKLFT[:3]*np.array([-1,-1,-1])[:,nxs],HKLFT[:3])
1119    #monoclinic
1120    #noncentrosymmetric - all ok
1121    elif Laue == '2': 
1122        HKLFT[:3] = np.where(HKLFT[0]<0,HKLFT[:3]*np.array([-1,1,-1])[:,nxs],HKLFT[:3])
1123        HKLFT[:3] = np.where((HKLFT[0]==0)&(HKLFT[2]<0),HKLFT[:3]*np.array([-1,1,-1])[:,nxs],HKLFT[:3])
1124    elif Laue == '1 1 2':
1125        HKLFT[:3] = np.where(HKLFT[0]<0,HKLFT[:3]*np.array([-1,-1,1])[:,nxs],HKLFT[:3])
1126        HKLFT[:3] = np.where((HKLFT[0]==0)&(HKLFT[1]<0),HKLFT[:3]*np.array([-1,-1,1])[:,nxs],HKLFT[:3])
1127    elif Laue == '2 1 1':   
1128        HKLFT[:3] = np.where(HKLFT[1]<0,HKLFT[:3]*np.array([1,-1,-1])[:,nxs],HKLFT[:3])
1129        HKLFT[:3] = np.where((HKLFT[1]==0)&(HKLFT[2]<0),HKLFT[:3]*np.array([1,-1,-1])[:,nxs],HKLFT[:3])
1130    elif Laue == 'm':
1131        HKLFT[:3] = np.where(HKLFT[1]<0,HKLFT[:3]*np.array([1,-1,1])[:,nxs],HKLFT[:3])
1132    elif Laue == 'm 1 1':
1133        HKLFT[:3] = np.where(HKLFT[0]<0,HKLFT[:3]*np.array([-1,1,1])[:,nxs],HKLFT[:3])
1134    elif Laue == '1 1 m':
1135        HKLFT[:3] = np.where(HKLFT[2]<0,HKLFT[:3]*np.array([1,1,-1])[:,nxs],HKLFT[:3])
1136    #centrosymmetric - all ok
1137    elif Laue == '2/m 1 1':       
1138        HKLFT[:3] = np.where(HKLFT[2]<0,HKLFT[:3]*np.array([1,-1,-1])[:,nxs],HKLFT[:3])
1139        HKLFT[:3] = np.where(HKLFT[0]<0,HKLFT[:3]*np.array([-1,1,1])[:,nxs],HKLFT[:3])
1140        HKLFT[:3] = np.where((HKLFT[2]*HKLFT[0]==0)&(HKLFT[1]<0),HKLFT[:3]*np.array([1,-1,1])[:,nxs],HKLFT[:3])
1141    elif Laue == '2/m':
1142        HKLFT[:3] = np.where(HKLFT[0]<0,HKLFT[:3]*np.array([-1,1,-1])[:,nxs],HKLFT[:3])
1143        HKLFT[:3] = np.where(HKLFT[1]<0,HKLFT[:3]*np.array([1,-1,1])[:,nxs],HKLFT[:3])
1144        HKLFT[:3] = np.where((HKLFT[0]*HKLFT[1]==0)&(HKLFT[2]<0),HKLFT[:3]*np.array([1,1,-1])[:,nxs],HKLFT[:3])
1145    elif Laue == '1 1 2/m':
1146        HKLFT[:3] = np.where(HKLFT[1]<0,HKLFT[:3]*np.array([-1,-1,1])[:,nxs],HKLFT[:3])
1147        HKLFT[:3] = np.where(HKLFT[2]<0,HKLFT[:3]*np.array([1,1,-1])[:,nxs],HKLFT[:3])
1148        HKLFT[:3] = np.where((HKLFT[1]*HKLFT[2]==0)&(HKLFT[0]<0),HKLFT[:3]*np.array([-1,1,1])[:,nxs],HKLFT[:3])
1149    #orthorhombic
1150    #noncentrosymmetric - all OK
1151    elif Laue == '2 2 2':
1152        HKLFT[:3] = np.where(HKLFT[0]<0,HKLFT[:3]*np.array([-1,-1,1])[:,nxs],HKLFT[:3])
1153        HKLFT[:3] = np.where(HKLFT[1]<0,HKLFT[:3]*np.array([1,-1,-1])[:,nxs],HKLFT[:3])
1154        HKLFT[:3] = np.where((HKLFT[0]==0)&(HKLFT[2]<0),HKLFT[:3]*np.array([1,1,-1])[:,nxs],HKLFT[:3])
1155        HKLFT[:3] = np.where((HKLFT[1]==0)&(HKLFT[2]<0),HKLFT[:3]*np.array([1,1,-1])[:,nxs],HKLFT[:3])
1156    elif Laue == 'm m 2':
1157        HKLFT[:3] = np.where(HKLFT[0]<0,HKLFT[:3]*np.array([-1,1,1])[:,nxs],HKLFT[:3])
1158        HKLFT[:3] = np.where(HKLFT[1]<0,HKLFT[:3]*np.array([1,-1,1])[:,nxs],HKLFT[:3])
1159    elif Laue == '2 m m': 
1160        HKLFT[:3] = np.where(HKLFT[1]<0,HKLFT[:3]*np.array([1,-1,1])[:,nxs],HKLFT[:3])
1161        HKLFT[:3] = np.where(HKLFT[2]<0,HKLFT[:3]*np.array([1,1,-1])[:,nxs],HKLFT[:3])
1162    elif Laue == 'm 2 m':
1163        HKLFT[:3] = np.where(HKLFT[0]<0,HKLFT[:3]*np.array([-1,1,1])[:,nxs],HKLFT[:3])
1164        HKLFT[:3] = np.where(HKLFT[2]<0,HKLFT[:3]*np.array([1,1,-1])[:,nxs],HKLFT[:3])
1165    #centrosymmetric - all ok
1166    elif Laue == 'm m m':
1167        HKLFT[:3] = np.where(HKLFT[0]<0,HKLFT[:3]*np.array([-1,1,1])[:,nxs],HKLFT[:3])
1168        HKLFT[:3] = np.where(HKLFT[1]<0,HKLFT[:3]*np.array([1,-1,1])[:,nxs],HKLFT[:3])
1169        HKLFT[:3] = np.where(HKLFT[2]<0,HKLFT[:3]*np.array([1,1,-1])[:,nxs],HKLFT[:3])
1170    #tetragonal
1171    #noncentrosymmetric - all ok
1172    elif Laue == '4':
1173        HKLFT[:3] = np.where(HKLFT[0]<0,HKLFT[:3]*np.array([-1,-1,1])[:,nxs],HKLFT[:3])
1174        HKLFT[:3] = np.where(HKLFT[1]<0,np.squeeze(np.inner(HKLF[:,:3],mat43[nxs,:,:])).T,HKLFT[:3])
1175        HKLFT[:3] = np.where((HKLFT[0]==0)&(HKLFT[1]>0),np.squeeze(np.inner(HKLF[:,:3],mat41[nxs,:,:])).T,HKLFT[:3])
1176    elif Laue == '-4': 
1177        HKLFT[:3] = np.where(HKLFT[0]<=0,HKLFT[:3]*np.array([-1,-1,1])[:,nxs],HKLFT[:3])     
1178        HKLFT[:3] = np.where(HKLFT[0]<=0,np.squeeze(np.inner(HKLF[:,:3],mat4bar[nxs,:,:])).T,HKLFT[:3])
1179        HKLFT[:3] = np.where(HKLFT[0]<=0,HKLFT[:3]*np.array([-1,-1,1])[:,nxs],HKLFT[:3])     
1180        HKLFT[:3] = np.where(HKLFT[1]<=0,np.squeeze(np.inner(HKLF[:,:3],mat4bar[nxs,:,:])).T,HKLFT[:3])
1181        HKLFT[:3] = np.where((HKLFT[0]==0)&(HKLFT[1]==0)&(HKLFT[2]<0),HKLFT[:3]*np.array([1,1,-1])[:,nxs],HKLFT[:3])
1182    elif Laue == '4 2 2':
1183        HKLFT[:3] = np.where(HKLFT[2]<0,HKLFT[:3]*np.array([1,-1,-1])[:,nxs],HKLFT[:3])
1184        HKLFT[:3] = np.where(HKLFT[0]<0,HKLFT[:3]*np.array([-1,-1,1])[:,nxs],HKLFT[:3])
1185        HKLFT[:3] = np.where(HKLFT[1]<0,np.squeeze(np.inner(HKLF[:,:3],mat43[nxs,:,:])).T,HKLFT[:3])
1186        HKLFT[:3] = np.where((HKLFT[2]==0)&(HKLFT[1]<HKLFT[0]),np.squeeze(np.inner(HKLF[:,:3],matd2[nxs,:,:])).T,HKLFT[:3])
1187        HKLFT[:3] = np.where(HKLFT[0]==0,np.squeeze(np.inner(HKLF[:,:3],matdm[nxs,:,:])).T,HKLFT[:3])   #in lieu od 2-fold
1188    elif Laue == '4 m m':
1189        HKLFT[:3] = np.where(HKLFT[0]<0,HKLFT[:3]*np.array([-1,-1,1])[:,nxs],HKLFT[:3])
1190        HKLFT[:3] = np.where(HKLFT[0]<0,HKLFT[:3]*np.array([-1,-1,1])[:,nxs],HKLFT[:3])
1191        HKLFT[:3] = np.where(HKLFT[1]<0,np.squeeze(np.inner(HKLF[:,:3],mat43[nxs,:,:])).T,HKLFT[:3])
1192        HKLFT[:3] = np.where(HKLFT[0]<HKLFT[1],np.squeeze(np.inner(HKLF[:,:3],matdm[nxs,:,:])).T,HKLFT[:3])
1193    elif Laue == '-4 2 m':
1194        HKLFT[:3] = np.where(HKLFT[0]<=0,HKLFT[:3]*np.array([-1,-1,1])[:,nxs],HKLFT[:3])     
1195        HKLFT[:3] = np.where(HKLFT[0]<=0,np.squeeze(np.inner(HKLF[:,:3],mat4bar[nxs,:,:])).T,HKLFT[:3])
1196        HKLFT[:3] = np.where(HKLFT[0]<=0,HKLFT[:3]*np.array([-1,-1,1])[:,nxs],HKLFT[:3])     
1197        HKLFT[:3] = np.where(HKLFT[1]<=0,np.squeeze(np.inner(HKLF[:,:3],mat4bar[nxs,:,:])).T,HKLFT[:3])
1198        HKLFT[:3] = np.where((HKLFT[0]==0)&(HKLFT[1]==0)&(HKLFT[2]<0),HKLFT[:3]*np.array([1,1,-1])[:,nxs],HKLFT[:3])
1199        HKLFT[:3] = np.where(HKLFT[1]<HKLFT[0],np.squeeze(np.inner(HKLF[:,:3],matdm[nxs,:,:])).T,HKLFT[:3])
1200        HKLFT[:3] = np.where((HKLFT[0]==0)&(HKLFT[2]<0),HKLFT[:3]*np.array([1,1,-1])[:,nxs],HKLFT[:3])
1201    elif Laue == '-4 m 2':
1202        HKLFT[:3] = np.where(HKLFT[2]<0,np.squeeze(np.inner(HKLF[:,:3],mat4bar[nxs,:,:])).T,HKLFT[:3])
1203        HKLFT[:3] = np.where(HKLFT[0]<=0,HKLFT[:3]*np.array([-1,-1,1])[:,nxs],HKLFT[:3])     
1204        HKLFT[:3] = np.where((HKLFT[2]==0)&(HKLFT[1]<=0),np.squeeze(np.inner(HKLF[:,:3],mat4bar[nxs,:,:])).T,HKLFT[:3])
1205        HKLFT[:3] = np.where((HKLFT[0]==0)&(HKLFT[1]<0),HKLFT[:3]*np.array([-1,-1,1])[:,nxs],HKLFT[:3])     
1206        HKLFT[:3] = np.where((HKLFT[2]==0)&(HKLFT[1]==0),np.squeeze(np.inner(HKLF[:,:3],mat4bar[nxs,:,:])).T,HKLFT[:3])
1207        HKLFT[:3] = np.where(HKLFT[1]<0,HKLFT[:3]*np.array([1,-1,1])[:,nxs],HKLFT[:3]) 
1208        HKLFT[:3] = np.where((HKLFT[2]==0)&(HKLFT[0]>HKLFT[1]),np.squeeze(np.inner(HKLF[:,:3],matdm[nxs,:,:])).T,HKLFT[:3])
1209    #centrosymmetric - all ok
1210    elif Laue == '4/m':
1211        HKLFT[:3] = np.where(HKLFT[2]<0,HKLFT[:3]*np.array([1,1,-1])[:,nxs],HKLFT[:3])
1212        HKLFT[:3] = np.where(HKLFT[0]<0,HKLFT[:3]*np.array([-1,-1,1])[:,nxs],HKLFT[:3])
1213        HKLFT[:3] = np.where(HKLFT[1]<0,np.squeeze(np.inner(HKLF[:,:3],mat43[nxs,:,:])).T,HKLFT[:3])
1214        HKLFT[:3] = np.where((HKLFT[0]==0)&(HKLFT[1]>0),np.squeeze(np.inner(HKLF[:,:3],mat41[nxs,:,:])).T,HKLFT[:3])
1215    elif Laue == '4/m m m':
1216        HKLFT[:3] = np.where(HKLFT[2]<0,HKLFT[:3]*np.array([1,1,-1])[:,nxs],HKLFT[:3])
1217        HKLFT[:3] = np.where(HKLFT[0]<0,HKLFT[:3]*np.array([-1,-1,1])[:,nxs],HKLFT[:3])
1218        HKLFT[:3] = np.where(HKLFT[1]<0,np.squeeze(np.inner(HKLF[:,:3],mat43[nxs,:,:])).T,HKLFT[:3])       
1219        HKLFT[:3] = np.where(HKLFT[1]<HKLFT[0],np.squeeze(np.inner(HKLF[:,:3],mat41[nxs,:,:])).T,HKLFT[:3])
1220        HKLFT[:3] = np.where(HKLFT[1]<0,HKLFT[:3]*np.array([1,-1,1])[:,nxs],HKLFT[:3])
1221    #trigonal - all hex cell
1222    #noncentrosymmetric - all ok
1223    elif Laue == '3':
1224        HKLFT[:3] = np.where(HKLFT[1]<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1225        HKLFT[:3] = np.where((HKLFT[0]+HKLFT[1])<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1226        HKLFT[:3] = np.where(HKLFT[1]==0,np.squeeze(np.inner(HKLF[:,:3],mat31[nxs,:,:])).T,HKLFT[:3])
1227    elif Laue == '3 1 2':
1228        HKLFT[:3] = np.where(HKLFT[2]<0,np.squeeze(np.inner(HKLF[:,:3],matk2[nxs,:,:])).T,HKLFT[:3])
1229        HKLFT[:3] = np.where(HKLFT[1]<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1230        HKLFT[:3] = np.where((HKLFT[0]+HKLFT[1])<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1231        HKLFT[:3] = np.where(HKLFT[1]==0,np.squeeze(np.inner(HKLF[:,:3],mat31[nxs,:,:])).T,HKLFT[:3])
1232        HKLFT[:3] = np.where(HKLFT[0]<0,np.squeeze(np.inner(HKLF[:,:3],matk2[nxs,:,:])).T,HKLFT[:3])
1233    elif Laue == '3 2 1':
1234        HKLFT[:3] = np.where(HKLFT[0]<=-2*HKLFT[1],np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1235        HKLFT[:3] = np.where(HKLFT[1]<-2*HKLFT[0],np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1236        HKLFT[:3] = np.where(HKLFT[1]<HKLFT[0],np.squeeze(np.inner(HKLF[:,:3],matd2[nxs,:,:])).T,HKLFT[:3])
1237        HKLFT[:3] = np.where((HKLFT[2]>0)&(HKLFT[1]==HKLFT[0]),np.squeeze(np.inner(HKLF[:,:3],matd2[nxs,:,:])).T,HKLFT[:3])
1238        HKLFT[:3] = np.squeeze(np.inner(HKLF[:,:3],matd2[nxs,:,:])).T
1239        HKLFT[:3] = np.where((HKLFT[0]!=0)&(HKLFT[2]>0)&(HKLFT[0]==-2*HKLFT[1]),HKLFT[:3]*np.array([1,1,-1])[:,nxs],HKLFT[:3])
1240    elif Laue == '3 1 m':
1241        HKLFT[:3] = np.where(HKLFT[0]>=HKLFT[1],np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1242        HKLFT[:3] = np.where(2*HKLFT[1]<-HKLFT[0],np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1243        HKLFT[:3] = np.where(HKLFT[1]>-2*HKLFT[0],np.squeeze(np.inner(HKLF[:,:3],matdmp[nxs,:,:])).T,HKLFT[:3])
1244        HKLFT[:3] = np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T
1245    elif Laue == '3 m 1':
1246        HKLFT[:3] = np.where(HKLFT[1]<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1247        HKLFT[:3] = np.where((HKLFT[1]+HKLFT[0])<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1248        HKLFT[:3] = np.where(HKLFT[0]<0,np.squeeze(np.inner(HKLF[:,:3],matkm[nxs,:,:])).T,HKLFT[:3])
1249    #centrosymmetric
1250    elif Laue == '-3':  #ok
1251        HKLFT[:3] = np.where(HKLFT[2]<0,HKLFT[:3]*np.array([-1,-1,-1])[:,nxs],HKLFT[:3])
1252        HKLFT[:3] = np.where(HKLFT[1]<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1253        HKLFT[:3] = np.where((HKLFT[0]+HKLFT[1])<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1254        HKLFT[:3] = np.where(HKLFT[1]==0,np.squeeze(np.inner(HKLF[:,:3],mat31[nxs,:,:])).T,HKLFT[:3])
1255        HKLFT[:3] = np.where((HKLFT[2]==0)&(HKLFT[0]<0),-np.squeeze(np.inner(HKLF[:,:3],mat31[nxs,:,:])).T,HKLFT[:3])
1256        HKLFT[:3] = np.where(HKLFT[0]<0,np.squeeze(np.inner(HKLF[:,:3],-mat31[nxs,:,:])).T,HKLFT[:3])   
1257    elif Laue == '-3 m 1':  #ok
1258        HKLFT[:3] = np.where(HKLFT[1]<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1259        HKLFT[:3] = np.where((HKLFT[1]+HKLFT[0])<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1260        HKLFT[:3] = np.where(HKLFT[0]<0,np.squeeze(np.inner(HKLF[:,:3],matkm[nxs,:,:])).T,HKLFT[:3])
1261        HKLFT[:3] = np.where(HKLFT[2]<0,np.squeeze(np.inner(HKLF[:,:3],matd2[nxs,:,:])).T,HKLFT[:3])
1262        HKLFT[:3] = np.where((HKLFT[2]==0)&(HKLFT[1]<HKLFT[0]),np.squeeze(np.inner(HKLF[:,:3],matd2[nxs,:,:])).T,HKLFT[:3])
1263    elif Laue == '-3 1 m':  #ok
1264        HKLFT[:3] = np.where(HKLFT[2]<0,HKLFT[:3]*np.array([-1,-1,-1])[:,nxs],HKLFT[:3])
1265        HKLFT[:3] = np.where(HKLFT[1]<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1266        HKLFT[:3] = np.where((HKLFT[0]+HKLFT[1])<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1267        HKLFT[:3] = np.where(HKLFT[1]==0,np.squeeze(np.inner(HKLF[:,:3],mat31[nxs,:,:])).T,HKLFT[:3])
1268        HKLFT[:3] = np.where(HKLFT[0]<=0,np.squeeze(np.inner(HKLF[:,:3],-mat31[nxs,:,:])).T,HKLFT[:3])   
1269        HKLFT[:3] = np.where(HKLFT[1]<HKLFT[0],np.squeeze(np.inner(HKLF[:,:3],matdm[nxs,:,:])).T,HKLFT[:3])
1270    #hexagonal
1271    #noncentrosymmetric
1272    elif Laue == '6':   #ok
1273        HKLFT[:3] = np.where(HKLFT[1]<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1274        HKLFT[:3] = np.where((HKLFT[0]+HKLFT[1])<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1275        HKLFT[:3] = np.where(HKLFT[0]<0,np.squeeze(np.inner(HKLF[:,:3],mat6[nxs,:,:])).T,HKLFT[:3])
1276        HKLFT[:3] = np.where(HKLFT[0]==0,np.squeeze(np.inner(HKLF[:,:3],mat6[nxs,:,:])).T,HKLFT[:3])
1277    elif Laue == '-6':  #ok
1278        HKLFT[:3] = np.where(HKLFT[2]<0,HKLFT[:3]*np.array([1,1,-1])[:,nxs],HKLFT[:3])
1279        HKLFT[:3] = np.where(HKLFT[1]<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1280        HKLFT[:3] = np.where((HKLFT[0]+HKLFT[1])<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1281        HKLFT[:3] = np.where(HKLFT[1]==0,np.squeeze(np.inner(HKLF[:,:3],mat31[nxs,:,:])).T,HKLFT[:3])
1282    elif Laue == '6 2 2':   #ok
1283        HKLFT[:3] = np.where(HKLFT[2]<0,np.squeeze(np.inner(HKLF[:,:3],matd2[nxs,:,:])).T,HKLFT[:3])
1284        HKLFT[:3] = np.where(HKLFT[1]<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1285        HKLFT[:3] = np.where((HKLFT[0]+HKLFT[1])<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1286        HKLFT[:3] = np.where(HKLFT[0]<0,np.squeeze(np.inner(HKLF[:,:3],mat6[nxs,:,:])).T,HKLFT[:3])
1287        HKLFT[:3] = np.where(HKLFT[1]==0,np.squeeze(np.inner(HKLF[:,:3],matdm[nxs,:,:])).T,HKLFT[:3])
1288        HKLFT[:3] = np.where((HKLFT[2]==0)&(HKLFT[0]>HKLFT[1]),np.squeeze(np.inner(HKLF[:,:3],matdm[nxs,:,:])).T,HKLFT[:3])
1289    elif Laue == '6 m m':   #ok
1290        HKLFT[:3] = np.where(HKLFT[1]<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1291        HKLFT[:3] = np.where((HKLFT[0]+HKLFT[1])<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1292        HKLFT[:3] = np.where(HKLFT[0]<0,np.squeeze(np.inner(HKLF[:,:3],mat6[nxs,:,:])).T,HKLFT[:3])
1293        HKLFT[:3] = np.where(HKLFT[0]==0,np.squeeze(np.inner(HKLF[:,:3],mat6[nxs,:,:])).T,HKLFT[:3])
1294        HKLFT[:3] = np.where(HKLFT[0]>HKLFT[1],np.squeeze(np.inner(HKLF[:,:3],matdm[nxs,:,:])).T,HKLFT[:3])
1295    elif Laue == '-6 m 2':  #ok
1296        HKLFT[:3] = np.where(HKLFT[2]<0,np.squeeze(np.inner(HKLF[:,:3],matk2[nxs,:,:])).T,HKLFT[:3])
1297        HKLFT[:3] = np.where(HKLFT[1]<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1298        HKLFT[:3] = np.where((HKLFT[0]+HKLFT[1])<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1299        HKLFT[:3] = np.where(HKLFT[1]==0,np.squeeze(np.inner(HKLF[:,:3],mat31[nxs,:,:])).T,HKLFT[:3])
1300        HKLFT[:3] = np.where(HKLFT[0]<0,np.squeeze(np.inner(HKLF[:,:3],matk2[nxs,:,:])).T,HKLFT[:3])
1301        HKLFT[:3] = np.where(HKLFT[2]<0,HKLFT[:3]*np.array([1,1,-1])[:,nxs],HKLFT[:3])
1302    elif Laue == '-6 2 m':  #ok
1303        HKLFT[:3] = np.where(HKLFT[2]<0,np.squeeze(np.inner(HKLF[:,:3],matd2[nxs,:,:])).T,HKLFT[:3])
1304        HKLFT[:3] = np.where(HKLFT[0]<=-2*HKLFT[1],np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1305        HKLFT[:3] = np.where(HKLFT[1]<-2*HKLFT[0],np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1306        HKLFT[:3] = np.where(HKLFT[1]<HKLFT[0],np.squeeze(np.inner(HKLF[:,:3],matd2[nxs,:,:])).T,HKLFT[:3])
1307        HKLFT[:3] = np.where((HKLFT[2]>0)&(HKLFT[1]==HKLFT[0]),np.squeeze(np.inner(HKLF[:,:3],matd2[nxs,:,:])).T,HKLFT[:3])
1308        HKLFT[:3] = np.squeeze(np.inner(HKLF[:,:3],matd2[nxs,:,:])).T
1309        HKLFT[:3] = np.where(HKLFT[2]<0,np.squeeze(np.inner(HKLF[:,:3],matd2[nxs,:,:])).T,HKLFT[:3])
1310        HKLFT[:3] = np.where(HKLFT[0]>HKLFT[1],np.squeeze(np.inner(HKLF[:,:3],matdm[nxs,:,:])).T,HKLFT[:3])
1311    #centrosymmetric
1312    elif Laue == '6/m': #ok
1313        HKLFT[:3] = np.where(HKLFT[2]<0,HKLFT[:3]*np.array([1,1,-1])[:,nxs],HKLFT[:3])
1314        HKLFT[:3] = np.where(HKLFT[1]<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1315        HKLFT[:3] = np.where((HKLFT[0]+HKLFT[1])<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1316        HKLFT[:3] = np.where(HKLFT[0]<0,np.squeeze(np.inner(HKLF[:,:3],mat6[nxs,:,:])).T,HKLFT[:3])
1317        HKLFT[:3] = np.where(HKLFT[0]==0,np.squeeze(np.inner(HKLF[:,:3],mat6[nxs,:,:])).T,HKLFT[:3])
1318    elif Laue == '6/m m m': #ok
1319        HKLFT[:3] = np.where(HKLFT[2]<0,HKLFT[:3]*np.array([1,1,-1])[:,nxs],HKLFT[:3])
1320        HKLFT[:3] = np.where(HKLFT[1]<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1321        HKLFT[:3] = np.where((HKLFT[0]+HKLFT[1])<0,np.squeeze(np.inner(HKLF[:,:3],mat32[nxs,:,:])).T,HKLFT[:3])
1322        HKLFT[:3] = np.where(HKLFT[0]<0,np.squeeze(np.inner(HKLF[:,:3],mat6[nxs,:,:])).T,HKLFT[:3])
1323        HKLFT[:3] = np.where(HKLFT[0]>HKLFT[1],np.squeeze(np.inner(HKLF[:,:3],matdm.T[nxs,:,:])).T,HKLFT[:3])
1324    #cubic - all ok
1325    #noncentrosymmetric -
1326    elif Laue == '2 3': 
1327        HKLFT[:3] = np.where(HKLFT[0]<0,HKLFT[:3]*np.array([-1,-1,1])[:,nxs],HKLFT[:3])
1328        HKLFT[:3] = np.where(HKLFT[1]<0,HKLFT[:3]*np.array([1,-1,-1])[:,nxs],HKLFT[:3])
1329        HKLFT[:3] = np.where((HKLFT[0]==0)&(HKLFT[2]<0),HKLFT[:3]*np.array([1,1,-1])[:,nxs],HKLFT[:3])
1330        HKLFT[:3] = np.where((HKLFT[1]==0)&(HKLFT[2]<0),HKLFT[:3]*np.array([1,1,-1])[:,nxs],HKLFT[:3])
1331        HKLFT[:3] = np.where((HKLFT[2]>=0)&((HKLFT[0]>=HKLFT[2])|(HKLFT[1]>HKLFT[2])),np.squeeze(np.inner(HKLF[:,:3],matd3[nxs,:,:])).T,HKLFT[:3])
1332        HKLFT[:3] = np.where((HKLFT[2]>=0)&((HKLFT[0]>=HKLFT[2])|(HKLFT[1]>HKLFT[2])),np.squeeze(np.inner(HKLF[:,:3],matd3[nxs,:,:])).T,HKLFT[:3])
1333        HKLFT[:3] = np.where((HKLFT[2]<0)&((HKLFT[0]>-HKLFT[2])|(HKLFT[1]>-HKLFT[2])),np.squeeze(np.inner(HKLF[:,:3],matd3t[nxs,:,:])).T,HKLFT[:3])
1334        HKLFT[:3] = np.where((HKLFT[2]<0)&((HKLFT[0]>-HKLFT[2])|(HKLFT[1]>=-HKLFT[2])),np.squeeze(np.inner(HKLF[:,:3],matd3t[nxs,:,:])).T,HKLFT[:3])
1335        HKLFT[:3] = np.where(HKLFT[2]<0,HKLFT[:3]*np.array([-1,1,-1])[:,nxs],HKLFT[:3])       
1336    elif Laue == '4 3 2':   
1337        HKLFT[:3] = np.where(HKLFT[2]<0,HKLFT[:3]*np.array([1,-1,-1])[:,nxs],HKLFT[:3])
1338        HKLFT[:3] = np.where(HKLFT[0]<0,HKLFT[:3]*np.array([-1,-1,1])[:,nxs],HKLFT[:3])
1339        HKLFT[:3] = np.where(HKLFT[1]<0,np.squeeze(np.inner(HKLF[:,:3],mat43[nxs,:,:])).T,HKLFT[:3])
1340        HKLFT[:3] = np.where((HKLFT[2]==0)&(HKLFT[1]<HKLFT[0]),np.squeeze(np.inner(HKLF[:,:3],matd2[nxs,:,:])).T,HKLFT[:3])
1341        HKLFT[:3] = np.where(HKLFT[0]==0,np.squeeze(np.inner(HKLF[:,:3],matdm[nxs,:,:])).T,HKLFT[:3])   #in lieu od 2-fold
1342        HKLFT[:3] = np.where((HKLFT[0]>=HKLFT[2])|(HKLFT[1]>HKLFT[2]),np.squeeze(np.inner(HKLF[:,:3],matd3[nxs,:,:])).T,HKLFT[:3])
1343        HKLFT[:3] = np.where((HKLFT[0]>=HKLFT[2])|(HKLFT[1]>HKLFT[2]),np.squeeze(np.inner(HKLF[:,:3],matd3[nxs,:,:])).T,HKLFT[:3])
1344        HKLFT[:3] = np.where(HKLFT[1]==0,np.squeeze(np.inner(HKLF[:,:3],mat2d43[nxs,:,:])).T,HKLFT[:3])
1345    elif Laue == '-4 3 m': 
1346        HKLFT[:3] = np.where(HKLFT[0]<=0,HKLFT[:3]*np.array([-1,-1,1])[:,nxs],HKLFT[:3])     
1347        HKLFT[:3] = np.where(HKLFT[0]<=0,np.squeeze(np.inner(HKLF[:,:3],mat4bar[nxs,:,:])).T,HKLFT[:3])
1348        HKLFT[:3] = np.where(HKLFT[0]<=0,HKLFT[:3]*np.array([-1,-1,1])[:,nxs],HKLFT[:3])     
1349        HKLFT[:3] = np.where(HKLFT[1]<=0,np.squeeze(np.inner(HKLF[:,:3],mat4bar[nxs,:,:])).T,HKLFT[:3])
1350        HKLFT[:3] = np.where((HKLFT[0]==0)&(HKLFT[1]==0)&(HKLFT[2]<0),HKLFT[:3]*np.array([1,1,-1])[:,nxs],HKLFT[:3])
1351        HKLFT[:3] = np.where(HKLFT[1]<HKLFT[0],np.squeeze(np.inner(HKLF[:,:3],matdm[nxs,:,:])).T,HKLFT[:3])
1352        HKLFT[:3] = np.where((HKLFT[0]==0)&(HKLFT[2]<0),HKLFT[:3]*np.array([1,1,-1])[:,nxs],HKLFT[:3])
1353        HKLFT[:3] = np.where((HKLFT[2]>=0)&((HKLFT[0]>=HKLFT[2])|(HKLFT[1]>HKLFT[2])),np.squeeze(np.inner(HKLF[:,:3],matd3[nxs,:,:])).T,HKLFT[:3])
1354        HKLFT[:3] = np.where((HKLFT[2]>=0)&((HKLFT[0]>=HKLFT[2])|(HKLFT[1]>HKLFT[2])),np.squeeze(np.inner(HKLF[:,:3],matd3[nxs,:,:])).T,HKLFT[:3])
1355        HKLFT[:3] = np.where((HKLFT[2]>=0)&(HKLFT[1]<HKLFT[0]),np.squeeze(np.inner(HKLF[:,:3],matdm[nxs,:,:])).T,HKLFT[:3])
1356        HKLFT[:3] = np.where(HKLFT[2]<0,HKLFT[:3]*np.array([-1,1,-1])[:,nxs],HKLFT[:3]) 
1357        HKLFT[:3] = np.where((HKLFT[0]<0)&(HKLFT[2]<-HKLFT[0])&(HKLFT[1]>HKLFT[2]),np.squeeze(np.inner(HKLF[:,:3],matd3q[nxs,:,:])).T,HKLFT[:3])
1358        HKLFT[:3] = np.where((HKLFT[0]<0)&(HKLFT[2]>=-HKLFT[0])&(HKLFT[1]>HKLFT[2]),np.squeeze(np.inner(HKLF[:,:3],matdm3[nxs,:,:])).T,HKLFT[:3])
1359    #centrosymmetric
1360    elif Laue == 'm 3':
1361        HKLFT[:3] = np.where(HKLFT[0]<0,HKLFT[:3]*np.array([-1,1,1])[:,nxs],HKLFT[:3])
1362        HKLFT[:3] = np.where(HKLFT[1]<0,HKLFT[:3]*np.array([1,-1,1])[:,nxs],HKLFT[:3])
1363        HKLFT[:3] = np.where(HKLFT[2]<0,HKLFT[:3]*np.array([1,1,-1])[:,nxs],HKLFT[:3])           
1364        HKLFT[:3] = np.where((HKLFT[2]>=0)&((HKLFT[0]>=HKLFT[2])|(HKLFT[1]>HKLFT[2])),np.squeeze(np.inner(HKLF[:,:3],matd3[nxs,:,:])).T,HKLFT[:3])
1365        HKLFT[:3] = np.where((HKLFT[2]>=0)&((HKLFT[0]>=HKLFT[2])|(HKLFT[1]>HKLFT[2])),np.squeeze(np.inner(HKLF[:,:3],matd3[nxs,:,:])).T,HKLFT[:3])
1366    elif Laue == 'm 3 m':
1367        HKLFT[:3] = np.where(HKLFT[0]<0,HKLFT[:3]*np.array([-1,1,1])[:,nxs],HKLFT[:3])
1368        HKLFT[:3] = np.where(HKLFT[1]<0,HKLFT[:3]*np.array([1,-1,1])[:,nxs],HKLFT[:3])
1369        HKLFT[:3] = np.where(HKLFT[2]<0,HKLFT[:3]*np.array([1,1,-1])[:,nxs],HKLFT[:3])           
1370        HKLFT[:3] = np.where((HKLFT[2]>=0)&((HKLFT[0]>=HKLFT[2])|(HKLFT[1]>HKLFT[2])),np.squeeze(np.inner(HKLF[:,:3],matd3[nxs,:,:])).T,HKLFT[:3])
1371        HKLFT[:3] = np.where((HKLFT[2]>=0)&((HKLFT[0]>=HKLFT[2])|(HKLFT[1]>HKLFT[2])),np.squeeze(np.inner(HKLF[:,:3],matd3[nxs,:,:])).T,HKLFT[:3])
1372        HKLFT[:3] = np.where(HKLFT[0]>HKLFT[1],np.squeeze(np.inner(HKLF[:,:3],matdm[nxs,:,:])).T,HKLFT[:3])
1373    return HKLFT.T
1374       
1375
1376#Spherical harmonics routines
1377def OdfChk(SGLaue,L,M):
1378    'needs doc string'
1379    if not L%2 and abs(M) <= L:
1380        if SGLaue == '0':                      #cylindrical symmetry
1381            if M == 0: return True
1382        elif SGLaue == '-1':
1383            return True
1384        elif SGLaue == '2/m':
1385            if not abs(M)%2: return True
1386        elif SGLaue == 'mmm':
1387            if not abs(M)%2 and M >= 0: return True
1388        elif SGLaue == '4/m':
1389            if not abs(M)%4: return True
1390        elif SGLaue == '4/mmm':
1391            if not abs(M)%4 and M >= 0: return True
1392        elif SGLaue in ['3R','3']:
1393            if not abs(M)%3: return True
1394        elif SGLaue in ['3mR','3m1','31m']:
1395            if not abs(M)%3 and M >= 0: return True
1396        elif SGLaue == '6/m':
1397            if not abs(M)%6: return True
1398        elif SGLaue == '6/mmm':
1399            if not abs(M)%6 and M >= 0: return True
1400        elif SGLaue == 'm3':
1401            if M > 0:
1402                if L%12 == 2:
1403                    if M <= L/12: return True
1404                else:
1405                    if M <= L/12+1: return True
1406        elif SGLaue == 'm3m':
1407            if M > 0:
1408                if L%12 == 2:
1409                    if M <= L/12: return True
1410                else:
1411                    if M <= L/12+1: return True
1412    return False
1413       
1414def GenSHCoeff(SGLaue,SamSym,L,IfLMN=True):
1415    'needs doc string'
1416    coeffNames = []
1417    for iord in [2*i+2 for i in range(L/2)]:
1418        for m in [i-iord for i in range(2*iord+1)]:
1419            if OdfChk(SamSym,iord,m):
1420                for n in [i-iord for i in range(2*iord+1)]:
1421                    if OdfChk(SGLaue,iord,n):
1422                        if IfLMN:
1423                            coeffNames.append('C(%d,%d,%d)'%(iord,m,n))
1424                        else:
1425                            coeffNames.append('C(%d,%d)'%(iord,n))
1426    return coeffNames
1427   
1428def CrsAng(H,cell,SGData):
1429    'needs doc string'
1430    a,b,c,al,be,ga = cell
1431    SQ3 = 1.732050807569
1432    H1 = np.array([1,0,0])
1433    H2 = np.array([0,1,0])
1434    H3 = np.array([0,0,1])
1435    H4 = np.array([1,1,1])
1436    G,g = cell2Gmat(cell)
1437    Laue = SGData['SGLaue']
1438    Naxis = SGData['SGUniq']
1439    if len(H.shape) == 1:
1440        DH = np.inner(H,np.inner(G,H))
1441    else:
1442        DH = np.array([np.inner(h,np.inner(G,h)) for h in H])
1443    if Laue == '2/m':
1444        if Naxis == 'a':
1445            DR = np.inner(H1,np.inner(G,H1))
1446            DHR = np.inner(H,np.inner(G,H1))
1447        elif Naxis == 'b':
1448            DR = np.inner(H2,np.inner(G,H2))
1449            DHR = np.inner(H,np.inner(G,H2))
1450        else:
1451            DR = np.inner(H3,np.inner(G,H3))
1452            DHR = np.inner(H,np.inner(G,H3))
1453    elif Laue in ['R3','R3m']:
1454        DR = np.inner(H4,np.inner(G,H4))
1455        DHR = np.inner(H,np.inner(G,H4))
1456    else:
1457        DR = np.inner(H3,np.inner(G,H3))
1458        DHR = np.inner(H,np.inner(G,H3))
1459    DHR /= np.sqrt(DR*DH)
1460    phi = np.where(DHR <= 1.0,acosd(DHR),0.0)
1461    if Laue == '-1':
1462        BA = H.T[1]*a/(b-H.T[0]*cosd(ga))
1463        BB = H.T[0]*sind(ga)**2
1464    elif Laue == '2/m':
1465        if Naxis == 'a':
1466            BA = H.T[2]*b/(c-H.T[1]*cosd(al))
1467            BB = H.T[1]*sind(al)**2
1468        elif Naxis == 'b':
1469            BA = H.T[0]*c/(a-H.T[2]*cosd(be))
1470            BB = H.T[2]*sind(be)**2
1471        else:
1472            BA = H.T[1]*a/(b-H.T[0]*cosd(ga))
1473            BB = H.T[0]*sind(ga)**2
1474    elif Laue in ['mmm','4/m','4/mmm']:
1475        BA = H.T[1]*a
1476        BB = H.T[0]*b
1477    elif Laue in ['3R','3mR']:
1478        BA = H.T[0]+H.T[1]-2.0*H.T[2]
1479        BB = SQ3*(H.T[0]-H.T[1])
1480    elif Laue in ['m3','m3m']:
1481        BA = H.T[1]
1482        BB = H.T[0]
1483    else:
1484        BA = H.T[0]+2.0*H.T[1]
1485        BB = SQ3*H.T[0]
1486    beta = atan2d(BA,BB)
1487    return phi,beta
1488   
1489def SamAng(Tth,Gangls,Sangl,IFCoup):
1490    """Compute sample orientation angles vs laboratory coord. system
1491
1492    :param Tth:        Signed theta                                   
1493    :param Gangls:     Sample goniometer angles phi,chi,omega,azmuth 
1494    :param Sangl:      Sample angle zeros om-0, chi-0, phi-0         
1495    :param IFCoup:     True if omega & 2-theta coupled in CW scan
1496    :returns: 
1497        psi,gam:    Sample odf angles                             
1498        dPSdA,dGMdA:    Angle zero derivatives
1499    """                         
1500   
1501    if IFCoup:
1502        GSomeg = sind(Gangls[2]+Tth)
1503        GComeg = cosd(Gangls[2]+Tth)
1504    else:
1505        GSomeg = sind(Gangls[2])
1506        GComeg = cosd(Gangls[2])
1507    GSTth = sind(Tth)
1508    GCTth = cosd(Tth)     
1509    GSazm = sind(Gangls[3])
1510    GCazm = cosd(Gangls[3])
1511    GSchi = sind(Gangls[1])
1512    GCchi = cosd(Gangls[1])
1513    GSphi = sind(Gangls[0]+Sangl[2])
1514    GCphi = cosd(Gangls[0]+Sangl[2])
1515    SSomeg = sind(Sangl[0])
1516    SComeg = cosd(Sangl[0])
1517    SSchi = sind(Sangl[1])
1518    SCchi = cosd(Sangl[1])
1519    AT = -GSTth*GComeg+GCTth*GCazm*GSomeg
1520    BT = GSTth*GSomeg+GCTth*GCazm*GComeg
1521    CT = -GCTth*GSazm*GSchi
1522    DT = -GCTth*GSazm*GCchi
1523   
1524    BC1 = -AT*GSphi+(CT+BT*GCchi)*GCphi
1525    BC2 = DT-BT*GSchi
1526    BC3 = AT*GCphi+(CT+BT*GCchi)*GSphi
1527     
1528    BC = BC1*SComeg*SCchi+BC2*SComeg*SSchi-BC3*SSomeg     
1529    psi = acosd(BC)
1530   
1531    BD = 1.0-BC**2
1532    C = np.where(BD>1.e-6,rpd/np.sqrt(BD),0.)
1533    dPSdA = [-C*(-BC1*SSomeg*SCchi-BC2*SSomeg*SSchi-BC3*SComeg),
1534        -C*(-BC1*SComeg*SSchi+BC2*SComeg*SCchi),
1535        -C*(-BC1*SSomeg-BC3*SComeg*SCchi)]
1536     
1537    BA = -BC1*SSchi+BC2*SCchi
1538    BB = BC1*SSomeg*SCchi+BC2*SSomeg*SSchi+BC3*SComeg
1539    gam = atan2d(BB,BA)
1540
1541    BD = (BA**2+BB**2)/rpd
1542
1543    dBAdO = 0
1544    dBAdC = -BC1*SCchi-BC2*SSchi
1545    dBAdF = BC3*SSchi
1546   
1547    dBBdO = BC1*SComeg*SCchi+BC2*SComeg*SSchi-BC3*SSomeg
1548    dBBdC = -BC1*SSomeg*SSchi+BC2*SSomeg*SCchi
1549    dBBdF = BC1*SComeg-BC3*SSomeg*SCchi
1550   
1551    dGMdA = np.where(BD > 1.e-6,[(BA*dBBdO-BB*dBAdO)/BD,(BA*dBBdC-BB*dBAdC)/BD, \
1552        (BA*dBBdF-BB*dBAdF)/BD],[np.zeros_like(BD),np.zeros_like(BD),np.zeros_like(BD)])
1553       
1554    return psi,gam,dPSdA,dGMdA
1555
1556BOH = {
1557'L=2':[[],[],[]],
1558'L=4':[[0.30469720,0.36418281],[],[]],
1559'L=6':[[-0.14104740,0.52775103],[],[]],
1560'L=8':[[0.28646862,0.21545346,0.32826995],[],[]],
1561'L=10':[[-0.16413497,0.33078546,0.39371345],[],[]],
1562'L=12':[[0.26141975,0.27266871,0.03277460,0.32589402],
1563    [0.09298802,-0.23773812,0.49446631,0.0],[]],
1564'L=14':[[-0.17557309,0.25821932,0.27709173,0.33645360],[],[]],
1565'L=16':[[0.24370673,0.29873515,0.06447688,0.00377,0.32574495],
1566    [0.12039646,-0.25330128,0.23950998,0.40962508,0.0],[]],
1567'L=18':[[-0.16914245,0.17017340,0.34598142,0.07433932,0.32696037],
1568    [-0.06901768,0.16006562,-0.24743528,0.47110273,0.0],[]],
1569'L=20':[[0.23067026,0.31151832,0.09287682,0.01089683,0.00037564,0.32573563],
1570    [0.13615420,-0.25048007,0.12882081,0.28642879,0.34620433,0.0],[]],
1571'L=22':[[-0.16109560,0.10244188,0.36285175,0.13377513,0.01314399,0.32585583],
1572    [-0.09620055,0.20244115,-0.22389483,0.17928946,0.42017231,0.0],[]],
1573'L=24':[[0.22050742,0.31770654,0.11661736,0.02049853,0.00150861,0.00003426,0.32573505],
1574    [0.13651722,-0.21386648,0.00522051,0.33939435,0.10837396,0.32914497,0.0],
1575    [0.05378596,-0.11945819,0.16272298,-0.26449730,0.44923956,0.0,0.0]],
1576'L=26':[[-0.15435003,0.05261630,0.35524646,0.18578869,0.03259103,0.00186197,0.32574594],
1577    [-0.11306511,0.22072681,-0.18706142,0.05439948,0.28122966,0.35634355,0.0],[]],
1578'L=28':[[0.21225019,0.32031716,0.13604702,0.03132468,0.00362703,0.00018294,0.00000294,0.32573501],
1579    [0.13219496,-0.17206256,-0.08742608,0.32671661,0.17973107,0.02567515,0.32619598,0.0],
1580    [0.07989184,-0.16735346,0.18839770,-0.20705337,0.12926808,0.42715602,0.0,0.0]],
1581'L=30':[[-0.14878368,0.01524973,0.33628434,0.22632587,0.05790047,0.00609812,0.00022898,0.32573594],
1582    [-0.11721726,0.20915005,-0.11723436,-0.07815329,0.31318947,0.13655742,0.33241385,0.0],
1583    [-0.04297703,0.09317876,-0.11831248,0.17355132,-0.28164031,0.42719361,0.0,0.0]],
1584'L=32':[[0.20533892,0.32087437,0.15187897,0.04249238,0.00670516,0.00054977,0.00002018,0.00000024,0.32573501],
1585    [0.12775091,-0.13523423,-0.14935701,0.28227378,0.23670434,0.05661270,0.00469819,0.32578978,0.0],
1586    [0.09703829,-0.19373733,0.18610682,-0.14407046,0.00220535,0.26897090,0.36633402,0.0,0.0]],
1587'L=34':[[-0.14409234,-0.01343681,0.31248977,0.25557722,0.08571889,0.01351208,0.00095792,0.00002550,0.32573508],
1588    [-0.11527834,0.18472133,-0.04403280,-0.16908618,0.27227021,0.21086614,0.04041752,0.32688152,0.0],
1589    [-0.06773139,0.14120811,-0.15835721,0.18357456,-0.19364673,0.08377174,0.43116318,0.0,0.0]]
1590}
1591
1592Lnorm = lambda L: 4.*np.pi/(2.0*L+1.)
1593
1594def GetKcl(L,N,SGLaue,phi,beta):
1595    'needs doc string'
1596    import pytexture as ptx
1597    if SGLaue in ['m3','m3m']:
1598        if 'array' in str(type(phi)) and np.any(phi.shape):
1599            Kcl = np.zeros_like(phi)
1600        else:
1601            Kcl = 0.
1602        for j in range(0,L+1,4):
1603            im = j/4
1604            if 'array' in str(type(phi)) and np.any(phi.shape):
1605                pcrs = ptx.pyplmpsi(L,j,len(phi),phi)[0]
1606            else:
1607                pcrs = ptx.pyplmpsi(L,j,1,phi)[0]
1608            Kcl += BOH['L=%d'%(L)][N-1][im]*pcrs*cosd(j*beta)       
1609    else:
1610        if 'array' in str(type(phi)) and np.any(phi.shape):
1611            pcrs = ptx.pyplmpsi(L,N,len(phi),phi)[0]
1612        else:
1613            pcrs = ptx.pyplmpsi(L,N,1,phi)[0]
1614        pcrs *= RSQ2PI
1615        if N:
1616            pcrs *= SQ2
1617        if SGLaue in ['mmm','4/mmm','6/mmm','R3mR','3m1','31m']:
1618            if SGLaue in ['3mR','3m1','31m']: 
1619                if N%6 == 3:
1620                    Kcl = pcrs*sind(N*beta)
1621                else:
1622                    Kcl = pcrs*cosd(N*beta)
1623            else:
1624                Kcl = pcrs*cosd(N*beta)
1625        else:
1626            Kcl = pcrs*(cosd(N*beta)+sind(N*beta))
1627    return Kcl
1628   
1629def GetKsl(L,M,SamSym,psi,gam):
1630    'needs doc string'
1631    import pytexture as ptx
1632    if 'array' in str(type(psi)) and np.any(psi.shape):
1633        psrs,dpdps = ptx.pyplmpsi(L,M,len(psi),psi)
1634    else:
1635        psrs,dpdps = ptx.pyplmpsi(L,M,1,psi)
1636    psrs *= RSQ2PI
1637    dpdps *= RSQ2PI
1638    if M:
1639        psrs *= SQ2
1640        dpdps *= SQ2
1641    if SamSym in ['mmm',]:
1642        dum = cosd(M*gam)
1643        Ksl = psrs*dum
1644        dKsdp = dpdps*dum
1645        dKsdg = -psrs*M*sind(M*gam)
1646    else:
1647        dum = cosd(M*gam)+sind(M*gam)
1648        Ksl = psrs*dum
1649        dKsdp = dpdps*dum
1650        dKsdg = psrs*M*(-sind(M*gam)+cosd(M*gam))
1651    return Ksl,dKsdp,dKsdg
1652   
1653def GetKclKsl(L,N,SGLaue,psi,phi,beta):
1654    """
1655    This is used for spherical harmonics description of preferred orientation;
1656        cylindrical symmetry only (M=0) and no sample angle derivatives returned
1657    """
1658    import pytexture as ptx
1659    Ksl,x = ptx.pyplmpsi(L,0,1,psi)
1660    Ksl *= RSQ2PI
1661    if SGLaue in ['m3','m3m']:
1662        Kcl = 0.0
1663        for j in range(0,L+1,4):
1664            im = j/4
1665            pcrs,dum = ptx.pyplmpsi(L,j,1,phi)
1666            Kcl += BOH['L=%d'%(L)][N-1][im]*pcrs*cosd(j*beta)       
1667    else:
1668        pcrs,dum = ptx.pyplmpsi(L,N,1,phi)
1669        pcrs *= RSQ2PI
1670        if N:
1671            pcrs *= SQ2
1672        if SGLaue in ['mmm','4/mmm','6/mmm','R3mR','3m1','31m']:
1673            if SGLaue in ['3mR','3m1','31m']: 
1674                if N%6 == 3:
1675                    Kcl = pcrs*sind(N*beta)
1676                else:
1677                    Kcl = pcrs*cosd(N*beta)
1678            else:
1679                Kcl = pcrs*cosd(N*beta)
1680        else:
1681            Kcl = pcrs*(cosd(N*beta)+sind(N*beta))
1682    return Kcl*Ksl,Lnorm(L)
1683   
1684def Glnh(Start,SHCoef,psi,gam,SamSym):
1685    'needs doc string'
1686    import pytexture as ptx
1687
1688    if Start:
1689        ptx.pyqlmninit()
1690        Start = False
1691    Fln = np.zeros(len(SHCoef))
1692    for i,term in enumerate(SHCoef):
1693        l,m,n = eval(term.strip('C'))
1694        pcrs,dum = ptx.pyplmpsi(l,m,1,psi)
1695        pcrs *= RSQPI
1696        if m == 0:
1697            pcrs /= SQ2
1698        if SamSym in ['mmm',]:
1699            Ksl = pcrs*cosd(m*gam)
1700        else:
1701            Ksl = pcrs*(cosd(m*gam)+sind(m*gam))
1702        Fln[i] = SHCoef[term]*Ksl*Lnorm(l)
1703    ODFln = dict(zip(SHCoef.keys(),list(zip(SHCoef.values(),Fln))))
1704    return ODFln
1705
1706def Flnh(Start,SHCoef,phi,beta,SGData):
1707    'needs doc string'
1708    import pytexture as ptx
1709   
1710    if Start:
1711        ptx.pyqlmninit()
1712        Start = False
1713    Fln = np.zeros(len(SHCoef))
1714    for i,term in enumerate(SHCoef):
1715        l,m,n = eval(term.strip('C'))
1716        if SGData['SGLaue'] in ['m3','m3m']:
1717            Kcl = 0.0
1718            for j in range(0,l+1,4):
1719                im = j/4
1720                pcrs,dum = ptx.pyplmpsi(l,j,1,phi)
1721                Kcl += BOH['L='+str(l)][n-1][im]*pcrs*cosd(j*beta)       
1722        else:                #all but cubic
1723            pcrs,dum = ptx.pyplmpsi(l,n,1,phi)
1724            pcrs *= RSQPI
1725            if n == 0:
1726                pcrs /= SQ2
1727            if SGData['SGLaue'] in ['mmm','4/mmm','6/mmm','R3mR','3m1','31m']:
1728               if SGData['SGLaue'] in ['3mR','3m1','31m']: 
1729                   if n%6 == 3:
1730                       Kcl = pcrs*sind(n*beta)
1731                   else:
1732                       Kcl = pcrs*cosd(n*beta)
1733               else:
1734                   Kcl = pcrs*cosd(n*beta)
1735            else:
1736                Kcl = pcrs*(cosd(n*beta)+sind(n*beta))
1737        Fln[i] = SHCoef[term]*Kcl*Lnorm(l)
1738    ODFln = dict(zip(SHCoef.keys(),list(zip(SHCoef.values(),Fln))))
1739    return ODFln
1740   
1741def polfcal(ODFln,SamSym,psi,gam):
1742    '''Perform a pole figure computation.
1743    Note that the the number of gam values must either be 1 or must
1744    match psi. Updated for numpy 1.8.0
1745    '''
1746    import pytexture as ptx
1747    PolVal = np.ones_like(psi)
1748    for term in ODFln:
1749        if abs(ODFln[term][1]) > 1.e-3:
1750            l,m,n = eval(term.strip('C'))
1751            psrs,dum = ptx.pyplmpsi(l,m,len(psi),psi)
1752            if SamSym in ['-1','2/m']:
1753                if m:
1754                    Ksl = RSQPI*psrs*(cosd(m*gam)+sind(m*gam))
1755                else:
1756                    Ksl = RSQPI*psrs/SQ2
1757            else:
1758                if m:
1759                    Ksl = RSQPI*psrs*cosd(m*gam)
1760                else:
1761                    Ksl = RSQPI*psrs/SQ2
1762            PolVal += ODFln[term][1]*Ksl
1763    return PolVal
1764   
1765def invpolfcal(ODFln,SGData,phi,beta):
1766    'needs doc string'
1767    import pytexture as ptx
1768   
1769    invPolVal = np.ones_like(beta)
1770    for term in ODFln:
1771        if abs(ODFln[term][1]) > 1.e-3:
1772            l,m,n = eval(term.strip('C'))
1773            if SGData['SGLaue'] in ['m3','m3m']:
1774                Kcl = 0.0
1775                for j in range(0,l+1,4):
1776                    im = j/4
1777                    pcrs,dum = ptx.pyplmpsi(l,j,len(beta),phi)
1778                    Kcl += BOH['L=%d'%(l)][n-1][im]*pcrs*cosd(j*beta)       
1779            else:                #all but cubic
1780                pcrs,dum = ptx.pyplmpsi(l,n,len(beta),phi)
1781                pcrs *= RSQPI
1782                if n == 0:
1783                    pcrs /= SQ2
1784                if SGData['SGLaue'] in ['mmm','4/mmm','6/mmm','R3mR','3m1','31m']:
1785                   if SGData['SGLaue'] in ['3mR','3m1','31m']: 
1786                       if n%6 == 3:
1787                           Kcl = pcrs*sind(n*beta)
1788                       else:
1789                           Kcl = pcrs*cosd(n*beta)
1790                   else:
1791                       Kcl = pcrs*cosd(n*beta)
1792                else:
1793                    Kcl = pcrs*(cosd(n*beta)+sind(n*beta))
1794            invPolVal += ODFln[term][1]*Kcl
1795    return invPolVal
1796   
1797   
1798def textureIndex(SHCoef):
1799    'needs doc string'
1800    Tindx = 1.0
1801    for term in SHCoef:
1802        l = eval(term.strip('C'))[0]
1803        Tindx += SHCoef[term]**2/(2.0*l+1.)
1804    return Tindx
1805   
1806# self-test materials follow.
1807selftestlist = []
1808'''Defines a list of self-tests'''
1809selftestquiet = True
1810def _ReportTest():
1811    'Report name and doc string of current routine when ``selftestquiet`` is False'
1812    if not selftestquiet:
1813        import inspect
1814        caller = inspect.stack()[1][3]
1815        doc = eval(caller).__doc__
1816        if doc is not None:
1817            print('testing '+__file__+' with '+caller+' ('+doc+')')
1818        else:
1819            print('testing '+__file__()+" with "+caller)
1820NeedTestData = True
1821def TestData():
1822    array = np.array
1823    global NeedTestData
1824    NeedTestData = False
1825    global CellTestData
1826    # output from uctbx computed on platform darwin on 2010-05-28
1827    CellTestData = [
1828# cell, g, G, cell*, V, V*
1829  [(4, 4, 4, 90, 90, 90), 
1830   array([[  1.60000000e+01,   9.79717439e-16,   9.79717439e-16],
1831       [  9.79717439e-16,   1.60000000e+01,   9.79717439e-16],
1832       [  9.79717439e-16,   9.79717439e-16,   1.60000000e+01]]), array([[  6.25000000e-02,   3.82702125e-18,   3.82702125e-18],
1833       [  3.82702125e-18,   6.25000000e-02,   3.82702125e-18],
1834       [  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],
1835# cell, g, G, cell*, V, V*
1836  [(4.0999999999999996, 5.2000000000000002, 6.2999999999999998, 100, 80, 130), 
1837   array([[ 16.81      , -13.70423184,   4.48533243],
1838       [-13.70423184,  27.04      ,  -5.6887143 ],
1839       [  4.48533243,  -5.6887143 ,  39.69      ]]), array([[ 0.10206349,  0.05083339, -0.00424823],
1840       [ 0.05083339,  0.06344997,  0.00334956],
1841       [-0.00424823,  0.00334956,  0.02615544]]), (0.31947376387537696, 0.25189277536327803, 0.16172643497798223, 85.283666420376008, 94.716333579624006, 50.825714168082683), 100.98576357983838, 0.0099023858863968445],
1842# cell, g, G, cell*, V, V*
1843  [(3.5, 3.5, 6, 90, 90, 120), 
1844   array([[  1.22500000e+01,  -6.12500000e+00,   1.28587914e-15],
1845       [ -6.12500000e+00,   1.22500000e+01,   1.28587914e-15],
1846       [  1.28587914e-15,   1.28587914e-15,   3.60000000e+01]]), array([[  1.08843537e-01,   5.44217687e-02,   3.36690552e-18],
1847       [  5.44217687e-02,   1.08843537e-01,   3.36690552e-18],
1848       [  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],
1849  ]
1850    global CoordTestData
1851    CoordTestData = [
1852# cell, ((frac, ortho),...)
1853  ((4,4,4,90,90,90,), [
1854 ((0.10000000000000001, 0.0, 0.0),(0.40000000000000002, 0.0, 0.0)),
1855 ((0.0, 0.10000000000000001, 0.0),(2.4492935982947065e-17, 0.40000000000000002, 0.0)),
1856 ((0.0, 0.0, 0.10000000000000001),(2.4492935982947065e-17, -2.4492935982947065e-17, 0.40000000000000002)),
1857 ((0.10000000000000001, 0.20000000000000001, 0.29999999999999999),(0.40000000000000013, 0.79999999999999993, 1.2)),
1858 ((0.20000000000000001, 0.29999999999999999, 0.10000000000000001),(0.80000000000000016, 1.2, 0.40000000000000002)),
1859 ((0.29999999999999999, 0.20000000000000001, 0.10000000000000001),(1.2, 0.80000000000000004, 0.40000000000000002)),
1860 ((0.5, 0.5, 0.5),(2.0, 1.9999999999999998, 2.0)),
1861]),
1862# cell, ((frac, ortho),...)
1863  ((4.1,5.2,6.3,100,80,130,), [
1864 ((0.10000000000000001, 0.0, 0.0),(0.40999999999999998, 0.0, 0.0)),
1865 ((0.0, 0.10000000000000001, 0.0),(-0.33424955703700043, 0.39834311042186865, 0.0)),
1866 ((0.0, 0.0, 0.10000000000000001),(0.10939835193016617, -0.051013289294572106, 0.6183281045774256)),
1867 ((0.10000000000000001, 0.20000000000000001, 0.29999999999999999),(0.069695941716497567, 0.64364635296002093, 1.8549843137322766)),
1868 ((0.20000000000000001, 0.29999999999999999, 0.10000000000000001),(-0.073350319180835066, 1.1440160419710339, 0.6183281045774256)),
1869 ((0.29999999999999999, 0.20000000000000001, 0.10000000000000001),(0.67089923785616512, 0.74567293154916525, 0.6183281045774256)),
1870 ((0.5, 0.5, 0.5),(0.92574397446582857, 1.7366491056364828, 3.0916405228871278)),
1871]),
1872# cell, ((frac, ortho),...)
1873  ((3.5,3.5,6,90,90,120,), [
1874 ((0.10000000000000001, 0.0, 0.0),(0.35000000000000003, 0.0, 0.0)),
1875 ((0.0, 0.10000000000000001, 0.0),(-0.17499999999999993, 0.3031088913245536, 0.0)),
1876 ((0.0, 0.0, 0.10000000000000001),(3.6739403974420595e-17, -3.6739403974420595e-17, 0.60000000000000009)),
1877 ((0.10000000000000001, 0.20000000000000001, 0.29999999999999999),(2.7675166561703527e-16, 0.60621778264910708, 1.7999999999999998)),
1878 ((0.20000000000000001, 0.29999999999999999, 0.10000000000000001),(0.17500000000000041, 0.90932667397366063, 0.60000000000000009)),
1879 ((0.29999999999999999, 0.20000000000000001, 0.10000000000000001),(0.70000000000000018, 0.6062177826491072, 0.60000000000000009)),
1880 ((0.5, 0.5, 0.5),(0.87500000000000067, 1.5155444566227676, 3.0)),
1881]),
1882]
1883    global LaueTestData             #generated by GSAS
1884    LaueTestData = {
1885    '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),
1886        (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),
1887        (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))],
1888    '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),
1889        (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),
1890        (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),
1891        (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))],
1892    '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),
1893        (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),
1894        (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),
1895        (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),
1896        (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),
1897        (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),
1898        (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),
1899        (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),
1900        (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),
1901        (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),
1902        (2,1,5,6),(2,1,-5,6),(3,-1,-5,6))],
1903    '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),
1904        (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),
1905        (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),
1906        (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),
1907        (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),
1908        (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),
1909        (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),
1910        (3,0,4,6),(3,1,-2,12),(3,0,-4,6),(1,1,6,12),(2,2,3,12))],
1911    '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),
1912        (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),
1913        (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),
1914        (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),
1915        (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),
1916        (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),
1917        (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))],
1918    }
1919   
1920    global FLnhTestData
1921    FLnhTestData = [{
1922    'C(4,0,0)': (0.965, 0.42760447),
1923    'C(2,0,0)': (1.0122, -0.80233610),
1924    'C(2,0,2)': (0.0061, 8.37491546E-03),
1925    'C(6,0,4)': (-0.0898, 4.37985696E-02),
1926    'C(6,0,6)': (-0.1369, -9.04081762E-02),
1927    'C(6,0,0)': (0.5935, -0.18234928),
1928    'C(4,0,4)': (0.1872, 0.16358127),
1929    'C(6,0,2)': (0.6193, 0.27573633),
1930    'C(4,0,2)': (-0.1897, 0.12530720)},[1,0,0]]
1931def test0():
1932    if NeedTestData: TestData()
1933    msg = 'test cell2Gmat, fillgmat, Gmat2cell'
1934    for (cell, tg, tG, trcell, tV, trV) in CellTestData:
1935        G, g = cell2Gmat(cell)
1936        assert np.allclose(G,tG),msg
1937        assert np.allclose(g,tg),msg
1938        tcell = Gmat2cell(g)
1939        assert np.allclose(cell,tcell),msg
1940        tcell = Gmat2cell(G)
1941        assert np.allclose(tcell,trcell),msg
1942selftestlist.append(test0)
1943
1944def test1():
1945    'test cell2A and A2Gmat'
1946    _ReportTest()
1947    if NeedTestData: TestData()
1948    msg = 'test cell2A and A2Gmat'
1949    for (cell, tg, tG, trcell, tV, trV) in CellTestData:
1950        G, g = A2Gmat(cell2A(cell))
1951        assert np.allclose(G,tG),msg
1952        assert np.allclose(g,tg),msg
1953selftestlist.append(test1)
1954
1955def test2():
1956    'test Gmat2A, A2cell, A2Gmat, Gmat2cell'
1957    _ReportTest()
1958    if NeedTestData: TestData()
1959    msg = 'test Gmat2A, A2cell, A2Gmat, Gmat2cell'
1960    for (cell, tg, tG, trcell, tV, trV) in CellTestData:
1961        G, g = cell2Gmat(cell)
1962        tcell = A2cell(Gmat2A(G))
1963        assert np.allclose(cell,tcell),msg
1964selftestlist.append(test2)
1965
1966def test3():
1967    'test invcell2Gmat'
1968    _ReportTest()
1969    if NeedTestData: TestData()
1970    msg = 'test invcell2Gmat'
1971    for (cell, tg, tG, trcell, tV, trV) in CellTestData:
1972        G, g = invcell2Gmat(trcell)
1973        assert np.allclose(G,tG),msg
1974        assert np.allclose(g,tg),msg
1975selftestlist.append(test3)
1976
1977def test4():
1978    'test calc_rVsq, calc_rV, calc_V'
1979    _ReportTest()
1980    if NeedTestData: TestData()
1981    msg = 'test calc_rVsq, calc_rV, calc_V'
1982    for (cell, tg, tG, trcell, tV, trV) in CellTestData:
1983        assert np.allclose(calc_rV(cell2A(cell)),trV), msg
1984        assert np.allclose(calc_V(cell2A(cell)),tV), msg
1985selftestlist.append(test4)
1986
1987def test5():
1988    'test A2invcell'
1989    _ReportTest()
1990    if NeedTestData: TestData()
1991    msg = 'test A2invcell'
1992    for (cell, tg, tG, trcell, tV, trV) in CellTestData:
1993        rcell = A2invcell(cell2A(cell))
1994        assert np.allclose(rcell,trcell),msg
1995selftestlist.append(test5)
1996
1997def test6():
1998    'test cell2AB'
1999    _ReportTest()
2000    if NeedTestData: TestData()
2001    msg = 'test cell2AB'
2002    for (cell,coordlist) in CoordTestData:
2003        A,B = cell2AB(cell)
2004        for (frac,ortho) in coordlist:
2005            to = np.inner(A,frac)
2006            tf = np.inner(B,to)
2007            assert np.allclose(ortho,to), msg
2008            assert np.allclose(frac,tf), msg
2009            to = np.sum(A*frac,axis=1)
2010            tf = np.sum(B*to,axis=1)
2011            assert np.allclose(ortho,to), msg
2012            assert np.allclose(frac,tf), msg
2013selftestlist.append(test6)
2014
2015def test7():
2016    'test GetBraviasNum(...) and GenHBravais(...)'
2017    _ReportTest()
2018    import os.path
2019    import sys
2020    import GSASIIspc as spc
2021    testdir = os.path.join(os.path.split(os.path.abspath( __file__ ))[0],'testinp')
2022    if os.path.exists(testdir):
2023        if testdir not in sys.path: sys.path.insert(0,testdir)
2024    import sgtbxlattinp
2025    derror = 1e-4
2026    def indexmatch(hklin, hkllist, system):
2027        for hklref in hkllist:
2028            hklref = list(hklref)
2029            # these permutations are far from complete, but are sufficient to
2030            # allow the test to complete
2031            if system == 'cubic':
2032                permlist = [(1,2,3),(1,3,2),(2,1,3),(2,3,1),(3,1,2),(3,2,1),]
2033            elif system == 'monoclinic':
2034                permlist = [(1,2,3),(-1,2,-3)]
2035            else:
2036                permlist = [(1,2,3)]
2037
2038            for perm in permlist:
2039                hkl = [abs(i) * hklin[abs(i)-1] / i for i in perm]
2040                if hkl == hklref: return True
2041                if [-i for i in hkl] == hklref: return True
2042        else:
2043            return False
2044
2045    for key in sgtbxlattinp.sgtbx7:
2046        spdict = spc.SpcGroup(key)
2047        cell = sgtbxlattinp.sgtbx7[key][0]
2048        system = spdict[1]['SGSys']
2049        center = spdict[1]['SGLatt']
2050
2051        bravcode = GetBraviasNum(center, system)
2052
2053        g2list = GenHBravais(sgtbxlattinp.dmin, bravcode, cell2A(cell))
2054
2055        assert len(sgtbxlattinp.sgtbx7[key][1]) == len(g2list), 'Reflection lists differ for %s' % key
2056        for h,k,l,d,num in g2list:
2057            for hkllist,dref in sgtbxlattinp.sgtbx7[key][1]: 
2058                if abs(d-dref) < derror:
2059                    if indexmatch((h,k,l,), hkllist, system):
2060                        break
2061            else:
2062                assert 0,'No match for %s at %s (%s)' % ((h,k,l),d,key)
2063selftestlist.append(test7)
2064
2065def test8():
2066    'test GenHLaue'
2067    _ReportTest()
2068    import GSASIIspc as spc
2069    import sgtbxlattinp
2070    derror = 1e-4
2071    dmin = sgtbxlattinp.dmin
2072
2073    def indexmatch(hklin, hklref, system, axis):
2074        # these permutations are far from complete, but are sufficient to
2075        # allow the test to complete
2076        if system == 'cubic':
2077            permlist = [(1,2,3),(1,3,2),(2,1,3),(2,3,1),(3,1,2),(3,2,1),]
2078        elif system == 'monoclinic' and axis=='b':
2079            permlist = [(1,2,3),(-1,2,-3)]
2080        elif system == 'monoclinic' and axis=='a':
2081            permlist = [(1,2,3),(1,-2,-3)]
2082        elif system == 'monoclinic' and axis=='c':
2083            permlist = [(1,2,3),(-1,-2,3)]
2084        elif system == 'trigonal':
2085            permlist = [(1,2,3),(2,1,3),(-1,-2,3),(-2,-1,3)]
2086        elif system == 'rhombohedral':
2087            permlist = [(1,2,3),(2,3,1),(3,1,2)]
2088        else:
2089            permlist = [(1,2,3)]
2090
2091        hklref = list(hklref)
2092        for perm in permlist:
2093            hkl = [abs(i) * hklin[abs(i)-1] / i for i in perm]
2094            if hkl == hklref: return True
2095            if [-i for i in hkl] == hklref: return True
2096        return False
2097
2098    for key in sgtbxlattinp.sgtbx8:
2099        spdict = spc.SpcGroup(key)[1]
2100        cell = sgtbxlattinp.sgtbx8[key][0]
2101        center = spdict['SGLatt']
2102        Laue = spdict['SGLaue']
2103        Axis = spdict['SGUniq']
2104        system = spdict['SGSys']
2105
2106        g2list = GenHLaue(dmin,spdict,cell2A(cell))
2107        #if len(g2list) != len(sgtbxlattinp.sgtbx8[key][1]):
2108        #    print 'failed',key,':' ,len(g2list),'vs',len(sgtbxlattinp.sgtbx8[key][1])
2109        #    print 'GSAS-II:'
2110        #    for h,k,l,d in g2list: print '  ',(h,k,l),d
2111        #    print 'SGTBX:'
2112        #    for hkllist,dref in sgtbxlattinp.sgtbx8[key][1]: print '  ',hkllist,dref
2113        assert len(g2list) == len(sgtbxlattinp.sgtbx8[key][1]), (
2114            'Reflection lists differ for %s' % key
2115            )
2116        #match = True
2117        for h,k,l,d in g2list:
2118            for hkllist,dref in sgtbxlattinp.sgtbx8[key][1]: 
2119                if abs(d-dref) < derror:
2120                    if indexmatch((h,k,l,), hkllist, system, Axis): break
2121            else:
2122                assert 0,'No match for %s at %s (%s)' % ((h,k,l),d,key)
2123                #match = False
2124        #if not match:
2125            #for hkllist,dref in sgtbxlattinp.sgtbx8[key][1]: print '  ',hkllist,dref
2126            #print center, Laue, Axis, system
2127selftestlist.append(test8)
2128           
2129def test9():
2130    'test GenHLaue'
2131    _ReportTest()
2132    import GSASIIspc as G2spc
2133    if NeedTestData: TestData()
2134    for spc in LaueTestData:
2135        data = LaueTestData[spc]
2136        cell = data[0]
2137        hklm = np.array(data[1])
2138        H = hklm[-1][:3]
2139        hklO = hklm.T[:3].T
2140        A = cell2A(cell)
2141        dmin = 1./np.sqrt(calc_rDsq(H,A))
2142        SGData = G2spc.SpcGroup(spc)[1]
2143        hkls = np.array(GenHLaue(dmin,SGData,A))
2144        hklN = hkls.T[:3].T
2145        #print spc,hklO.shape,hklN.shape
2146        err = True
2147        for H in hklO:
2148            if H not in hklN:
2149                print H,' missing from hkl from GSASII'
2150                err = False
2151        assert(err)
2152selftestlist.append(test9)
2153       
2154       
2155   
2156
2157if __name__ == '__main__':
2158    # run self-tests
2159    selftestquiet = False
2160    for test in selftestlist:
2161        test()
2162    print "OK"
Note: See TracBrowser for help on using the repository browser.