-
Notifications
You must be signed in to change notification settings - Fork 0
/
fitting.py
4724 lines (3797 loc) · 150 KB
/
fitting.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
#!/usr/bin/python
#-*- coding: latin-1 -*-
"""Module for fitting routines and representation of fit results.
@group fit routines: Fitting NoFit Gauss2d GaussSym2d GaussBose2d Bimodal2d Bimodal2dSplit BimodalGaussGauss2d BoseBimodal2d ThomasFermi2d
@sort: Fitting NoFit Gauss2d GaussSym2d GaussBose2d Bimodal2d Bimodal2dSplit BoseBimodal2d ThomasFermi2d
@group fit result objects: FitPars FitParsNoFit FitParsGauss2d FitParsBimodal2d FitParsBimodal2dSplit FitParsBimodalGaussGauss2d FitParsTF2d
@sort: FitPars FitParsNoFit FitParsGauss2d FitParsTF2d FitParsBimodal2d FitParsBimodal2dSplit FitParsBimodalGaussGauss2d
"""
# use_minpack = False
use_minpack = False
if use_minpack:
from scipy.optimize import leastsq
import numpy
import scipy.special
import LM
reload(LM)
import sys
from time import clock as time
imgtype = numpy.float32
def pickpeak(x, npicks=2, rdiff = 5):
"""
Search for peaks in data. Reurn arrays may contain NaN, e.g., if less peaks than required are found.
@param x: data sequence
@type x: ndarray
@param npicks: number of peaks to return.
@param rdiff: minimum spacing (in data points) between two peaks
@return: tuple of ndarray.
@rtype: (peak values, peak locations)
"""
#initialize result values with NaN
vals = numpy.array([numpy.NaN]*npicks)
loc = numpy.array([0]*npicks)
rmin = numpy.nanmin(x)-1
dx = numpy.diff(numpy.r_[rmin, x, rmin])
# find position and their values of peaks (local maxima)
pos_peaks, = numpy.nonzero((dx[0:-1]>=0.0) & (dx[1:]<=0.0))
val_peaks = x[pos_peaks] #corresponding
# select peaks in descending order, seperated by at least rdiff
for i in range(npicks):
mi = numpy.nanargmax(val_peaks) #find index of largest peak
peakval = val_peaks[mi]
peakpos = pos_peaks[mi]
vals[i] = peakval
loc[i] = peakpos
# for next iteration: only keep peaks at least rdiff points
# distance from last peak
ind = numpy.nonzero(abs(pos_peaks - peakpos) > rdiff)
if len(ind) == 0: #nothing left!
break
val_peaks = val_peaks[ind]
pos_peaks = pos_peaks[ind]
if numpy.isfinite(val_peaks).sum() == 0:
break
return vals, loc
class Fitting(object):
"""Base class for fitting. Provides common interface for handling
of imaging parameters.
@ivar imaging_pars: contains imaging parameters like, e.g.,
magnification, absorption coefficient.
@type imaging_pars: L{ImagingPars}"""
imaging_pars = None
verbose = False
rotation_angle = 0.0
rotation_active = False
def rotate_coord(self, x, y, mx, my):
if self.rotation_active:
a = numpy.cos(self.rotation_angle)
b = numpy.sin(self.rotation_angle)
return (x-mx)*a -(y-my)*b +mx, (x-mx)*b + a*(y-my) +my
else:
return x, y
def set_imaging_pars(self, ip):
self.imaging_pars = ip
def do_fit(self, img, roi):
"""perform fitting.
@param img:
@type img: 2d ndarray
@param roi: region of interest (ROI) if image, where to perform fitting.
@type roi: L{ROI}
@return: [fit image,...], fit background, FitPars
@rtype: [ndarray,...], ndarray, L{FitPars}
"""
pass
def fJ_masked(self, pars, x, y, v0=0, sel = None):
"""
ignore masked values in v0. somewhat specialized for 2d fitting functions
"""
f, J = self.fJ(pars, x, y, v0)
if sel is None:
sel = numpy.ma.getmaskarray(v0.ravel())
f[sel] = 0
J[:,sel] = 0
return f, J
class NoFit(Fitting):
"""Performs no fit."""
def __init__(self, imaging_pars=None):
self.imaging_pars = imaging_pars
def do_fit(self, img, roi):
background = numpy.array([0.0], dtype = imgtype)
return [], background, FitParsNoFit(), None
class Gauss1d(Fitting):
"""Perform fit of 2 separate 1d Gaussian to data averaged along orthogonal
direction.
@sort: do_fit, gauss1d, Dgauss1d, gauss2d, gauss2d_flat, Dgauss2d
"""
def __init__(self, imaging_pars=None):
"""Constructor.
@type imaging_pars: L{ImagingPars}
"""
self.imaging_pars = imaging_pars
self.cache = {}
def gauss1d(self, pars, x, v0 = 0):
"""calculate 1d gaussian.
@return: difference of 1d gaussian and reference (data) values
@param pars: parameters of gaussian. see source.
@param x: x values
@param v0: reference value
"""
A, m, s, offs = pars[0:4]
v = A*numpy.exp(- (x-m)**2 / (2*s**2)) + offs
return v-v0
def Dgauss1d(self, pars, x, v=0):
"""
calculated Jacobian matrix for 1d gauss
"""
A, m, s, offs = pars[0:4]
f = A*numpy.exp( - (x-m)**2 / (2*s**2))
J = numpy.empty(shape = (4,)+x.shape, dtype = imgtype)
J[0] = 1.0/A * f
J[1] = f*(x-m)/s**2
J[2] = f*(x-m)**2/s**3
J[3] = 1
return J
def fJgauss1d(self, pars, x, v = 0):
A, m, s, offs = pars[0:4]
f = A*numpy.exp( - (x-m)**2 / (2*s**2))
if 1:
J = numpy.empty(shape = (4,)+x.shape, dtype = imgtype)
J[0] = 1.0/A * f
J[1] = f*(x-m)/s**2
J[2] = f*(x-m)**2/s**3
J[3] = 1
return f + (offs - v), J
return f + (offs - v)
def gauss2d(self, pars, x, y, v0=0):
"""calculate 2d gaussian. uses caching strategy.
@rtype: 2d ndarray (MxN)
@param pars: see source
@param x: x values
@type x: ndarray (1xM row vector)
@param y: y values
@type y: ndarray (Nx1 column vector)
@param v0: reference value
@type v0: 2d ndarray (MxN) or scalar
"""
Ax, mx, sx, offsx, Ay, my, sy, offsy = pars[0:8]
key = (Ax, Ay, mx, my, sx, sy)
if self.cache.has_key(key):
v = self.cache[key]
else:
v = (Ax+Ay)*numpy.exp( - (x-mx)**2 / (2*sx**2)
- (y-my)**2 / (2*sy**2))
self.cache.clear()
#caching in effect only for calculating of Jacobi, clear
#cache after result has been retrieved to avoid excessive
#memory use
self.cache[key] = v
return v + (offsx + offsy - v0)
def _find_startpar_gauss(self, x, prof):
"""
find good initial estimates for fit parameters based on
horizontal or vertical profiles
@param x: x or y values
@param prof: horizontal of vertical profiles
@return: [A, mu, sigma, offset]
"""
Nsh = 20 # number (half) of points for smoothing
gs = Nsh/2 # width gaussian
#use gaussian for smoothing
gx = numpy.arange(2*Nsh+1, dtype = imgtype) - Nsh
gy = numpy.exp(-gx**2/gs**2)
gy/= gy.sum()
#smooth profil, limit axes to valid values
profsmooth = numpy.convolve(prof, gy, mode = 'valid')
xs = x[Nsh:-Nsh]
#estimate peak position and fwhm width
peakval, peakpos = pickpeak(profsmooth, 1)
try:
halfval, halfpos = pickpeak(
-numpy.abs(profsmooth - (peakval + numpy.nanmin(profsmooth))/2.0),
npicks = 2)
width = numpy.abs(numpy.diff(xs[halfpos]))
except:
print "Warning: can't determine initial guess for width", sys.exc_info()
width = 20
off = numpy.nanmin(profsmooth) #TODO: can we do better (robust?)
try:
m = xs[peakpos]
except IndexError:
m = 0.5*(x[0] + x[-1])
s = width
A = peakval - off
#make gaussian fit
startpars = numpy.r_[A, m, s, off]
if use_minpack:
fitpar, foo = leastsq(self.gauss1d,
startpars,
args = (x, prof),
Dfun = self.Dgauss1d, col_deriv = 1,
maxfev = 30,
ftol = 1e-4
)
else:
fitpar = LM.LM(self.fJgauss1d,
startpars,
args = (x, prof),
kmax = 30,
eps1 = 1e-6,
eps2 = 1e-6,
verbose = self.verbose,
)
return fitpar
def do_fit(self, img, roi):
x = numpy.asarray(roi.xrange_clipped(img), dtype = imgtype)
y = numpy.asarray(roi.yrange_clipped(img), dtype = imgtype)
imgroi = img[roi.y, roi.x]
try:
imgroifilled = imgroi.filled()
except AttributeError:
imgroifilled = imgroi
xprof = imgroifilled.sum(0)/roi.numline
yprof = imgroifilled.sum(1)/roi.numcol
try:
startparx = self._find_startpar_gauss(x,xprof)
startpary = self._find_startpar_gauss(y,yprof)
except Exception:
startparx = numpy.array([1, 100, 10, 0, 1, 100, 10, 0])
startpary = numpy.array([1, 100, 10, 0, 1, 100, 10, 0])
print "Warning: can't determine initial guess for fitting parameters"
fitpar = numpy.array([ startparx[0], #A_x
startparx[1], #m_x
startparx[2], #sigma_x
startparx[3], #offset_x
startpary[0], #A_y
startpary[1], #m_y
startpary[2], #sigma_y
startpary[3] #offset_y
])
x.shape = (1,-1)
y.shape = (-1, 1)
mask = numpy.array([1.,1.,1.,1.,0.,0.,1.,0.])
imgfitx = self.gauss2d(fitpar*mask, x, y*0.)
mask = numpy.array([0.,0.,1.,0.,1.,1.,1.,1.])
imgfity = self.gauss2d(fitpar*mask, x*0., y)
fitpars = FitParsGauss1d(fitpar, self.imaging_pars, roi)
#validity check
Ax, mx, sx, offsx, Ay, my, sy, offsy = fitpar[0:8]
sx, sy = abs(sx), abs(sy)
if mx < roi.xmin - 100 or mx > roi.xmax + 100:
fitpars.invalidate()
if my < roi.ymin - 100 or my > roi.ymax + 100:
fitpars.invalidate()
if sx > 3*abs(roi.xmax - roi.xmin) or \
sy > 3*abs(roi.ymax - roi.ymin):
fitpars.invalidate()
background = numpy.array([fitpars.offsetx], dtype = imgtype)
return [imgfitx, imgfity], background, fitpars, None
class LorentzGauss1d(Gauss1d):
"""Perform fit of 2 separate 1d Gaussian to data averaged along orthogonal
direction.
@sort: do_fit, gauss1d, Dgauss1d, gauss2d, gauss2d_flat, Dgauss2d
"""
def __init__(self, imaging_pars = None):
super(LorentzGauss1d, self).__init__(imaging_pars)
self.MyFitPars = FitParsLorentzGauss1d
def lorentzgauss2d(self, pars, x, y, v0=0):
"""calculate 2d gaussian. uses caching strategy.
@rtype: 2d ndarray (MxN)
@param pars: see source
@param x: x values
@type x: ndarray (1xM row vector)
@param y: y values
@type y: ndarray (Nx1 column vector)
@param v0: reference value
@type v0: 2d ndarray (MxN) or scalar
"""
Ax, mx, sx, offsx, Ay, my, sy, offsy = pars[0:8]
key = (Ax, Ay, mx, my, sx, sy)
if self.cache.has_key(key):
v = self.cache[key]
else:
#here either Ax or Ay is zero
v = (Ax+Ay)/( 1+ (x-mx)**2 / sx**2 )* \
numpy.exp(- (y-my)**2 / (2*sy**2))
self.cache.clear()
#caching in effect only for calculating of Jacobi, clear
#cache after result has been retrieved to avoid excessive
#memory use
self.cache[key] = v
return v + (offsx + offsy - v0)
def lorentz1d(self, pars, x, v0 = 0):
"""calculate 1d gaussian.
@return: difference of 1d gaussian and reference (data) values
@param pars: parameters of gaussian. see source.
@param x: x values
@param v0: reference value
"""
A, m, s, offs = pars[0:4]
v = A/(1 + (x-m)**2 / s**2) + offs
return v-v0
def Dlorentz1d(self, pars, x, v=0):
"""
calculated Jacobian matrix for 1d gauss
"""
A, m, s, offs = pars[0:4]
f = 1.0*A/(1 + (x-m)**2 / s**2)
J = numpy.empty(shape = (4,)+x.shape, dtype = imgtype)
J[0] = 1.0/A * f
J[1] = f*f*2*(x-m)/s**2
J[2] = f*f*2*(x-m)**2/s**3
J[3] = 1
return J
def fJlorentz1d(self, pars, x, v = 0):
A, m, s, offs = pars[0:4]
f = A*1.0/(1+(x-m)**2 / s**2)
if 1:
J = numpy.empty(shape = (4,)+x.shape, dtype = imgtype)
J[0] = 1.0/A * f
J[1] = f*f*2*(x-m)/s**2
J[2] = f*f*2*(x-m)**2/s**3
J[3] = 1
return f + (offs - v), J
return f + (offs - v)
def _find_startpar_lorentz(self, x, prof):
"""
find good initial estimates for fit parameters based on
horizontal or vertical profiles
@param x: x or y values
@param prof: horizontal of vertical profiles
@return: [A, mu, sigma, offset]
"""
Nsh = 10 # number (half) of points for smoothing
gs = Nsh/2 # width gaussian
#use gaussian for smoothing
gx = numpy.arange(2*Nsh+1, dtype = imgtype) - Nsh
gy = numpy.exp(-gx**2/gs**2)
gy/= gy.sum()
#smooth profil, limit axes to valid values
profsmooth = numpy.convolve(prof, gy, mode = 'valid')
xs = x[Nsh:-Nsh]
#estimate peak position and fwhm width
peakval, peakpos = pickpeak(profsmooth, 1)
try:
halfval, halfpos = pickpeak(
-numpy.abs(profsmooth - (peakval + numpy.nanmin(profsmooth))/2.0),
npicks = 2)
width = numpy.abs(numpy.diff(xs[halfpos]))
except:
print "Warning: can't determine initial guess for width", sys.exc_info()
width = 20
off = numpy.nanmin(profsmooth) #TODO: can we do better (robust?)
try:
m = xs[peakpos]
except IndexError:
m = 0.5*(x[0] + x[-1])
s = width
A = peakval - off
#make lorentzian fit
startpars = numpy.r_[A, m, s, off]
fitpar = LM.LM(self.fJlorentz1d,
startpars,
args = (x, prof),
kmax = 30,
eps1 = 1e-6,
eps2 = 1e-6,
verbose = self.verbose,
)
return fitpar
def do_fit(self,img, roi):
x = numpy.asarray(roi.xrange_clipped(img), dtype = imgtype)
y = numpy.asarray(roi.yrange_clipped(img), dtype = imgtype)
imgroi = img[roi.y, roi.x]
try:
imgroifilled = imgroi.filled()
except AttributeError:
imgroifilled = imgroi
xprof = imgroifilled.sum(0)/roi.numline
yprof = imgroifilled.sum(1)/roi.numcol
try:
startparx = self._find_startpar_lorentz(x,xprof)
startpary = self._find_startpar_gauss(y,yprof)
except Exception:
startparx = numpy.array([1, 100, 10, 0, 1, 100, 10, 0])
startpary = numpy.array([1, 100, 10, 0, 1, 100, 10, 0])
print "Warning: can't determine initial guess for fitting parameters"
fitpar = numpy.array([ startparx[0], #A_x
startparx[1], #m_x
startparx[2], #sigma_x
startparx[3], #offset_x
startpary[0], #A_y
startpary[1], #m_y
startpary[2], #sigma_y
startpary[3] #offset_y
])
x.shape = (1,-1)
y.shape = (-1, 1)
mask = numpy.array([1.,1.,1.,1.,0.,0.,1.,0.])
imgfitx = self.lorentzgauss2d(fitpar*mask, x, y*0.)
mask = numpy.array([0.,0.,1.,0.,1.,1.,1.,1.])
imgfity = self.lorentzgauss2d(fitpar*mask, x*0., y)
fitpars = self.MyFitPars(fitpar, self.imaging_pars, roi)
#validity check
Ax, mx, sx, offsx, Ay, my, sy, offsy = fitpar[0:8]
sx, sy = abs(sx), abs(sy)
if mx < roi.xmin - 100 or mx > roi.xmax + 100:
fitpars.invalidate()
if my < roi.ymin - 100 or my > roi.ymax + 100:
fitpars.invalidate()
if sx > 3*abs(roi.xmax - roi.xmin) or \
sy > 3*abs(roi.ymax - roi.ymin):
fitpars.invalidate()
background = numpy.array([fitpars.offsetx], dtype = imgtype)
return [imgfitx, imgfity], background, fitpars, None
###########################
class GaussGauss1d(Gauss1d):
"""Perform fit of 2 separate 1d Gaussian to data averaged along orthogonal
direction.
@sort: do_fit, gauss1d, Dgauss1d, gauss2d, gauss2d_flat, Dgauss2d
"""
def __init__(self, imaging_pars = None, center_pos = None):
super(GaussGauss1d, self).__init__(imaging_pars)
self.MyFitPars = FitParsGaussGauss1d
self.center_pos = center_pos
def gaussgauss2d(self, pars, x, y, v0=0):
"""calculate 2d gaussian. uses caching strategy.
@rtype: 2d ndarray (MxN)
@param pars: see source
@param x: x values
@type x: ndarray (1xM row vector)
@param y: y values
@type y: ndarray (Nx1 column vector)
@param v0: reference value
@type v0: 2d ndarray (MxN) or scalar
"""
Ax, mx, sx, offsx, Ay, my, sy, offsy, A1x, m1x, s1x = pars[0:11]
key = (Ax, Ay, mx, my, sx, sy, A1x, m1x, s1x)
if self.cache.has_key(key):
v = self.cache[key]
else:
#here either Ax=A1x=0 or Ay=0
v = Ax*numpy.exp(-(x-mx)**2 /(2*sx**2))+\
A1x*numpy.exp(-(x-m1x)**2 /(2*s1x**2))+\
Ay*numpy.exp(-(y-my)**2 / (2*sy**2))
self.cache.clear()
#caching in effect only for calculating of Jacobi, clear
#cache after result has been retrieved to avoid excessive
#memory use
self.cache[key] = v
return v + (offsx + offsy - v0)
def gaussgauss1d(self, pars, x, v0 = 0):
"""calculate 1d gaussian.
@return: difference of 1d gaussian and reference (data) values
@param pars: parameters of gaussian. see source.
@param x: x values
@param v0: reference value
"""
A, m, s, offs, A1, m1, s1 = pars[0:7]
v = A*numpy.exp(-(x-m)**2 /(2*s**2))+\
A1*numpy.exp(-(x-m1)**2 /(2*s1**2))+ offs
return v-v0
def Dgaussgauss1d(self, pars, x, v=0):
"""
calculated Jacobian matrix for 1d gauss
"""
A, m, s, offs, A1, m1, s1 = pars[0:7]
f = 1.0*A*numpy.exp(-(x-m)**2 / (2*s**2))
f1 = 1.0*A1*numpy.exp(-(x-m1)**2 / (2*s1**2))
J = numpy.empty(shape = (7,)+x.shape, dtype = imgtype)
J[0] = 1.0/A * f
J[1] = f*(x-m)/s**2
J[2] = f*(x-m)**2/s**3
J[3] = 1
J[4] = 1.0/A1 * f1
J[5] = f1*(x-m1)/s1**2
J[6] = f1*(x-m1)**2/s1**3
return J
def fJgaussgauss1d(self, pars, x, v = 0):
A, m, s, offs, A1, m1, s1 = pars[0:7]
f = 1.0*A*numpy.exp(-(x-m)**2 / (2*s**2))
f1 = 1.0*A1*numpy.exp(-(x-m1)**2 / (2*s1**2))
if 1:
J = numpy.empty(shape = (7,)+x.shape, dtype = imgtype)
J[0] = 1.0/A * f
J[1] = f*(x-m)/s**2
J[2] = f*(x-m)**2/s**3
J[3] = 1
J[4] = 1.0/A1 * f1
J[5] = f1*(x-m1)/s1**2
J[6] = f1*(x-m1)**2/s1**3
return f + f1 + (offs - v), J
return f + f1 + (offs - v)
def _find_startpar_gaussgauss(self, x, prof):
"""
find good initial estimates for fit parameters based on
horizontal or vertical profiles
@param x: x or y values
@param prof: horizontal of vertical profiles
@return: [A, mu, sigma, offset]
"""
Nsh = 20 # number (half) of points for smoothing
gs = Nsh/2 # width gaussian
#use gaussian for smoothing
gx = numpy.arange(2*Nsh+1, dtype = imgtype) - Nsh
gy = numpy.exp(-gx**2/gs**2)
gy/= gy.sum()
#smooth profil, limit axes to valid values
profsmooth = numpy.convolve(prof, gy, mode = 'valid')
xs = x[Nsh:-Nsh]
#estimate peak position and fwhm width
peakval, peakpos = pickpeak(profsmooth, 1)
try:
halfval, halfpos = pickpeak(
-numpy.abs(profsmooth - (peakval + numpy.nanmin(profsmooth))/2.0),
npicks = 2)
width = numpy.abs(numpy.diff(xs[halfpos]))
# print 'halfval/pos', halfval, halfpos, width
except:
print "Warning: can't determine initial guess for width", sys.exc_info()
width = 20
off = numpy.nanmin(profsmooth) #TODO: can we do better (robust?)
try:
m = xs[peakpos]
except IndexError:
m = 0.5*(x[0] + x[-1])
if self.center_pos:
m = self.center_pos[0]
m1 = self.center_pos[2]
else:
m1 = m
s = min(width, abs(m1-m))
A = peakval - off
#make gaussian fit
startpars = numpy.r_[A, m, s, off, A*.5, m1, s]
fitpar = LM.LM(self.fJgaussgauss1d,
startpars,
args = (x, prof),
kmax = 30,
eps1 = 1e-6,
eps2 = 1e-6,
verbose = self.verbose,
)
return fitpar
def do_fit(self,img, roi):
x = numpy.asarray(roi.xrange_clipped(img), dtype = imgtype)
y = numpy.asarray(roi.yrange_clipped(img), dtype = imgtype)
imgroi = img[roi.y, roi.x]
try:
imgroifilled = imgroi.filled()
except AttributeError:
imgroifilled = imgroi
xprof = imgroifilled.sum(0)/roi.numline
yprof = imgroifilled.sum(1)/roi.numcol
startparx = self._find_startpar_gaussgauss(x,xprof)
startpary = self._find_startpar_gauss(y,yprof)
[Ax, mx, sx, ox, A1x, m1x, s1x] = startparx[0:7]
[Ay, my, sy, oy] = startpary[0:4]
#A = Ay/(numpy.sqrt(2*numpy.pi)*sx)
fitpar = numpy.array([ startparx[0], #A_x
startparx[1], #m_x
startparx[2], #s_x
startparx[3], #offset_x
startpary[0], #A_y
startpary[1], #m_y
startpary[2], #s_y
startpary[3], #offset_y
startparx[4], #A1x,
startparx[5], #m1x,
startparx[6], #s1x,
])
x.shape = (1,-1)
y.shape = (-1, 1)
mask = numpy.array([1.,1.,1.,1.,0.,0.,1.,0.,1.,1.,1.])
imgfitx = self.gaussgauss2d(fitpar*mask, x, y*0.)
mask = numpy.array([0.,0.,1.,0.,1.,1.,1.,1.,0.,0.,1.])
imgfity = self.gaussgauss2d(fitpar*mask, x*0., y)
fitpars = self.MyFitPars(fitpar, self.imaging_pars, roi)
#validity check
# Ax, mx, sx, offsx, A1x, m1x, s1x, Ay, my, sy, offsy = fitpar[0:11]
# sx, sy = abs(sx), abs(sy)
# if mx < roi.xmin - 100 or mx > roi.xmax + 100:
# fitpars.invalidate()
# if m1x < roi.xmin - 100 or m1x > roi.xmax + 100:
# fitpars.invalidate()
# if my < roi.ymin - 100 or my > roi.ymax + 100:
# fitpars.invalidate()
# if sx > 3*abs(roi.xmax - roi.xmin) or \
# s1x > 3*abs(roi.xmax - roi.xmin): or \
# sy > 3*abs(roi.ymax - roi.ymin):
# fitpars.invalidate()
background = numpy.array([fitpars.offsetx], dtype = imgtype)
return [imgfitx, imgfity], background, fitpars, None
class Gauss2d(Gauss1d):
"""Perform fit of 2d Gaussian to data.
@sort: do_fit, gauss1d, Dgauss1d, gauss2d, gauss2d_flat, Dgauss2d
"""
def __init__(self, imaging_pars = None):
super(Gauss2d, self).__init__(imaging_pars)
self.MyFitPars = FitParsGauss2d
def gauss2d(self, pars, x, y, v0=0):
"""calculate 2d gaussian. uses caching strategy.
@rtype: 2d ndarray (MxN)
@param pars: see source
@param x: x values
@type x: ndarray (1xM row vector)
@param y: y values
@type y: ndarray (Nx1 column vector)
@param v0: reference value
@type v0: 2d ndarray (MxN) or scalar
"""
A, mx, my, sx, sy, offs = pars[0:6]
key = (A, mx, my, sx, sy)
if self.cache.has_key(key):
v = self.cache[key]
else:
v = A*numpy.exp( - (x-mx)**2 / (2*sx**2)
- (y-my)**2 / (2*sy**2))
self.cache.clear()
#caching in effect only for calculating of Jacobi, clear
#cache after result has been retrieved to avoid excessive
#memory use
self.cache[key] = v
return v + (offs - v0)
def gauss2d_flat(self, pars, x, y, v0=0):
"""return flattened result of L{gauss2d}"""
return self.gauss2d(pars, x, y, v0).reshape((-1,))
def Dgauss2d(self, pars, x, y, v=0):
"""calculate Jacobian for 2d gaussian.
@rtype: 2d ndarray (see source)
"""
A, mx, my, sx, sy, offs = pars[0:6]
f = self.gauss2d([A, mx, my, sx, sy, 0], x, y)
J = numpy.empty(shape = (6,) + f.shape, dtype = imgtype)
J[0] = 1.0/A * f
J[1] = f*(x-mx)/sx**2
J[2] = f*(y-my)/sy**2
J[3] = f*(x-mx)**2/sx**3
J[4] = f*(y-my)**2/sy**3
J[5] = 1
return J.reshape((6,-1))
def fJ(self, pars, x, y, v0=0):
A, mx, my, sx, sy, offs = pars[0:6]
f = A*numpy.exp( - (x-mx)**2 / (2*sx**2)
- (y-my)**2 / (2*sy**2))
J = numpy.empty(shape = (6,) + f.shape, dtype = imgtype)
J[0] = 1.0/A * f
J[1] = f*(x-mx)/sx**2
J[2] = f*(y-my)/sy**2
J[3] = f*(x-mx)**2/sx**3
J[4] = f*(y-my)**2/sy**3
J[5] = 1
f += offs
f -= v0
f.shape = (-1,)
J.shape = (6,-1)
return f, J
def do_fit(self,img, roi, tot_fit=False):
x = numpy.asarray(roi.xrange_clipped(img), dtype = imgtype)
y = numpy.asarray(roi.yrange_clipped(img), dtype = imgtype)
imgroi = img[roi.y, roi.x]
try:
imgroifilled = imgroi.filled()
except AttributeError:
imgroifilled = imgroi
xprof = imgroifilled.sum(0)
yprof = imgroifilled.sum(1)
try:
startparx = self._find_startpar_gauss(x,xprof)
startpary = self._find_startpar_gauss(y,yprof)
except Exception:
startparx = numpy.array([1, 100, 100, 10, 10, 0])
startpary = numpy.array([1, 100, 100, 10, 10, 0])
print "Warning: can't determine initial guess for fitting parameters"
startpar = numpy.array([startparx[0]/(startpary[2]*numpy.sqrt(2*numpy.pi)),
startparx[1], #m_x
startpary[1], #m_y
startparx[2], #sigma_x
startpary[2], #sigma_y
0 #offset
])
x.shape = (1,-1)
y.shape = (-1, 1)
if use_minpack:
fitpar, cov_x, infodict, mesg, ier = \
leastsq(self.gauss2d_flat,
startpar,
args=(x,y, imgroi),
Dfun = self.Dgauss2d, col_deriv=1,
maxfev = 50,
ftol = 1e-6,
full_output=1,
)
else:
imgsel = numpy.ma.getmaskarray(imgroi.ravel())
fitpar, J, r = LM.LM(self.fJ_masked,
startpar,
args = (x, y, imgroi, imgsel),
kmax = 30,
eps1 = 1e-6,
eps2 = 1e-6,
verbose = self.verbose,
full_output = True,
)
fitparerr, sigma = LM.fitparerror(fitpar, J, r)
imgfit_tot=None
if tot_fit:
x_tot=numpy.asarray(range( 0, img.shape[1]), dtype = imgtype)
y_tot=numpy.asarray(range( 0, img.shape[0]), dtype = imgtype)
x_tot.shape = (1,-1)
y_tot.shape = (-1, 1)
self.cache.clear()
imgfit_tot = self.gauss2d(fitpar, x_tot , y_tot)
self.cache.clear()
imgfit = self.gauss2d(fitpar, x, y)
fitpars = FitParsGauss2d(fitpar, self.imaging_pars, fitparerr, sigma)
#validity check
A, mx, my, sx, sy, offs = fitpar[0:6]
A, sx, sy = abs(A), abs(sx), abs(sy)
if A<0:
fitpars.invalidate()
if mx < roi.xmin - 100 or mx > roi.xmax + 100:
fitpars.invalidate()
if my < roi.ymin - 100 or my > roi.ymax + 100:
fitpars.invalidate()
if sx > 3*abs(roi.xmax - roi.xmin) or \
sy > 3*abs(roi.ymax - roi.ymin):
fitpars.invalidate()
background = numpy.array([fitpars.offset], dtype = imgtype)
return [imgfit,], background, fitpars, imgfit_tot
class GaussSym2d(Fitting):
"""Perform fit of 2d symmetric Gaussian to data.
@sort: do_fit, fJgauss1d, gauss2d, gauss2d_flat, fJgauss2d
"""
def __init__(self, imaging_pars=None):
"""Constructor.
@type imaging_pars: L{ImagingPars}
"""
self.imaging_pars = imaging_pars
self.cache = {}
def fJgauss1d(self, pars, x, v = 0):
A, m, s, offs = pars[0:4]
f = A*numpy.exp( - (x-m)**2 / (2*s**2))
if 1:
J = numpy.empty(shape = (4,)+x.shape, dtype = imgtype)
J[0] = 1.0/A * f
J[1] = f*(x-m)/s**2
J[2] = f*(x-m)**2/s**3
J[3] = 1
return f + (offs - v), J
return f + (offs - v)
def gauss2d(self, pars, x, y, v0=0):
"""calculate 2d gaussian. uses caching strategy.
@rtype: 2d ndarray (MxN)
@param pars: see source
@param x: x values
@type x: ndarray (1xM row vector)
@param y: y values
@type y: ndarray (Nx1 column vector)
@param v0: reference value
@type v0: 2d ndarray (MxN) or scalar
"""
A, mx, my, s, offs = pars[0:5]
key = (A, mx, my, s)
if self.cache.has_key(key):
v = self.cache[key]
else:
v = A*numpy.exp( - (x-mx)**2 / (2*s**2)
- (y-my)**2 / (2*s**2))
self.cache.clear()
#caching in effect only for calculating of Jacobi, clear
#cache after result has been retrieved to avoid excessive
#memory use
self.cache[key] = v
return v + (offs - v0)
def gauss2d_flat(self, pars, x, y, v0=0):
"""return flattened result of L{gauss2d}"""
return self.gauss2d(pars, x, y, v0).reshape((-1,))
def fJ(self, pars, x, y, v0=0):
A, mx, my, s, offs = pars[0:5]
f = A*numpy.exp( - (x-mx)**2 / (2*s**2)
- (y-my)**2 / (2*s**2))
J = numpy.empty(shape = (5,) + f.shape, dtype = imgtype)
J[0] = 1.0/A * f
J[1] = f*(x-mx)/s**2
J[2] = f*(y-my)/s**2
J[3] = f*( (x-mx)**2/s**3 + (y-my)**2/s**3) #TODO: nachrechnen
J[4] = 1
f += offs
f -= v0
f.shape = (-1,)
J.shape = (5,-1)
return f, J
def _find_startpar_gauss(self, x, prof):
"""
find good initial estimates for fit parameters based on
horizontal or vertical profiles
@param x: x or y values
@param prof: horizontal of vertical profiles
@return: [A, mu, sigma, offset]
"""
Nsh = 20 # number (half) of points for smoothing
gs = Nsh/2 # width gaussian
#use gaussian for smoothing
gx = numpy.arange(2*Nsh+1, dtype = imgtype) - Nsh
gy = numpy.exp(-gx**2/gs**2)
gy/= gy.sum()
#smooth profil, limit axes to valid values
profsmooth = numpy.convolve(prof, gy, mode = 'valid')
xs = x[Nsh:-Nsh]
#TODO: ensure enough points (>3?)
#estimate peak position and fwhm width
peakval, peakpos = pickpeak(profsmooth, 1)