This repository has been archived by the owner on Sep 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGSASIIimage.py
2058 lines (1930 loc) · 84.7 KB
/
GSASIIimage.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#GSASII image calculations: Image calibration, masking & integration routines.
########### SVN repository information ###################
# $Date: 2023-10-28 16:43:36 -0500 (Sat, 28 Oct 2023) $
# $Author: vondreele $
# $Revision: 5687 $
# $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/GSASIIimage.py $
# $Id: GSASIIimage.py 5687 2023-10-28 21:43:36Z vondreele $
########### SVN repository information ###################
'''
Classes and routines defined in :mod:`GSASIIimage` follow.
'''
from __future__ import division, print_function
import math
import time
import copy
import sys
import numpy as np
import numpy.linalg as nl
import numpy.ma as ma
from scipy.optimize import leastsq
import scipy.interpolate as scint
import scipy.special as sc
import GSASIIpath
GSASIIpath.SetVersionNumber("$Revision: 5687 $")
try:
import GSASIIplot as G2plt
except ImportError: # expected in scriptable w/o matplotlib and/or wx
pass
import GSASIIlattice as G2lat
import GSASIIpwd as G2pwd
import GSASIIspc as G2spc
#import GSASIImath as G2mth
import GSASIIfiles as G2fil
import ImageCalibrants as calFile
# trig functions in degrees
sind = lambda x: math.sin(x*math.pi/180.)
asind = lambda x: 180.*math.asin(x)/math.pi
tand = lambda x: math.tan(x*math.pi/180.)
atand = lambda x: 180.*math.atan(x)/math.pi
atan2d = lambda y,x: 180.*math.atan2(y,x)/math.pi
cosd = lambda x: math.cos(x*math.pi/180.)
acosd = lambda x: 180.*math.acos(x)/math.pi
rdsq2d = lambda x,p: round(1.0/math.sqrt(x),p)
#numpy versions
npsind = lambda x: np.sin(x*np.pi/180.)
npasind = lambda x: 180.*np.arcsin(x)/np.pi
npcosd = lambda x: np.cos(x*np.pi/180.)
npacosd = lambda x: 180.*np.arccos(x)/np.pi
nptand = lambda x: np.tan(x*np.pi/180.)
npatand = lambda x: 180.*np.arctan(x)/np.pi
npatan2d = lambda y,x: 180.*np.arctan2(y,x)/np.pi
nxs = np.newaxis
debug = False
def pointInPolygon(pXY,xy):
'Needs a doc string'
#pXY - assumed closed 1st & last points are duplicates
Inside = False
N = len(pXY)
p1x,p1y = pXY[0]
for i in range(N+1):
p2x,p2y = pXY[i%N]
if (max(p1y,p2y) >= xy[1] > min(p1y,p2y)) and (xy[0] <= max(p1x,p2x)):
if p1y != p2y:
xinters = (xy[1]-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or xy[0] <= xinters:
Inside = not Inside
p1x,p1y = p2x,p2y
return Inside
def peneCorr(tth,dep,dist):
'Needs a doc string'
return dep*(1.-npcosd(tth))*dist**2/1000. #best one
def makeMat(Angle,Axis):
'''Make rotation matrix from Angle and Axis
:param float Angle: in degrees
:param int Axis: 0 for rotation about x, 1 for about y, etc.
'''
cs = npcosd(Angle)
ss = npsind(Angle)
M = np.array(([1.,0.,0.],[0.,cs,-ss],[0.,ss,cs]),dtype=np.float32)
return np.roll(np.roll(M,Axis,axis=0),Axis,axis=1)
def FitEllipse(xy):
def ellipse_center(p):
''' gives ellipse center coordinates
'''
b,c,d,f,a = p[1]/2., p[2], p[3]/2., p[4]/2., p[0]
num = b*b-a*c
x0=(c*d-b*f)/num
y0=(a*f-b*d)/num
return np.array([x0,y0])
def ellipse_angle_of_rotation( p ):
''' gives rotation of ellipse major axis from x-axis
range will be -90 to 90 deg
'''
b,c,a = p[1]/2., p[2], p[0]
return 0.5*npatand(2*b/(a-c))
def ellipse_axis_length( p ):
''' gives ellipse radii in [minor,major] order
'''
b,c,d,f,g,a = p[1]/2., p[2], p[3]/2., p[4]/2, p[5], p[0]
up = 2*(a*f*f+c*d*d+g*b*b-2*b*d*f-a*c*g)
down1=(b*b-a*c)*( (c-a)*np.sqrt(1+4*b*b/((a-c)*(a-c)))-(c+a))
down2=(b*b-a*c)*( (a-c)*np.sqrt(1+4*b*b/((a-c)*(a-c)))-(c+a))
res1=np.sqrt(up/down1)
res2=np.sqrt(up/down2)
return np.array([ res2,res1])
xy = np.array(xy)
x = np.asarray(xy.T[0])[:,np.newaxis]
y = np.asarray(xy.T[1])[:,np.newaxis]
D = np.hstack((x*x, x*y, y*y, x, y, np.ones_like(x)))
S = np.dot(D.T,D)
C = np.zeros([6,6])
C[0,2] = C[2,0] = 2; C[1,1] = -1
E, V = nl.eig(np.dot(nl.inv(S), C))
n = np.argmax(np.abs(E))
a = V[:,n]
cent = ellipse_center(a)
phi = ellipse_angle_of_rotation(a)
radii = ellipse_axis_length(a)
phi += 90.
if radii[0] > radii[1]:
radii = [radii[1],radii[0]]
phi -= 90.
return cent,phi,radii
def FitDetector(rings,varyList,parmDict,Print=True,covar=False):
'''Fit detector calibration parameters
:param np.array rings: vector of ring positions
:param list varyList: calibration parameters to be refined
:param dict parmDict: all calibration parameters
:param bool Print: set to True (default) to print the results
:param bool covar: set to True to return the covariance matrix (default is False)
:returns: [chisq,vals,sigList] unless covar is True, then
[chisq,vals,sigList,coVarMatrix] is returned
'''
def CalibPrint(ValSig,chisq,Npts):
print ('Image Parameters: chi**2: %12.3g, Np: %d'%(chisq,Npts))
ptlbls = 'names :'
ptstr = 'values:'
sigstr = 'esds :'
for name,value,sig in ValSig:
ptlbls += "%s" % (name.rjust(12))
if name == 'phi':
ptstr += Fmt[name] % (value%360.)
else:
ptstr += Fmt[name] % (value)
if sig:
sigstr += Fmt[name] % (sig)
else:
sigstr += 12*' '
print (ptlbls)
print (ptstr)
print (sigstr)
def ellipseCalcD(B,xyd,varyList,parmDict):
x,y,dsp = xyd
varyDict = dict(zip(varyList,B))
parms = {}
for parm in parmDict:
if parm in varyList:
parms[parm] = varyDict[parm]
else:
parms[parm] = parmDict[parm]
phi = parms['phi']-90. #get rotation of major axis from tilt axis
tth = 2.0*npasind(parms['wave']/(2.*dsp))
phi0 = npatan2d(y-parms['det-Y'],x-parms['det-X'])
dxy = peneCorr(tth,parms['dep'],parms['dist'])
stth = npsind(tth)
cosb = npcosd(parms['tilt'])
tanb = nptand(parms['tilt'])
tbm = nptand((tth-parms['tilt'])/2.)
tbp = nptand((tth+parms['tilt'])/2.)
d = parms['dist']+dxy
fplus = d*tanb*stth/(cosb+stth)
fminus = d*tanb*stth/(cosb-stth)
vplus = d*(tanb+(1+tbm)/(1-tbm))*stth/(cosb+stth)
vminus = d*(tanb+(1-tbp)/(1+tbp))*stth/(cosb-stth)
R0 = np.sqrt((vplus+vminus)**2-(fplus+fminus)**2)/2. #+minor axis
R1 = (vplus+vminus)/2. #major axis
zdis = (fplus-fminus)/2.
Robs = np.sqrt((x-parms['det-X'])**2+(y-parms['det-Y'])**2)
rsqplus = R0**2+R1**2
rsqminus = R0**2-R1**2
R = rsqminus*npcosd(2.*phi0-2.*phi)+rsqplus
Q = np.sqrt(2.)*R0*R1*np.sqrt(R-2.*zdis**2*npsind(phi0-phi)**2)
P = 2.*R0**2*zdis*npcosd(phi0-phi)
Rcalc = (P+Q)/R
M = (Robs-Rcalc)*25. #why 25? does make "chi**2" more reasonable
return M
names = ['dist','det-X','det-Y','tilt','phi','dep','wave']
fmt = ['%12.3f','%12.3f','%12.3f','%12.3f','%12.3f','%12.4f','%12.6f']
Fmt = dict(zip(names,fmt))
p0 = [parmDict[key] for key in varyList]
result = leastsq(ellipseCalcD,p0,args=(rings.T,varyList,parmDict),full_output=True,ftol=1.e-8)
chisq = np.sum(result[2]['fvec']**2)/(rings.shape[0]-len(p0)) #reduced chi^2 = M/(Nobs-Nvar)
parmDict.update(zip(varyList,result[0]))
vals = list(result[0])
if not len(vals):
sig = []
ValSig = []
sigList = []
else:
sig = list(np.sqrt(chisq*np.diag(result[1])))
sigList = np.zeros(7)
for i,name in enumerate(varyList):
sigList[i] = sig[varyList.index(name)]
ValSig = zip(varyList,vals,sig)
if Print:
if len(sig):
CalibPrint(ValSig,chisq,rings.shape[0])
else:
print(' Nothing refined')
if covar:
return [chisq,vals,sigList,result[1]]
else:
return [chisq,vals,sigList]
def FitMultiDist(rings,varyList,parmDict,Print=True,covar=False):
'''Fit detector calibration parameters with multi-distance data
:param np.array rings: vector of ring positions (x,y,dist,d-space)
:param list varyList: calibration parameters to be refined
:param dict parmDict: calibration parameters
:param bool Print: set to True (default) to print the results
:param bool covar: set to True to return the covariance matrix (default is False)
:returns: [chisq,vals,sigDict] unless covar is True, then
[chisq,vals,sigDict,coVarMatrix] is returned
'''
def CalibPrint(parmDict,sigDict,chisq,Npts):
ptlbls = 'names :'
ptstr = 'values:'
sigstr = 'esds :'
for d in sorted(set([i[5:] for i in parmDict.keys() if 'det-X' in i]),key=lambda x:int(x)):
fmt = '%12.3f'
for key in 'det-X','det-Y','delta':
name = key+d
if name not in parmDict: continue
ptlbls += "%12s" % name
ptstr += fmt % (parmDict[name])
if name in sigDict:
sigstr += fmt % (sigDict[name])
else:
sigstr += 12*' '
if len(ptlbls) > 68:
print()
print (ptlbls)
print (ptstr)
print (sigstr)
ptlbls = 'names :'
ptstr = 'values:'
sigstr = 'esds :'
if len(ptlbls) > 8:
print()
print (ptlbls)
print (ptstr)
print (sigstr)
print ('\nImage Parameters: chi**2: %12.3g, Np: %d'%(chisq,Npts))
ptlbls = 'names :'
ptstr = 'values:'
sigstr = 'esds :'
names = ['wavelength', 'dep', 'phi', 'tilt']
if 'deltaDist' in parmDict:
names += ['deltaDist']
for name in names:
if name == 'wavelength':
fmt = '%12.6f'
elif name == 'dep':
fmt = '%12.4f'
else:
fmt = '%12.3f'
ptlbls += "%s" % (name.rjust(12))
if name == 'phi':
ptstr += fmt % (parmDict[name]%360.)
else:
ptstr += fmt % (parmDict[name])
if name in sigDict:
sigstr += fmt % (sigDict[name])
else:
sigstr += 12*' '
print (ptlbls)
print (ptstr)
print (sigstr)
print()
def ellipseCalcD(B,xyd,varyList,parmDict):
x,y,dist,dsp = xyd
varyDict = dict(zip(varyList,B))
parms = {}
for parm in parmDict:
if parm in varyList:
parms[parm] = varyDict[parm]
else:
parms[parm] = parmDict[parm]
# create arrays with detector center values
detX = np.array([parms['det-X'+str(int(d))] for d in dist])
detY = np.array([parms['det-Y'+str(int(d))] for d in dist])
if 'deltaDist' in parms:
deltaDist = parms['deltaDist']
else:
deltaDist = np.array([parms['delta'+str(int(d))] for d in dist])
phi = parms['phi']-90. #get rotation of major axis from tilt axis
tth = 2.0*npasind(parms['wavelength']/(2.*dsp))
phi0 = npatan2d(y-detY,x-detX)
dxy = peneCorr(tth,parms['dep'],dist-deltaDist)
stth = npsind(tth)
cosb = npcosd(parms['tilt'])
tanb = nptand(parms['tilt'])
tbm = nptand((tth-parms['tilt'])/2.)
tbp = nptand((tth+parms['tilt'])/2.)
d = (dist-deltaDist)+dxy
fplus = d*tanb*stth/(cosb+stth)
fminus = d*tanb*stth/(cosb-stth)
vplus = d*(tanb+(1+tbm)/(1-tbm))*stth/(cosb+stth)
vminus = d*(tanb+(1-tbp)/(1+tbp))*stth/(cosb-stth)
R0 = np.sqrt((vplus+vminus)**2-(fplus+fminus)**2)/2. #+minor axis
R1 = (vplus+vminus)/2. #major axis
zdis = (fplus-fminus)/2.
Robs = np.sqrt((x-detX)**2+(y-detY)**2)
rsqplus = R0**2+R1**2
rsqminus = R0**2-R1**2
R = rsqminus*npcosd(2.*phi0-2.*phi)+rsqplus
Q = np.sqrt(2.)*R0*R1*np.sqrt(R-2.*zdis**2*npsind(phi0-phi)**2)
P = 2.*R0**2*zdis*npcosd(phi0-phi)
Rcalc = (P+Q)/R
return (Robs-Rcalc)*25. #why 25? does make "chi**2" more reasonable
p0 = [parmDict[key] for key in varyList]
result = leastsq(ellipseCalcD,p0,args=(rings.T,varyList,parmDict),full_output=True,ftol=1.e-8)
chisq = np.sum(result[2]['fvec']**2)/(rings.shape[0]-len(p0)) #reduced chi^2 = M/(Nobs-Nvar)
parmDict.update(zip(varyList,result[0]))
vals = list(result[0])
if chisq > 1:
sig = list(np.sqrt(chisq*np.diag(result[1])))
else:
sig = list(np.sqrt(np.diag(result[1])))
sigDict = {name:s for name,s in zip(varyList,sig)}
if Print:
CalibPrint(parmDict,sigDict,chisq,rings.shape[0])
if covar:
return [chisq,vals,sigDict,result[1]]
else:
return [chisq,vals,sigDict]
def ImageLocalMax(image,w,Xpix,Ypix):
'Needs a doc string'
w2 = w*2
sizey,sizex = image.shape
xpix = int(Xpix) #get reference corner of pixel chosen
ypix = int(Ypix)
if not w:
ZMax = np.sum(image[ypix-2:ypix+2,xpix-2:xpix+2])
return xpix,ypix,ZMax,0.0001
if (w2 < xpix < sizex-w2) and (w2 < ypix < sizey-w2) and image[ypix,xpix]:
ZMax = image[ypix-w:ypix+w,xpix-w:xpix+w]
Zmax = np.argmax(ZMax)
ZMin = image[ypix-w2:ypix+w2,xpix-w2:xpix+w2]
Zmin = np.argmin(ZMin)
xpix += Zmax%w2-w
ypix += Zmax//w2-w
return xpix,ypix,np.ravel(ZMax)[Zmax],max(0.0001,np.ravel(ZMin)[Zmin]) #avoid neg/zero minimum
else:
return 0,0,0,0
def makeRing(dsp,ellipse,pix,reject,scalex,scaley,image,mul=1):
'Needs a doc string'
def ellipseC():
'compute estimate of ellipse circumference'
if radii[0] < 0: #hyperbola
# theta = npacosd(1./np.sqrt(1.+(radii[0]/radii[1])**2))
# print (theta)
return 0
apb = radii[1]+radii[0]
amb = radii[1]-radii[0]
return np.pi*apb*(1+3*(amb/apb)**2/(10+np.sqrt(4-3*(amb/apb)**2)))
cent,phi,radii = ellipse
cphi = cosd(phi-90.) #convert to major axis rotation
sphi = sind(phi-90.)
ring = []
C = int(ellipseC())*mul #ring circumference in mm
azm = []
for i in range(0,C,1): #step around ring in 1mm increments
a = 360.*i/C
x = radii[1]*cosd(a-phi+90.) #major axis
y = radii[0]*sind(a-phi+90.)
X = (cphi*x-sphi*y+cent[0])*scalex #convert mm to pixels
Y = (sphi*x+cphi*y+cent[1])*scaley
X,Y,I,J = ImageLocalMax(image,pix,X,Y)
if I and J and float(I)/J > reject:
X += .5 #set to center of pixel
Y += .5
X /= scalex #convert back to mm
Y /= scaley
if [X,Y,dsp] not in ring: #no duplicates!
ring.append([X,Y,dsp])
azm.append(a)
if len(ring) < 10:
ring = []
azm = []
return ring,azm
def GetEllipse2(tth,dxy,dist,cent,tilt,phi):
'''uses Dandelin spheres to find ellipse or hyperbola parameters from detector geometry
on output
radii[0] (b-minor axis) set < 0. for hyperbola
'''
radii = [0,0]
stth = sind(tth)
cosb = cosd(tilt)
tanb = tand(tilt)
tbm = tand((tth-tilt)/2.)
tbp = tand((tth+tilt)/2.)
sinb = sind(tilt)
d = dist+dxy
if tth+abs(tilt) < 90.: #ellipse
fplus = d*tanb*stth/(cosb+stth)
fminus = d*tanb*stth/(cosb-stth)
vplus = d*(tanb+(1+tbm)/(1-tbm))*stth/(cosb+stth)
vminus = d*(tanb+(1-tbp)/(1+tbp))*stth/(cosb-stth)
radii[0] = np.sqrt((vplus+vminus)**2-(fplus+fminus)**2)/2. #+minor axis
radii[1] = (vplus+vminus)/2. #major axis
zdis = (fplus-fminus)/2.
else: #hyperbola!
f = d*abs(tanb)*stth/(cosb+stth)
v = d*(abs(tanb)+tand(tth-abs(tilt)))
delt = d*stth*(1.+stth*cosb)/(abs(sinb)*cosb*(stth+cosb))
eps = (v-f)/(delt-v)
radii[0] = -eps*(delt-f)/np.sqrt(eps**2-1.) #-minor axis
radii[1] = eps*(delt-f)/(eps**2-1.) #major axis
if tilt > 0:
zdis = f+radii[1]*eps
else:
zdis = -f
#NB: zdis is || to major axis & phi is rotation of minor axis
#thus shift from beam to ellipse center is [Z*sin(phi),-Z*cos(phi)]
elcent = [cent[0]+zdis*sind(phi),cent[1]-zdis*cosd(phi)]
return elcent,phi,radii
def GetEllipse(dsp,data):
'''uses Dandelin spheres to find ellipse or hyperbola parameters from detector geometry
as given in image controls dictionary (data) and a d-spacing (dsp)
'''
cent = data['center']
tilt = data['tilt']
phi = data['rotation']
dep = data.get('DetDepth',0.0)
tth = 2.0*asind(data['wavelength']/(2.*dsp))
dist = data['distance']
dxy = peneCorr(tth,dep,dist)
return GetEllipse2(tth,dxy,dist,cent,tilt,phi)
def GetDetectorXY(dsp,azm,data):
'''Get detector x,y position from d-spacing (dsp), azimuth (azm,deg)
& image controls dictionary (data) - new version
it seems to be only used in plotting
'''
def LinePlaneCollision(planeNormal, planePoint, rayDirection, rayPoint, epsilon=1e-6):
ndotu = planeNormal.dot(rayDirection)
if ndotu < epsilon:
return None
w = rayPoint - planePoint
si = -planeNormal.dot(w) / ndotu
Psi = w + si * rayDirection + planePoint
return Psi
dist = data['distance']
cent = data['center']
T = makeMat(data['tilt'],0)
R = makeMat(data['rotation'],2)
MN = np.inner(R,np.inner(R,T))
iMN= nl.inv(MN)
tth = 2.0*npasind(data['wavelength']/(2.*dsp))
vect = np.array([npsind(tth)*npcosd(azm),npsind(tth)*npsind(azm),npcosd(tth)])
dxyz0 = np.inner(np.array([0.,0.,1.0]),MN) #tilt detector normal
dxyz0 += np.array([0.,0.,dist]) #translate to distance
dxyz0 = np.inner(dxyz0,makeMat(data['det2theta'],1).T) #rotate on 2-theta
dxyz1 = np.inner(np.array([cent[0],cent[1],0.]),MN) #tilt detector cent
dxyz1 += np.array([0.,0.,dist]) #translate to distance
dxyz1 = np.inner(dxyz1,makeMat(data['det2theta'],1).T) #rotate on 2-theta
xyz = LinePlaneCollision(dxyz0,dxyz1,vect,2.*dist*vect)
if xyz is None:
return np.zeros(2)
# return None
xyz = np.inner(xyz,makeMat(-data['det2theta'],1).T)
xyz -= np.array([0.,0.,dist]) #translate back
xyz = np.inner(xyz,iMN)
return np.squeeze(xyz)[:2]+cent
def GetDetectorXY2(dsp,azm,data):
'''Get detector x,y position from d-spacing (dsp), azimuth (azm,deg)
& image controls dictionary (data)
it seems to be only used in plotting
'''
elcent,phi,radii = GetEllipse(dsp,data)
phi = data['rotation']-90. #to give rotation of major axis
tilt = data['tilt']
dist = data['distance']
cent = data['center']
tth = 2.0*asind(data['wavelength']/(2.*dsp))
stth = sind(tth)
cosb = cosd(tilt)
if radii[0] > 0.:
sinb = sind(tilt)
tanb = tand(tilt)
fplus = dist*tanb*stth/(cosb+stth)
fminus = dist*tanb*stth/(cosb-stth)
zdis = (fplus-fminus)/2.
rsqplus = radii[0]**2+radii[1]**2
rsqminus = radii[0]**2-radii[1]**2
R = rsqminus*cosd(2.*azm-2.*phi)+rsqplus
Q = np.sqrt(2.)*radii[0]*radii[1]*np.sqrt(R-2.*zdis**2*sind(azm-phi)**2)
P = 2.*radii[0]**2*zdis*cosd(azm-phi)
radius = (P+Q)/R
xy = np.array([radius*cosd(azm),radius*sind(azm)])
xy += cent
else: #hyperbola - both branches (one is way off screen!)
sinb = abs(sind(tilt))
tanb = abs(tand(tilt))
f = dist*tanb*stth/(cosb+stth)
v = dist*(tanb+tand(tth-abs(tilt)))
delt = dist*stth*(1+stth*cosb)/(sinb*cosb*(stth+cosb))
ecc = (v-f)/(delt-v)
R = radii[1]*(ecc**2-1)/(1-ecc*cosd(azm))
if tilt > 0.:
offset = 2.*radii[1]*ecc+f #select other branch
xy = [-R*cosd(azm)-offset,-R*sind(azm)]
else:
offset = -f
xy = [-R*cosd(azm)-offset,R*sind(azm)]
xy = -np.array([xy[0]*cosd(phi)+xy[1]*sind(phi),xy[0]*sind(phi)-xy[1]*cosd(phi)])
xy += cent
if data['det2theta']:
xy[0] += dist*nptand(data['det2theta']+data['tilt']*npsind(data['rotation']))
return xy
def GetDetXYfromThAzm(Th,Azm,data):
'''Computes a detector position from a 2theta angle and an azimultal
angle (both in degrees) - apparently not used!
'''
dsp = data['wavelength']/(2.0*npsind(Th))
return GetDetectorXY(dsp,Azm,data)
def GetTthAzmDsp2(x,y,data): #expensive
'''Computes a 2theta, etc. from a detector position and calibration constants - checked
OK for ellipses & hyperbola.
Use only for detector 2-theta = 0
:returns: np.array(tth,azm,G,dsp) where tth is 2theta, azm is the azimutal angle,
G is ? and dsp is the d-space
'''
wave = data['wavelength']
cent = data['center']
tilt = data['tilt']
dist = data['distance']/cosd(tilt)
x0 = dist*tand(tilt)
phi = data['rotation']
dep = data.get('DetDepth',0.)
azmthoff = data['azmthOff']
dx = np.array(x-cent[0],dtype=np.float32)
dy = np.array(y-cent[1],dtype=np.float32)
D = ((dx-x0)**2+dy**2+dist**2) #sample to pixel distance
X = np.array(([dx,dy,np.zeros_like(dx)]),dtype=np.float32).T
X = np.dot(X,makeMat(phi,2))
Z = np.dot(X,makeMat(tilt,0)).T[2]
tth = npatand(np.sqrt(dx**2+dy**2-Z**2)/(dist-Z))
dxy = peneCorr(tth,dep,dist)
DX = dist-Z+dxy
DY = np.sqrt(dx**2+dy**2-Z**2)
tth = npatan2d(DY,DX)
dsp = wave/(2.*npsind(tth/2.))
azm = (npatan2d(dy,dx)+azmthoff+720.)%360.
G = D/dist**2 #for geometric correction = 1/cos(2theta)^2 if tilt=0.
return np.array([tth,azm,G,dsp])
def GetTthAzmDsp(x,y,data): #expensive
'''Computes a 2theta, etc. from a detector position and calibration constants - checked
OK for ellipses & hyperbola.
Use for detector 2-theta != 0.
:returns: np.array(tth,azm,G,dsp) where tth is 2theta, azm is the azimutal angle,
G is ? and dsp is the d-space
'''
def costth(xyz):
u = xyz/nl.norm(xyz,axis=-1)[:,:,nxs]
return np.dot(u,np.array([0.,0.,1.]))
#zero detector 2-theta: tested with tilted images - perfect integrations
wave = data['wavelength']
dx = x-data['center'][0]
dy = y-data['center'][1]
tilt = data['tilt']
dist = data['distance']/npcosd(tilt) #sample-beam intersection point
T = makeMat(tilt,0)
R = makeMat(data['rotation'],2)
MN = np.inner(R,np.inner(R,T))
dxyz0 = np.inner(np.dstack([dx,dy,np.zeros_like(dx)]),MN) #correct for 45 deg tilt
dxyz0 += np.array([0.,0.,dist])
if data['DetDepth']:
ctth0 = costth(dxyz0)
tth0 = npacosd(ctth0)
dzp = peneCorr(tth0,data['DetDepth'],dist)
dxyz0[:,:,2] += dzp
#non zero detector 2-theta:
if data['det2theta']:
tthMat = makeMat(data['det2theta'],1)
dxyz = np.inner(dxyz0,tthMat.T)
else:
dxyz = dxyz0
ctth = costth(dxyz)
tth = npacosd(ctth)
dsp = wave/(2.*npsind(tth/2.))
azm = (npatan2d(dxyz[:,:,1],dxyz[:,:,0])+data['azmthOff']+720.)%360.
# G-calculation
x0 = data['distance']*nptand(tilt)
x0x = x0*npcosd(data['rotation'])
x0y = x0*npsind(data['rotation'])
distsq = data['distance']**2
G = ((dx-x0x)**2+(dy-x0y)**2+distsq)/distsq #for geometric correction = 1/cos(2theta)^2 if tilt=0.
return [tth,azm,G,dsp]
def GetTth(x,y,data):
'Give 2-theta value for detector x,y position; calibration info in data'
if data['det2theta']:
return GetTthAzmDsp(x,y,data)[0]
else:
return GetTthAzmDsp2(x,y,data)[0]
def GetTthAzm(x,y,data):
'Give 2-theta, azimuth values for detector x,y position; calibration info in data'
if data['det2theta']:
return GetTthAzmDsp(x,y,data)[0:2]
else:
return GetTthAzmDsp2(x,y,data)[0:2]
def GetTthAzmG2(x,y,data):
'''Give 2-theta, azimuth & geometric corr. values for detector x,y position;
calibration info in data - only used in integration for detector 2-theta = 0
'''
tilt = data['tilt']
dist = data['distance']/npcosd(tilt)
MN = -np.inner(makeMat(data['rotation'],2),makeMat(tilt,0))
dx = x-data['center'][0]
dy = y-data['center'][1]
dz = np.dot(np.dstack([dx.T,dy.T,np.zeros_like(dx.T)]),MN).T[2]
xyZ = dx**2+dy**2-dz**2
tth0 = npatand(np.sqrt(xyZ)/(dist-dz))
dzp = peneCorr(tth0,data['DetDepth'],dist)
tth = npatan2d(np.sqrt(xyZ),dist-dz+dzp)
azm = (npatan2d(dy,dx)+data['azmthOff']+720.)%360.
distsq = data['distance']**2
x0 = data['distance']*nptand(tilt)
x0x = x0*npcosd(data['rotation'])
x0y = x0*npsind(data['rotation'])
G = ((dx-x0x)**2+(dy-x0y)**2+distsq)/distsq #for geometric correction = 1/cos(2theta)^2 if tilt=0.
return tth,azm,G
def GetTthAzmG(x,y,data):
'''Give 2-theta, azimuth & geometric corr. values for detector x,y position;
calibration info in data - only used in integration for detector 2-theta != 0.
checked OK for ellipses & hyperbola
This is the slow step in image integration
'''
def costth(xyz):
u = xyz/nl.norm(xyz,axis=-1)[:,:,nxs]
return np.dot(u,np.array([0.,0.,1.]))
#zero detector 2-theta: tested with tilted images - perfect integrations
dx = x-data['center'][0]
dy = y-data['center'][1]
tilt = data['tilt']
dist = data['distance']/npcosd(tilt) #sample-beam intersection point
T = makeMat(tilt,0)
R = makeMat(data['rotation'],2)
MN = np.inner(R,np.inner(R,T))
dxyz0 = np.inner(np.dstack([dx,dy,np.zeros_like(dx)]),MN) #correct for 45 deg tilt
dxyz0 += np.array([0.,0.,dist])
if data['DetDepth']:
ctth0 = costth(dxyz0)
tth0 = npacosd(ctth0)
dzp = peneCorr(tth0,data['DetDepth'],dist)
dxyz0[:,:,2] += dzp
#non zero detector 2-theta:
if data.get('det2theta',0):
tthMat = makeMat(data['det2theta'],1)
dxyz = np.inner(dxyz0,tthMat.T)
else:
dxyz = dxyz0
ctth = costth(dxyz)
tth = npacosd(ctth)
azm = (npatan2d(dxyz[:,:,1],dxyz[:,:,0])+data['azmthOff']+720.)%360.
# G-calculation
x0 = data['distance']*nptand(tilt)
x0x = x0*npcosd(data['rotation'])
x0y = x0*npsind(data['rotation'])
distsq = data['distance']**2
G = ((dx-x0x)**2+(dy-x0y)**2+distsq)/distsq #for geometric correction = 1/cos(2theta)^2 if tilt=0.
return tth,azm,G
def GetDsp(x,y,data):
'Give d-spacing value for detector x,y position; calibration info in data'
if data['det2theta']:
return GetTthAzmDsp(x,y,data)[3]
else:
return GetTthAzmDsp2(x,y,data)[3]
def GetAzm(x,y,data):
'Give azimuth value for detector x,y position; calibration info in data'
if data['det2theta']:
return GetTthAzmDsp(x,y,data)[1]
else:
return GetTthAzmDsp2(x,y,data)[1]
def meanAzm(a,b):
AZM = lambda a,b: npacosd(0.5*(npsind(2.*b)-npsind(2.*a))/(np.pi*(b-a)/180.))/2.
azm = AZM(a,b)
# quad = int((a+b)/180.)
# if quad == 1:
# azm = 180.-azm
# elif quad == 2:
# azm += 180.
# elif quad == 3:
# azm = 360-azm
return azm
def ImageCompress(image,scale):
''' Reduces size of image by selecting every n'th point
param: image array: original image
param: scale int: intervsl between selected points
returns: array: reduced size image
'''
if scale == 1:
return image
else:
return image[::scale,::scale]
def checkEllipse(Zsum,distSum,xSum,ySum,dist,x,y):
'Needs a doc string'
avg = np.array([distSum/Zsum,xSum/Zsum,ySum/Zsum])
curr = np.array([dist,x,y])
return abs(avg-curr)/avg < .02
def GetLineScan(image,data):
Nx,Ny = data['size']
pixelSize = data['pixelSize']
scalex = 1000./pixelSize[0] #microns --> 1/mm
scaley = 1000./pixelSize[1]
wave = data['wavelength']
numChans = data['outChannels']
LUtth = np.array(data['IOtth'],dtype=np.float)
azm = data['linescan'][1]-data['azmthOff']
Tx = np.array([tth for tth in np.linspace(LUtth[0],LUtth[1],numChans+1)])
Ty = np.zeros_like(Tx)
dsp = wave/(2.0*npsind(Tx/2.0))
xy = [GetDetectorXY(d,azm,data) for d in dsp]
xy = np.array(xy).T
xy[1] *= scalex
xy[0] *= scaley
xy = np.array(xy,dtype=int)
Xpix = ma.masked_outside(xy[1],0,Ny-1)
Ypix = ma.masked_outside(xy[0],0,Nx-1)
xpix = Xpix[~(Xpix.mask+Ypix.mask)].compressed()
ypix = Ypix[~(Xpix.mask+Ypix.mask)].compressed()
Ty = image[xpix,ypix]
Tx = ma.array(Tx,mask=Xpix.mask+Ypix.mask).compressed()
return [Tx,Ty]
def EdgeFinder(image,data):
'''this makes list of all x,y where I>edgeMin suitable for an ellipse search?
Not currently used but might be useful in future?
'''
import numpy.ma as ma
Nx,Ny = data['size']
pixelSize = data['pixelSize']
edgemin = data['edgemin']
scalex = pixelSize[0]/1000.
scaley = pixelSize[1]/1000.
tay,tax = np.mgrid[0:Nx,0:Ny]
tax = np.asfarray(tax*scalex,dtype=np.float32)
tay = np.asfarray(tay*scaley,dtype=np.float32)
tam = ma.getmask(ma.masked_less(image.flatten(),edgemin))
tax = ma.compressed(ma.array(tax.flatten(),mask=tam))
tay = ma.compressed(ma.array(tay.flatten(),mask=tam))
return zip(tax,tay)
def MakeFrameMask(data,frame):
'''Assemble a Frame mask for a image, according to the input supplied.
Note that this requires use of the Fortran polymask routine that is limited
to 1024x1024 arrays, so this computation is done in blocks (fixed at 512)
and the master image is assembled from that.
:param dict data: Controls for an image. Used to find the image size
and the pixel dimensions.
:param list frame: Frame parameters, typically taken from ``Masks['Frames']``.
:returns: a mask array with dimensions matching the image Controls.
'''
import polymask as pm
pixelSize = data['pixelSize']
scalex = pixelSize[0]/1000.
scaley = pixelSize[1]/1000.
blkSize = 512
Nx,Ny = data['size']
nXBlks = (Nx-1)//blkSize+1
nYBlks = (Ny-1)//blkSize+1
tam = ma.make_mask_none(data['size'])
for iBlk in range(nXBlks):
iBeg = iBlk*blkSize
iFin = min(iBeg+blkSize,Nx)
for jBlk in range(nYBlks):
jBeg = jBlk*blkSize
jFin = min(jBeg+blkSize,Ny)
nI = iFin-iBeg
nJ = jFin-jBeg
tax,tay = np.mgrid[iBeg+0.5:iFin+.5,jBeg+.5:jFin+.5] #bin centers not corners
tax = np.asfarray(tax*scalex,dtype=np.float32)
tay = np.asfarray(tay*scaley,dtype=np.float32)
tamp = ma.make_mask_none((1024*1024))
tamp = ma.make_mask(pm.polymask(nI*nJ,tax.flatten(),
tay.flatten(),len(frame),frame,tamp)[:nI*nJ])^True #switch to exclude around frame
if tamp.shape:
tamp = np.reshape(tamp[:nI*nJ],(nI,nJ))
tam[iBeg:iFin,jBeg:jFin] = ma.mask_or(tamp[0:nI,0:nJ],tam[iBeg:iFin,jBeg:jFin])
else:
tam[iBeg:iFin,jBeg:jFin] = True
return tam.T
def CalcRings(G2frame,ImageZ,data,masks):
pixelSize = data['pixelSize']
scalex = 1000./pixelSize[0]
scaley = 1000./pixelSize[1]
data['rings'] = []
data['ellipses'] = []
if not data['calibrant']:
G2fil.G2Print ('warning: no calibration material selected')
return
skip = data['calibskip']
dmin = data['calibdmin']
if data['calibrant'] not in calFile.Calibrants:
G2fil.G2Print('Warning: %s not in local copy of image calibrants file'%data['calibrant'])
return
calibrant = calFile.Calibrants[data['calibrant']]
Bravais,SGs,Cells = calibrant[:3]
HKL = []
for bravais,sg,cell in zip(Bravais,SGs,Cells):
A = G2lat.cell2A(cell)
if sg:
SGData = G2spc.SpcGroup(sg)[1]
hkl = G2pwd.getHKLpeak(dmin,SGData,A,Inst=None,nodup=True)
HKL += list(hkl)
else:
hkl = G2lat.GenHBravais(dmin,bravais,A)
HKL += list(hkl)
if len(calibrant) > 5:
absent = calibrant[5]
else:
absent = ()
HKL = G2lat.sortHKLd(HKL,True,False)
wave = data['wavelength']
frame = masks['Frames']
tam = ma.make_mask_none(ImageZ.shape)
if frame:
tam = ma.mask_or(tam,MakeFrameMask(data,frame))
for iH,H in enumerate(HKL):
if debug: print (H)
dsp = H[3]
tth = 2.0*asind(wave/(2.*dsp))
if tth+abs(data['tilt']) > 90.:
G2fil.G2Print ('next line is a hyperbola - search stopped')
break
ellipse = GetEllipse(dsp,data)
if iH not in absent and iH >= skip:
Ring = makeRing(dsp,ellipse,0,-1.,scalex,scaley,ma.array(ImageZ,mask=tam))[0]
else:
Ring = makeRing(dsp,ellipse,0,-1.,scalex,scaley,ma.array(ImageZ,mask=tam))[0]
if Ring:
if iH not in absent and iH >= skip:
data['rings'].append(np.array(Ring))
data['ellipses'].append(copy.deepcopy(ellipse+('r',)))
def ImageRecalibrate(G2frame,ImageZ,data,masks,getRingsOnly=False):
'''Called to repeat the calibration on an image, usually called after
calibration is done initially to improve the fit, but also
can be used after reading approximate calibration parameters,
if they are close enough that the first ring can be found.
:param G2frame: The top-level GSAS-II frame or None, to skip plotting
:param np.Array ImageZ: the image to calibrate
:param dict data: the Controls dict for the image
:param dict masks: a dict with masks
:returns: a list containing vals,varyList,sigList,parmDict,covar or rings
(with an array of x, y, and d-space values) if getRingsOnly is True
or an empty list, in case of an error
'''
if not getRingsOnly:
G2fil.G2Print ('Image recalibration:')
time0 = time.time()
pixelSize = data['pixelSize']
scalex = 1000./pixelSize[0]
scaley = 1000./pixelSize[1]
pixLimit = data['pixLimit']
cutoff = data['cutoff']
data['rings'] = []
data['ellipses'] = []
if data['DetDepth'] > 0.5: #patch - redefine DetDepth
data['DetDepth'] /= data['distance']
if not data['calibrant']:
G2fil.G2Print ('warning: no calibration material selected')
return []
skip = data['calibskip']
dmin = data['calibdmin']
if data['calibrant'] not in calFile.Calibrants:
G2fil.G2Print('Warning: %s not in local copy of image calibrants file'%data['calibrant'])
return []
calibrant = calFile.Calibrants[data['calibrant']]
Bravais,SGs,Cells = calibrant[:3]
HKL = []
for bravais,sg,cell in zip(Bravais,SGs,Cells):
A = G2lat.cell2A(cell)
if sg:
SGData = G2spc.SpcGroup(sg)[1]
hkl = G2pwd.getHKLpeak(dmin,SGData,A,Inst=None,nodup=True)
HKL += list(hkl)
else:
hkl = G2lat.GenHBravais(dmin,bravais,A)
HKL += list(hkl)
if len(calibrant) > 5:
absent = calibrant[5]
else:
absent = ()
HKL = G2lat.sortHKLd(HKL,True,False)
varyList = [item for item in data['varyList'] if data['varyList'][item]]
parmDict = {'dist':data['distance'],'det-X':data['center'][0],'det-Y':data['center'][1],
'setdist':data.get('setdist',data['distance']),
'tilt':data['tilt'],'phi':data['rotation'],'wave':data['wavelength'],'dep':data['DetDepth']}
Found = False
wave = data['wavelength']
frame = masks['Frames']
tam = ma.make_mask_none(ImageZ.shape)
if frame:
tam = ma.mask_or(tam,MakeFrameMask(data,frame))
for iH,H in enumerate(HKL):
if debug: print (H)
dsp = H[3]
tth = 2.0*asind(wave/(2.*dsp))
if tth+abs(data['tilt']) > 90.:
G2fil.G2Print ('next line is a hyperbola - search stopped')
break
ellipse = GetEllipse(dsp,data)
if iH not in absent and iH >= skip:
Ring = makeRing(dsp,ellipse,pixLimit,cutoff,scalex,scaley,ma.array(ImageZ,mask=tam))[0]
else:
Ring = makeRing(dsp,ellipse,pixLimit,1000.0,scalex,scaley,ma.array(ImageZ,mask=tam))[0]
if Ring:
if iH not in absent and iH >= skip:
data['rings'].append(np.array(Ring))
data['ellipses'].append(copy.deepcopy(ellipse+('r',)))
Found = True
elif not Found: #skipping inner rings, keep looking until ring found
continue
else: #no more rings beyond edge of detector
data['ellipses'].append([])
continue
if not data['rings']:
G2fil.G2Print ('no rings found; try lower Min ring I/Ib',mode='warn')
return []
rings = np.concatenate((data['rings']),axis=0)
if getRingsOnly:
return rings,HKL
[chisq,vals,sigList,covar] = FitDetector(rings,varyList,parmDict,True,True)
data['wavelength'] = parmDict['wave']
data['distance'] = parmDict['dist']
data['center'] = [parmDict['det-X'],parmDict['det-Y']]
data['rotation'] = np.mod(parmDict['phi'],360.0)
data['tilt'] = parmDict['tilt']
data['DetDepth'] = parmDict['dep']
data['chisq'] = chisq