source: trunk/GSASIIlattice.py @ 2233

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

force transposed phase atoms to be in unit cell
modify structure plot to reflect moved, transposed, etc. atoms directly

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