source: trunk/GSASIIimage.py @ 4104

Last change on this file since 4104 was 4104, checked in by toby, 4 years ago

new mode for combined fit of wavelength to a set of images

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 60.7 KB
Line 
1# -*- coding: utf-8 -*-
2#GSASII image calculations: ellipse fitting & image integration       
3########### SVN repository information ###################
4# $Date: 2019-08-21 02:06:16 +0000 (Wed, 21 Aug 2019) $
5# $Author: toby $
6# $Revision: 4104 $
7# $URL: trunk/GSASIIimage.py $
8# $Id: GSASIIimage.py 4104 2019-08-21 02:06:16Z toby $
9########### SVN repository information ###################
10'''
11*GSASIIimage: Image calc module*
12================================
13
14Ellipse fitting & image integration
15
16'''
17from __future__ import division, print_function
18import math
19import time
20import numpy as np
21import numpy.linalg as nl
22import numpy.ma as ma
23from scipy.optimize import leastsq
24import scipy.interpolate as scint
25import copy
26import GSASIIpath
27GSASIIpath.SetVersionNumber("$Revision: 4104 $")
28try:
29    import GSASIIplot as G2plt
30except ImportError: # expected in scriptable w/o matplotlib and/or wx
31    pass
32import GSASIIlattice as G2lat
33import GSASIIpwd as G2pwd
34import GSASIIspc as G2spc
35import GSASIImath as G2mth
36import GSASIIfiles as G2fil
37
38# trig functions in degrees
39sind = lambda x: math.sin(x*math.pi/180.)
40asind = lambda x: 180.*math.asin(x)/math.pi
41tand = lambda x: math.tan(x*math.pi/180.)
42atand = lambda x: 180.*math.atan(x)/math.pi
43atan2d = lambda y,x: 180.*math.atan2(y,x)/math.pi
44cosd = lambda x: math.cos(x*math.pi/180.)
45acosd = lambda x: 180.*math.acos(x)/math.pi
46rdsq2d = lambda x,p: round(1.0/math.sqrt(x),p)
47#numpy versions
48npsind = lambda x: np.sin(x*np.pi/180.)
49npasind = lambda x: 180.*np.arcsin(x)/np.pi
50npcosd = lambda x: np.cos(x*np.pi/180.)
51npacosd = lambda x: 180.*np.arccos(x)/np.pi
52nptand = lambda x: np.tan(x*np.pi/180.)
53npatand = lambda x: 180.*np.arctan(x)/np.pi
54npatan2d = lambda y,x: 180.*np.arctan2(y,x)/np.pi
55nxs = np.newaxis
56debug = False
57   
58def pointInPolygon(pXY,xy):
59    'Needs a doc string'
60    #pXY - assumed closed 1st & last points are duplicates
61    Inside = False
62    N = len(pXY)
63    p1x,p1y = pXY[0]
64    for i in range(N+1):
65        p2x,p2y = pXY[i%N]
66        if (max(p1y,p2y) >= xy[1] > min(p1y,p2y)) and (xy[0] <= max(p1x,p2x)):
67            if p1y != p2y:
68                xinters = (xy[1]-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
69            if p1x == p2x or xy[0] <= xinters:
70                Inside = not Inside
71        p1x,p1y = p2x,p2y
72    return Inside
73   
74def peneCorr(tth,dep,dist,tilt=0.,azm=0.):
75    'Needs a doc string'
76#    return dep*(1.-npcosd(abs(tilt*npsind(azm))-tth*npcosd(azm)))  #something wrong here
77    return dep*(1.-npcosd(tth))*dist**2/1000.         #best one
78#    return dep*npsind(tth)             #not as good as 1-cos2Q
79       
80def makeMat(Angle,Axis):
81    '''Make rotation matrix from Angle and Axis
82
83    :param float Angle: in degrees
84    :param int Axis: 0 for rotation about x, 1 for about y, etc.
85    '''
86    cs = npcosd(Angle)
87    ss = npsind(Angle)
88    M = np.array(([1.,0.,0.],[0.,cs,-ss],[0.,ss,cs]),dtype=np.float32)
89    return np.roll(np.roll(M,Axis,axis=0),Axis,axis=1)
90                   
91def FitEllipse(xy):
92   
93    def ellipse_center(p):
94        ''' gives ellipse center coordinates
95        '''
96        b,c,d,f,a = p[1]/2., p[2], p[3]/2., p[4]/2., p[0]
97        num = b*b-a*c
98        x0=(c*d-b*f)/num
99        y0=(a*f-b*d)/num
100        return np.array([x0,y0])
101   
102    def ellipse_angle_of_rotation( p ):
103        ''' gives rotation of ellipse major axis from x-axis
104        range will be -90 to 90 deg
105        '''
106        b,c,a = p[1]/2., p[2], p[0]
107        return 0.5*npatand(2*b/(a-c))
108   
109    def ellipse_axis_length( p ):
110        ''' gives ellipse radii in [minor,major] order
111        '''
112        b,c,d,f,g,a = p[1]/2., p[2], p[3]/2., p[4]/2, p[5], p[0]
113        up = 2*(a*f*f+c*d*d+g*b*b-2*b*d*f-a*c*g)
114        down1=(b*b-a*c)*( (c-a)*np.sqrt(1+4*b*b/((a-c)*(a-c)))-(c+a))
115        down2=(b*b-a*c)*( (a-c)*np.sqrt(1+4*b*b/((a-c)*(a-c)))-(c+a))
116        res1=np.sqrt(up/down1)
117        res2=np.sqrt(up/down2)
118        return np.array([ res2,res1])
119   
120    xy = np.array(xy)
121    x = np.asarray(xy.T[0])[:,np.newaxis]
122    y = np.asarray(xy.T[1])[:,np.newaxis]
123    D =  np.hstack((x*x, x*y, y*y, x, y, np.ones_like(x)))
124    S = np.dot(D.T,D)
125    C = np.zeros([6,6])
126    C[0,2] = C[2,0] = 2; C[1,1] = -1
127    E, V =  nl.eig(np.dot(nl.inv(S), C))
128    n = np.argmax(np.abs(E))
129    a = V[:,n]
130    cent = ellipse_center(a)
131    phi = ellipse_angle_of_rotation(a)
132    radii = ellipse_axis_length(a)
133    phi += 90.
134    if radii[0] > radii[1]:
135        radii = [radii[1],radii[0]]
136        phi -= 90.
137    return cent,phi,radii
138
139def FitDetector(rings,varyList,parmDict,Print=True,covar=False):
140    '''Fit detector calibration parameters
141
142    :param np.array rings: vector of ring positions
143    :param list varyList: calibration parameters to be refined
144    :param dict parmDict: all calibration parameters
145    :param bool Print: set to True (default) to print the results
146    :param bool covar: set to True to return the covariance matrix (default is False)
147    :returns: [chisq,vals,sigList] unless covar is True, then
148        [chisq,vals,sigList,coVarMatrix] is returned
149    '''
150       
151    def CalibPrint(ValSig,chisq,Npts):
152        print ('Image Parameters: chi**2: %12.3g, Np: %d'%(chisq,Npts))
153        ptlbls = 'names :'
154        ptstr =  'values:'
155        sigstr = 'esds  :'
156        for name,value,sig in ValSig:
157            ptlbls += "%s" % (name.rjust(12))
158            if name == 'phi':
159                ptstr += Fmt[name] % (value%360.)
160            else:
161                ptstr += Fmt[name] % (value)
162            if sig:
163                sigstr += Fmt[name] % (sig)
164            else:
165                sigstr += 12*' '
166        print (ptlbls)
167        print (ptstr)
168        print (sigstr)       
169       
170    def ellipseCalcD(B,xyd,varyList,parmDict):
171       
172        x,y,dsp = xyd
173        varyDict = dict(zip(varyList,B))
174        parms = {}
175        for parm in parmDict:
176            if parm in varyList:
177                parms[parm] = varyDict[parm]
178            else:
179                parms[parm] = parmDict[parm]
180        phi = parms['phi']-90.               #get rotation of major axis from tilt axis
181        tth = 2.0*npasind(parms['wave']/(2.*dsp))
182        phi0 = npatan2d(y-parms['det-Y'],x-parms['det-X'])
183        dxy = peneCorr(tth,parms['dep'],parms['dist'],parms['tilt'],phi0)
184        stth = npsind(tth)
185        cosb = npcosd(parms['tilt'])
186        tanb = nptand(parms['tilt'])       
187        tbm = nptand((tth-parms['tilt'])/2.)
188        tbp = nptand((tth+parms['tilt'])/2.)
189        d = parms['dist']+dxy
190        fplus = d*tanb*stth/(cosb+stth)
191        fminus = d*tanb*stth/(cosb-stth)
192        vplus = d*(tanb+(1+tbm)/(1-tbm))*stth/(cosb+stth)
193        vminus = d*(tanb+(1-tbp)/(1+tbp))*stth/(cosb-stth)
194        R0 = np.sqrt((vplus+vminus)**2-(fplus+fminus)**2)/2.      #+minor axis
195        R1 = (vplus+vminus)/2.                                    #major axis
196        zdis = (fplus-fminus)/2.
197        Robs = np.sqrt((x-parms['det-X'])**2+(y-parms['det-Y'])**2)
198        rsqplus = R0**2+R1**2
199        rsqminus = R0**2-R1**2
200        R = rsqminus*npcosd(2.*phi0-2.*phi)+rsqplus
201        Q = np.sqrt(2.)*R0*R1*np.sqrt(R-2.*zdis**2*npsind(phi0-phi)**2)
202        P = 2.*R0**2*zdis*npcosd(phi0-phi)
203        Rcalc = (P+Q)/R
204        M = (Robs-Rcalc)*10.        #why 10? does make "chi**2" more reasonable
205        return M
206       
207    names = ['dist','det-X','det-Y','tilt','phi','dep','wave']
208    fmt = ['%12.3f','%12.3f','%12.3f','%12.3f','%12.3f','%12.4f','%12.6f']
209    Fmt = dict(zip(names,fmt))
210    p0 = [parmDict[key] for key in varyList]
211    result = leastsq(ellipseCalcD,p0,args=(rings.T,varyList,parmDict),full_output=True,ftol=1.e-8)
212    chisq = np.sum(result[2]['fvec']**2)/(rings.shape[0]-len(p0))   #reduced chi^2 = M/(Nobs-Nvar)
213    parmDict.update(zip(varyList,result[0]))
214    vals = list(result[0])
215    sig = list(np.sqrt(chisq*np.diag(result[1])))
216    sigList = np.zeros(7)
217    for i,name in enumerate(varyList):
218        sigList[i] = sig[varyList.index(name)]
219    ValSig = zip(varyList,vals,sig)
220    if Print:
221        CalibPrint(ValSig,chisq,rings.shape[0])
222    if covar:
223        return [chisq,vals,sigList,result[1]]
224    else:
225        return [chisq,vals,sigList]
226
227def FitMultiDist(rings,varyList,parmDict,Print=True,covar=False):
228    '''Fit detector calibration parameters with multi-distance data
229
230    :param np.array rings: vector of ring positions (x,y,dist,d-space)
231    :param list varyList: calibration parameters to be refined
232    :param dict parmDict: calibration parameters
233    :param bool Print: set to True (default) to print the results
234    :param bool covar: set to True to return the covariance matrix (default is False)
235    :returns: [chisq,vals,sigDict] unless covar is True, then
236        [chisq,vals,sigDict,coVarMatrix] is returned
237    '''
238       
239    def CalibPrint(parmDict,sigDict,chisq,Npts):
240        print ('Image Parameters: chi**2: %12.3g, Np: %d'%(chisq,Npts))
241        ptlbls = 'names :'
242        ptstr =  'values:'
243        sigstr = 'esds  :'
244        names = ['wavelength', 'dep', 'phi', 'tilt']
245        if 'deltaDist' in parmDict:
246            names += ['deltaDist']
247        for name in names:
248            if name == 'wavelength':
249                fmt = '%12.6f'
250            elif name == 'dep':
251                fmt = '%12.4f'
252            else:
253                fmt = '%12.3f'
254               
255            ptlbls += "%s" % (name.rjust(12))
256            if name == 'phi':
257                ptstr += fmt % (parmDict[name]%360.)
258            else:
259                ptstr += fmt % (parmDict[name])
260            if name in sigDict:
261                sigstr += fmt % (sigDict[name])
262            else:
263                sigstr += 12*' '
264        print (ptlbls)
265        print (ptstr)
266        print (sigstr)
267        ptlbls = 'names :'
268        ptstr =  'values:'
269        sigstr = 'esds  :'
270        for d in sorted(set([i[5:] for i in parmDict.keys() if 'det-X' in i]),key=lambda x:int(x)):
271            fmt = '%12.3f'
272            for key in 'det-X','det-Y','delta':
273                name = key+d
274                if name not in parmDict: continue
275                ptlbls += "%12s" % name
276                ptstr += fmt % (parmDict[name])
277                if name in sigDict:
278                    sigstr += fmt % (sigDict[name])
279                else:
280                    sigstr += 12*' '
281                if len(ptlbls) > 68:
282                    print()
283                    print (ptlbls)
284                    print (ptstr)
285                    print (sigstr)
286                    ptlbls = 'names :'
287                    ptstr =  'values:'
288                    sigstr = 'esds  :'
289        if len(ptlbls) > 0:
290            print()
291            print (ptlbls)
292            print (ptstr)
293            print (sigstr)
294
295    def ellipseCalcD(B,xyd,varyList,parmDict):
296        x,y,dist,dsp = xyd
297        varyDict = dict(zip(varyList,B))
298        parms = {}
299        for parm in parmDict:
300            if parm in varyList:
301                parms[parm] = varyDict[parm]
302            else:
303                parms[parm] = parmDict[parm]
304        # create arrays with detector center values
305        detX = np.array([parms['det-X'+str(int(d))] for d in dist])
306        detY = np.array([parms['det-Y'+str(int(d))] for d in dist])
307        if 'deltaDist' in parms:
308            deltaDist = parms['deltaDist']
309        else:
310            deltaDist = np.array([parms['delta'+str(int(d))] for d in dist])
311               
312        phi = parms['phi']-90.               #get rotation of major axis from tilt axis
313        tth = 2.0*npasind(parms['wavelength']/(2.*dsp))
314        phi0 = npatan2d(y-detY,x-detX)
315        dxy = peneCorr(tth,parms['dep'],dist-deltaDist,parms['tilt'],phi0)
316        stth = npsind(tth)
317        cosb = npcosd(parms['tilt'])
318        tanb = nptand(parms['tilt'])       
319        tbm = nptand((tth-parms['tilt'])/2.)
320        tbp = nptand((tth+parms['tilt'])/2.)
321        d = (dist-deltaDist)+dxy
322        fplus = d*tanb*stth/(cosb+stth)
323        fminus = d*tanb*stth/(cosb-stth)
324        vplus = d*(tanb+(1+tbm)/(1-tbm))*stth/(cosb+stth)
325        vminus = d*(tanb+(1-tbp)/(1+tbp))*stth/(cosb-stth)
326        R0 = np.sqrt((vplus+vminus)**2-(fplus+fminus)**2)/2.      #+minor axis
327        R1 = (vplus+vminus)/2.                                    #major axis
328        zdis = (fplus-fminus)/2.
329        Robs = np.sqrt((x-detX)**2+(y-detY)**2)
330        rsqplus = R0**2+R1**2
331        rsqminus = R0**2-R1**2
332        R = rsqminus*npcosd(2.*phi0-2.*phi)+rsqplus
333        Q = np.sqrt(2.)*R0*R1*np.sqrt(R-2.*zdis**2*npsind(phi0-phi)**2)
334        P = 2.*R0**2*zdis*npcosd(phi0-phi)
335        Rcalc = (P+Q)/R
336        return (Robs-Rcalc)*10.        #why 10? does make "chi**2" more reasonable
337       
338    p0 = [parmDict[key] for key in varyList]
339    result = leastsq(ellipseCalcD,p0,args=(rings.T,varyList,parmDict),full_output=True,ftol=1.e-8)
340    chisq = np.sum(result[2]['fvec']**2)/(rings.shape[0]-len(p0))   #reduced chi^2 = M/(Nobs-Nvar)
341    parmDict.update(zip(varyList,result[0]))
342    vals = list(result[0])
343    if chisq > 1:
344        sig = list(np.sqrt(chisq*np.diag(result[1])))
345    else:
346        sig = list(np.sqrt(np.diag(result[1])))
347    sigDict = {name:s for name,s in zip(varyList,sig)}
348    if Print:
349        CalibPrint(parmDict,sigDict,chisq,rings.shape[0])
350    if covar:
351        return [chisq,vals,sigDict,result[1]]
352    else:
353        return [chisq,vals,sigDict]
354   
355def ImageLocalMax(image,w,Xpix,Ypix):
356    'Needs a doc string'
357    w2 = w*2
358    sizey,sizex = image.shape
359    xpix = int(Xpix)            #get reference corner of pixel chosen
360    ypix = int(Ypix)
361    if not w:
362        ZMax = np.sum(image[ypix-2:ypix+2,xpix-2:xpix+2])
363        return xpix,ypix,ZMax,0.0001
364    if (w2 < xpix < sizex-w2) and (w2 < ypix < sizey-w2) and image[ypix,xpix]:
365        ZMax = image[ypix-w:ypix+w,xpix-w:xpix+w]
366        Zmax = np.argmax(ZMax)
367        ZMin = image[ypix-w2:ypix+w2,xpix-w2:xpix+w2]
368        Zmin = np.argmin(ZMin)
369        xpix += Zmax%w2-w
370        ypix += Zmax//w2-w
371        return xpix,ypix,np.ravel(ZMax)[Zmax],max(0.0001,np.ravel(ZMin)[Zmin])   #avoid neg/zero minimum
372    else:
373        return 0,0,0,0     
374   
375def makeRing(dsp,ellipse,pix,reject,scalex,scaley,image,mul=1):
376    'Needs a doc string'
377    def ellipseC():
378        'compute estimate of ellipse circumference'
379        if radii[0] < 0:        #hyperbola
380#            theta = npacosd(1./np.sqrt(1.+(radii[0]/radii[1])**2))
381#            print (theta)
382            return 0
383        apb = radii[1]+radii[0]
384        amb = radii[1]-radii[0]
385        return np.pi*apb*(1+3*(amb/apb)**2/(10+np.sqrt(4-3*(amb/apb)**2)))
386       
387    cent,phi,radii = ellipse
388    cphi = cosd(phi-90.)        #convert to major axis rotation
389    sphi = sind(phi-90.)
390    ring = []
391    C = int(ellipseC())*mul         #ring circumference in mm
392    azm = []
393    for i in range(0,C,1):      #step around ring in 1mm increments
394        a = 360.*i/C
395        x = radii[1]*cosd(a-phi+90.)        #major axis
396        y = radii[0]*sind(a-phi+90.)
397        X = (cphi*x-sphi*y+cent[0])*scalex      #convert mm to pixels
398        Y = (sphi*x+cphi*y+cent[1])*scaley
399        X,Y,I,J = ImageLocalMax(image,pix,X,Y)
400        if I and J and float(I)/J > reject:
401            X += .5                             #set to center of pixel
402            Y += .5
403            X /= scalex                         #convert back to mm
404            Y /= scaley
405            if [X,Y,dsp] not in ring:           #no duplicates!
406                ring.append([X,Y,dsp])
407                azm.append(a)
408    if len(ring) < 10:
409        ring = []
410        azm = []
411    return ring,azm
412   
413def GetEllipse2(tth,dxy,dist,cent,tilt,phi):
414    '''uses Dandelin spheres to find ellipse or hyperbola parameters from detector geometry
415    on output
416    radii[0] (b-minor axis) set < 0. for hyperbola
417   
418    '''
419    radii = [0,0]
420    stth = sind(tth)
421    cosb = cosd(tilt)
422    tanb = tand(tilt)
423    tbm = tand((tth-tilt)/2.)
424    tbp = tand((tth+tilt)/2.)
425    sinb = sind(tilt)
426    d = dist+dxy
427    if tth+abs(tilt) < 90.:      #ellipse
428        fplus = d*tanb*stth/(cosb+stth)
429        fminus = d*tanb*stth/(cosb-stth)
430        vplus = d*(tanb+(1+tbm)/(1-tbm))*stth/(cosb+stth)
431        vminus = d*(tanb+(1-tbp)/(1+tbp))*stth/(cosb-stth)
432        radii[0] = np.sqrt((vplus+vminus)**2-(fplus+fminus)**2)/2.      #+minor axis
433        radii[1] = (vplus+vminus)/2.                                    #major axis
434        zdis = (fplus-fminus)/2.
435    else:   #hyperbola!
436        f = d*abs(tanb)*stth/(cosb+stth)
437        v = d*(abs(tanb)+tand(tth-abs(tilt)))
438        delt = d*stth*(1.+stth*cosb)/(abs(sinb)*cosb*(stth+cosb))
439        eps = (v-f)/(delt-v)
440        radii[0] = -eps*(delt-f)/np.sqrt(eps**2-1.)                     #-minor axis
441        radii[1] = eps*(delt-f)/(eps**2-1.)                             #major axis
442        if tilt > 0:
443            zdis = f+radii[1]*eps
444        else:
445            zdis = -f
446#NB: zdis is || to major axis & phi is rotation of minor axis
447#thus shift from beam to ellipse center is [Z*sin(phi),-Z*cos(phi)]
448    elcent = [cent[0]+zdis*sind(phi),cent[1]-zdis*cosd(phi)]
449    return elcent,phi,radii
450   
451def GetEllipse(dsp,data):
452    '''uses Dandelin spheres to find ellipse or hyperbola parameters from detector geometry
453    as given in image controls dictionary (data) and a d-spacing (dsp)
454    '''
455    cent = data['center']
456    tilt = data['tilt']
457    phi = data['rotation']
458    dep = data.get('DetDepth',0.0)
459    tth = 2.0*asind(data['wavelength']/(2.*dsp))
460    dist = data['distance']
461    dxy = peneCorr(tth,dep,dist,tilt)
462    return GetEllipse2(tth,dxy,dist,cent,tilt,phi)
463       
464def GetDetectorXY(dsp,azm,data):
465    '''Get detector x,y position from d-spacing (dsp), azimuth (azm,deg)
466    & image controls dictionary (data)
467    it seems to be only used in plotting
468    '''   
469    elcent,phi,radii = GetEllipse(dsp,data)
470    phi = data['rotation']-90.          #to give rotation of major axis
471    tilt = data['tilt']
472    dist = data['distance']
473    cent = data['center']
474    tth = 2.0*asind(data['wavelength']/(2.*dsp))
475    stth = sind(tth)
476    cosb = cosd(tilt)
477    if radii[0] > 0.:
478        sinb = sind(tilt)
479        tanb = tand(tilt)
480        fplus = dist*tanb*stth/(cosb+stth)
481        fminus = dist*tanb*stth/(cosb-stth)
482        zdis = (fplus-fminus)/2.
483        rsqplus = radii[0]**2+radii[1]**2
484        rsqminus = radii[0]**2-radii[1]**2
485        R = rsqminus*cosd(2.*azm-2.*phi)+rsqplus
486        Q = np.sqrt(2.)*radii[0]*radii[1]*np.sqrt(R-2.*zdis**2*sind(azm-phi)**2)
487        P = 2.*radii[0]**2*zdis*cosd(azm-phi)
488        radius = (P+Q)/R
489        xy = np.array([radius*cosd(azm),radius*sind(azm)])
490        xy += cent
491    else:   #hyperbola - both branches (one is way off screen!)
492        sinb = abs(sind(tilt))
493        tanb = abs(tand(tilt))
494        f = dist*tanb*stth/(cosb+stth)
495        v = dist*(tanb+tand(tth-abs(tilt)))
496        delt = dist*stth*(1+stth*cosb)/(sinb*cosb*(stth+cosb))
497        ecc = (v-f)/(delt-v)
498        R = radii[1]*(ecc**2-1)/(1-ecc*cosd(azm))
499        if tilt > 0.:
500            offset = 2.*radii[1]*ecc+f      #select other branch
501            xy = [-R*cosd(azm)-offset,-R*sind(azm)]
502        else:
503            offset = -f
504            xy = [-R*cosd(azm)-offset,R*sind(azm)]
505        xy = -np.array([xy[0]*cosd(phi)+xy[1]*sind(phi),xy[0]*sind(phi)-xy[1]*cosd(phi)])
506        xy += cent
507    return xy
508   
509def GetDetXYfromThAzm(Th,Azm,data):
510    '''Computes a detector position from a 2theta angle and an azimultal
511    angle (both in degrees) - apparently not used!
512    '''
513    dsp = data['wavelength']/(2.0*npsind(Th))   
514    return GetDetectorXY(dsp,Azm,data)
515                   
516def GetTthAzmDsp(x,y,data): #expensive
517    '''Computes a 2theta, etc. from a detector position and calibration constants - checked
518    OK for ellipses & hyperbola.
519
520    :returns: np.array(tth,azm,G,dsp) where tth is 2theta, azm is the azimutal angle,
521       G is ? and dsp is the d-space
522    '''
523    wave = data['wavelength']
524    cent = data['center']
525    tilt = data['tilt']
526    dist = data['distance']/cosd(tilt)
527    x0 = dist*tand(tilt)
528    phi = data['rotation']
529    dep = data.get('DetDepth',0.)
530    azmthoff = data['azmthOff']
531    dx = np.array(x-cent[0],dtype=np.float32)
532    dy = np.array(y-cent[1],dtype=np.float32)
533    D = ((dx-x0)**2+dy**2+dist**2)      #sample to pixel distance
534    X = np.array(([dx,dy,np.zeros_like(dx)]),dtype=np.float32).T
535    X = np.dot(X,makeMat(phi,2))
536    Z = np.dot(X,makeMat(tilt,0)).T[2]
537    tth = npatand(np.sqrt(dx**2+dy**2-Z**2)/(dist-Z))
538    dxy = peneCorr(tth,dep,dist,tilt,npatan2d(dy,dx))
539    DX = dist-Z+dxy
540    DY = np.sqrt(dx**2+dy**2-Z**2)
541    tth = npatan2d(DY,DX) 
542    dsp = wave/(2.*npsind(tth/2.))
543    azm = (npatan2d(dy,dx)+azmthoff+720.)%360.
544    G = D/dist**2       #for geometric correction = 1/cos(2theta)^2 if tilt=0.
545    return np.array([tth,azm,G,dsp])
546   
547def GetTth(x,y,data):
548    'Give 2-theta value for detector x,y position; calibration info in data'
549    return GetTthAzmDsp(x,y,data)[0]
550   
551def GetTthAzm(x,y,data):
552    'Give 2-theta, azimuth values for detector x,y position; calibration info in data'
553    return GetTthAzmDsp(x,y,data)[0:2]
554   
555def GetTthAzmG(x,y,data):
556    '''Give 2-theta, azimuth & geometric corr. values for detector x,y position;
557     calibration info in data - only used in integration
558    '''
559    'Needs a doc string - checked OK for ellipses & hyperbola'
560    tilt = data['tilt']
561    dist = data['distance']/npcosd(tilt)
562    x0 = data['distance']*nptand(tilt)
563    MN = -np.inner(makeMat(data['rotation'],2),makeMat(tilt,0))
564    distsq = data['distance']**2
565    dx = x-data['center'][0]
566    dy = y-data['center'][1]
567    G = ((dx-x0)**2+dy**2+distsq)/distsq       #for geometric correction = 1/cos(2theta)^2 if tilt=0.
568    Z = np.dot(np.dstack([dx.T,dy.T,np.zeros_like(dx.T)]),MN).T[2]
569    xyZ = dx**2+dy**2-Z**2   
570    tth = npatand(np.sqrt(xyZ)/(dist-Z))
571    dxy = peneCorr(tth,data['DetDepth'],dist,tilt,npatan2d(dy,dx))
572    tth = npatan2d(np.sqrt(xyZ),dist-Z+dxy) 
573    azm = (npatan2d(dy,dx)+data['azmthOff']+720.)%360.
574    return tth,azm,G
575
576def GetDsp(x,y,data):
577    'Give d-spacing value for detector x,y position; calibration info in data'
578    return GetTthAzmDsp(x,y,data)[3]
579       
580def GetAzm(x,y,data):
581    'Give azimuth value for detector x,y position; calibration info in data'
582    return GetTthAzmDsp(x,y,data)[1]
583   
584def meanAzm(a,b):
585    AZM = lambda a,b: npacosd(0.5*(npsind(2.*b)-npsind(2.*a))/(np.pi*(b-a)/180.))/2.
586    azm = AZM(a,b)
587#    quad = int((a+b)/180.)
588#    if quad == 1:
589#        azm = 180.-azm
590#    elif quad == 2:
591#        azm += 180.
592#    elif quad == 3:
593#        azm = 360-azm
594    return azm     
595       
596def ImageCompress(image,scale):
597    ''' Reduces size of image by selecting every n'th point
598    param: image array: original image
599    param: scale int: intervsl between selected points
600    returns: array: reduced size image
601    '''
602    if scale == 1:
603        return image
604    else:
605        return image[::scale,::scale]
606       
607def checkEllipse(Zsum,distSum,xSum,ySum,dist,x,y):
608    'Needs a doc string'
609    avg = np.array([distSum/Zsum,xSum/Zsum,ySum/Zsum])
610    curr = np.array([dist,x,y])
611    return abs(avg-curr)/avg < .02
612
613def GetLineScan(image,data):
614    Nx,Ny = data['size']
615    pixelSize = data['pixelSize']
616    scalex = 1000./pixelSize[0]         #microns --> 1/mm
617    scaley = 1000./pixelSize[1]
618    wave = data['wavelength']
619    numChans = data['outChannels']
620    LUtth = np.array(data['IOtth'],dtype=np.float)
621    azm = data['linescan'][1]-data['azmthOff']
622    Tx = np.array([tth for tth in np.linspace(LUtth[0],LUtth[1],numChans+1)])
623    Ty = np.zeros_like(Tx)
624    dsp = wave/(2.0*npsind(Tx/2.0))
625    xy = np.array([GetDetectorXY(d,azm,data) for d in dsp]).T
626    xy[1] *= scalex
627    xy[0] *= scaley
628    xy = np.array(xy,dtype=int)
629    Xpix = ma.masked_outside(xy[1],0,Ny-1)
630    Ypix = ma.masked_outside(xy[0],0,Nx-1)
631    xpix = Xpix[~(Xpix.mask+Ypix.mask)].compressed()
632    ypix = Ypix[~(Xpix.mask+Ypix.mask)].compressed()
633    Ty = image[xpix,ypix]
634    Tx = ma.array(Tx,mask=Xpix.mask+Ypix.mask).compressed()
635    return [Tx,Ty]
636
637def EdgeFinder(image,data):
638    '''this makes list of all x,y where I>edgeMin suitable for an ellipse search?
639    Not currently used but might be useful in future?
640    '''
641    import numpy.ma as ma
642    Nx,Ny = data['size']
643    pixelSize = data['pixelSize']
644    edgemin = data['edgemin']
645    scalex = pixelSize[0]/1000.
646    scaley = pixelSize[1]/1000.   
647    tay,tax = np.mgrid[0:Nx,0:Ny]
648    tax = np.asfarray(tax*scalex,dtype=np.float32)
649    tay = np.asfarray(tay*scaley,dtype=np.float32)
650    tam = ma.getmask(ma.masked_less(image.flatten(),edgemin))
651    tax = ma.compressed(ma.array(tax.flatten(),mask=tam))
652    tay = ma.compressed(ma.array(tay.flatten(),mask=tam))
653    return zip(tax,tay)
654   
655def MakeFrameMask(data,frame):
656    import polymask as pm
657    pixelSize = data['pixelSize']
658    scalex = pixelSize[0]/1000.
659    scaley = pixelSize[1]/1000.
660    blkSize = 512
661    Nx,Ny = data['size']
662    nXBlks = (Nx-1)//blkSize+1
663    nYBlks = (Ny-1)//blkSize+1
664    tam = ma.make_mask_none(data['size'])
665    for iBlk in range(nXBlks):
666        iBeg = iBlk*blkSize
667        iFin = min(iBeg+blkSize,Nx)
668        for jBlk in range(nYBlks):
669            jBeg = jBlk*blkSize
670            jFin = min(jBeg+blkSize,Ny)               
671            nI = iFin-iBeg
672            nJ = jFin-jBeg
673            tax,tay = np.mgrid[iBeg+0.5:iFin+.5,jBeg+.5:jFin+.5]         #bin centers not corners
674            tax = np.asfarray(tax*scalex,dtype=np.float32)
675            tay = np.asfarray(tay*scaley,dtype=np.float32)
676            tamp = ma.make_mask_none((1024*1024))
677            tamp = ma.make_mask(pm.polymask(nI*nJ,tax.flatten(),
678                tay.flatten(),len(frame),frame,tamp)[:nI*nJ])^True  #switch to exclude around frame
679            if tamp.shape:
680                tamp = np.reshape(tamp[:nI*nJ],(nI,nJ))
681                tam[iBeg:iFin,jBeg:jFin] = ma.mask_or(tamp[0:nI,0:nJ],tam[iBeg:iFin,jBeg:jFin])
682            else:
683                tam[iBeg:iFin,jBeg:jFin] = True
684    return tam.T
685   
686def ImageRecalibrate(G2frame,ImageZ,data,masks,getRingsOnly=False):
687    '''Called to repeat the calibration on an image, usually called after
688    calibration is done initially to improve the fit.
689
690    :param G2frame: The top-level GSAS-II frame or None, to skip plotting
691    :param np.Array ImageZ: the image to calibrate
692    :param dict data: the Controls dict for the image
693    :param dict masks: a dict with masks
694    :returns: a list containing vals,varyList,sigList,parmDict,covar or rings
695      (with an array of x, y, and d-space values) if getRingsOnly is True
696      or an empty list, in case of an error
697    '''
698    import ImageCalibrants as calFile
699    if not getRingsOnly:
700        G2fil.G2Print ('Image recalibration:')
701    time0 = time.time()
702    pixelSize = data['pixelSize']
703    scalex = 1000./pixelSize[0]
704    scaley = 1000./pixelSize[1]
705    pixLimit = data['pixLimit']
706    cutoff = data['cutoff']
707    data['rings'] = []
708    data['ellipses'] = []
709    if data['DetDepth'] > 0.5:          #patch - redefine DetDepth
710        data['DetDepth'] /= data['distance']
711    if not data['calibrant']:
712        G2fil.G2Print ('warning: no calibration material selected')
713        return []   
714    skip = data['calibskip']
715    dmin = data['calibdmin']
716    if data['calibrant'] not in calFile.Calibrants:
717        G2fil.G2Print('Warning: %s not in local copy of image calibrants file'%data['calibrant'])
718        return []
719    calibrant = calFile.Calibrants[data['calibrant']]
720    Bravais,SGs,Cells = calibrant[:3]
721    HKL = []
722    for bravais,sg,cell in zip(Bravais,SGs,Cells):
723        A = G2lat.cell2A(cell)
724        if sg:
725            SGData = G2spc.SpcGroup(sg)[1]
726            hkl = G2pwd.getHKLpeak(dmin,SGData,A,Inst=None,nodup=True)
727            HKL += list(hkl)
728        else:
729            hkl = G2lat.GenHBravais(dmin,bravais,A)
730            HKL += list(hkl)
731    if len(calibrant) > 5:
732        absent = calibrant[5]
733    else:
734        absent = ()
735    HKL = G2lat.sortHKLd(HKL,True,False)
736    varyList = [item for item in data['varyList'] if data['varyList'][item]]
737    parmDict = {'dist':data['distance'],'det-X':data['center'][0],'det-Y':data['center'][1],
738        'setdist':data.get('setdist',data['distance']),
739        'tilt':data['tilt'],'phi':data['rotation'],'wave':data['wavelength'],'dep':data['DetDepth']}
740    Found = False
741    wave = data['wavelength']
742    frame = masks['Frames']
743    tam = ma.make_mask_none(ImageZ.shape)
744    if frame:
745        tam = ma.mask_or(tam,MakeFrameMask(data,frame))
746    for iH,H in enumerate(HKL):
747        if debug:   print (H) 
748        dsp = H[3]
749        tth = 2.0*asind(wave/(2.*dsp))
750        if tth+abs(data['tilt']) > 90.:
751            G2fil.G2Print ('next line is a hyperbola - search stopped')
752            break
753        ellipse = GetEllipse(dsp,data)
754        if iH not in absent and iH >= skip:
755            Ring = makeRing(dsp,ellipse,pixLimit,cutoff,scalex,scaley,ma.array(ImageZ,mask=tam))[0]
756        else:
757            Ring = makeRing(dsp,ellipse,pixLimit,1000.0,scalex,scaley,ma.array(ImageZ,mask=tam))[0]
758        if Ring:
759            if iH not in absent and iH >= skip:
760                data['rings'].append(np.array(Ring))
761            data['ellipses'].append(copy.deepcopy(ellipse+('r',)))
762            Found = True
763        elif not Found:         #skipping inner rings, keep looking until ring found
764            continue
765        else:                   #no more rings beyond edge of detector
766            data['ellipses'].append([])
767            continue
768    if not data['rings']:
769        G2fil.G2Print ('no rings found; try lower Min ring I/Ib',mode='warn')
770        return []   
771       
772    rings = np.concatenate((data['rings']),axis=0)
773    if getRingsOnly:
774        return rings
775    [chisq,vals,sigList,covar] = FitDetector(rings,varyList,parmDict,True,True)
776    data['wavelength'] = parmDict['wave']
777    data['distance'] = parmDict['dist']
778    data['center'] = [parmDict['det-X'],parmDict['det-Y']]
779    data['rotation'] = np.mod(parmDict['phi'],360.0)
780    data['tilt'] = parmDict['tilt']
781    data['DetDepth'] = parmDict['dep']
782    data['chisq'] = chisq
783    N = len(data['ellipses'])
784    data['ellipses'] = []           #clear away individual ellipse fits
785    for H in HKL[:N]:
786        ellipse = GetEllipse(H[3],data)
787        data['ellipses'].append(copy.deepcopy(ellipse+('b',)))   
788    G2fil.G2Print ('calibration time = %.3f'%(time.time()-time0))
789    if G2frame:
790        G2plt.PlotImage(G2frame,newImage=True)       
791    return [vals,varyList,sigList,parmDict,covar]
792
793def ImageCalibrate(G2frame,data):
794    '''Called to perform an initial image calibration after points have been
795    selected for the inner ring.
796    '''
797    import ImageCalibrants as calFile
798    G2fil.G2Print ('Image calibration:')
799    time0 = time.time()
800    ring = data['ring']
801    pixelSize = data['pixelSize']
802    scalex = 1000./pixelSize[0]
803    scaley = 1000./pixelSize[1]
804    pixLimit = data['pixLimit']
805    cutoff = data['cutoff']
806    varyDict = data['varyList']
807    if varyDict['dist'] and varyDict['wave']:
808        G2fil.G2Print ('ERROR - you can not simultaneously calibrate distance and wavelength')
809        return False
810    if len(ring) < 5:
811        G2fil.G2Print ('ERROR - not enough inner ring points for ellipse')
812        return False
813       
814    #fit start points on inner ring
815    data['ellipses'] = []
816    data['rings'] = []
817    outE = FitEllipse(ring)
818    fmt  = '%s X: %.3f, Y: %.3f, phi: %.3f, R1: %.3f, R2: %.3f'
819    fmt2 = '%s X: %.3f, Y: %.3f, phi: %.3f, R1: %.3f, R2: %.3f, chi**2: %.3f, Np: %d'
820    if outE:
821        G2fil.G2Print (fmt%('start ellipse: ',outE[0][0],outE[0][1],outE[1],outE[2][0],outE[2][1]))
822        ellipse = outE
823    else:
824        return False
825       
826    #setup 360 points on that ring for "good" fit
827    data['ellipses'].append(ellipse[:]+('g',))
828    Ring = makeRing(1.0,ellipse,pixLimit,cutoff,scalex,scaley,G2frame.ImageZ)[0]
829    if Ring:
830        ellipse = FitEllipse(Ring)
831        Ring = makeRing(1.0,ellipse,pixLimit,cutoff,scalex,scaley,G2frame.ImageZ)[0]    #do again
832        ellipse = FitEllipse(Ring)
833    else:
834        G2fil.G2Print ('1st ring not sufficiently complete to proceed',mode='warn')
835        return False
836    if debug:
837        G2fil.G2Print (fmt2%('inner ring:    ',ellipse[0][0],ellipse[0][1],ellipse[1],
838            ellipse[2][0],ellipse[2][1],0.,len(Ring)))     #cent,phi,radii
839    data['ellipses'].append(ellipse[:]+('r',))
840    data['rings'].append(np.array(Ring))
841    G2plt.PlotImage(G2frame,newImage=True)
842   
843#setup for calibration
844    data['rings'] = []
845    if not data['calibrant']:
846        G2fil.G2Print ('Warning: no calibration material selected')
847        return True
848   
849    skip = data['calibskip']
850    dmin = data['calibdmin']
851#generate reflection set
852    calibrant = calFile.Calibrants[data['calibrant']]
853    Bravais,SGs,Cells = calibrant[:3]
854    HKL = []
855    for bravais,sg,cell in zip(Bravais,SGs,Cells):
856        A = G2lat.cell2A(cell)
857        if sg:
858            SGData = G2spc.SpcGroup(sg)[1]
859            hkl = G2pwd.getHKLpeak(dmin,SGData,A,Inst=None,nodup=True)
860            #G2fil.G2Print(hkl)
861            HKL += list(hkl)
862        else:
863            hkl = G2lat.GenHBravais(dmin,bravais,A)
864            HKL += list(hkl)
865    HKL = G2lat.sortHKLd(HKL,True,False)[skip:]
866#set up 1st ring
867    elcent,phi,radii = ellipse              #from fit of 1st ring
868    dsp = HKL[0][3]
869    G2fil.G2Print ('1st ring: try %.4f'%(dsp))
870    if varyDict['dist']:
871        wave = data['wavelength']
872        tth = 2.0*asind(wave/(2.*dsp))
873    else:   #varyDict['wave']!
874        dist = data['distance']
875        tth = npatan2d(radii[0],dist)
876        data['wavelength'] = wave =  2.0*dsp*sind(tth/2.0)
877    Ring0 = makeRing(dsp,ellipse,3,cutoff,scalex,scaley,G2frame.ImageZ)[0]
878    ttth = nptand(tth)
879    ctth = npcosd(tth)
880#1st estimate of tilt; assume ellipse - don't know sign though
881    if varyDict['tilt']:
882        tilt = npasind(np.sqrt(max(0.,1.-(radii[0]/radii[1])**2))*ctth)
883        if not tilt:
884            G2fil.G2Print ('WARNING - selected ring was fitted as a circle')
885            G2fil.G2Print (' - if detector was tilted we suggest you skip this ring - WARNING')
886    else:
887        tilt = data['tilt']
888#1st estimate of dist: sample to detector normal to plane
889    if varyDict['dist']:
890        data['distance'] = dist = radii[0]**2/(ttth*radii[1])
891    else:
892        dist = data['distance']
893    if varyDict['tilt']:
894#ellipse to cone axis (x-ray beam); 2 choices depending on sign of tilt
895        zdisp = radii[1]*ttth*tand(tilt)
896        zdism = radii[1]*ttth*tand(-tilt)
897#cone axis position; 2 choices. Which is right?     
898#NB: zdisp is || to major axis & phi is rotation of minor axis
899#thus shift from beam to ellipse center is [Z*sin(phi),-Z*cos(phi)]
900        centp = [elcent[0]+zdisp*sind(phi),elcent[1]-zdisp*cosd(phi)]
901        centm = [elcent[0]+zdism*sind(phi),elcent[1]-zdism*cosd(phi)]
902#check get same ellipse parms either way
903#now do next ring; estimate either way & do a FitDetector each way; best fit is correct one
904        fail = True
905        i2 = 1
906        while fail:
907            dsp = HKL[i2][3]
908            G2fil.G2Print ('2nd ring: try %.4f'%(dsp))
909            tth = 2.0*asind(wave/(2.*dsp))
910            ellipsep = GetEllipse2(tth,0.,dist,centp,tilt,phi)
911            G2fil.G2Print (fmt%('plus ellipse :',ellipsep[0][0],ellipsep[0][1],ellipsep[1],ellipsep[2][0],ellipsep[2][1]))
912            Ringp = makeRing(dsp,ellipsep,3,cutoff,scalex,scaley,G2frame.ImageZ)[0]
913            parmDict = {'dist':dist,'det-X':centp[0],'det-Y':centp[1],
914                'tilt':tilt,'phi':phi,'wave':wave,'dep':0.0}       
915            varyList = [item for item in varyDict if varyDict[item]]
916            if len(Ringp) > 10:
917                chip = FitDetector(np.array(Ring0+Ringp),varyList,parmDict,True)[0]
918                tiltp = parmDict['tilt']
919                phip = parmDict['phi']
920                centp = [parmDict['det-X'],parmDict['det-Y']]
921                fail = False
922            else:
923                chip = 1e6
924            ellipsem = GetEllipse2(tth,0.,dist,centm,-tilt,phi)
925            G2fil.G2Print (fmt%('minus ellipse:',ellipsem[0][0],ellipsem[0][1],ellipsem[1],ellipsem[2][0],ellipsem[2][1]))
926            Ringm = makeRing(dsp,ellipsem,3,cutoff,scalex,scaley,G2frame.ImageZ)[0]
927            if len(Ringm) > 10:
928                parmDict['tilt'] *= -1
929                chim = FitDetector(np.array(Ring0+Ringm),varyList,parmDict,True)[0]
930                tiltm = parmDict['tilt']
931                phim = parmDict['phi']
932                centm = [parmDict['det-X'],parmDict['det-Y']]
933                fail = False
934            else:
935                chim = 1e6
936            if fail:
937                i2 += 1
938        if chip < chim:
939            data['tilt'] = tiltp
940            data['center'] = centp
941            data['rotation'] = phip
942        else:
943            data['tilt'] = tiltm
944            data['center'] = centm
945            data['rotation'] = phim
946        data['ellipses'].append(ellipsep[:]+('b',))
947        data['rings'].append(np.array(Ringp))
948        data['ellipses'].append(ellipsem[:]+('r',))
949        data['rings'].append(np.array(Ringm))
950        G2plt.PlotImage(G2frame,newImage=True)
951    if data['DetDepth'] > 0.5:          #patch - redefine DetDepth
952        data['DetDepth'] /= data['distance']
953    parmDict = {'dist':data['distance'],'det-X':data['center'][0],'det-Y':data['center'][1],
954        'tilt':data['tilt'],'phi':data['rotation'],'wave':data['wavelength'],'dep':data['DetDepth']}
955    varyList = [item for item in varyDict if varyDict[item]]
956    data['rings'] = []
957    data['ellipses'] = []
958    for i,H in enumerate(HKL):
959        dsp = H[3]
960        tth = 2.0*asind(wave/(2.*dsp))
961        if tth+abs(data['tilt']) > 90.:
962            G2fil.G2Print ('next line is a hyperbola - search stopped')
963            break
964        if debug:   print ('HKLD:'+str(H[:4])+'2-theta: %.4f'%(tth))
965        elcent,phi,radii = ellipse = GetEllipse(dsp,data)
966        data['ellipses'].append(copy.deepcopy(ellipse+('g',)))
967        if debug:   print (fmt%('predicted ellipse:',elcent[0],elcent[1],phi,radii[0],radii[1]))
968        Ring = makeRing(dsp,ellipse,pixLimit,cutoff,scalex,scaley,G2frame.ImageZ)[0]
969        if Ring:
970            data['rings'].append(np.array(Ring))
971            rings = np.concatenate((data['rings']),axis=0)
972            if i:
973                chisq = FitDetector(rings,varyList,parmDict,False)[0]
974                data['distance'] = parmDict['dist']
975                data['center'] = [parmDict['det-X'],parmDict['det-Y']]
976                data['rotation'] = parmDict['phi']
977                data['tilt'] = parmDict['tilt']
978                data['DetDepth'] = parmDict['dep']
979                data['chisq'] = chisq
980                elcent,phi,radii = ellipse = GetEllipse(dsp,data)
981                if debug:   print (fmt2%('fitted ellipse:   ',elcent[0],elcent[1],phi,radii[0],radii[1],chisq,len(rings)))
982            data['ellipses'].append(copy.deepcopy(ellipse+('r',)))
983#            G2plt.PlotImage(G2frame,newImage=True)
984        else:
985            if debug:   print ('insufficient number of points in this ellipse to fit')
986#            break
987    G2plt.PlotImage(G2frame,newImage=True)
988    fullSize = len(G2frame.ImageZ)/scalex
989    if 2*radii[1] < .9*fullSize:
990        G2fil.G2Print ('Are all usable rings (>25% visible) used? Try reducing Min ring I/Ib')
991    N = len(data['ellipses'])
992    if N > 2:
993        FitDetector(rings,varyList,parmDict)[0]
994        data['wavelength'] = parmDict['wave']
995        data['distance'] = parmDict['dist']
996        data['center'] = [parmDict['det-X'],parmDict['det-Y']]
997        data['rotation'] = parmDict['phi']
998        data['tilt'] = parmDict['tilt']
999        data['DetDepth'] = parmDict['dep']
1000    for H in HKL[:N]:
1001        ellipse = GetEllipse(H[3],data)
1002        data['ellipses'].append(copy.deepcopy(ellipse+('b',)))
1003    G2fil.G2Print ('calibration time = %.3f'%(time.time()-time0))
1004    G2plt.PlotImage(G2frame,newImage=True)       
1005    return True
1006   
1007def Make2ThetaAzimuthMap(data,iLim,jLim): #most expensive part of integration!
1008    'Needs a doc string'
1009    #transforms 2D image from x,y space to 2-theta,azimuth space based on detector orientation
1010    pixelSize = data['pixelSize']
1011    scalex = pixelSize[0]/1000.
1012    scaley = pixelSize[1]/1000.
1013   
1014    tay,tax = np.mgrid[iLim[0]+0.5:iLim[1]+.5,jLim[0]+.5:jLim[1]+.5]         #bin centers not corners
1015    tax = np.asfarray(tax*scalex,dtype=np.float32).flatten()
1016    tay = np.asfarray(tay*scaley,dtype=np.float32).flatten()
1017    nI = iLim[1]-iLim[0]
1018    nJ = jLim[1]-jLim[0]
1019    TA = np.array(GetTthAzmG(np.reshape(tax,(nI,nJ)),np.reshape(tay,(nI,nJ)),data))     #includes geom. corr. as dist**2/d0**2 - most expensive step
1020    TA[1] = np.where(TA[1]<0,TA[1]+360,TA[1])
1021    return TA           #2-theta, azimuth & geom. corr. arrays
1022
1023def MakeMaskMap(data,masks,iLim,jLim,tamp):
1024    import polymask as pm
1025    pixelSize = data['pixelSize']
1026    scalex = pixelSize[0]/1000.
1027    scaley = pixelSize[1]/1000.
1028   
1029    tay,tax = np.mgrid[iLim[0]+0.5:iLim[1]+.5,jLim[0]+.5:jLim[1]+.5]         #bin centers not corners
1030    tax = np.asfarray(tax*scalex,dtype=np.float32).flatten()
1031    tay = np.asfarray(tay*scaley,dtype=np.float32).flatten()
1032    nI = iLim[1]-iLim[0]
1033    nJ = jLim[1]-jLim[0]
1034    #make position masks here
1035    frame = masks['Frames']
1036    tam = ma.make_mask_none((nI*nJ))
1037    if frame:
1038        tam = ma.mask_or(tam,ma.make_mask(pm.polymask(nI*nJ,tax,
1039            tay,len(frame),frame,tamp)[:nI*nJ])^True)
1040    polygons = masks['Polygons']
1041    for polygon in polygons:
1042        if polygon:
1043            tam = ma.mask_or(tam,ma.make_mask(pm.polymask(nI*nJ,tax,
1044                tay,len(polygon),polygon,tamp)[:nI*nJ]))
1045    for X,Y,rsq in masks['Points'].T:
1046        tam = ma.mask_or(tam,ma.getmask(ma.masked_less((tax-X)**2+(tay-Y)**2,rsq)))
1047    if tam.shape: 
1048        tam = np.reshape(tam,(nI,nJ))
1049    else:
1050        tam = ma.make_mask_none((nI,nJ))
1051    for xline in masks.get('Xlines',[]):    #a y pixel position
1052        if iLim[0] <= xline <= iLim[1]:
1053            tam[xline-iLim[0],:] = True
1054    for yline in masks.get('Ylines',[]):    #a x pixel position
1055        if jLim[0] <= yline <= jLim[1]:
1056            tam[:,yline-jLim[0]] = True           
1057    return tam           #position mask
1058
1059def Fill2ThetaAzimuthMap(masks,TA,tam,image):
1060    'Needs a doc string'
1061    Zlim = masks['Thresholds'][1]
1062    rings = masks['Rings']
1063    arcs = masks['Arcs']
1064    TA = np.dstack((ma.getdata(TA[1]),ma.getdata(TA[0]),ma.getdata(TA[2])))    #azimuth, 2-theta, dist
1065    tax,tay,tad = np.dsplit(TA,3)    #azimuth, 2-theta, dist**2/d0**2
1066    for tth,thick in rings:
1067        tam = ma.mask_or(tam.flatten(),ma.getmask(ma.masked_inside(tay.flatten(),max(0.01,tth-thick/2.),tth+thick/2.)))
1068    for tth,azm,thick in arcs:
1069        tamt = ma.getmask(ma.masked_inside(tay.flatten(),max(0.01,tth-thick/2.),tth+thick/2.))
1070        tama = ma.getmask(ma.masked_inside(tax.flatten(),azm[0],azm[1]))
1071        tam = ma.mask_or(tam.flatten(),tamt*tama)
1072    taz = ma.masked_outside(image.flatten(),int(Zlim[0]),Zlim[1])
1073    tabs = np.ones_like(taz)
1074    tam = ma.mask_or(tam.flatten(),ma.getmask(taz))
1075    tax = ma.compressed(ma.array(tax.flatten(),mask=tam))   #azimuth
1076    tay = ma.compressed(ma.array(tay.flatten(),mask=tam))   #2-theta
1077    taz = ma.compressed(ma.array(taz.flatten(),mask=tam))   #intensity
1078    tad = ma.compressed(ma.array(tad.flatten(),mask=tam))   #dist**2/d0**2
1079    tabs = ma.compressed(ma.array(tabs.flatten(),mask=tam)) #ones - later used for absorption corr.
1080    return tax,tay,taz,tad,tabs
1081
1082def MakeUseTA(data,blkSize=128):
1083    Nx,Ny = data['size']
1084    nXBlks = (Nx-1)//blkSize+1
1085    nYBlks = (Ny-1)//blkSize+1
1086    useTA = []
1087    for iBlk in range(nYBlks):
1088        iBeg = iBlk*blkSize
1089        iFin = min(iBeg+blkSize,Ny)
1090        useTAj = []
1091        for jBlk in range(nXBlks):
1092            jBeg = jBlk*blkSize
1093            jFin = min(jBeg+blkSize,Nx)
1094            TA = Make2ThetaAzimuthMap(data,(iBeg,iFin),(jBeg,jFin))          #2-theta & azimuth arrays & create position mask
1095            useTAj.append(TA)
1096        useTA.append(useTAj)
1097    return useTA
1098
1099def MakeUseMask(data,masks,blkSize=128):
1100    Masks = copy.deepcopy(masks)
1101    Masks['Points'] = np.array(Masks['Points']).T           #get spots as X,Y,R arrays
1102    if np.any(masks['Points']):
1103        Masks['Points'][2] = np.square(Masks['Points'][2]/2.)
1104    Nx,Ny = data['size']
1105    nXBlks = (Nx-1)//blkSize+1
1106    nYBlks = (Ny-1)//blkSize+1
1107    useMask = []
1108    tamp = ma.make_mask_none((1024*1024))       #NB: this array size used in the fortran histogram2d
1109    for iBlk in range(nYBlks):
1110        iBeg = iBlk*blkSize
1111        iFin = min(iBeg+blkSize,Ny)
1112        useMaskj = []
1113        for jBlk in range(nXBlks):
1114            jBeg = jBlk*blkSize
1115            jFin = min(jBeg+blkSize,Nx)
1116            mask = MakeMaskMap(data,Masks,(iBeg,iFin),(jBeg,jFin),tamp)          #2-theta & azimuth arrays & create position mask
1117            useMaskj.append(mask)
1118        useMask.append(useMaskj)
1119    return useMask
1120
1121def ImageIntegrate(image,data,masks,blkSize=128,returnN=False,useTA=None,useMask=None):
1122    'Integrate an image; called from OnIntegrateAll and OnIntegrate in G2imgGUI'    #for q, log(q) bins need data['binType']
1123    import histogram2d as h2d
1124    G2fil.G2Print ('Begin image integration; image range: %d %d'%(np.min(image),np.max(image)))
1125    CancelPressed = False
1126    LUtth = np.array(data['IOtth'])
1127    LRazm = np.array(data['LRazimuth'],dtype=np.float64)
1128    numAzms = data['outAzimuths']
1129    numChans = (data['outChannels']//4)*4
1130    Dazm = (LRazm[1]-LRazm[0])/numAzms
1131    if '2-theta' in data.get('binType','2-theta'):
1132        lutth = LUtth               
1133    elif 'log(q)' in data['binType']:
1134        lutth = np.log(4.*np.pi*npsind(LUtth/2.)/data['wavelength'])
1135    elif 'q' == data['binType'].lower():
1136        lutth = 4.*np.pi*npsind(LUtth/2.)/data['wavelength']
1137    dtth = (lutth[1]-lutth[0])/numChans
1138    muT = data.get('SampleAbs',[0.0,''])[0]
1139    if data['DetDepth'] > 0.5:          #patch - redefine DetDepth
1140        data['DetDepth'] /= data['distance']
1141    if 'SASD' in data['type']:
1142        muT = -np.log(muT)/2.       #Transmission to 1/2 thickness muT
1143    Masks = copy.deepcopy(masks)
1144    Masks['Points'] = np.array(Masks['Points']).T           #get spots as X,Y,R arrays
1145    if np.any(masks['Points']):
1146        Masks['Points'][2] = np.square(Masks['Points'][2]/2.)
1147    NST = np.zeros(shape=(numAzms,numChans),order='F',dtype=np.float32)
1148    H0 = np.zeros(shape=(numAzms,numChans),order='F',dtype=np.float32)
1149    H2 = np.linspace(lutth[0],lutth[1],numChans+1)
1150    Nx,Ny = data['size']
1151    nXBlks = (Nx-1)//blkSize+1
1152    nYBlks = (Ny-1)//blkSize+1
1153    tbeg = time.time()
1154    times = [0,0,0,0,0]
1155    tamp = ma.make_mask_none((1024*1024))       #NB: this array size used in the fortran histogram2d
1156    for iBlk in range(nYBlks):
1157        iBeg = iBlk*blkSize
1158        iFin = min(iBeg+blkSize,Ny)
1159        for jBlk in range(nXBlks):
1160            jBeg = jBlk*blkSize
1161            jFin = min(jBeg+blkSize,Nx)
1162            # next is most expensive step!
1163            t0 = time.time()
1164            if useTA:
1165                TA = useTA[iBlk][jBlk]
1166            else:
1167                TA = Make2ThetaAzimuthMap(data,(iBeg,iFin),(jBeg,jFin))           #2-theta & azimuth arrays & create position mask
1168            times[1] += time.time()-t0
1169            t0 = time.time()
1170            if useMask:
1171                tam = useMask[iBlk][jBlk]
1172            else:
1173                tam = MakeMaskMap(data,Masks,(iBeg,iFin),(jBeg,jFin),tamp)
1174            Block = image[iBeg:iFin,jBeg:jFin]
1175            tax,tay,taz,tad,tabs = Fill2ThetaAzimuthMap(Masks,TA,tam,Block)    #and apply masks
1176            pol = G2pwd.Polarization(data['PolaVal'][0],tay,tax-90.)[0]         #for pixel pola correction
1177            times[0] += time.time()-t0
1178            t0 = time.time()
1179            tax = np.where(tax > LRazm[1],tax-360.,tax)                 #put azm inside limits if possible
1180            tax = np.where(tax < LRazm[0],tax+360.,tax)
1181            if data.get('SampleAbs',[0.0,''])[1]:
1182                if 'Cylind' in data['SampleShape']:
1183                    muR = muT*(1.+npsind(tax)**2/2.)/(npcosd(tay))      #adjust for additional thickness off sample normal
1184                    tabs = G2pwd.Absorb(data['SampleShape'],muR,tay)
1185                elif 'Fixed' in data['SampleShape']:    #assumes flat plate sample normal to beam
1186                    tabs = G2pwd.Absorb('Fixed',muT,tay)
1187            if 'log(q)' in data.get('binType',''):
1188                tay = np.log(4.*np.pi*npsind(tay/2.)/data['wavelength'])
1189            elif 'q' == data.get('binType','').lower():
1190                tay = 4.*np.pi*npsind(tay/2.)/data['wavelength']
1191            times[2] += time.time()-t0
1192            t0 = time.time()
1193            taz = np.array((taz*tad/tabs),dtype='float32')/pol
1194            if any([tax.shape[0],tay.shape[0],taz.shape[0]]):
1195                NST,H0 = h2d.histogram2d(len(tax),tax,tay,taz,
1196                    numAzms,numChans,LRazm,lutth,Dazm,dtth,NST,H0)
1197            times[3] += time.time()-t0
1198    G2fil.G2Print('End integration loops')
1199    t0 = time.time()
1200    #prepare masked arrays of bins with pixels for interpolation setup
1201    H2msk = [ma.array(H2[:-1],mask=np.logical_not(nst)) for nst in NST]
1202    H0msk = [ma.array(np.divide(h0,nst),mask=np.logical_not(nst)) for nst,h0 in zip(NST,H0)]
1203    #make linear interpolators; outside limits give NaN
1204    H0int = [scint.interp1d(h2msk.compressed(),h0msk.compressed(),bounds_error=False) for h0msk,h2msk in zip(H0msk,H2msk)]
1205    #do interpolation on all points - fills in the empty bins; leaves others the same
1206    H0 = np.array([h0int(H2[:-1]) for h0int in H0int])
1207    H0 = np.nan_to_num(H0)
1208    if 'log(q)' in data.get('binType',''):
1209        H2 = 2.*npasind(np.exp(H2)*data['wavelength']/(4.*np.pi))
1210    elif 'q' == data.get('binType','').lower():
1211        H2 = 2.*npasind(H2*data['wavelength']/(4.*np.pi))
1212    if Dazm:       
1213        H1 = np.array([azm for azm in np.linspace(LRazm[0],LRazm[1],numAzms+1)])
1214    else:
1215        H1 = LRazm
1216    if 'SASD' not in data['type']:
1217        H0 *= np.array(G2pwd.Polarization(data['PolaVal'][0],H2[:-1],0.)[0])
1218    H0 /= npcosd(H2[:-1])           #**2? I don't think so, **1 is right for powders
1219    if 'SASD' in data['type']:
1220        H0 /= npcosd(H2[:-1])           #one more for small angle scattering data?
1221    if data['Oblique'][1]:
1222        H0 /= G2pwd.Oblique(data['Oblique'][0],H2[:-1])
1223    times[4] += time.time()-t0
1224    G2fil.G2Print ('Step times: \n apply masks  %8.3fs xy->th,azm   %8.3fs fill map     %8.3fs \
1225        \n binning      %8.3fs cleanup      %8.3fs'%(times[0],times[1],times[2],times[3],times[4]))
1226    G2fil.G2Print ("Elapsed time:","%8.3fs"%(time.time()-tbeg))
1227    G2fil.G2Print ('Integration complete')
1228    if returnN:     #As requested by Steven Weigand
1229        return H0,H1,H2,NST,CancelPressed
1230    else:
1231        return H0,H1,H2,CancelPressed
1232   
1233def MakeStrStaRing(ring,Image,Controls):
1234    ellipse = GetEllipse(ring['Dset'],Controls)
1235    pixSize = Controls['pixelSize']
1236    scalex = 1000./pixSize[0]
1237    scaley = 1000./pixSize[1]
1238    Ring = np.array(makeRing(ring['Dset'],ellipse,ring['pixLimit'],ring['cutoff'],scalex,scaley,Image)[0]).T   #returns x,y,dsp for each point in ring
1239    if len(Ring):
1240        ring['ImxyObs'] = copy.copy(Ring[:2])
1241        TA = GetTthAzm(Ring[0],Ring[1],Controls)       #convert x,y to tth,azm
1242        TA[0] = Controls['wavelength']/(2.*npsind(TA[0]/2.))      #convert 2th to d
1243        ring['ImtaObs'] = TA
1244        ring['ImtaCalc'] = np.zeros_like(ring['ImtaObs'])
1245        Ring[0] = TA[0]
1246        Ring[1] = TA[1]
1247        return Ring,ring
1248    else:
1249        ring['ImxyObs'] = [[],[]]
1250        ring['ImtaObs'] = [[],[]]
1251        ring['ImtaCalc'] = [[],[]]
1252        return [],[]    #bad ring; no points found
1253   
1254def FitStrSta(Image,StrSta,Controls):
1255    'Needs a doc string'
1256   
1257    StaControls = copy.deepcopy(Controls)
1258    phi = StrSta['Sample phi']
1259    wave = Controls['wavelength']
1260    pixelSize = Controls['pixelSize']
1261    scalex = 1000./pixelSize[0]
1262    scaley = 1000./pixelSize[1]
1263    StaType = StrSta['Type']
1264    StaControls['distance'] += StrSta['Sample z']*cosd(phi)
1265
1266    for ring in StrSta['d-zero']:       #get observed x,y,d points for the d-zeros
1267        dset = ring['Dset']
1268        Ring,R = MakeStrStaRing(ring,Image,StaControls)
1269        if len(Ring):
1270            ring.update(R)
1271            p0 = ring['Emat']
1272            val,esd,covMat = FitStrain(Ring,p0,dset,wave,phi,StaType)
1273            ring['Emat'] = val
1274            ring['Esig'] = esd
1275            ellipse = FitEllipse(R['ImxyObs'].T)
1276            ringxy,ringazm = makeRing(ring['Dcalc'],ellipse,0,0.,scalex,scaley,Image)
1277            ring['ImxyCalc'] = np.array(ringxy).T[:2]
1278            ringint = np.array([float(Image[int(x*scalex),int(y*scaley)]) for y,x in np.array(ringxy)[:,:2]])
1279            ringint /= np.mean(ringint)
1280            ring['Ivar'] = np.var(ringint)
1281            ring['covMat'] = covMat
1282            G2fil.G2Print ('Variance in normalized ring intensity: %.3f'%(ring['Ivar']))
1283    CalcStrSta(StrSta,Controls)
1284   
1285def IntStrSta(Image,StrSta,Controls):
1286    StaControls = copy.deepcopy(Controls)
1287    pixelSize = Controls['pixelSize']
1288    scalex = 1000./pixelSize[0]
1289    scaley = 1000./pixelSize[1]
1290    phi = StrSta['Sample phi']
1291    StaControls['distance'] += StrSta['Sample z']*cosd(phi)
1292    RingsAI = []
1293    for ring in StrSta['d-zero']:       #get observed x,y,d points for the d-zeros
1294        Ring,R = MakeStrStaRing(ring,Image,StaControls)
1295        if len(Ring):
1296            ellipse = FitEllipse(R['ImxyObs'].T)
1297            ringxy,ringazm = makeRing(ring['Dcalc'],ellipse,0,0.,scalex,scaley,Image,5)
1298            ring['ImxyCalc'] = np.array(ringxy).T[:2]
1299            ringint = np.array([float(Image[int(x*scalex),int(y*scaley)]) for y,x in np.array(ringxy)[:,:2]])
1300            ringint /= np.mean(ringint)
1301            G2fil.G2Print (' %s %.3f %s %.3f %s %d'%('d-spacing',ring['Dcalc'],'sig(MRD):',np.sqrt(np.var(ringint)),'# points:',len(ringint)))
1302            RingsAI.append(np.array(zip(ringazm,ringint)).T)
1303    return RingsAI
1304   
1305def CalcStrSta(StrSta,Controls):
1306
1307    wave = Controls['wavelength']
1308    phi = StrSta['Sample phi']
1309    StaType = StrSta['Type']
1310    for ring in StrSta['d-zero']:
1311        Eij = ring['Emat']
1312        E = [[Eij[0],Eij[1],0],[Eij[1],Eij[2],0],[0,0,0]]
1313        th,azm = ring['ImtaObs']
1314        th0 = np.ones_like(azm)*npasind(wave/(2.*ring['Dset']))
1315        V = -np.sum(np.sum(E*calcFij(90.,phi,azm,th0).T/1.e6,axis=2),axis=1)
1316        if StaType == 'True':
1317            ring['ImtaCalc'] = np.array([np.exp(V)*ring['Dset'],azm])
1318        else:
1319            ring['ImtaCalc'] = np.array([(V+1.)*ring['Dset'],azm])
1320        dmin = np.min(ring['ImtaCalc'][0])
1321        dmax = np.max(ring['ImtaCalc'][0])
1322        if ring.get('fixDset',True):
1323            if abs(Eij[0]) < abs(Eij[2]):         #tension
1324                ring['Dcalc'] = dmin+(dmax-dmin)/4.
1325            else:                       #compression
1326                ring['Dcalc'] = dmin+3.*(dmax-dmin)/4.
1327        else:
1328            ring['Dcalc'] = np.mean(ring['ImtaCalc'][0])
1329
1330def calcFij(omg,phi,azm,th):
1331    '''    Uses parameters as defined by Bob He & Kingsley Smith, Adv. in X-Ray Anal. 41, 501 (1997)
1332
1333    :param omg: his omega = sample omega rotation; 0 when incident beam || sample surface,
1334        90 when perp. to sample surface
1335    :param phi: his phi = sample phi rotation; usually = 0, axis rotates with omg.
1336    :param azm: his chi = azimuth around incident beam
1337    :param th:  his theta = theta
1338    '''
1339    a = npsind(th)*npcosd(omg)+npsind(azm)*npcosd(th)*npsind(omg)
1340    b = -npcosd(azm)*npcosd(th)
1341    c = npsind(th)*npsind(omg)-npsind(azm)*npcosd(th)*npcosd(omg)
1342    d = a*npsind(phi)+b*npcosd(phi)
1343    e = a*npcosd(phi)-b*npsind(phi)
1344    Fij = np.array([
1345        [d**2,d*e,c*d],
1346        [d*e,e**2,c*e],
1347        [c*d,c*e,c**2]])
1348    return -Fij
1349
1350def FitStrain(rings,p0,dset,wave,phi,StaType):
1351    'Needs a doc string'
1352    def StrainPrint(ValSig,dset):
1353        print ('Strain tensor for Dset: %.6f'%(dset))
1354        ptlbls = 'names :'
1355        ptstr =  'values:'
1356        sigstr = 'esds  :'
1357        for name,fmt,value,sig in ValSig:
1358            ptlbls += "%s" % (name.rjust(12))
1359            ptstr += fmt % (value)
1360            if sig:
1361                sigstr += fmt % (sig)
1362            else:
1363                sigstr += 12*' '
1364        print (ptlbls)
1365        print (ptstr)
1366        print (sigstr)
1367       
1368    def strainCalc(p,xyd,dset,wave,phi,StaType):
1369        E = np.array([[p[0],p[1],0],[p[1],p[2],0],[0,0,0]])
1370        dspo,azm,dsp = xyd
1371        th = npasind(wave/(2.0*dspo))
1372        V = -np.sum(np.sum(E*calcFij(90.,phi,azm,th).T/1.e6,axis=2),axis=1)
1373        if StaType == 'True':
1374            dspc = dset*np.exp(V)
1375        else:
1376            dspc = dset*(V+1.)
1377        return dspo-dspc
1378       
1379    names = ['e11','e12','e22']
1380    fmt = ['%12.2f','%12.2f','%12.2f']
1381    result = leastsq(strainCalc,p0,args=(rings,dset,wave,phi,StaType),full_output=True)
1382    vals = list(result[0])
1383    chisq = np.sum(result[2]['fvec']**2)/(rings.shape[1]-3)     #reduced chi^2 = M/(Nobs-Nvar)
1384    covM = result[1]
1385    covMatrix = covM*chisq
1386    sig = list(np.sqrt(chisq*np.diag(result[1])))
1387    ValSig = zip(names,fmt,vals,sig)
1388    StrainPrint(ValSig,dset)
1389    return vals,sig,covMatrix
1390
1391def FitImageSpots(Image,ImMax,ind,pixSize,nxy,spotSize=1.0):
1392   
1393    def calcMean(nxy,pixSize,img):
1394        gdx,gdy = np.mgrid[0:nxy,0:nxy]
1395        gdx = ma.array((gdx-nxy//2)*pixSize[0]/1000.,mask=~ma.getmaskarray(ImBox))
1396        gdy = ma.array((gdy-nxy//2)*pixSize[1]/1000.,mask=~ma.getmaskarray(ImBox))
1397        posx = ma.sum(gdx)/ma.count(gdx)
1398        posy = ma.sum(gdy)/ma.count(gdy)
1399        return posx,posy
1400   
1401    def calcPeak(values,nxy,pixSize,img):
1402        back,mag,px,py,sig = values
1403        peak = np.zeros([nxy,nxy])+back
1404        nor = 1./(2.*np.pi*sig**2)
1405        gdx,gdy = np.mgrid[0:nxy,0:nxy]
1406        gdx = (gdx-nxy//2)*pixSize[0]/1000.
1407        gdy = (gdy-nxy//2)*pixSize[1]/1000.
1408        arg = (gdx-px)**2+(gdy-py)**2       
1409        peak += mag*nor*np.exp(-arg/(2.*sig**2))
1410        return ma.compressed(img-peak)/np.sqrt(ma.compressed(img))
1411   
1412    def calc2Peak(values,nxy,pixSize,img):
1413        back,mag,px,py,sigx,sigy,rho = values
1414        peak = np.zeros([nxy,nxy])+back
1415        nor = 1./(2.*np.pi*sigx*sigy*np.sqrt(1.-rho**2))
1416        gdx,gdy = np.mgrid[0:nxy,0:nxy]
1417        gdx = (gdx-nxy//2)*pixSize[0]/1000.
1418        gdy = (gdy-nxy//2)*pixSize[1]/1000.
1419        argnor = -1./(2.*(1.-rho**2))
1420        arg = (gdx-px)**2/sigx**2+(gdy-py)**2/sigy**2-2.*rho*(gdx-px)*(gdy-py)/(sigx*sigy)       
1421        peak += mag*nor*np.exp(argnor*arg)
1422        return ma.compressed(img-peak)/np.sqrt(ma.compressed(img))       
1423   
1424    nxy2 = nxy//2
1425    ImBox = Image[ind[1]-nxy2:ind[1]+nxy2+1,ind[0]-nxy2:ind[0]+nxy2+1]
1426    back = np.min(ImBox)
1427    mag = np.sum(ImBox-back)
1428    vals = [back,mag,0.,0.,0.2,0.2,0.]
1429    ImBox = ma.array(ImBox,dtype=float,mask=ImBox>0.75*ImMax)
1430    px = (ind[0]+.5)*pixSize[0]/1000.
1431    py = (ind[1]+.5)*pixSize[1]/1000.
1432    if ma.any(ma.getmaskarray(ImBox)):
1433        vals = calcMean(nxy,pixSize,ImBox)
1434        posx,posy = [px+vals[0],py+vals[1]]
1435        return [posx,posy,spotSize]
1436    else:
1437        result = leastsq(calc2Peak,vals,args=(nxy,pixSize,ImBox),full_output=True)
1438        vals = result[0]
1439        ratio = vals[4]/vals[5]
1440        if 0.5 < ratio < 2.0 and vals[2] < 2. and vals[3] < 2.:
1441            posx,posy = [px+vals[2],py+vals[3]]
1442            return [posx,posy,min(6.*vals[4],spotSize)]
1443        else:
1444            return None
1445   
1446def AutoSpotMasks(Image,Masks,Controls):
1447   
1448    G2fil.G2Print ('auto spot search')
1449    nxy = 15
1450    rollImage = lambda rho,roll: np.roll(np.roll(rho,roll[0],axis=0),roll[1],axis=1)
1451    pixelSize = Controls['pixelSize']
1452    spotMask = ma.array(Image,mask=(Image<np.mean(Image)))
1453    indices = (-1,0,1)
1454    rolls = np.array([[ix,iy] for ix in indices for iy in indices])
1455    time0 = time.time()
1456    for roll in rolls:
1457        if np.any(roll):        #avoid [0,0]
1458            spotMask = ma.array(spotMask,mask=(spotMask-rollImage(Image,roll)<0.),dtype=float)
1459    mags = spotMask[spotMask.nonzero()]
1460    indx = np.transpose(spotMask.nonzero())
1461    size1 = mags.shape[0]
1462    magind = [[indx[0][0],indx[0][1],mags[0]],]
1463    for ind,mag in list(zip(indx,mags))[1:]:        #remove duplicates
1464#            ind[0],ind[1],I,J = ImageLocalMax(Image,nxy,ind[0],ind[1])
1465        if (magind[-1][0]-ind[0])**2+(magind[-1][1]-ind[1])**2 > 16:
1466            magind.append([ind[0],ind[1],Image[ind[0],ind[1]]]) 
1467    magind = np.array(magind).T
1468    indx = np.array(magind[0:2],dtype=np.int32)
1469    mags = magind[2]
1470    size2 = mags.shape[0]
1471    G2fil.G2Print ('Initial search done: %d -->%d %.2fs'%(size1,size2,time.time()-time0))
1472    nx,ny = Image.shape
1473    ImMax = np.max(Image)
1474    peaks = []
1475    nxy2 = nxy//2
1476    mult = 0.001
1477    num = 1e6
1478    while num>500:
1479        mult += .0001           
1480        minM = mult*np.max(mags)
1481        num = ma.count(ma.array(mags,mask=mags<=minM))
1482        G2fil.G2Print('try',mult,minM,num)
1483    minM = mult*np.max(mags)
1484    G2fil.G2Print ('Find biggest spots:',mult,num,minM)
1485    for i,mag in enumerate(mags):
1486        if mag > minM:
1487            if (nxy2 < indx[0][i] < nx-nxy2-1) and (nxy2 < indx[1][i] < ny-nxy2-1):
1488#                    G2fil.G2Print ('try:%d %d %d %.2f'%(i,indx[0][i],indx[1][i],mags[i]))
1489                peak = FitImageSpots(Image,ImMax,[indx[1][i],indx[0][i]],pixelSize,nxy)
1490                if peak and not any(np.isnan(np.array(peak))):
1491                    peaks.append(peak)
1492#                    G2fil.G2Print (' Spot found: %s'%str(peak))
1493    peaks = G2mth.sortArray(G2mth.sortArray(peaks,1),0)
1494    Peaks = [peaks[0],]
1495    for peak in peaks[1:]:
1496        if GetDsp(peak[0],peak[1],Controls) >= 1.:      #toss non-diamond low angle spots
1497            continue
1498        if (peak[0]-Peaks[-1][0])**2+(peak[1]-Peaks[-1][1])**2 > peak[2]*Peaks[-1][2] :
1499            Peaks.append(peak)
1500#            G2fil.G2Print (' Spot found: %s'%str(peak))
1501    G2fil.G2Print ('Spots found: %d time %.2fs'%(len(Peaks),time.time()-time0))
1502    Masks['Points'] = Peaks
1503    return None
Note: See TracBrowser for help on using the repository browser.