-
Notifications
You must be signed in to change notification settings - Fork 0
/
calcStats.py
4430 lines (4185 loc) · 149 KB
/
calcStats.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
import itertools
import re
import mathPlus
import optPlus
import arrayPlus
import genUtil
import vorpalUtil
import numpy
import numpy.linalg
import scipy
import scipy.optimize
import scipy.special
import scipy.interpolate
import scipy.integrate
import string
#import disthistMac
# for debugging
#import warnings
c=2.99792458e8
mu0=4e-7*numpy.pi
suppressOutput = False
# default max function evaluations for curve fitting optimization
defMaxFev = 50000
defFontSize = 22
def setFontSize():
import matplotlib
matplotlib.rcParams.update({'font.size': defFontSize,
'axes.labelsize':defFontSize+2})
return
def getEnergyDisFrac(sigma, Ly, rho0): #{
""" for square sims"""
if sigma >= 9.9:
res = 60.8 - 897./(0.5*Ly/rho0 * 16./sigma)
elif abs(sigma-3.) < 0.1:
res = 60.8 - 160./(0.5*Ly/rho0 * 16./sigma)**0.5
else:
msg = "cannot handle sigma = %g" % sigma
raise ValueError, msg
return res/100.
#}
def subtractMaxwell(gEdges, dNdg, thb, m = None): #{
"""
Fits a maxwellian to the low-energy part of dNdg vs g
where g is gamma.
maxwellian(g) = A g sqrt{g^2-1} exp(-(g-1)/thb)
gEdges = array of length N+1
dNdg = array of length N, where dNdg[i] contains the number of
particles with gamma between gEdges[i] and gEdges[i+1]
thb = the initial (or expected) temperature of particles
m = integer method of fitting the maxwellian
0: assumes maxwellian of temperature thb, and simply sets A
to fit dNdg[0]
1: don't use this
2: From the temperature thb,
computes an average gamma for the associated Maxwellian;
Finds maximum value of dNdg up to the average gamma, and
fits a Maxwellian (for A and new temp thb) to dNdg up to
the gamma where that max of dNdg occurs.
3: Iterates 2 until thb converges.
returns (dNdgSub, A, thb, fail)
dNdgMaxwell = the fitted Maxwellian (same shape as dNdg)
A = fitted value of A (see maxwellian(g))
thb = fitted value of thb (see maxwellian(g))
fracInMax = the fraction of particles in the low-energy maxwellian
energyFracInMax = the fraction of (kinetic) energy in the low-energy maxwellian
e.g., not gamma but (gamma-1)
gMinInd: gEdge[gMinInd] is the smallest gamma for which
dNdgSub should be trusted, due to negative values in dNdgSub
fail = 0 if success; if m=2 or 3 and there's an error (e.g., failure
to converge), then returns value for m=0 with fail=1.
N.B. to subtract the maxwellian, I recommend taking
abs(dNdg - dNdgMaxwell) to avoid negative numbers.
"""
dg = gEdges[1:] - gEdges[:-1]
g = 0.5 * (gEdges[1:] + gEdges[:-1])
fail = 0
def maxwell(g, A, th): #{
#print "maxwell called with A, th =", repr(A), repr(th)
res = A * g * numpy.sqrt((g+1.)*(g-1.))*numpy.exp(-(g-1.)/abs(th))
return res
#}
def intMaxwell(ge, A, th): #{
""" integrated maxwell: ge = edges
"""
#print "intMaxwell called with A, th =", repr(A), repr(th)
res = 0.*ge[1:]
for i in range(ge.size-1):
res[i] = scipy.integrate.quad(maxwell, ge[i], ge[i+1], args=(A,th))[0]
res[i] /= ge[i+1]-ge[i]
return res
#}
if m is None:
if (dNdg > 0.).sum() <= 2:
m = 0
else:
m = 3
if m == 0: #}{
A = dNdg[0]/maxwell(g[0], 1., thb)
elif m == 1: #}{
gAvg = (g * dNdg * dg).sum() / (dNdg * dg).sum()
thb = gAvg/3.
A = dNdg[0]/maxwell(g[0], 1., thb)
elif m == 2 or m == 3: #}{
thbOld = thb
def maxwell2(g, A, th): #{
return numpy.log10(A * g * numpy.sqrt(g**2-1.)*numpy.exp(-g/th))
#}
thbs = [thb]
# not clear if scaleFactors do any good (or if I'm using them correctly)
# N.B. do not let these get negative
scaleFactors = None #[numpy.log(dNdg[0]/maxwell(g[0],1.,thb)), thb]
converged = False
iteration = 0
try: #{
while not converged: #{
# can't evaluate k1 for very small thb
# gb = scipy.special.k1(1./thb)/scipy.special.kn(2,1./thb)+3*thb
gb = 1. + disthistMac.avgMaxwellianGammaM1(thb)
if g[1] > gb:
ptslgb = 4
elif gb >= g[-10]:
ptslgb = g.size - 10
else:
ptslgb = numpy.where(g>=gb)[0][0] + 4
igmax = numpy.argmax(dNdg[:ptslgb])
pts = max(7, igmax)
#print iteration, gb, ptslgb, pts, g[ptslgb], g[igmax]
#pts = numpy.where(g>=gb)[0][0] + 3
#print pts
if 0: #{
import pylab
pylab.semilogx(g, dNdg)
pylab.semilogx(g[:pts], dNdg[:pts], 'o', mfc='none')
pylab.show()
import sys
sys.exit()
#}
#logdNdg = numpy.log10(dNdg[:pts])
A0 = dNdg[0] / maxwell(g[0], 1., thb)
thb0 = max(g[0]-1, thb)
if 0: #{
import pylab
pylab.loglog(g, intMaxwell(gEdges,A0, thb))
pylab.loglog(g, dNdg, 'o', mfc='none')
pylab.loglog(g[igmax], dNdg[igmax], 'x')
pylab.show()
#}
#print A0, thb0, scaleFactors
#print "Starting opt"
#(popt,pcov) = scipy.optimize.curve_fit(
# maxwell, g[:pts], dNdg[:pts], p0=(A0,thb0), maxfev=60000,
# diag = scaleFactors)
#print "About to fit for maxwellian starting at A0, thb0", A0, thb0
#print " using", pts, "points"
(popt,pcov) = scipy.optimize.curve_fit(
intMaxwell, gEdges[:pts+1], dNdg[:pts], p0=(A0,thb0), maxfev=60000,
diag = scaleFactors)
#(popt,pcov) = scipy.optimize.curve_fit(
# maxwell2, g[:pts], logdNdg, p0=(dNdg[0],1.))
A = popt[0]
thbLast = thb
thb = abs(popt[1])
#print "iteration, A, thb, dif", iteration, A, thb, thb-thbLast
thbs.append(thb)
fit = maxwell(g[:pts], A, thb)
if m == 2 or abs(1.-thb/thbs[-2]) < 0.01:
converged = True
iteration += 1
if iteration > 1000:
raise ValueError, "iteration for maxwellian fit exceeded " + str(iteration-1)
#}
except: #}{
raise
fail = 1
#raise
#return subtractMaxwell(gEdges, dNdg, thbOld, m=0)
#print g[0], dNdg[0], thbOld, maxwell(g[0],1.,thbOld)
A = dNdg[0]/maxwell(g[0], 1., thbOld)
#print A
#}
#print thbs, gb, pts
else: #}{
raise ValueError, "m = %i is invalid" % m
#}
# calculate maxwellian with thb
#print "final", A, thb
dNdgMax = maxwell(g, A, thb)
dNdgSub = dNdg - dNdgMax
if 0:
import pylab
pylab.semilogx(g, dNdgSub)
pylab.show()
# find small g such that dNdgMax < dNdg for all larger g
z = numpy.logical_and(dNdgSub <= 0, dNdg != 0)
if z.any():
gMinInd = numpy.where(z)[0][-1]+1
if gMinInd >= z.size:
gMinInd = z.size-1
else:
gMinInd = 0
# Don't return gMinInd if dNdg[gMinInd] = 0
while (gMinInd > 0) and dNdg[gMinInd] == 0.:
gMinInd -= 1
# calculate fraction of particles in low-energy maxwellian
if 1: #{
dg = gEdges[1:] - gEdges[:-1]
dN = dNdg * dg
dNMax = dNdgMax * dg
maxTooMuch = (dNMax > dN)
dNMax[maxTooMuch] = dN[maxTooMuch]
dNsum = dN.sum()
if dNsum == 0.:
fracInMax = 0.
else:
fracInMax = dNMax.sum() / dN.sum()
energyFracInMax = (dNMax * (g-1.)).sum() / (dN * (g-1.)).sum()
#}
# and subtract
if 1: #{
dNdgSub = abs(dNdgSub)
else: #}{
maxRed = 1e-4
overRed = (dNdgSub < 0)
dNdgSub[overRed] = 0.01*maxRed*dNdg[overRed]
overRed = numpy.logical_and(dNdgSub < maxRed*dNdg, numpy.logical_not(overRed))
dNdgSub[overRed] = maxRed * dNdg[overRed]
#}
#print "Using", pts, "points"
#import os
#print os.getcwd()
return (dNdgMax, A, thb, fracInMax, energyFracInMax, gMinInd, fail)
#}
def saturationPoint(ra, fracOfSaturation, logScale = False): #{
"""
supposes that ra represents an increasing sequence; ideally, but not
actually monotonic.
returns (i1, i2) where i1 is the smallest index where ra first goes above
the maximum value times fracOfSaturation, and i2 is the highest index where
ra is below that.
"""
iMin = numpy.argmin(ra)
raMin = ra[iMin]
iMax = iMin + numpy.argmax(ra[iMin:])
raMax = ra[iMax]
def growth(x, A, a, x0): #{
res = A*(1.-numpy.exp(-a*(x-x0)))
return res
#}
xs = numpy.arange(len(ra))
A0 = raMax
a0 = 10./xs[-1]
x00 = 0.
(popt, pcov) = scipy.optimize.curve_fit(growth, xs[iMin:], ra[iMin:], p0 = (A0, a0, x00))
(A, a, x0) = popt
nra = growth(xs, *popt)
nraMax = min(A, raMax)
if logScale:
threshold = numpy.exp(
numpy.log(raMin)
+ fracOfSaturation*(numpy.log(nraMax) - numpy.log(raMin)))
else:
threshold = raMin + fracOfSaturation*(nraMax - raMin)
graph = False
try:
i1 = iMin + numpy.where(nra[iMin:] >= threshold)[0][0]
i2 = iMin + numpy.where(nra[iMin:] <= threshold)[0][-1]
except:
import sys
i1 = 0
i2 = 1
msg = os.getcwd() + ": Failed to find g2 saturation point\n"
sys.stderr.write(msg)
raise
#"iMin, iMax = ", iMin, iMax
#print "nra.size = ", nra.size
#print "Finding i1, i2 failed: setting to 0 and 1"
#graph = True
if graph: #{
import pylab
print "ra: %g -> %g" % (raMin, raMax)
print " frac: %g" % fracOfSaturation
print " threshold: %g" % threshold
print " i1, i2 = %i, %i" % (i1,i2)
print " popt =", popt
xs = numpy.arange(len(ra))
ys = growth(xs, *popt)
pylab.semilogy(xs, ra, ':')
pylab.semilogy(xs, ys, '-')
pylab.semilogy(i1, ra[i1], 'o', mfc='none')
pylab.semilogy(i2, ra[i2], 's', mfc='none')
pylab.show()
#}
return (i1, i2)
#}
def fit1(gEdges, dNdg, thb): #{
"""
fits
dNdg = C g^a e^{b1 g + b2 g^2 + c1/(g-1)}
returns C, a, b1, b2, c1, cov
where cov is the normalized covariance of the parameters
let (C, a, b) = (a_0, a_1, a_2)
Then cov_ij = < [a_i - <a_i>] [a_j - <a_j>] >
where <a_i> is the value returned (e.g., C, a, or b).
E.g., sqrt(cov_ii) is the std. dev. of a_i.
If the ySigmas are known, then the "real" cov can be find by
real cov = N/(N-M) r^2 cov
where r^2 = Sum_n (y_n - fitted_y_n(C,a,b))^2 / ySigmas_n^2.
"""
def lnPowLawExp2(g,lnC,a,b1,b2,c1):
res = lnC + a*numpy.log(g) + b1*g + b2*g*g + c1/(g-1.)
return res
(dNdgMax, A, thb, fracInMax, energyFracInMax, gMinInd, fail
) = subtractMaxwell(gEdges, dNdg, thb)
dNdgSub = abs(dNdg - dNdgMax)
gAll = 0.5*(gEdges[1:] + gEdges[:-1])
dNdgSub = dNdgSub[gMinInd:]
g = gAll[gMinInd:]
# get rid of zeros
nz = (dNdgSub > 0.)
dNdgSub = dNdgSub[nz]
g = g[nz]
# rescale so points are weighted sort of the same
lndNdgSub = numpy.log(dNdgSub)
lnScaleFactor = 1. - lndNdgSub.min()
lndNdgSub += lnScaleFactor
lndNdgSubMaxInd = lndNdgSub.argmax()
if 1: #{
if 1: #ySigmas is None:
lnySigmas = None
else:
lnySigmas = numpy.log(ys+ySigmas) - numpy.log(ys)
a0 = -1.5
b10 = -1./g.max()
b20 = -b10**2
c10 = -1.
gc = max(2., g[lndNdgSubMaxInd])
print lnPowLawExp2(gc, 0., a0, b10, b20, c10)
lnC0 = lndNdgSub[lndNdgSubMaxInd] - lnPowLawExp2(
gc, 0., a0, b10, b20, c10)
print "gc = %g, lnC0 = %g, lndNdgMax = %g" % (
gc, lnC0, lndNdgSub[lndNdgSubMaxInd])
#popt = (lnC0, a0, b10, b20, c10)
fit = scipy.optimize.curve_fit(lnPowLawExp2,
g, lndNdgSub, p0=(lnC0,a0,b10,b20,c10), sigma=lnySigmas)
print fit
popt, pcov = fit
(lnC,a,b1,b2,c1) = popt
lnC -= lnScaleFactor
C = numpy.exp(lnC)
# Not sure if this is the right thing to do with lnScaleFactor != 0
# :TODO: double check
#pcov[0,:] *= C
#pcov[:,0] *= C
#}
#print popt
def lnFitFn(g):
return lnPowLawExp2(g, lnC, a, b1, b2, c1)
def fitFn(g):
return numpy.exp(lnFitFn(g))
if 1: #{
import pylab
pylab.loglog(g, dNdgSub, 'o', mfc='none')
pylab.loglog(g, fitFn(g))
#pylab.semilogx(g, lnFitFn(g))
pylab.title("%.3g, %.3g, %.3g, %.3g, %.3g" % (lnC, a, b1, b2, c1))
pylab.show()
raise RuntimeError, "Quitting after this diagnostic plot"
#}
return (C,a,b1,b2,c1,pcov)
#}
def fit2(gEdges, dNdg, thb): #{
"""
fits
dNdg = C g^a e^{b1 g + b2 g^2 + c1/(g-1)} + MC g sqrt{g^2-1} exp(-g/th)
returns C, a, b1, b2, c1, MC, th cov
where cov is the normalized covariance of the parameters
let (C, a, b) = (a_0, a_1, a_2)
Then cov_ij = < [a_i - <a_i>] [a_j - <a_j>] >
where <a_i> is the value returned (e.g., C, a, or b).
E.g., sqrt(cov_ii) is the std. dev. of a_i.
If the ySigmas are known, then the "real" cov can be find by
real cov = N/(N-M) r^2 cov
where r^2 = Sum_n (y_n - fitted_y_n(C,a,b))^2 / ySigmas_n^2.
"""
absb = True
def lnPowLawExp2(g,lnC,a,a2,b1,b2,c1,d):
if absb:
b1 = -abs(b1)
b2 = -abs(b2)
c1 = -abs(c1)
d = min(10., abs(d))
res = lnC + a*numpy.log(g) + a2*numpy.log(g)**2 + b1*g + b2*g*g
res += c1/(g**d)
return res
def lnMaxwell(g, lnA, th):
res = lnA + numpy.log(g) + 0.5*numpy.log((g-1.)*(g+1.)) - (g-1.)/th
return res
def lnPowLawExpPlusMaxwell(g,lnC,a,a2,b1,b2,c1,d,lnMC, th):
#th = 0.0431
#d=1.
a2=0.
#b2=0.
#b1=0.
#b2=0.
res = numpy.exp(lnPowLawExp2(g,lnC,a,a2,b1,b2,c1,d))
maxwell = numpy.exp(lnMaxwell(g, lnMC, th))
res += maxwell
lnres = numpy.log(res)
return lnres
# fit low-E maxwell to get initial parametrs for Maxwellian
(dNdgMax, MC0, th0, fracInMax, energyFracInMax, gMinInd, fail
) = subtractMaxwell(gEdges, dNdg, thb)
# get rid of zeros
nz = (dNdg > 0.)
dNdgNz = dNdg[nz]
gAll = 0.5*(gEdges[1:] + gEdges[:-1])
g = gAll[nz]
# rescale so points are weighted sort of the same
lndNdg = numpy.log(dNdgNz)
lnScaleFactor = 1. - lndNdg.min()
lndNdg += lnScaleFactor
lnMC0 = numpy.log(MC0) + lnScaleFactor
lndNdgMaxInd = lndNdg.argmax()
if 1: #{
if 1: #ySigmas is None:
lnySigmas = None
else:
lnySigmas = numpy.log(ys+ySigmas) - numpy.log(ys)
a0 = -1.5
a20 = -0.01
b10 = -1./g.max()
b20 = -b10**2
c10 = -1.
d0 = 1.
lnC0 = numpy.log(dNdg[gMinInd]) - lnPowLawExpPlusMaxwell(
gEdges[gMinInd], 0., a0, a20, b10, b20, c10, d0, 0., th0)
popt = (lnC0, a0, a20, b10, b20, c10, d0, lnMC0, th0)
fit = scipy.optimize.curve_fit(lnPowLawExpPlusMaxwell,
g, lndNdg, p0=popt, sigma=lnySigmas, maxfev = 60000)
fit = scipy.optimize.curve_fit(lnPowLawExpPlusMaxwell,
g, lndNdg, p0=fit[0], sigma=lnySigmas, maxfev = 60000)
print fit
popt, pcov = fit
(lnC,a,a2, b1,b2,c1,d, lnMC, th) = popt
if absb:
b1 = -abs(b1)
b2 = -abs(b2)
c1 = -abs(c1)
d = min(10., abs(d))
lnC -= lnScaleFactor
lnMC -= lnScaleFactor
C = numpy.exp(lnC)
# Not sure if this is the right thing to do with lnScaleFactor != 0
# :TODO: double check
#pcov[0,:] *= C
#pcov[:,0] *= C
#}
#print popt
lndNdg -= lnScaleFactor
def lnFitFn(g):
return lnPowLawExpPlusMaxwell(g, lnC, a, a2, b1, b2, c1, d, lnMC, th)
def fitFn(g):
return numpy.exp(lnFitFn(g))
if 0: #{
avgResidSqr = ((lnFitFn(g) - lndNdg)**2).sum() / g.size
print "avgResidSqr = %g" % avgResidSqr
#import pylab
#pylab.plot(g, lnFitFn(g))
#pylab.plot(g,lndNdg)
#pylab.show()
#}
if 1: #{
import pylab
p = 0.
pylab.loglog(gAll, gAll**p *dNdg, 'o', mfc='none', mec='c', alpha=0.2)
pylab.loglog(gAll, gAll**p *fitFn(gAll), '-b')
pylab.loglog(gAll, gAll**p *fitFn(gAll[gMinInd+40])*(gAll/gAll[gMinInd+40])**a, "--r")
#pylab.semilogx(g, lnFitFn(g))
pylab.title("%.3g, a=%.3g, %.3g, -1/b1=%.3g,\n$1/\\sqrt{-b_2}$=%.3g, %.3g, d=%.2g, %.3g, %.3g" % (
lnC, a, a2, -1./b1, (-b2)**(-0.5), (-c1)**(1./d), d, lnMC, th))
pylab.xlim(xmax = 2*g[-1])
pylab.ylim(ymin = 0.5*g[-1]**p * dNdgNz.min(), ymax = 2*g[gMinInd]**p*dNdgNz.max())
#pylab.gca().set_xscale("linear")
pylab.subplots_adjust(top=0.86)
pylab.show()
raise RuntimeError, "Quitting after this diagnostic plot"
#}
return (C,a,b1,b2,c1,pcov)
#}
def fitJustPowerAndExp(g, dNdg, b1, b2, lnFitLowEnergy, lnFitPowerLaw): #{
"""
Given g and dNdg data, excludes the low (Maxwellian) and high
(steep cutoff) energy parts, and fits the remainder to
f(g) = C g^a exp(-b g)
returns (C, a, b, pCov)
Assumes that dNdg > 0 so we can take its log.
"""
numPts = len(g)
# Find where maxwellian finally falls below power law part
partsDif = lnFitLowEnergy(g) - lnFitPowerLaw(g)
iX1 = 1 + numpy.where(partsDif > 0.)[0][-1]
# Now move to higher energies until we enter a concave-down region.
lngdif = numpy.diff(numpy.log(g))
lngdif2 = 0.5*(lngdif[1:] + lngdif[:-1])
d2 = numpy.diff(numpy.diff(numpy.log(dNdg))/lngdif)/lngdif2
d2 = arrayPlus.smooth1d(d2, 4)
concaveDown = (d2 <= 0.)
dnsInARowMin = 5
for iX2 in range(iX1, numPts - dnsInARowMin):
print iX2, concaveDown[iX2:iX2+dnsInARowMin]
if concaveDown[iX2:iX2+dnsInARowMin].all():
print "Found!"
break
if 0: #{
import pylab
pylab.loglog(g, dNdg, 'o')
pylab.show()
#}
if iX2 == numPts - dnsInARowMin - 1:
msg = "Never found %i points of ln(dNdg) vs. ln(g) in a row that" % dnsInARowMin
msg += " were concave down"
print "concaveDns = ", concaveDown
raise ValueError, msg
# Find the point at which the tail drops the distribution by dipFactor
# exp(b1*g+b2*g^2) = 1/dipFactor
# b1 g + b2 g^2 + ln(dipFactor) = 0
dipFactor = 10.
# If b1 and b2 are both negative (usual), then roots are of opposite
# sign, and we take positive.
# If b1 > 0 (b1 is probably extremely small) and b2 < 0,
# roots are of opposite sign and again we want the positive root.
# If b2 > 0 (b2 is probably extremely small) and b1 < 0,
# roots are booth positive, and we want the smaller.
gDip = arrayPlus.quadraticSoln([b2], b1, numpy.log(dipFactor),
sortBy = "nonnegativeOrAbsSmallestFirst")[:,0]
iX3 = numpy.where(g>gDip)[0][0]
# fit power law with exp cutoff
(C, a, b, powLawExpCov) = mathPlus.fitPowerLawExp(g[iX2:iX3],
dNdg[iX2:iX3])
if 1: #{
import pylab
pylab.loglog(g, dNdg, 'o')
pylab.loglog(g, C*g**a * numpy.exp(b*g))
pylab.title(r"a=%g, b=%g" % (a, b))
pylab.show()
#}
return (C, a, b, powLawExpCov)
#}
def fit3(gEdges, dNdg, thb, dMacro = None, startWithPrevFit = None,
useCachedData = None, fitPowExp = False): #{
"""
fits
dNdg = C g^a e^{b1 g + b2 g^2 - (c1/g)^d)}
+ \int_{th1}^{th2} MC/(th2-th1) (1/th) g sqrt{g^2-1} exp(-g/th) dth
returns C, a, b1, b2, c1, MC, th1, th2 cov
where cov is the normalized covariance of the parameters
let (C, a, b) = (a_0, a_1, a_2)
Then cov_ij = < [a_i - <a_i>] [a_j - <a_j>] >
where <a_i> is the value returned (e.g., C, a, or b).
E.g., sqrt(cov_ii) is the std. dev. of a_i.
If the ySigmas are known, then the "real" cov can be find by
real cov = N/(N-M) r^2 cov
where r^2 = Sum_n (y_n - fitted_y_n(C,a,b))^2 / ySigmas_n^2.
if startWithPrevFit is the popt from a previous call to fit3
(presumably with a similar dNdg), then starts with those parameters,
rather than calling a bunch of initial conditions.
"""
#useCachedData = None
#print 'Warning: not using cached data'
absb = False
dMax = 10.
def lnPowLawExp2(g,lnC,a,a2,b1,b2,c1,d):
if absb:
b1 = -abs(b1)
b2 = -abs(b2)
#c1 = -abs(c1)
d = min(dMax, abs(d))
res = lnC + a*numpy.log(g) + a2*numpy.log(g)**2 + b1*g + b2*g*g
# Don't let c and d get ridiculous
d = min(d, 100)
c1 = min(c1, 10**(100./max(1.,d)) )
#tmp = (c1/g)**d
#if not numpy.isfinite(tmp).all():
# inds = numpy.where(numpy.logical_not(numpy.isfinite(tmp)))[0]
# print c1, d
# print g[inds]
res += -abs(c1/g)**d
#res += c1/g**d
return res
def lnMaxwell(g, lnA, th):
res = lnA + numpy.log(g) + 0.5*numpy.log((g-1.)*(g+1.)) - (g-1.)/th
return res
def lnIntMaxwell(g, lnA, th1, dth = None):
if numpy.isnan(g).any():
raise RuntimeError, "g is nan"
if numpy.isnan(lnA).any():
raise RuntimeError, "lnA is nan"
if numpy.isnan(th1).any():
raise RuntimeError, "th1 is nan"
if dth is not None and numpy.isnan(dth).any():
raise RuntimeError, "dth is nan"
if dth is None:
return lnMaxwell(g,lnA,th1)
if absb:
th1 = abs(th1)
dth = abs(dth)
th2 = th1 + dth
if not isinstance(g, numpy.ndarray):
return lnIntMaxwell(numpy.array([g]), lnA, th1, dth)[0]
if (g<=1).any():
raise ValueError, "g =" + repr(g)
res = lnA + numpy.log(g) + 0.5*numpy.log((g-1.)*(g+1.))
# (d/d th) exp1(a/th) = exp(-a/th) / th
# We want to calculate:
# IntMaxwell = A g sqrt(g^2-1) (thAvg/(th2-th1))
# int_{th1}^{th2} exp(- (g-1)/th) / th d th
# = A g sqrt(g^2-1) (thAvg/(th2-th1)) [exp((g-1)/th)]_th1^th2
# where
# thAvg = (th1+th2)/2
# But we need to make sure things work correctly in limits.
#
# First, if (th2 - th1) << th1:
# IntMaxwell = A g sqrt(g^2-1) exp(-(g-1)/thAvg)
# (which is why we added (thAvg/(th2-th1)) to the normalization)
# Second, when (g-1)/th is very large, we run into underflow and
# precision loss.
# The integral int_th1^th2 exp(-(g-1)/th) / th dth
# is bounded by:
# (lower bound) (th2-th1)/th2 exp(-(g-1)/th1)
# (upper bound) (th2-th1)/th1 exp(-(g-1)/th2)
thAvg = 0.5*(th1+th2)
lnUpperBound = numpy.log(thAvg/th1) - (g-1.)/th2 if th1 > 0. else -460.5+0*g
gBig = (lnUpperBound < -345.4) # e^(-345.4) = 1e-150
gSmall = numpy.logical_not(gBig)
gs = g[gSmall].copy()
# exp1(0) = infinity, but expA2-expA1 = 1/th2 - 1/th1
g1 = (gs==1.)
gs[g1] = 1. + 1e-6*th1
expA1 = scipy.special.exp1( (gs-1.)/th1 ) if th1 > 0. else 0.
expA2 = scipy.special.exp1( (gs-1.)/th2 ) if th2 > 0. else 0.
expA = (expA2 - expA1) * thAvg / dth if (dth > 0.) else 0.
expA[g1] = numpy.log(th2/th1) * thAvg/dth if (dth>0. and th1>0.) else 0.
if 0:
iBad = numpy.where(numpy.logical_not(numpy.isfinite(expA)))[0]
if len(iBad) > 0:
print iBad, th1, th2
print gs[iBad], gs[iBad]-1.
print expA1[iBad]
print expA2[iBad]
expC = numpy.exp( -(gs-1.)/ thAvg)
dthThresh = th1/10.
if th1 > 0. and dth < dthThresh:
mixParam = dth/dthThresh
expRes = expC * (1. - mixParam) + expA * mixParam
else:
expRes = expA
res[gBig] += lnUpperBound[gBig]
res[gSmall] += numpy.log(expRes)
return res
def lnPowLawExpPlusMaxwell(g,lnC,a,a2,b1,b2,c1,d,lnMC, th1, dth = None):
#if dth is None:
# dth = 0.001*abs(th2)
#th = 0.0431
#d=1.
#a2=0.
#b2=0.
#b1=0.
#b2=0.
lnplaw = lnPowLawExp2(g,lnC,a,a2,b1,b2,c1,d)
lnmax = lnIntMaxwell(g, lnMC, th1, dth)
if isinstance(lnplaw, numpy.ndarray):
# avoid overflow
lnplaw[lnplaw > 460.5] = 460.5 # ln(1e200) = 460
lnmax[lnmax > 460.5] = 460.5 # ln(1e200) = 460
# and underflow
lnplaw[lnplaw < -460.5] = -460.5 # ln(1e-200) = -460
lnmax[lnmax < -460.5] = -460.5
else:
lnplaw = max(-460.5, min(460.5, lnplaw))
lnmax = max(-460.5, min(460.5, lnmax))
res = numpy.exp(lnplaw)
maxwell = numpy.exp(lnmax)
res += maxwell
#if (res==0).any():
# iBad = numpy.where(res==0)[0]
# print "lnplaw", lnplaw[iBad]
# print "lnmax", lnmax[iBad]
# print g[iBad]
# print (lnC,a,a2,b1,b2,c1,d,lnMC, th1, dth)
# raise ValueError
lnres = numpy.log(res)
return lnres
# get rid of zeros
nz = (dNdg > 0.)
dNdgNz = dNdg[nz]
gAll = 0.5*(gEdges[1:] + gEdges[:-1])
g = gAll[nz]
if dMacro is not None: #{
# amount dNdg varies due to counting noise
dNdgSig = dNdgNz * (1. + 1./numpy.sqrt(dMacro[nz]))
#}
# rescale so points are weighted sort of the same
lndNdg = numpy.log(dNdgNz)
lnScaleFactor = 1. - lndNdg.min()
lndNdg += lnScaleFactor
if 0: #{
import pylab
pylab.loglog(g, numpy.exp(lnMaxwell(g,lnMC0, th20)))
pylab.loglog(g, numpy.exp(lnIntMaxwell(g,lnMC0, th20, dth20)))
pylab.show()
#}
numNonZero = nz.sum()
if numNonZero < 10: #{
lnC = -100.
a = 0.
a2 = 0.
b1 = 0.
b2 = 0.
c1 = 0.
d = 1.
if numNonZero == 0:
lnMC = 0.
else:
lnMC = lndNdg.max()
th1 = thb
dth = thb/100.
popt = [lnC, a, a2, b1, b2, c1, d, lnMC, th1, dth]
pcov = numpy.zeros((len(popt),)*2)
elif 1: #}{
if dMacro is None: #ySigmas is None:
lnySigmas = None
else:
#lnySigmas = None
lnySigmas = numpy.log(dNdgNz+dNdgSig) - numpy.log(dNdgNz)
if True: # startWithPrevFit is None: #{
# fit low-E maxwell to get initial parameters for Maxwellian
th10 = thb
(dNdgMax, MC0, th20, fracInMax, energyFracInMax, gMinInd, fail
) = subtractMaxwell(gEdges, dNdg, thb)
if (MC0 <= 0): #{ can easily happen for power with negative index
lnMC0 = lndNdg.min() - 3.
else: #}{
lnMC0 = numpy.log(MC0) + lnScaleFactor
#}
dth0 = abs(th20-th10)
th10 = min(th10, th20)
a0 = -1.5
a20 = 0.
b10 = -1./g.max()
b20 = -b10**2
#c10 = -1.
c10 = 1.
d0 = 2.
dth0 = 0.01 * th20
# occasionally have problems (especially with initial distributions)
# where dNdg has only a few non-zero elements
igMax = numpy.argmax(dNdg)
igUse = gMinInd
if dNdg[gMinInd] < 0.01 * dNdg[igMax]:
igUse = igMax
lnC0 = numpy.log(dNdg[igUse]) - lnPowLawExpPlusMaxwell(
0.5*(gEdges[igUse]+gEdges[igUse+1]),
0., a0, a20, b10, b20, c10, d0, 0., th10, dth0)
if 0: #{
lnC0 = -1.28+lnScaleFactor
a0 = -1.18
b10 = -1./912.
b20 = -1./1.85e3**2
c10 = -4.14**10.
d0 = 10.
lnMC0 = -2.03+lnScaleFactor
th20 = 0.807
#}
else: #}{
(lnC0, a0, a20, b10, b20, c10, d0, lnMC0, th10, dth0) = startWithPrevFit
#}
lnCInd = 0
aInd = 1
dInd = 6
b1Ind = 3
b2Ind = b1Ind+1
c1Ind = 5
thInd = -2
dthInd = -1
popt = [lnC0, a0, a20, b10, b20, c10, d0, lnMC0, th10, dth0]
pScale = [1., 1., 1., 1./g[-1], 1./g[-1]**2, 1., 0.5, 1., 1., thb]
pBnds = [None, [-10.,0.], [0., 0.], [-1.,0.], [-1.,0.],
[0., g[-1]], [1., dMax], None, [0., g[-1]/3.],
[min(1e-5, thb/10.), g[-1]/3.]]
useCache = False #(useCachedData is not None)
if useCache: #{
poptCache = list(useCachedData[:len(popt)])
popt = list(poptCache)
#}
# first optimization, keep d constant -- otherwise, algorithm likes
# to increase d without bound for some reason
if useCache: #{
starts = [["orig"]]
else: #}{
starts = [
["orig",],
["follow",],
["orig", [dthInd], [dInd], [thInd, th20], [b2Ind, 0.], [c1Ind, 3*th20]],
#["follow", [dthInd], [dInd], [b2Ind, 0.]],
["follow",],
["orig", [dthInd], [dInd], [thInd, th20], [b1Ind, 0.], [c1Ind, 3*th20]],
#["follow", [dthInd], [dInd], [b1Ind, 0.]],
["follow",],
["orig", [dthInd], [dInd] ],
#["follow", [dthInd]],
["follow",],
["best", [dInd], [c1Ind, 3*th20]],
["follow",],
#["orig", [dInd]],
#["follow",],
#["best", [dthInd], [dInd, 2.]],
#["follow",],
#["best", [dthInd]],
#["follow",],
["best"],
]
if startWithPrevFit is not None:
starts.append(["new", startWithPrevFit])
starts.append(["best"])
starts.append(["follow"])
#}
redo = False
try:
(fit, residImprovement) = optPlus.curveFitWithBoundedParamsMultipleStarts(
scipy.optimize.curve_fit,
lnPowLawExpPlusMaxwell, g, lndNdg, pScale, pBnds,
starts = starts, p0 = popt, sigma = lnySigmas)
except:
if useCache:
redo = True
else:
raise
popt, pcov = fit
(lnC,a,a2, b1,b2,c1,d, lnMC, th1, dth) = popt
def lnFitLowEnergy(g):
p = list([lnMC, th1, dth])
return lnIntMaxwell(g, *p)
def lnFitPowerLaw(g):
p = list([lnC, a, a2, b1, b2, c1, d])
return lnPowLawExp2(g, *p)
if fitPowExp: #{
(CPowExp, aPowExp, bPowExp, powExpCov) = fitJustPowerAndExp(
g, dNdgNz, b1, b2, lnFitLowEnergy, lnFitPowerLaw)
lnCPowExp = numpy.log(CPowExp)
starts2 = [
["orig", [aInd, aPowExp], [b1Ind, bPowExp], [lnCInd, lnCPowExp]],
["follow", [aInd, aPowExp], [b1Ind, bPowExp], [lnCInd, lnCPowExp]],
]
popt[lnCInd] = lnCPowExp
popt[aInd] = aPowExp
popt[b1Ind] = bPowExp
print "popt new", popt
(fit, residImprovement) = optPlus.curveFitWithBoundedParamsMultipleStarts(
scipy.optimize.curve_fit,
lnPowLawExpPlusMaxwell, g, lndNdg, pScale, pBnds,
starts = starts2, p0 = popt, sigma = lnySigmas)
popt, pcov = fit
(lnC,a,a2, b1,b2,c1,d, lnMC, th1, dth) = popt
print 'a=%g', a, aPowExp
def lnFitLowEnergy(g):
p = list([lnMC, th1, dth])
return lnIntMaxwell(g, *p)
def lnFitPowerLaw(g):
p = list([lnC, a, a2, b1, b2, c1, d])
return lnPowLawExp2(g, *p)
#}
if useCache: #{
# check that popt hasn't change significantly
# if it has, run whole optimization
dif = numpy.array(popt) - numpy.array(poptCache)
mag = numpy.array([max(abs(a),abs(b)) for (a,b) in zip(popt, poptCache)])
mag[mag==0.] = 1e-16
reldif = abs(dif)/mag
if redo or (dif > 9e-3).any() or (residImprovement > 1.+1e-6):
res = fit3(gEdges, dNdg, thb, dMacro = dMacro,
startWithPrevFit = startWithPrevFit,
useCachedData = None)
return res
#}
#print fit
if absb:
b1 = -abs(b1)
b2 = -abs(b2)
#c1 = -abs(c1)
d = min(dMax, abs(d))
th1 = abs(th1)
dth = abs(dth)
th2 = th1 + dth
lnC -= lnScaleFactor
lnMC -= lnScaleFactor
C = numpy.exp(lnC)
# Not sure if this is the right thing to do with lnScaleFactor != 0
# :TODO: double check
#pcov[0,:] *= C
#pcov[:,0] *= C
#}
lndNdg -= lnScaleFactor
def lnFitLowEnergy(g):
p = list([lnMC, th1, dth])
return lnIntMaxwell(g, *p)
def lnFitPowerLaw(g):
p = list([lnC, a, a2, b1, b2, c1, d])
return lnPowLawExp2(g, *p)
def lnFitFn(g):
p = list([lnC, a, a2, b1, b2, c1, d, lnMC, th1, dth])
return lnPowLawExpPlusMaxwell(g, *p)
def fitLowEnergy(g):
return numpy.exp(lnFitLowEnergy(g))
def fitPowerLaw(g):
return numpy.exp(lnFitPowerLaw(g))
def fitFn(g):
return fitLowEnergy(g) + fitPowerLaw(g)
#return fit3(gEdges[iX2:iX3+1], dNdg[iX2:iX3], thb, dMacro = dMacro,
# startWithPrevFit = startWithPrevFit,
# useCachedData = None, deweightBelowG = g[iX2])
if 0: #{
avgResidSqr = ((lnFitFn(g) - lndNdg)**2).sum() / g.size
print "avgResidSqr = %g" % avgResidSqr
#import pylab
#pylab.plot(g, lnFitFn(g))
#pylab.plot(g,lndNdg)
#pylab.show()
#}
if 0: #{
import pylab
print "popt =", popt
p = 0.
pylab.loglog(gAll, gAll**p *dNdg, 'o', mfc='none', mec='c', alpha=0.3)
pylab.loglog(gAll, gAll**p *fitFn(gAll), '-b')
pylab.loglog(gAll, gAll**p *fitFn(gAll[gMinInd+40])* (gAll/ gAll[gMinInd+40])**a, "--r")
ylimits = pylab.ylim()
if 1: #{# make parts
mwell = fitLowEnergy(g)
plaw = fitPowerLaw(g)
pylab.loglog(g, mwell, '-', color='0.1')
pylab.loglog(g, plaw, '--', color='0.1')
#}
pylab.ylim(ylimits)
#pylab.semilogx(g, lnFitFn(g))
title = "%.3g, a=%.3g, %.3g, -1/b1=%.3g,\n$1/\\sqrt{-b_2}$=%.3g, %.3g, d=%.2g, %.3g, " % (
lnC, a, a2, -1./b1 if b1!=0. else 1e99, (-b2)**(-0.5) if b2 != 0. else 1e99,
c1, d, lnMC)
title += "th=%.3g-%.3g" % (th1, th2)
pylab.xlabel(r"$\gamma$")
if p==0:
ylabel = r"$dN/d\gamma$"
elif p==1:
ylabel = r"$\gamma dN/d\gamma$"
else:
ylabel = r"$\gamma^{%.3g} dN/d\gamma$" % p
pylab.ylabel(ylabel)
pylab.title(title)
pylab.xlim(xmax = 2*g[-1])
pylab.ylim(ymin = 0.5*g[-1]**p * dNdgNz.min(), ymax = 2*g[gMinInd]**p*dNdgNz.max())
#pylab.gca().set_xscale("linear")
pylab.subplots_adjust(top=0.86)
pylab.show()
raise RuntimeError, "Quitting after this diagnostic plot"
#}
return (popt, pcov, fitFn, fitLowEnergy, fitPowerLaw)
#}
def fit4(gEdges, dNdg, thb, dMacro = None, startWithPrevFit = None,
useCachedData = None, deweightBelowG = None): #{
"""
fits