-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSyn_kmpfit.py
executable file
·3818 lines (2992 loc) · 174 KB
/
Syn_kmpfit.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/env python
# Kmpfit fitting of the JP CI synchrotrom model
import sys
#sys.path.append('/Users/shulevski/Documents/Kapteyn/1431+1331_spix/')
#from Synfit import Synfit
import Synfit_Leith as sl
#from Synfit_Eint import Synfit
import numpy as np
import math as mt
import matplotlib.pyplot as plt
from pylab import *
from scipy.integrate import quad, quadrature, fixed_quad, simps
import scipy.special as ss
#from kapteyn import kmpfit
from scipy.special import gammainc, chdtrc
from scipy.optimize import fminbound
from scipy.optimize import curve_fit
import scipy.ndimage as spn
global call_counter
call_counter = 0
def synfit_opt_func(freqs, t_a, t_i, N, a_inj):
z = 0.026141
B = 1.35e-6
synfit = Synfit(z, 0., 0., B, 10.**freqs, 0., 0., 'CI_off', 'JP')
'''
print "Freqs: ", 10.**freqs
print t_a
print t_i
print N
print a_inj
'''
synfit.set_ti(10.**t_i)
synfit.set_ta(10.**t_a)
synfit.set_ntot(10.**N)
synfit.set_inj((10.**a_inj) * -1.)
model_flux = synfit()
#print "S: ", model_flux
#print np.log10(1.), np.log10(80.)
#print np.log10(1.e-8), np.log10(1.e-15)
#print np.log10(0.5), np.log10(1.)
if (np.log10(1.) < t_a < np.log10(80.)) and (np.log10(1.) < t_i < np.log10(80.)) and (np.log10(1.e-15) < N < np.log10(1.e-8)) and (np.log10(0.5) < a_inj < np.log10(1.)):
print "Return Something"
return np.log10(np.array(model_flux))
else:
print "Return Inf"
return np.log10(np.array(model_flux)) * np.Inf
def residuals(p, data):
#t_a, t_i, angle, scale= p
###t_a, t_i, N = 10.**p
t_a, t_i, N, a_inj = 10.**p
#scale= p
#meas_frequencies, meas_flux, meas_flux_rms, redshift, a_in, B_field, model, variant, t_a, t_i = data
###meas_frequencies, meas_flux, meas_flux_rms, redshift, B_field, a_inj, model, loss = data
meas_frequencies, meas_flux, meas_flux_rms, redshift, B_field, model, loss = data
####meas_frequencies = np.array(meas_frequencies)
meas_flux = np.array(meas_flux)
###s = Synfit(redshift, t_a, t_i, B_field, meas_frequencies, a_inj * -1., N, model, loss)
###s = Synfit(redshift, t_a, t_i, B_field, meas_frequencies, a_inj, N, model, loss)
global synfit
global call_counter
call_counter += 1
sys.stdout.write('Synfit call: ' + str(call_counter) + '\r')
sys.stdout.flush()
synfit.set_ti(t_i)
synfit.set_ta(t_a)
synfit.set_ntot(N)
synfit.set_inj(a_inj * -1.)
model_flux = synfit()
#print model_flux
#print meas_flux
#print N
return (meas_flux - model_flux) / meas_flux_rms ## Return logarithm? 2015-11-04
def residuals_leith(p, data):
#t_a, t_i, q, a_inj = 10.**p
###t_a, q, a_inj = 10.**p # JP, fit for a_inj
###t_a, q = 10.**p # JP
t_a, t_i, q = 10.**p # CI_off
#meas_frequencies, meas_flux, meas_flux_rms, redshift, B_field, vol, delta, model = data
meas_frequencies, meas_flux, meas_flux_rms, redshift, B_field, vol, delta, model, a_inj = data
meas_frequencies = np.array(meas_frequencies)
meas_flux = np.array(meas_flux)
gamma = 1.0 - 2.0 * (a_inj * -1.)
#gamma = 1.0 - 2.0 * (a_inj) # only for JP Leith age maps fit, or when a_inj is not fitted for
#print 'T_off: ', t_a, 'T_on: ', t_i, 'Q: ', q
model_flux = sl.get_fluxes(meas_frequencies, t_a * 1.e6, (t_a + t_i) / t_a, q, gamma, B_field, vol, redshift, delta, model)
###model_flux = sl.get_fluxes(meas_frequencies, t_a * 1.e6, 1., q, gamma, B_field, vol, redshift, delta, model) # JP model, a_inj fit
return (meas_flux - model_flux) / meas_flux_rms ## Return logarithm? 2015-11-04
'''
# Input Data
meas_flux = [64.5e-3, 63.3e-3, 63.6e-3, 59.9e-3, 47.9e-3, 52.8e-3, 51.6e-3, 25.2e-3, 9.1e-3, 0.8e-3]
meas_flux_rms = [0.013, 0.013, 0.013, 0.012, 0.01, 0.01, 0.01, 0.001, 6.867e-05, 4.120e-05]
meas_frequencies = [116.9e6, 124.7e6, 132.5e6, 140.3e6, 148.1e6, 155.9e6, 163.8e6, 325.e6, 610.e6, 1425.e6]
'''
def fit(meas_frequencies, meas_flux, meas_flux_rms, model, loss, constant_params, fitted_params):
# Fitting setup
# Fit parameters are: t_a, t_i, B, alpha_in and scale factor. We may model B (equipartition) or fix alpha_in.
# ts = t_i + t_a
#p0 = [51., 0.05, np.pi / 2.5, 1.e-24] # Initial fitting parameters (variable model parameters)
#p0 = [100., 100., 1.e-24] # Initial fitting parameters (variable model parameters)
#p0 = [40., 40., 1.e-24]
#p0 = [40.0, 1.e-26]
# Fixed model parameters: a_in, z, B_field
z = constant_params[0]
B_field = constant_params[1]
###a_inj = constant_params[2]
meas_frequencies = np.array(meas_frequencies)
meas_flux = np.array(meas_flux)
global synfit
synfit = Synfit(z, 0., 0., B_field, meas_frequencies, 0., 0., model, loss)
#fitter = kmpfit.Fitter(residuals=residuals, data=(meas_frequencies, meas_flux, meas_flux_rms, z, a_inj, B_field, model, variant, t_a, t_i))
###fitter = kmpfit.Fitter(residuals=residuals, data=(meas_frequencies, meas_flux, meas_flux_rms, z, B_field, a_inj, model, loss))
fitter = kmpfit.Fitter(residuals=residuals, data=(meas_frequencies, meas_flux, meas_flux_rms, z, B_field, model, loss))
#fitter.parinfo = [{'limits': (50., 120.)}, {'limits': (0.01, 1.)}, {'limits': (0., np.pi / 2.)}, {}]
#fitter.parinfo = [{'limits': (90., 110.)}, {'limits': (90., 110.)}, {}]
#fitter.parinfo = [{'limits': (20., 110.)}, {'limits': (1., 10.)}, {}, {'limits': (0.5, 1.5)}]
##fitter.parinfo = [{'limits': np.log10((10., 150.))}, {'limits': np.log10((0.09, 40.))}, {}]
#fitter.parinfo = [{'limits': np.log10((5., 80.))}, {'limits': np.log10((5., 80.))}, {'limits: ': np.log10((1.e-8, 1.e-15))}, {'limits: ': np.log10((0.5, 1.))}]
fitter.parinfo = [{'limits': np.log10((1., 150.))}, {}, {'limits: ': np.log10((1.e-7, 1.e-15))}] # JP model fit
#fitter.parinfo = [{'limits': np.log10((10., 150.))}, {'fixed': True}, {}]
#fitter.parinfo = [{}]
#fitter.parinfo = [{'limits': (5., 500.)}, {'limits': (1., 50.)}, {'limits': (-0.9, 0.)}, {}, {'limits': (1.e-6, 15.e-6)}]
#fitter.parinfo = [{'limits': np.log10((10., 170.))}, {}, {}, {'limits': np.log10((0.6, 1.5))}]
fitter.fit(params0=np.log10(fitted_params))
if (fitter.status <= 0):
print "Status: ", fitter.status
print 'error message = ', fitter.errmsg
raise SystemExit
# Rescale the errors to force a reasonable result:
#err[:] *= np.sqrt(0.9123*fitter.rchi2_min)
fitter.fit()
print "======== Fit results =========="
prms0 = np.array(fitter.params0)
prms = np.array(fitter.params)
#print "Initial params:", 'Source off time: ', prms0[0], ' [Myr], Source on time: ', prms0[1], ' [Myr], Pitch angle: ', prms0[2], ', Scale factor: ', prms0[3]
#print "Fitted params:", 'Source off time: ', prms[0], ' [Myr], Source on time: ', prms[1], ', [Myr], Pitch angle: ', prms[2], ', Scale factor: ', prms[3]
#print "Initial params:", 'Source off time: ', prms0[0], ' [Myr], Source on time: ', prms0[1], ' [Myr], Scale factor: ', prms0[2]
#print "Fitted params:", 'Source off time: ', prms[0], ' [Myr], Source on time: ', prms[1], ' [Myr], Scale factor: ', prms[2]
#print "Initial params:", 'Source off time: ', prms0[0], ' [Myr], Scale factor: ', prms0[1], 'Injection index: ', prms0[2]
#print "Fitted params:", 'Source off time: ', prms[0], ' [Myr], Scale factor: ', prms[1], 'Injection index: ', prms[2]
print "Initial params:", 'Source off time: ', 10.**prms0[0], ' [Myr], Source on time: ', 10.**prms0[1], ' [Myr] N_tot: ', 10.**prms0[2], 'Injection index: ', 10.**prms0[3] * -1
print "Fitted params:", 'Source off time: ', 10.**prms[0], ' [Myr], Source on time: ', 10.**prms[1], ' [Myr] N_tot: ', 10.**prms[2], 'Injection index: ', 10.**prms[3] * -1
###print "Initial params:", 'Source off time: ', 10.**prms0[0], ' [Myr], Source on time: ', 10.**prms0[1], ' [Myr] N_tot: ', 10.**prms0[2]
###print "Fitted params:", 'Source off time: ', 10.**prms[0], ' [Myr], Source on time: ', 10.**prms[1], ' [Myr] N_tot: ', 10.**prms[2]
##print "Initial params:", 'Source off time: ', 10.**prms0[0], ' [Myr], Source on time: ', 10.**prms0[1], ' [Myr] Scale factor: ', 10.**prms0[2], ' Injection index: ', (10.**prms0[3]) * -1.
##print "Fitted params:", 'Source off time: ', 10.**prms[0], ' [Myr], Source on time: ', 10.**prms[1], ' [Myr] Scale factor: ', 10.**prms[2], ' injection index: ', (10.**prms[3]) * -1.
#print "Initial params:", 'Source off time: ', prms0[0], ' [Myr], Scale factor: ', prms0[1]
#print "Fitted params:", 'Source off time: ', prms[0], ' [Myr], Scale factor: ', prms[1]
#print "Initial params:", ' Scale factor: ', prms0[0]
#print "Fitted params:", ' Scale factor: ', prms[0]
print "Iterations: ", fitter.niter
print "Function ev: ", fitter.nfev
print "Uncertainties: ", np.divide(fitter.xerror, np.multiply(np.array([10.**i for i in prms]), np.log(10.)))
print "Uncertainties_default: ", fitter.xerror
print "Uncertainties_trans: ", np.log(10.) * fitter.xerror
print "Uncertainties_pow: ", 10.**(np.log(10.) * fitter.xerror)
print "Uncertainties_pow_mod: ", (10.**prms) * (np.log(10.) * fitter.xerror)
print "Uncertainties_onebyone: ", 10.**(np.log(10.) * fitter.xerror[0]), 10.**(np.log(10.) * fitter.xerror[1]), 10.**(np.log(10.) * fitter.xerror[2]), 10.**(np.log(10.) * (fitter.xerror[3] * -1.))
print "Uncertainties_ord: ", 10.**fitter.xerror
print "dof: ", fitter.dof
print "chi^2, rchi2: ", fitter.chi2_min, fitter.rchi2_min
print "stderr: ", fitter.stderr
print "Covariance: ", fitter.covar
print "Status: ", fitter.status
print "Message ", fitter.message
print "\n======== Statistics ========"
from scipy.stats import chi2
rv = chi2(fitter.dof)
print "Three methods to calculate the right tail cumulative probability:"
print "1. with gammainc(dof/2,chi2/2): ", 1-gammainc(0.5*fitter.dof, 0.5*fitter.chi2_min)
print "2. with scipy's chdtrc(dof,chi2):", chdtrc(fitter.dof,fitter.chi2_min)
print "3. with scipy's chi2.cdf(chi2): ", 1-rv.cdf(fitter.chi2_min)
print ""
xc = fitter.chi2_min
print "Threshold chi-squared at alpha=0.05: ", rv.ppf(1-0.05)
print "Threshold chi-squared at alpha=0.01: ", rv.ppf(1-0.01)
f = lambda x: -rv.pdf(x)
x_max = fminbound(f,1,200)
print """For %d degrees of freedom, the maximum probability in the distribution is
at chi-squared=%g """%(fitter.dof, x_max)
alpha = 0.05 # Select a p-value
chi2max = max(3*x_max, fitter.chi2_min)
chi2_threshold = rv.ppf(1-alpha)
print "For a p-value alpha=%g, we found a threshold chi-squared of %g"%(alpha, chi2_threshold)
print "The chi-squared of the fit was %g. Therefore: "%fitter.chi2_min
if fitter.chi2_min <= chi2_threshold:
print "we do NOT reject the hypothesis that the data is consistent with the model"
else:
print "we REJECT the hypothesis that the data is consistent with the model"
'''
# Plot data and best fit model
model_frequencies = np.linspace(30.e6, 1.5e9, 500)
#t_a, t_i, a_in, scale, B_field = prms
t_a, t_i, a_in, scale = prms
#t_a, t_i, a_in, scale, B_field = 180.25, 28.3, -0.396, 9.8316924e-26, 2.567e-6
s = Synfit(redshift, t_a, t_i, B_field, model_frequencies, a_in, scale, 0., model, variant)
model_flux = s()
fig = plt.figure()
axis = fig.add_subplot(111)
axis.grid()
axis.set_aspect('equal')
axis.tick_params(axis='x', labelsize=17, pad=15)
axis.tick_params(axis='y', labelsize=17)
axis.tick_params(length=10)
data = axis.errorbar(meas_frequencies, meas_flux, meas_flux_rms, markerfacecolor='g', ecolor='g', marker='h', markersize=6, alpha=0.75, linestyle='none')
data = axis.loglog(model_frequencies, model_flux, '-r', linewidth=2)
xlabel('Frequency [Hz]', fontsize=18, fontweight='bold', color='#000000', labelpad=5)
ylabel('Flux [mJy]', fontsize=18, fontweight='bold', color='#000000')
#plt.xlim(1.e8, 2.e9)
#plt.ylim(7.e-4, 7.e-2)
plt.show()
'''
return fitter
def fit_leith(meas_frequencies, meas_flux, meas_flux_rms, constant_params, fitted_params):
z = constant_params[0]
B_field = constant_params[1]
vol = constant_params[2]
delta = constant_params[3]
model = constant_params[4]
a_inj = constant_params[5]
meas_frequencies = np.array(meas_frequencies)
meas_flux = np.array(meas_flux)
###fitter = kmpfit.Fitter(residuals=residuals, data=(meas_frequencies, meas_flux, meas_flux_rms, z, B_field, a_inj, vol, delta))
###fitter = kmpfit.Fitter(residuals=residuals_leith, data=(meas_frequencies, meas_flux, meas_flux_rms, z, B_field, vol, delta, model))
fitter = kmpfit.Fitter(residuals=residuals_leith, data=(meas_frequencies, meas_flux, meas_flux_rms, z, B_field, vol, delta, model, a_inj))
###fitter.parinfo = [{'limits': np.log10((1., 80.))}, {'limits': np.log10((1., 80.))}, {'limits: ': np.log10((2.e-3, 4.e-3))}, {'limits: ': np.log10((0.5, 1.))}]
###fitter.parinfo = [{'limits': np.log10((0.01, 150.))}, {'limits': np.log10((0.01, 70.))}, {}, {'limits: ': np.log10((0.5, 1.))}] # CI_off model fit
###fitter.parinfo = [{'limits': np.log10((1., 80.))}, {}, {'limits: ': np.log10((0.5, 1.))}] # JP model fit, a_inj too
fitter.parinfo = [{'limits': np.log10((0.01, 150.))}, {'limits: ': np.log10((0.01, 70.))}, {}] # CI_off model fit
###fitter.parinfo = [{'limits': np.log10((1., 180.))}, {}] # JP model fit
fitter.fit(params0=np.log10(fitted_params))
if (fitter.status <= 0):
print "Status: ", fitter.status
print 'error message = ', fitter.errmsg
raise SystemExit
fitter.fit()
print "======== Fit results =========="
prms0 = np.array(fitter.params0)
prms = np.array(fitter.params)
#print "Initial params:", 'Source off time: ', 10.**prms0[0], ' [Myr], Source on time: ', 10.**prms0[1], ' [Myr] Q: ', 10.**prms0[2], 'Injection index: ', 10.**prms0[3] * -1
#print "Fitted params:", 'Source off time: ', 10.**prms[0], ' [Myr], Source on time: ', 10.**prms[1], '[Myr] Q: ', 10.**prms[2], 'Injection index: ', 10.**prms[3] * -1
###print "Initial params:", 'Source off time: ', 10.**prms0[0], ' [Myr] Q: ', 10.**prms0[1], 'Injection index: ', 10.**prms0[2] * -1
###print "Fitted params:", 'Source off time: ', 10.**prms[0], '[Myr] Q: ', 10.**prms[1], 'Injection index: ', 10.**prms[2] * -1
print "Initial params:", 'Source off time: ', 10.**prms0[0], ' Source on time: ', 10.**prms0[1], ' [Myr] Q: ', 10.**prms0[2]
print "Fitted params:", 'Source off time: ', 10.**prms[0], 'Source on time: ', 10.**prms[1], ' [Myr] Q: ', 10.**prms[2]
###print "Initial params:", 'Source off time: ', 10.**prms0[0], ' [Myr] Q: ', 10.**prms0[1]
###print "Fitted params:", 'Source off time: ', 10.**prms[0], '[Myr] Q: ', 10.**prms[1]
print "Iterations: ", fitter.niter
print "Function ev: ", fitter.nfev
print "Uncertainties: ", np.divide(fitter.xerror, np.multiply(np.array([10.**i for i in prms]), np.log(10.)))
print "Uncertainties_default: ", fitter.xerror
print "Uncertainties_trans: ", np.log(10.) * fitter.xerror
print "Uncertainties_pow: ", 10.**(np.log(10.) * fitter.xerror)
print "Uncertainties_pow_mod: ", (10.**prms) * (np.log(10.) * fitter.xerror)
###print "Uncertainties_onebyone: ", 10.**(np.log(10.) * fitter.xerror[0]), 10.**(np.log(10.) * fitter.xerror[1]), 10.**(np.log(10.) * fitter.xerror[2]), 10.**(np.log(10.) * (fitter.xerror[3] * -1.))
###print "Uncertainties_onebyone: ", 10.**(np.log(10.) * fitter.xerror[0]), 10.**(np.log(10.) * fitter.xerror[1]), 10.**(np.log(10.) * fitter.xerror[2])
'''
print "Uncertainties_onebyone: ", 10.**(np.log(10.) * fitter.xerror[0]), 10.**(np.log(10.) * fitter.xerror[1]), 10.**(np.log(10.) * fitter.xerror[2])
print "Uncertainties_ord: ", 10.**fitter.xerror
print "dof: ", fitter.dof
print "chi^2, rchi2: ", fitter.chi2_min, fitter.rchi2_min
print "1-sigma error in parameter estimates: ", (10.**prms[0]) * (np.log(10.) * fitter.stderr[0]), (10.**prms[1]) * (np.log(10.) * fitter.stderr[1]), (10.**prms[2]) * (np.log(10.) * fitter.stderr[2])
print "1-sigma error in parameter estimates (xerr): ", (10.**prms[0]) * (np.log(10.) * fitter.xerror[0]), (10.**prms[1]) * (np.log(10.) * fitter.xerror[1]), (10.**prms[2]) * (np.log(10.) * fitter.xerror[2])
print "1-sigma error in parameter estimates (uncorrected): ", fitter.stderr[0], fitter.stderr[1], fitter.stderr[2]
print "1-sigma error in parameter estimates (pow): ", 10.**fitter.stderr[0], 10.**fitter.stderr[1], 10.**fitter.stderr[2]
print "1-sigma error in parameter estimates (inverse): ", (10.**prms[0]) * np.log(10.) * fitter.stderr[0]
print "Uncertainities stderr: ", 10.**fitter.xerror[0], 10.**fitter.xerror[1], 10.**fitter.xerror[2]
'''
print "Covariance: ", fitter.covar
print "Status: ", fitter.status
print "Message ", fitter.message
print "\n======== Statistics ========"
from scipy.stats import chi2
rv = chi2(fitter.dof)
print "Three methods to calculate the right tail cumulative probability:"
print "1. with gammainc(dof/2,chi2/2): ", 1-gammainc(0.5*fitter.dof, 0.5*fitter.chi2_min)
print "2. with scipy's chdtrc(dof,chi2):", chdtrc(fitter.dof,fitter.chi2_min)
print "3. with scipy's chi2.cdf(chi2): ", 1-rv.cdf(fitter.chi2_min)
print ""
xc = fitter.chi2_min
print "Threshold chi-squared at alpha=0.05: ", rv.ppf(1-0.05)
print "Threshold chi-squared at alpha=0.01: ", rv.ppf(1-0.01)
f = lambda x: -rv.pdf(x)
x_max = fminbound(f,1,200)
print """For %d degrees of freedom, the maximum probability in the distribution is
at chi-squared=%g """%(fitter.dof, x_max)
alpha = 0.001 # Select a p-value
chi2max = max(3*x_max, fitter.chi2_min)
chi2_threshold = rv.ppf(1-alpha)
print "For a p-value alpha=%g, we found a threshold chi-squared of %g"%(alpha, chi2_threshold)
print "The chi-squared of the fit was %g. Therefore: "%fitter.chi2_min
if fitter.chi2_min <= chi2_threshold:
print "we do NOT reject the hypothesis that the data is consistent with the model"
else:
print "we REJECT the hypothesis that the data is consistent with the model"
return fitter
def fit_regions_age(region_data_path, filename, N_pix_beam, N_pix_sigma, noise_arr, freq_arr, z, model, variant):
'''
with open(path + filename, 'r') as f:
content = f.readlines()
for line in content:
line.strip()
if not line.startswith('#'):
np_arr = np.(line[1 :])
print len(np_arr)
'''
fit_res = fit([74.e6, 135.e6, 325.e6, 610.e6, 1425.e6], [3.65, 1953.5e-3, 364.8e-3, 109.8e-3, 14.7e-3], [3.6602447133273364, 0.39078236526415172, 0.072961526321674436, 0.021964107215696166, 0.0029494543219208613], 0.1559, -0.75, 1.75, 'CI_off', True) # 1 HBA and LBA point, integrated spectrum
'''
regions = np.genfromtxt(path + filename, comments='#')
noise_area = N_pix_sigma / N_pix_beam
fit_regions_res = []
#region = regions[6]
for region in regions:
region_area = region[1] / N_pix_beam
#print 'Input noise: ', noise_arr
for idx in range(len(noise_arr)):
if idx in range(0, 7):
flux_rms = region[idx + 2] * 0.2
elif idx in range(7, 8):
flux_rms = region[idx + 2] * 0.05
else:
flux_rms = 0.
noise_arr[idx] = np.sqrt((((noise_arr[idx]**2.) * region_area**2.) / noise_area) + ((noise_arr[idx]**2.) / region_area) + flux_rms**2.)
#print 'Corrected noise:', noise_arr
print 'Fitting model for region ', region[0], '...'
# B field calculated per region, with the path through the source taken to be the average of the overall source dimensions - 239.85 kpc
#print 'The magnetic field for region ', region[0], ' is: ', B_field_estimator(1., 1., 0.1599, 10., 10., 239.85, np.pi/2., region[8], 0.325, 0.01, 100., region[11]), ' G'
a_in = -0.7 # Injection spectral index
fit_res = fit(freq_arr, region[2:11], noise_arr, z, a_in, region[12], model, variant)
fit_regions_res.append(region[0])
fit_regions_res.append(fit_res.params[1])
fit_regions_res.append(fit_res.params[0])
fit_regions_res.append(fit_res.rchi2_min)
'''
return fit_res
def fit_pixels(path, images, N_pix_beam, N_pix_sigma, noise_arr, freq_arr):
from astropy.io import fits
import pyfits
import aplpy
import matplotlib.pyplot as plt
import aplpy
flux_arr = []
im_dict = dict()
header = []
for im_idx in range(len(images)):
hdulist = fits.open(path + images[im_idx], do_not_scale_image_data=True)
im_dict[im_idx] = hdulist[0]
if im_idx == 0:
header = hdulist[0].header
#hdulist.info()
#header = hdulist[0].header
#print hdulist[0]
#scidata = hdulist[0].data
#print scidata.shape
#print scidata[0][0][50:100,50:100].shape
#scidata = scidata[0][0][50:350,50:350]
#print scidata.shape
#scidata.shape()
#print scidata
#new_hdu = fits.PrimaryHDU(scidata[0][0][50:100,50:100])
keys = im_dict.keys()
#im_noise_arr = [0.135, 0.0014, 0.0014, 0.0005] # noise measured in an empty region in each image
# Calculate the scaled measurement error
noise_area = N_pix_sigma / N_pix_beam
target_area = 1. / N_pix_beam
noise_arr_bckp = []
for idx in range(len(noise_arr)):
noise_arr_bckp.append(noise_arr[idx])
noise_arr[idx] = np.sqrt((((noise_arr[idx]**2.) * target_area**2.) / noise_area) + ((noise_arr[idx]**2.) / target_area))
#print 'Scaled noise: ', noise_arr
#freq_arr = [127.e6, 325.e6, 610.e6, 1425.e6]
#freq_arr = [127.e6, 325.e6]
#freq_arr = [325.e6, 610.e6]
specdata0 = im_dict[keys[0]].data[0][0]
specdata1 = im_dict[keys[1]].data[0][0]
specdata2 = im_dict[keys[2]].data[0][0]
#specdata3 = im_dict[keys[3]].data[0]
islands = where(specdata0 > 0.015, specdata0, 0.)
islands1 = where(islands > 0.11, islands, 0.)
#gauss = spn.filters.gaussian_filter(islands, sigma=3)
imshow(islands1, vmin=0.001, vmax=0.1)
plt.show()
'''
islands = where(specdata0 > 0.015, specdata0, 0.)
mask1 = where(specdata0 > 0.15, 2, 0)
mask2 = where((specdata0 < 0.15) and (specdata0 > 0.11), 1, 0)
mask = mask1 + mask2
mask[0, 0] = 0
imshow(islands, vmin=0.001, vmax=0.01)
plt.show()
imshow(mask, vmin=0.001, vmax=0.01)
plt.show()
watershed = spm.watershed_ift(uint8(islands), mask)
imshow(watershed, vmin=0.001, vmax=0.01)
plt.show()
'''
#specdata = specdata0
'''
inj_age = specdata0
rel_age = specdata1
chisq_red = specdata2
'''
'''
color1,color2 = [],[]
factor = 0.05
num_pix = 0.
curr_pix = 0.
# Calculate the number of pixels in the run
for col in range(len(specdata1[0][:])):
for row in range(len(specdata1[:][0])):
for idx in range(len(noise_arr)):
if idx < 6:
noise_arr[idx] = np.sqrt(noise_arr[idx]**2. + (0.2 * (im_dict[keys[idx]].data[0][0])[col, row])**2.) # scale the LOFAR flux error by 20% in quadrature
#if idx==0: print 'Scaled noise after flux scaling: ', noise_arr[0], 'Flux: ', (im_dict[keys[idx]].data[0][0])[col, row]
else:
if idx == 7:
noise_arr[idx] = np.sqrt(noise_arr[idx]**2. + (0.05 * (im_dict[keys[idx]].data[0][0])[col, row])**2.) # scale the GMRT flux error by 5% in quadrature
else:
noise_arr[idx] = np.sqrt(noise_arr[idx]**2. + (0.05 * (im_dict[keys[idx]].data[0])[col, row])**2.) # scale the GMRT flux error by 5% in quadrature
#print 'Flux: ', (im_dict[keys[0]].data[0][0])[col, row]
#print 'Noise: ', noise_arr[0]
if (im_dict[keys[0]].data[0][0])[col, row] > factor * noise_arr[0] and (im_dict[keys[1]].data[0][0])[col, row] > factor * noise_arr[1] and (im_dict[keys[2]].data[0][0])[col, row] > factor * noise_arr[2] and (im_dict[keys[3]].data[0][0])[col, row] > factor * noise_arr[3] and (im_dict[keys[4]].data[0][0])[col, row] > factor * noise_arr[4] and (im_dict[keys[5]].data[0][0])[col, row] > factor * noise_arr[5] and (im_dict[keys[6]].data[0])[col, row] > factor * noise_arr[6] and (im_dict[keys[7]].data[0][0])[col, row] > factor * noise_arr[7] and (im_dict[keys[8]].data[0])[col, row] > factor * noise_arr[8]:
num_pix += 1.
noise_arr = noise_arr_bckp
for idx in range(len(noise_arr)):
noise_arr[idx] = np.sqrt((((noise_arr[idx]**2.) * target_area**2.) / noise_area) + ((noise_arr[idx]**2.) / target_area))
for col in range(len(specdata1[0][:])):
for row in range(len(specdata1[:][0])):
for idx in range(len(noise_arr)):
if idx < 6:
noise_arr[idx] = np.sqrt(noise_arr[idx]**2. + (0.2 * (im_dict[keys[idx]].data[0][0])[col, row])**2.) # scale the LOFAR flux error by 20% in quadrature
#if idx==0: print 'Scaled noise after flux scaling: ', noise_arr[0], 'Flux: ', (im_dict[keys[idx]].data[0][0])[col, row]
else:
if idx == 7:
noise_arr[idx] = np.sqrt(noise_arr[idx]**2. + (0.05 * (im_dict[keys[idx]].data[0][0])[col, row])**2.) # scale the GMRT flux error by 5% in quadrature
else:
noise_arr[idx] = np.sqrt(noise_arr[idx]**2. + (0.05 * (im_dict[keys[idx]].data[0])[col, row])**2.) # scale the GMRT flux error by 5% in quadrature
#print 'Flux: ', (im_dict[keys[0]].data[0][0])[col, row]
#print 'Noise: ', noise_arr[0]
if (im_dict[keys[0]].data[0][0])[col, row] > factor * noise_arr[0] and (im_dict[keys[1]].data[0][0])[col, row] > factor * noise_arr[1] and (im_dict[keys[2]].data[0][0])[col, row] > factor * noise_arr[2] and (im_dict[keys[3]].data[0][0])[col, row] > factor * noise_arr[3] and (im_dict[keys[4]].data[0][0])[col, row] > factor * noise_arr[4] and (im_dict[keys[5]].data[0][0])[col, row] > factor * noise_arr[5] and (im_dict[keys[6]].data[0])[col, row] > factor * noise_arr[6] and (im_dict[keys[7]].data[0][0])[col, row] > factor * noise_arr[7] and (im_dict[keys[8]].data[0])[col, row] > factor * noise_arr[8]:
#if (specdata1[col,row] > im_noise_arr[1]) and (specdata2[col,row] > im_noise_arr[2]):
#if (specdata0[col,row] > im_noise_arr[0]) and (specdata1[col,row] > im_noise_arr[1]):
flux_arr = []
# Enable for age maps
for idx in range(len(noise_arr)):
if idx < 6:
flux_arr.append((im_dict[keys[idx]].data[0][0])[col, row])
else:
if idx == 7:
flux_arr.append((im_dict[keys[idx]].data[0][0])[col, row])
else:
flux_arr.append((im_dict[keys[idx]].data[0])[col, row])
#inj_age[col, row] = flux_arr[0]
fit_res = fit(freq_arr, flux_arr, noise_arr, 'JP', True)
inj_age[col, row] = fit_res.params[1]
rel_age[col, row] = fit_res.params[0]
chisq_red[col, row] = fit_res.rchi2_min
#print fit_res[1], fit_res[0]
# Enable for spcetral index maps
#flux_arr = [specdata0[col,row], specdata1[col,row], specdata2[col,row], specdata3[col,row]]
#flux_arr = [specdata1[col,row], specdata2[col,row]]
#flux_arr = [specdata0[col,row], specdata1[col,row]]
#specdata[col,row] = np.polyfit(np.log10(freq_arr), np.log10(flux_arr), 1)[0]
# Enable for color-color plot
#color1.append(np.polyfit(np.log10(freq_arr[:2]), np.log10(flux_arr[:2]), 1)[0])
#color2.append(np.polyfit(np.log10(freq_arr[1:]), np.log10(flux_arr[1:]), 1)[0])
curr_pix += 1.
pct_done = int(curr_pix * 10. / num_pix)
sys.stdout.write('\r[{0}] {1}%'.format('#' * (pct_done * 2), pct_done * 10))
sys.stdout.flush()
else:
#specdata[col,row] = NaN
inj_age[col,row] = NaN
rel_age[col,row] = NaN
chisq_red[col, row] = NaN
'''
# Enable for spectral maps
'''
new_hdu = fits.PrimaryHDU(specdata)
new_hdu.header = header
new_hdu.writeto(path + "temp.fits", clobber=True)
im = aplpy.FITSFigure(path + "temp.fits") # Will not read <astropy.io.fits.hdu.image.PrimaryHDU object>, so we have to use a tmp fits file
#im.show_grayscale()
im.show_colorscale(cmap='jet', stretch='linear', vmin=-3.5, vmax=0.5)
im.add_colorbar()
im.add_beam()
'''
'''
# Enable for age maps
inj_hdu = fits.PrimaryHDU(inj_age)
inj_hdu.header = header
inj_hdu.writeto(path + "temp_inj.fits", clobber=True)
inj_map = aplpy.FITSFigure(path + "temp_inj.fits") # Will not read <astropy.io.fits.hdu.image.PrimaryHDU object>, so we have to use a tmp fits file
#inj_map.show_grayscale()
#inj_map.show_colorscale(cmap='jet', stretch='linear')
#inj_map.add_colorbar()
#inj_map.add_beam()
rel_hdu = fits.PrimaryHDU(rel_age)
rel_hdu.header = header
rel_hdu.writeto(path + "temp_rel.fits", clobber=True)
#rel_map = aplpy.FITSFigure(path + "temp_rel.fits") # Will not read <astropy.io.fits.hdu.image.PrimaryHDU object>, so we have to use a tmp fits file
#rel_map.show_grayscale()
#rel_map.show_colorscale(cmap='jet', stretch='linear')
#rel_map.add_colorbar()
#rel_map.add_beam()
chr_hdu = fits.PrimaryHDU(chisq_red)
chr_hdu.header = header
chr_hdu.writeto(path + "temp_chr.fits", clobber=True)
#data = plt.plot(color1, color2, 'or')
#plt.show()
'''
hdulist.close()
def show_images(path):
import aplpy
rel_map = aplpy.FITSFigure(path + "temp_rel.fits") # Will not read <astropy.io.fits.hdu.image.PrimaryHDU object>, so we have to use a tmp fits file
#rel_map.show_grayscale()
rel_map.show_colorscale(cmap='jet', stretch='linear')
rel_map.add_colorbar()
rel_map.add_beam()
inj_map = aplpy.FITSFigure(path + "temp_inj.fits") # Will not read <astropy.io.fits.hdu.image.PrimaryHDU object>, so we have to use a tmp fits file
#inj_map.show_grayscale()
inj_map.show_colorscale(cmap='jet', stretch='linear')
inj_map.add_colorbar()
inj_map.add_beam()
plt.show()
# Calculate the magnetic field in a plasma from equipartition assumptions (Miley, 1980)
# k - ratio of the energy contained in heavy particles vs. that in electrons
# eta - filling factor of the emitting regions
# z - redshift
# th_x - equivalent beam width or source component size in arcsec in direction x
# th_y - equivalent beam width or source component size in arcsec in direction y
# s - path length through the source (kpc) in the line of sight
# phi - angle between the uniform magnetic field and the line of sight
# F_0 - flux density (Jy) or brightness (Jy / beam) of the source region at frequency nu_0
# nu_0 - frequency of measurement in GHz
# nu_1 - lower cutoff frequency in GHz
# nu_2 - upper cutoff frequency in GHz
# sp_in - spectral index (F(nu) ~ nu^sp_in, nu_1 < nu < nu_2)
# gamma_min - Lorentz factor of lowest energy electrons
#
# returns the strength of the equipartition magnetic field in Gauss
def B_field_estimator(k, eta, z, th_x, th_y, s, phi, F_0, nu_0, nu_1, nu_2, sp_in, gamma_min):
B_eq = 5.69e-5 * (((1. + k) / eta) * ((1. + z)**(3. - sp_in)) * (1. / (th_x * th_y * s * np.sin(phi)**(3. / 2.))) * (F_0 / (nu_0**sp_in)) * (((nu_2**(sp_in + 1. / 2.)) - (nu_1**(sp_in + 1. / 2.))) / (sp_in + (1. / 2.))))**(2. / 7.)
print 'Equipartition magnetic fied: B_eq = ', B_eq, ' G'
sp_in = -sp_in
B_eq_corr = 1.1 * (gamma_min**((1. - 2. * sp_in) / (3. + sp_in))) * (B_eq**(7. / (6. + 2. * sp_in)))
print 'Corrected equipartition magnetic fied: B_eq_corr = ', B_eq_corr, ' G'
B_CMB = 3.25 * (1. + z)**2. * 1.e-6
B_min = B_CMB / np.sqrt(3.)
print 'Minimum magnetic field (for maximum particle age): B_max = ', B_min, ' G'
B_IC = np.sqrt(2. / 3.) * B_CMB
print 'IC equivalent magnetic fied: B_IC = ', B_IC, ' G'
print 'CMB equivalent magnetuc filed B_CMB = ', B_CMB, ' G'
# Calculate the magnetic field in a plasma from equipartition assumptions (Govoni, 2004)
# k - ratio of the energy contained in heavy particles vs. that in electrons
# z - redshift
# s - path length through the source (kpc) in the line of sight
# F_0 - Surface brightness (mJy / arcsec^2) of the source region at frequency nu_0
# nu_0 - frequency of measurement in MHz
# nu_1 - lower cutoff frequency in Hz
# nu_2 - upper cutoff frequency in Hz
# sp_in - spectral index (F(nu) ~ nu^sp_in, nu_1 < nu < nu_2)
# gamma_min - Lorentz factor of lowest energy electrons
#
# returns the strength of the equipartition magnetic field in Gauss
def B_field_estimator_1(k, z, s, F_0, nu_0, nu_1, nu_2, sp_in, gamma_min):
sp_in = np.abs(sp_in)
print 'spix = ', sp_in
ksi = ((2. * sp_in - 2.) / (2. * sp_in - 1.)) * ((nu_1**((1. - 2. * sp_in) / 2.) - nu_2**((1. - 2. * sp_in) / 2.)) / (nu_1**(1. - sp_in) - nu_2**(1. - sp_in)))
ksi = 1.72e-12
u_min = ksi * ((1. + k)**(4. / 7.)) * nu_0**((4. * sp_in) / 7.) * (1. + z)**((12. + (4. * sp_in)) / 7.) * F_0**(4. / 7.) * s**(-4. / 7.)
print 'ksi = ', ksi
B_eq = np.sqrt(24. * np.pi * u_min / 7.)
print 'Equipartition magnetic fied: B_eq = ', B_eq, ' G'
sp_in = -sp_in
B_eq_corr = 1.1 * (gamma_min**((1. - 2. * sp_in) / (3. + sp_in))) * (B_eq**(7. / (6. + 2. * sp_in)))
print 'Corrected equipartition magnetic fied: B_eq_corr = ', B_eq_corr, ' G'
def plotModelFit(redshift, meas_frequencies, a_in, model, variant):
# JP model, CI + aging
#t_a = [109.27, 111.85, 79.04, 109.34, 109.87, 76.60, 116.91, 160.35, 52.70, 85.74, 108.18, 109.00, 107.42, 74.58, 82.12, 67.03, 72.61]
#t_i = [0.1, 0.1, 0.53, 0.1, 0.1, 0.58, 0.29, 0.21, 0.44, 0.86, 0.1, 0.1, 0.1, 0.85, 0.65, 0.42, 0.10]
#t_a = [109.27, 111.85, 79.04, 109.34, 109.87, 76.60, 500.0, 160.35, 52.70, 85.74, 108.18, 109.00, 107.42, 74.58, 82.12, 67.03, 72.61, 96.94]
#t_i = [0.1, 0.1, 0.53, 0.1, 0.1, 0.58, 422.70234163, 0.21, 0.44, 0.86, 0.1, 0.1, 0.1, 0.85, 0.65, 0.42, 0.10, 0.028]
#scale = [-1.98994191798e-25, -2.09157957122e-25, 8.93294642352e-26, -1.89206245098e-25, -2.05614089832e-25, 8.36171642773e-26, 4.99058280421e-28, 3.70010017002e-25, 8.2680854393e-26, 6.2498342171e-26, -2.26962884483e-25, -2.45551230387e-25, -2.60744556032e-25, 9.99486468129e-27, 1.21748029245e-26, 3.8872384655e-26, 1.10807781949e-25, 1.94971399534e-24]
t_a = 101.91
t_i = 17.87
scale = 0.05e-23
model_frequencies = linspace(1.e8, 1.5e9, 10)
angle = 1.25663706144
path = '/Users/users/shulevski/brooks/Research_Vault/1431+1331_spix/Images_Feb_2014/'
filename_1 = 'region_data.txt'
filename_2 = 'region_rms.txt'
regions = np.genfromtxt(path + filename_1, comments='#')
rms = np.genfromtxt(path + filename_2, comments='#')
#for idx in range(len(regions)):
#if scale[idx] > 0.:
fig = plt.figure()
axis = fig.add_subplot(111)
axis.grid()
axis.tick_params(axis='x', labelsize=17)
axis.tick_params(axis='y', labelsize=17)
axis.tick_params(length=10)
axis.set_aspect('equal')
#s = Synfit(redshift, t_a[idx], t_i[idx], regions[idx][12], model_frequencies, a_in, scale[idx], angle, model, variant)
s = Synfit(redshift, t_a, t_i, 4.e-6, model_frequencies, a_in, scale, angle, model, variant)
model_flux = s()
#meas_flux = regions[idx][2:11]
meas_flux = [6.90e-2, 1.61e-2, 6.86e-3, 1.38e-3]
rms = [0.0139078986086372, 0.0032216059330584515, 0.00035500461717153059, 5.0854665266358703e-05]
#data = axis.errorbar(meas_frequencies, meas_flux, rms[idx][2:], markerfacecolor='g', ecolor='g', marker='h', markersize=6, alpha=0.75, linestyle='none')
data = axis.errorbar(meas_frequencies, meas_flux, rms, markerfacecolor='g', ecolor='g', marker='h', markersize=6, alpha=0.75, linestyle='none')
data = axis.loglog(model_frequencies, model_flux, '-r')
xlabel('Frequency [Hz]', fontsize=18, fontweight='bold', color='#000000')
ylabel('Flux [Jy]', fontsize=18, fontweight='bold', color='#000000')
title('', fontsize=20, fontweight='bold')
plt.xlim(4.e7, 3.e9)
plt.ylim(1.e-4, 4.0)
plt.show()
def explore_fit_space(mfr, mfl, mfle):
t_a = np.logspace(1., 8.2, 200)
t_i = np.logspace(1., 8.2, 200)
x, y = np.meshgrid(t_a, t_i)
chisq = np.zeros([len(t_a), len(t_a)])
for i in range(len(t_a)):
for j in range(len(t_i)):
print 'Fitting ', i, 'x', j
fitter = fit(mfr, mfl, mfle, 0.1599, -0.7, 4.25e-6, 'CI_off', True, t_a[i] / 1.e6, t_i[j] / 1.e6)
print 'T_a: ', i, 'T_i: ', j
chisq[i, j] = fitter.chi2_min
#chisq[i, j] = np.random.randn(1)
#print chisq.index(np.min(chisq))
#print chisq.index(np.max(chisq))
#imshow(chisq)
plt.figure()
minim = np.amin(chisq)
maxim = np.amax(chisq)
cs = plt.contour(x, y, chisq)
plt.clabel(cs, inline=1, fontsize=10)
cb = plt.colorbar(cs, shrink=0.8, extend='both')
plt.show()
def generate_model_fluxes(redshift, t_a, t_i, B_field, model_frequencies, a_in, scale, angle, model, variant):
s = Synfit(redshift, t_a, t_i, B_field, model_frequencies, a_in, scale, angle, model, variant)
print s()
'''
model_fluxes = s()
fig = plt.figure()
axis = fig.add_subplot(111)
axis.grid()
axis.tick_params(axis='x', labelsize=17)
axis.tick_params(axis='y', labelsize=17)
axis.tick_params(length=10)
axis.set_aspect('equal')
data = axis.loglog(model_frequencies, model_fluxes, '-r')
xlabel('Frequency [Hz]', fontsize=18, fontweight='bold', color='#000000')
ylabel('Flux [Jy]', fontsize=18, fontweight='bold', color='#000000')
title('Model', fontsize=20, fontweight='bold')
plt.xlim(4.e7, 3.e9)
plt.ylim(1.e-4, 4.0)
plt.show()
'''
# B [\muG], nu_b [GHz]
def age_estimate(B, z, nu_b):
B_IC = 3.25 * (1. + z)**2.
return 1590. * ((B**0.5) / ((B**2. + B_IC**2.) * ((1. + z) * nu_b)**0.5))
# B [\muG], nu_b [GHz], t_s = t_a + t_i [Myr]
def break_estimate(B, z, t_s):
B_IC = 3.25 * (1. + z)**2.
return B / ((1. + z) * ((t_s / 1590.) * (B**2. + B_IC**2.))**2.)
def convert_data_synage():
freq_arr = [120.e6, 127.e6, 135.e6, 145.e6, 154.e6, 164.e6, 325.e6, 610.e6, 1425.e6]
path = '/Users/users/shulevski/brooks/Research_Vault/1431+1331_spix/Images_Feb_2014/'
fluxfile = 'region_data.txt'
rmsfile = 'region_rms.txt'
flux_regions = np.genfromtxt(path + fluxfile, comments='#')
rms_regions = np.genfromtxt(path + rmsfile, comments='#')
f = open('/Users/users/shulevski/Desktop/Synage_input_regions_allLP.tab', 'w')
f.write('freq_units: MHz\nflux_units: Jy\n\n')
for flr, rmr in zip(flux_regions, rms_regions):
f.write('point ' + str(int(flr[0]) - 1) + '\nlabel: Region' + str(int(flr[0])) + '\n\n')
f.write(str(freq_arr[0] / 1.e6) + ' ' + str(flr[2]) + ' ' + str(rmr[2]) + '\n')
f.write(str(freq_arr[1] / 1.e6) + ' ' + str(flr[3]) + ' ' + str(rmr[3]) + '\n')
f.write(str(freq_arr[2] / 1.e6) + ' ' + str(flr[4]) + ' ' + str(rmr[4]) + '\n')
f.write(str(freq_arr[3] / 1.e6) + ' ' + str(flr[5]) + ' ' + str(rmr[5]) + '\n')
f.write(str(freq_arr[4] / 1.e6) + ' ' + str(flr[6]) + ' ' + str(rmr[6]) + '\n')
f.write(str(freq_arr[5] / 1.e6) + ' ' + str(flr[7]) + ' ' + str(rmr[7]) + '\n')
f.write(str(freq_arr[6] / 1.e6) + ' ' + str(flr[8]) + ' ' + str(rmr[8]) + '\n')
f.write(str(freq_arr[7] / 1.e6) + ' ' + str(flr[9]) + ' ' + str(rmr[9]) + '\n')
f.write(str(freq_arr[8] / 1.e6) + ' ' + str(flr[10]) + ' ' + str(rmr[10]) + '\n\n')
def read_synage_model_compute_ages():
# CIoff_fixed_07_allLP
#path = '/Users/users/shulevski/Desktop/all_fits_synage/CIoff-fixed_07_allLP/'
#modelfile = 'regions_allLP_CIOFF_0.7fixed.txt'
# CIoff_fixed_07_oneLP
#path = '/Users/users/shulevski/Desktop/all_fits_synage/CIoff-fixed_07_oneLP/'
#modelfile = 'regions_oneLP_CIOFF_0.7fixed.txt'
# CIoff_free_allLP
#path = '/Users/users/shulevski/Desktop/all_fits_synage/CIoff-free_allLP/'
#modelfile = 'regions_allLP_CIOFF.txt'
# JP_free_allLP
path = '/Users/users/shulevski/Desktop/all_fits_synage/JP-free_allLP/'
modelfile = 'regions_allLP_JP.txt'
# JP_fixed_allLP
#path = '/Users/users/shulevski/Desktop/all_fits_synage/JP-fixed_07_allLP/'
#modelfile = 'regions_allLP_JP_0.7fixed.txt'
# JP_fixed_oneLP
#path = '/Users/users/shulevski/Desktop/all_fits_synage/JP-fixed_07_oneLP/'
#modelfile = 'regions_oneLP_JP_0.7fixed.txt'
model_regions = np.genfromtxt(path + modelfile, comments='#')
# NE: 70" x 50", alpha = -2.04
B_NE = B_field_estimator(1., 1., 0.1599, 50., 70., 5.6e3, np.pi / 2., 0.29, 0.325, 0.01, 100., -2.04)
# SW: 23" x 25", alpha = -1.66
B_SW = B_field_estimator(1., 1., 0.1599, 25., 23., 76.54, np.pi / 2., 3.01e-2, 0.325, 0.01, 100., -1.66)
print 'B_SW: ', B_SW, 'B_NE: ', B_NE, 'B_4C: ', B_field_estimator(1., 1., 0.1599, 50., 70., 5.6e3, np.pi / 2., 364.8e-3, 0.325, 0.01, 100., -1.76), 'Age 4C: ', age_estimate(1.46, 0.1559, 74 * 1.e-3)
t_arr = []
t_arr_e_lo = []
t_arr_e_hi = []
toff_arr = []
toff_arr_e_lo = []
toff_arr_e_hi = []
for region in model_regions:
if int(region[0]) + 1 <= 11:
B = B_NE
else:
B = B_SW
t = age_estimate(float(B) * 1.e6, 0.1559, float(region[5]) * 1.e-3)
t_e_lo = age_estimate(float(B) * 1.e6, 0.1559, (float(region[5]) + float(region[6])) * 1.e-3)
t_e_hi = age_estimate(float(B) * 1.e6, 0.1559, (float(region[5]) + float(region[7])) * 1.e-3)
t_arr.append(t)
t_arr_e_lo.append(t_e_lo)
t_arr_e_hi.append(t_e_hi)
print 'Region ', int(region[0]) + 1, ' is ', t, ' Myr old, + ', t_e_lo, ' - ', t_e_hi, ' Myr.'
if 'CI' in modelfile:
t_off = float(region[14]) * t
t_off_e_lo = abs((float(region[15]))) * t
t_off_e_hi = float(region[16]) * t
toff_arr.append(t_off)
toff_arr_e_lo.append(t_off_e_lo)
toff_arr_e_hi.append(t_off_e_hi)
print 'T_OFF: ', t_off, ' Myr - ', t_off_e_lo, ' Myr + ', t_off_e_hi, 'Myr'
print t_arr
print t_arr_e_lo
print t_arr_e_hi
if 'CI' in modelfile:
print toff_arr
print toff_arr_e_lo
print toff_arr_e_hi
def color_shift():
'''
#J1431.8+1331
freq_arr = np.array([120.e6, 127.e6, 135.e6, 145.e6, 154.e6, 164.e6, 325.e6, 610.e6, 1425.e6])
#path = '/Users/users/shulevski/brooks/Research_Vault/1431+1331_spix/Images_Feb_2014/'
path = '/Users/shulevski/Documents/Kapteyn/1431+1331_spix/Images_Feb_2014/'
fluxfile = 'region_data.txt'
rmsfile = 'region_rms.txt'
flux_regions = np.genfromtxt(path + fluxfile, comments='#')
rms_regions = np.genfromtxt(path + rmsfile, comments='#')
dn_select = [2, 3, 6]
up_select = [6, 7, 8]
'''
#'''
#B2 0924+30
#path = '/Users/users/shulevski/brooks/Research_Vault/B20924+30/August_2014/HBA_Low_Res/Spix/'
#fluxfile = 'region_data.txt'
#freq_arr = np.array([132., 136., 160., 163., 167., 609., 1400.]) * 1.e6
#flux_regions = np.genfromtxt(path + fluxfile, comments='#')
#'''
path = '/Users/shulevski/Documents/Kapteyn/B20924+30_spix/'
fluxfile = 'region_data_new.txt'
'''
freq = np.array([113., 132., 136., 159., 163., 167., 609., 1400.]) * 1.e6
flux_regions = np.genfromtxt(path + fluxfile, comments='#')
mask = np.array([1., 1., 1., 1., 1., 1., 0., 0.]) * 1.e-3
beam_pix_num = np.array([23., 23., 23., 23., 23., 23., 27., 28.])
rms_pix_num = np.array([1392., 1392., 1392., 1392., 1392.,1392., 1757., 1757.])
'''
freq_arr = np.array([113., 132., 136., 159., 163., 167., 609., 1400.]) * 1.e6
flux_regions = np.genfromtxt(path + fluxfile, comments='#')
mask = np.array([1., 1., 1., 1., 1., 1., 0., 0.]) * 1.e-3
beam_pix_num = np.array([28., 28., 28., 28., 28., 28., 27., 28.])
rms_pix_num = np.array([1008., 1008., 1008., 1008., 1008., 1008., 1008., 1008.])
#dn_select = [0, 1, 2, 3, 4, 5]
dn_select = [2, 6]
up_select = [6, 7]
freqs_dn = freq_arr[dn_select]
freqs_up = freq_arr[up_select]
spec_dn = []
spec_up = []
spec_dn_err = []
spec_up_err = []
spec_tot = []
flux_tot = []
freq_tot = []
rms_tot = []
labels = []
mod_spec_dn_KGJP = []
mod_spec_up_KGJP = []
mod_spec_dn_CIJP = []
mod_spec_up_CIJP = []
mod_spec_dn_JP = []
mod_spec_up_JP = []
mod_spec_dn_KGJP_1 = []
mod_spec_up_KGJP_1 = []