source: trunk/GSASIIlattice.py @ 2219

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

allow fractions in transformation matrix/vector elements
fix cell doubling transformations

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