-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMakePlots.py
1913 lines (1451 loc) · 69.3 KB
/
MakePlots.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 matplotlib.pyplot as plt
import matplotlib.colors as matcol
import matplotlib as mpl
import matplotlib.patches as mpatches
from matplotlib.lines import Line2D
import seaborn as sns
from astropy.table import Table
import os
import aplpy
import glob
import pandas as pd
import matplotlib.transforms as tf
from astropy.table import Table
from astropy.io import fits
from astropy.stats import biweight_midvariance
from astropy.cosmology import FlatLambdaCDM
from photutils import CircularAperture
from photutils import aperture_photometry
from photutils import Background2D
import numpy as np
from lifelines import KaplanMeierFitter
from lifelines.utils import median_survival_times
from scipy.optimize import curve_fit
from scipy.interpolate import UnivariateSpline
import scipy.stats as st
import astropy.units as u
from mpl_toolkits.axes_grid1 import make_axes_locatable
import CalcSFRs
reload(CalcSFRs)
import WISE
reload(WISE)
import GetGalaxyList
reload(GetGalaxyList)
import Templates
reload(Templates)
kmf = KaplanMeierFitter(alpha=0.16)
####################################################################################
# parameters
# Keep this true
use_imfit = True
# Use plt.annotate to place the names of the galaxies next to points
label_points = False
marker_size = 10
####################################################################################
# Read in astropy table
t = Table.read('table.csv')
# read in Smolcic 2017 COSMOS data
t_survey_raw = Table.read('smolcic.fit')
if use_imfit:
correlation = t['detect']
else:
correlation = np.multiply(t['detect_pix'], t['detect_aper'])
# Table containing detections only
t_detect = t[np.where(correlation == 1)[0]]
# Filter table into 3 separate tables, one for detections, non-detections, and flagged sources (AGN)
t_nondetect = t[np.where(correlation == 0)[0]]
t_ok = t_detect[np.where(t_detect['21 cm SFR'] < 1000)[0]]
t_bad = t_detect[np.where(t_detect['21 cm SFR'] > 1000)[0]]
t_color = t[np.where(~np.isnan(t['w3-w4']))[0]]
t_shift = t_color[np.where(t_color['IR SFR'] > (1.5 * t_color['21 cm SFR']))[0]]
t_else = t_color[np.where((t_color['IR SFR'] < (1.5 * t_color['21 cm SFR'])) & (t_color['21 cm SFR'] < 1000))[0]]
# survey data to plot on top of SFR comparison plot
surv_redshift = np.array(t_survey_raw['zbest'])
surv_rad_lum = np.array(t_survey_raw['logL21cm'])
surv_ir_lum = np.array(t_survey_raw['logLTIRSF'])
# multiplying columns, so we can eliminate data points which don't have all 3 (redshift, radio luminosity, and IR luminosity)
multed = np.multiply(np.multiply(surv_redshift, surv_rad_lum), surv_ir_lum)
t_survey_data = t_survey_raw[np.where(multed > 0)[0]]
# applying redshift cut similar to our sample
surv_z = np.array(t_survey_data['zbest'])
t_survey = t_survey_data[np.where((surv_z > 0.4) & (surv_z < 0.75))]
# Do two weighted linear fits to detections only. Fix the second fit to have a y-intercept of zero
def linear_fit(x_vals, y_vals, x_err, y_err):
# Do first fit with just y errors
tmp_fit = np.polyfit(x_vals, y_vals, 1, w=1. / y_err)
tmp_fit_fn = np.poly1d(tmp_fit)
# Determine total error from previous fit
err_tot = np.sqrt((y_err) ** 2 + (tmp_fit_fn[1] * x_err) ** 2)
# Fit again with total error
fit, residuals, _, _, _ = np.polyfit(x_vals, y_vals, 1, w=1 / err_tot, full=True)
fit_fn = np.poly1d(fit)
print(fit_fn)
# Define linear function for scipy.curve_fit to fit
def func(x, a, b):
return a + b * x
# Fit while holding y intercept to zero, use y errors as weights
tmp_popt_cons, _ = curve_fit(func, x_vals, y_vals, bounds=([0, -10], [1e-10, 10]), sigma=y_err)
# Use fitted function to calculate the total error as a result of x and y errors
new_err_tot = np.sqrt((y_err) ** 2 + (tmp_popt_cons[1] * x_err) ** 2)
# Use the total error to fit the data again
popt_cons, _ = curve_fit(func, x_vals, y_vals, bounds=([0, -10], [1e-10, 10]), sigma=new_err_tot)
held_to_zero = np.poly1d([popt_cons[1], 0])
print(held_to_zero)
"""reduced_chi_squared = residuals[0] / (float(len(x_vals) - 2))
print(reduced_chi_squared)"""
return [fit_fn, held_to_zero]
sfr_to_use = 'MySFR'
err_to_use = 'MySFR Err'
# main plot for paper
# comparing SFRs derived from radio & IR, plus extra axes for comparing luminosities in radio & IR
def plot_all_SFRs():
x_axis_lim = 600
y_axis_lim = 600
# Making arrays of SFRs and uncertainties for non-AGN detections
irsfrok = np.array(t_ok[sfr_to_use]).astype(float)
irok_uncertainty = np.array(t_ok[err_to_use])
##############################
radiosfr_ok = np.array(t_ok['21 cm SFR']).astype(float)
sfr_ok_uncertainty = np.array(t_ok['21 cm SFR Error (stat.)']).astype(float)
names = t_ok['Name']
labels = np.random.randint(0, 3, size=len(irsfrok))
# and for non-detections
ir_non_detect = np.array(t_nondetect[sfr_to_use])
ir_non_unc = np.array(t_nondetect[err_to_use])
radio_non = np.array(t_nondetect['21 cm SFR'])
radio_non_unc = np.array(t_nondetect['21 cm SFR Error (stat.)'])
non_names = t_nondetect['Name']
# Get indices of sources which lie below proposed detection limit
# detect_x_lims = (irsfrok < 30)
# non_detect_x_lims = (ir_non_detect < 30)
# Generate one-to-one line
one_to_one = np.poly1d([1, 0])
# Do the linear fits to non-AGN detections only
#fits = linear_fit(irsfrok, radiosfr_ok, irok_uncertainty, sfr_ok_uncertainty)
# Generate subplots for the broken axis effect, ax2 for majority of data and ax for AGN
#fig, (ax, ax2) = plt.subplots(2, 1, sharex=True, figsize=(8, 10), dpi=300, gridspec_kw={'height_ratios': [1, 4]})
fig, ax = plt.subplots(figsize=(10, 10), dpi=300)
plt.style.use('default')
plt.rcParams["font.family"] = "serif"
plt.rcParams["mathtext.fontset"] = "dejavuserif"
# Plot all data with different markers. For non-detections, make y-axis upper-limit arrows. For sources below
# proposed detection limit, make x-axis upper limit arrows.
ok = ax.errorbar(irsfrok, radiosfr_ok, yerr=sfr_ok_uncertainty, xerr=irok_uncertainty, fmt='o', ecolor='k',
markeredgecolor='b', markerfacecolor='b', capsize=3, ms=marker_size, elinewidth=2.)
non_detect = ax.errorbar(ir_non_detect, radio_non, yerr=2 * radio_non / 20, xerr=ir_non_unc, fmt='o', ecolor='k',
c='gold', capsize=3, uplims=True, marker='o', ms=marker_size, elinewidth=2.)
# Plot the linear fits, the one-to-one line, and the detection limit dashed lines
# fit_line = ax2.plot(np.linspace(0, x_axis_lim), fits[0](np.linspace(0, x_axis_lim)), 'g')
one_to_one_line = ax.plot(np.linspace(0, x_axis_lim), one_to_one(np.linspace(0, x_axis_lim)), 'k', linestyle='--')
fixed_line = ax.plot(np.linspace(0, x_axis_lim), np.poly1d([1. / 2.5, 0])(np.linspace(0, x_axis_lim)), color='k', alpha=0.7, linestyle=':')
# copy of bottom axis to show luminosities
tempax = ax.twinx()
ax2 = tempax.twiny()
# Titles
# plt.suptitle('Star Formation Rate Comparison', y=0.91)
fig.text(0.04, 0.5, '$\mathrm{SFR_{1.5 GHz} \ (M_{\odot} yr^{-1}})$', va='center', rotation='vertical', fontsize=24)
fig.text(0.97, 0.5, '$\mathrm{L_{1.5 GHz}}$ (W Hz $^{-1}$)', va='center', rotation='vertical', fontsize=24)
ax.set_xlabel('$\mathrm{SFR_{IR}} \ (\mathrm{M}_{\odot} \mathrm{yr}^{-1})$', fontsize=24)
ax2.set_xlabel('$\mathrm{L_{IR}}$ (W)', fontsize=24)
# put equations of linear fits on plot
# plt.annotate('%s' % fits[0], (45, 180))
# plt.annotate('%s' % fits[1], (50, 80))
# ratio between radio luminosity (erg/s/Hz) and SFR. Multiplying SFR bounds by this number translates them to lumiosity bounds (W/Hz)
radio_conversion = (t_ok['Luminosity'][0]/1e7)/t_ok['21 cm SFR'][0]
low_sfr_lim = 10.
# Log scales, axis limits
#ax.set_ylim(flagRadioSFR[0] - 10000, flagRadioSFR[0] + 10000)
ax.set_xscale('log')
ax.set_yscale('log')
ax2.set_xscale('log')
ax2.set_yscale('log')
ax.set_ylim(low_sfr_lim, y_axis_lim)
ax2.set_ylim(low_sfr_lim * radio_conversion, y_axis_lim * radio_conversion)
# multiplying an IR SFR limit by this number converts to a luminosity in Watts
# 3.88e-37 is murphy2011 factor
ir_conversion = 1./(3.88e-37)
ax.set_xlim(low_sfr_lim, x_axis_lim)
ax2.set_xlim(low_sfr_lim * ir_conversion, x_axis_lim * ir_conversion)
"""# star forming population defined by any galaxy with SFG = True
SFG = t_survey[np.where(np.array(t_survey['SFG']) == 'T')[0]]
# AGN population defined by any galaxy with EITHER Xray, MIR, or SED flagged AGN
AGN = t_survey[np.where((np.array(t_survey['XrayAGN']) == 'T') | (np.array(t_survey['MIRAGN']) == 'T') | (
np.array(t_survey['SEDAGN']) == 'T'))[0]]
# plot contours of density of points on plot
SFG_plot = sns.kdeplot(((10 ** SFG['logLTIRSF']) * (l_solar)), (10 ** SFG['logL21cm']), ax=ax3, n_levels=4,
cmap='Blues', alpha=0.3)
AGN_plot = sns.kdeplot(((10 ** AGN['logLTIRSF']) * (l_solar)), (10 ** AGN['logL21cm']), ax=ax3, n_levels=4,
cmap='Reds', alpha=0.3)
agn_legend = Line2D([0], [0], marker='o', color='w', label='Scatter',
markerfacecolor='w', markeredgecolor='darkred')
SFG_legend = Line2D([0], [0], marker='o', color='w', label='Scatter',
markerfacecolor='w', markeredgecolor='midnightblue')"""
# Legend
legs = plt.legend((ok, non_detect),
('Detections', '$3\sigma$ Upper Limits'), prop={'size': 18},
loc=2)
ax.tick_params(axis='both', which='both', labelsize=16)
ax2.tick_params(axis='both', which='both', labelsize=16)
tempax.yaxis.set_tick_params(labelsize=16)
ax.text(14.5, 16, '$\mathrm{SFR}_{\mathrm{IR}} = \mathrm{SFR}_{\mathrm{1.5 GHz}}$', rotation=47, rotation_mode='anchor', fontsize=16)
ax.text(39.6, 13, r'$\mathrm{SFR}_{\mathrm{IR}} = 2.5 \times \mathrm{SFR}_{\mathrm{1.5 GHz}}$', rotation=46,
rotation_mode='anchor', fontsize=16)
plt.savefig('SFRs.pdf', overwrite=True, bbox_inches='tight', dpi=400)
plt.clf()
plt.cla()
plt.close()
plt.clf()
plt.cla()
plt.close()
plt.clf()
plt.cla()
plt.close()
# deprecated version of lum vs speed, comparing radio lum and outflow v linearly
"""def lum_v_speed():
lum_ok = np.array(t_ok['Luminosity'])
lum_uncertainty_ok = np.array(t_ok['Luminosity Error (stat.)'])
z_ok = np.array(t_ok['v_out'])
z_uncertainty_ok = 0
names_ok = t_ok['Name']
lum_bad = np.array(t_bad['Luminosity'])
lum_uncertainty_bad = np.array(t_bad['Luminosity Error (stat.)'])
z_bad = np.array(t_bad['v_out'])
z_uncertainty_bad = 0
names_bad = t_bad['Name']
lum_non = np.array(t_nondetect['Luminosity'])
lum_uncertainty_non = np.array(t_nondetect['Luminosity Error (stat.)'])
z_non = np.array(t_nondetect['v_out'])
z_uncertainty_non = 0
names_non = t_nondetect['Name']
fig, (ax, ax2) = plt.subplots(2, 1, sharex=True, figsize=(10, 10), dpi=300, gridspec_kw={'height_ratios': [1, 4]})
ok = ax2.errorbar(z_ok, lum_ok, yerr=lum_uncertainty_ok, xerr=z_uncertainty_ok,
fmt='o', ecolor='k', capsize=2, c='b', ms=marker_size)
bad = ax.errorbar(z_bad, lum_bad, yerr=lum_uncertainty_bad, xerr=z_uncertainty_bad,
fmt='o', ecolor='k', capsize=2, c='r', marker='x', ms=marker_size)
non = ax2.errorbar(z_non, lum_non, yerr=lum_non/5, xerr=z_uncertainty_non,
fmt='o', ecolor='k', capsize=2, c='gold', uplims=True, marker='v', ms=marker_size)
ax.legend((ok, bad, non), ('Detections', 'AGN', 'Non-Detection Upper Limits'))
#plt.suptitle('Luminosity vs. Wind Speed', y=0.92)
fig.text(0.05, 0.5, '1.5 GHz Luminosity (erg s$^{-1}$ Hz$^{-1}$)', va='center', rotation='vertical', fontsize=18)
plt.yscale('log')
plt.xlabel('Outflow Velocity (km s$^{-1}$)', fontsize=18)
# Hack to make the diagonal hashes on broken axis
d = .015 # how big to make the diagonal lines in axes coordinates
# arguments to pass to plot, just so we don't keep repeating them
kwargs = dict(transform=ax.transAxes, color='k', clip_on=False)
ax.plot((-d, +d), (-3.5 * d, 3.5 * d), **kwargs) # top-left diagonal
ax.plot((1 - d, 1 + d), (-3.5 * d, +3.5 * d), **kwargs) # top-right diagonal
# plt.gca().set_aspect('equal', adjustable='box')
kwargs.update(transform=ax2.transAxes) # switch to the bottom axes
ax2.plot((-d, +d), (1 - d, 1 + d), **kwargs) # bottom-left diagonal
ax2.plot((1 - d, 1 + d), (1 - d, 1 + d), **kwargs) # bottom-right diagonal
# hide the spines between ax and ax2
ax.spines['bottom'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax.xaxis.tick_top()
ax.tick_params(labeltop='off') # don't put tick labels at the top
ax2.xaxis.tick_bottom()
if label_points:
for x in range(len(lum_ok)):
plt.annotate((names_ok[x].split('.')[0])[:5], (z_ok[x], lum_ok[x]), xytext=(0, 2), textcoords='offset points',
ha='right', va='bottom')
for x in range(len(lum_bad)):
plt.annotate((names_bad[x].split('.')[0])[:5], (z_bad[x], lum_bad[x]), xytext=(0, 2), textcoords='offset points',
ha='right', va='bottom')
for x in range(len(lum_non)):
plt.annotate((names_non[x].split('.')[0])[:5], (z_non[x], lum_non[x]), xytext=(0, 2), textcoords='offset points',
ha='right', va='bottom')
plt.savefig('lum_vs_speed.png', overwrite=True, bbox_inches=0)
plt.clf()
plt.cla()
plt.close()
plt.clf()
plt.cla()
plt.close()
plt.clf()
plt.cla()
plt.close()"""
# compare sfr derived from radio vs outflow speed (exclude J0827, the radio loud AGN)
def sfr_v_speed():
t_fine = t[np.where((t['21 cm SFR'] < 1000))[0]]
radsfrs = np.log10(np.array(t_fine['21 cm SFR'])/(np.pi * np.square(np.array(t_fine['Re']))))
irsfrs = np.log10(np.array(t_fine['MySFR'])/(np.pi * np.square(np.array(t_fine['Re']))))
vsa = np.array(t_fine['v_out'])
idxs1 = np.where(vsa > 0)[0]
radsfrs = radsfrs[idxs1]
vsa = vsa[idxs1]
irsfrs = irsfrs[idxs1]
# detections
SFR_ok = np.log10(np.array(t_ok['21 cm SFR'])/(np.pi * np.square(np.array(t_ok['Re']))))
SFR_uncertainty_ok = (np.array(t_ok['21 cm SFR Error (stat.)'])/np.array(t_ok['21 cm SFR']))/np.log(10)
irsfr_ok = np.log10(np.array(t_ok['MySFR'])/(np.pi * np.square(np.array(t_ok['Re']))))
irsfr_unc_ok = (np.array(t_ok['MySFR Err'])/np.array(t_ok['MySFR']))/np.log(10)
v_ok = np.array(t_ok['v_out'])
idxs = np.where(v_ok > 0)[0]
SFR_ok = SFR_ok[idxs]
v_ok = v_ok[idxs]
SFR_uncertainty_ok = SFR_uncertainty_ok[idxs]
irsfr_ok = irsfr_ok[idxs]
irsfr_unc_ok = irsfr_unc_ok[idxs]
v_uncertainty_ok = 0
names_ok = t_ok['Name']
# non-detections
SFR_non = np.log10(np.array(t_nondetect['21 cm SFR'])/(np.pi * np.square(np.array(t_nondetect['Re']))))
SFR_uncertainty_non = np.array(t_nondetect['21 cm SFR Error (stat.)'])/np.array(t_nondetect['21 cm SFR'])/np.log(10)
irsfr_non = np.log10(np.array(t_nondetect['MySFR'])/(np.pi * np.square(np.array(t_nondetect['Re']))))
irsfr_unc_non = np.array(t_nondetect['MySFR Err'])/np.array(t_nondetect['MySFR'])/np.log(10)
v_non = np.array(t_nondetect['v_out'])
idxs2 = np.where(v_non > 0)[0]
SFR_non = SFR_non[idxs2]
v_non = v_non[idxs2]
irsfr_non = irsfr_non[idxs2]
irsfr_unc_non = irsfr_unc_non[idxs2]
v_uncertainty_non = 0
names_non = t_nondetect['Name']
"""all_vs = np.log10(np.concatenate((v_ok, v_non)))
all_IR = np.concatenate([irsfr_ok, irsfr_non])
all_rad = np.concatenate([SFR_ok, SFR_non])
print(list(radsfrs), list(np.log10(vsa)))"""
ir_coeff = st.spearmanr(list(irsfrs), list(np.log10(vsa)))
print(ir_coeff[1])
avgerr = np.average(irsfr_unc_ok)
avgerr2 = np.average(irsfr_unc_non)
avgerrfinal = (avgerr+avgerr2)/2
fig = plt.figure(45, (10, 5))
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2, sharey=ax1)
plt.setp(ax2.get_yticklabels(), visible=False)
plt.style.use('default')
plt.rcParams["font.family"] = "serif"
plt.rcParams["mathtext.fontset"] = "dejavuserif"
ok = ax1.scatter(SFR_ok, v_ok, c='b', s=5*marker_size, zorder=3, label='Radio Detections')
non = ax1.scatter(SFR_non, v_non, c='gold', marker='o', s=5*marker_size, zorder=3, label=r'Radio 3$\sigma$ Upper Limits')
ax1.errorbar(SFR_non, v_non, xerr=0.1, fmt='o', ecolor='k', xuplims=True, marker='None', zorder=2)
ax1.axvline(3.47, c='k', linestyle='--')
ax1.text(3.3, 500, 'Eddington Limit', rotation=90)
ax1.text(0.9, 2200, r'$\rho = %s$' % 0.46)
ax2.axvline(3.47, c='k', linestyle='--')
ax2.text(3.3, 500, 'Eddington Limit', rotation=90)
ax2.text(0.9, 2200, r'$\rho = %s$' % round(ir_coeff[0], 2))
ir = ax2.scatter(irsfr_ok, v_ok, c='r', s=5*marker_size, zorder=1, label='IR Detections')
ax2.scatter(irsfr_non, v_non, c='r', s=5*marker_size, zorder=1)
ax1.errorbar(1, 1000, xerr=avgerrfinal, ecolor='gray', capsize=2)
ax2.errorbar(1, 1000, xerr=avgerrfinal, ecolor='gray', capsize=2)
plt.yscale('log')
ax1.set_ylabel(r'Average Mg$_{\mathrm{II}}$ Outflow Velocity (km s$^{-1})$', fontsize=12)
ax1.set_xlabel(r'log$\left(\mathrm{\frac{\Sigma_{SFR_{1.5 GHz}}}{M_{\odot} yr^{-1} kpc^{-2}}} \right)$', fontsize=12)
ax2.set_xlabel(r'log$\left(\mathrm{\frac{\Sigma_{SFR_{IR}}}{M_{\odot} yr^{-1} kpc^{-2}}} \right)$', fontsize=12)
#plt.legend(loc='upper left', prop={'size': 8})
if label_points:
for x in range(len(SFR_ok)):
plt.annotate((names_ok[x].split('.')[0])[:5], (v_ok[x], SFR_ok[x]), xytext=(0, 2),
textcoords='offset points',
ha='right', va='bottom')
for x in range(len(SFR_non)):
plt.annotate((names_non[x].split('.')[0])[:5], (v_non[x], SFR_non[x]), xytext=(0, 2),
textcoords='offset points',
ha='right', va='bottom')
ax2.tick_params(axis='y', which='both', left=False, labelleft=False)
plt.subplots_adjust(wspace=0.05)
plt.savefig('sigma_vs_speed.pdf', overwrite=True, bbox_inches='tight', dpi=400)
plt.clf()
plt.cla()
plt.close()
plt.clf()
plt.cla()
plt.close()
plt.clf()
plt.cla()
plt.close('all')
def plot_lum_vs_z():
es_to_W = 10 ** 7
lum_ok = np.array(t_ok['Luminosity']) / es_to_W
lum_uncertainty_ok = np.array(t_ok['Luminosity Error (stat.)']) / es_to_W
z_ok = np.array(t_ok['Z'])
z_uncertainty_ok = 0
names_ok = t_ok['Name']
lum_bad = np.array(t_bad['Luminosity']) / es_to_W
lum_uncertainty_bad = np.array(t_bad['Luminosity Error (stat.)']) / es_to_W
z_bad = np.array(t_bad['Z'])
z_uncertainty_bad = 0
names_bad = t_bad['Name']
lum_non = np.array(t_nondetect['Luminosity']) / es_to_W
lum_uncertainty_non = np.array(t_nondetect['Luminosity Error (stat.)']) / es_to_W
z_non = np.array(t_nondetect['Z'])
z_uncertainty_non = 0
names_non = t_nondetect['Name']
print(st.spearmanr(list(z_non), list(np.log10(lum_non))))
plt.style.use('default')
plt.rcParams["font.family"] = "serif"
plt.rcParams["mathtext.fontset"] = "dejavuserif"
fig = plt.figure(0, (8, 8))
ok = plt.errorbar(z_ok, lum_ok, yerr=lum_uncertainty_ok, xerr=z_uncertainty_ok,
fmt='o', ecolor='k', capsize=2, c='b', ms=marker_size)
bad = plt.errorbar(z_bad, lum_bad, yerr=lum_uncertainty_bad, xerr=z_uncertainty_bad,
fmt='o', ecolor='k', capsize=2, c='r', marker='x', ms=marker_size)
non = plt.errorbar(z_non, lum_non, yerr=lum_non / 5, xerr=z_uncertainty_non,
fmt='o', ecolor='k', capsize=2, c='gold', uplims=True, marker='o', ms=marker_size)
plt.legend((ok, bad, non), ('Detections', 'Radio AGN', '$3\sigma$ Upper Limits'), loc=2, fontsize=15)
fig.text(0, 0.5, '$\mathrm{L_{1.5GHz}} \ (\mathrm{W \ Hz}^{-1}$)', va='center', rotation='vertical', fontsize=25)
plt.yscale('log')
plt.xlabel('$z$', fontsize=25)
plt.tick_params(axis='both', which='major', labelsize=16)
plt.savefig('lum_vs_z.pdf', overwrite=True, bbox_inches='tight', dpi=400)
plt.clf()
plt.cla()
plt.close()
plt.clf()
plt.cla()
plt.close()
plt.clf()
plt.cla()
plt.close()
def Lum_hist():
plt.clf()
plt.cla()
plt.close()
plt.style.use('default')
plt.rcParams["font.family"] = "serif"
plt.rcParams["mathtext.fontset"] = "dejavuserif"
lums_ok = list(np.array(t_ok['Luminosity']) / (10000000.))
lums_non = list(np.array(t_nondetect['Luminosity']) / (10000000.))
plt.clf()
plt.cla()
plt.close()
plt.close()
plt.close()
plt.close()
#fig = plt.figure(24, (4,3))
colors = ['b', 'gold']
plt.hist([lums_ok, lums_non], bins=20, stacked=True, color=colors, label=['Detections', '$\mathrm{3 \sigma \ Upper \ Limits}$'])
plt.legend()
plt.gca().xaxis.set_major_formatter(plt.ScalarFormatter(useMathText=True))
plt.xlabel('$\mathrm{L_{1.5 GHz} \ (W \ Hz}^{-1}$)', fontsize=18)
plt.ylabel('Number', fontsize=18)
plt.savefig('lum_hist.png', overwrite=True, bbox_inches='tight', dpi=300)
plt.clf()
plt.close()
plt.clf()
plt.cla()
plt.close()
def wise_colors():
""""# w1-w2 vs w3-w4
y_shift = np.array(t_shift['w1-w2']).astype(float)
x_shift = np.array(t_shift['w3-w4']).astype(float)
names = t_shift['Name']
y_else = np.array(t_else['w1-w2']).astype(float)
x_else = np.array(t_else['w3-w4']).astype(float)
else_names = t_else['Name']
plt.clf()
plt.cla()
plt.close()
plt.close()
plt.close()
plt.close()
fig = plt.figure(81)
shifted = plt.scatter(x_shift, y_shift, c='g')
other = plt.scatter(x_else, y_else, c='m')
plt.xlabel('W3-W4')
plt.ylabel('W1-W2')
plt.legend((shifted, other), ('Shifted', 'Other'))
if label_points:
for x in range(len(y_shift)):
plt.annotate((names[x].split('.')[0])[:5], (x_shift[x], y_shift[x]), xytext=(0, 2),
textcoords='offset points', ha='right', va='bottom')
for x in range(len(y_else)):
plt.annotate((else_names[x].split('.')[0])[:5], (x_else[x], y_else[x]), xytext=(0, 2),
textcoords='offset points', ha='right', va='bottom')
plt.savefig('wisecolors.png', overwrite=True, bbox_inches='tight', dpi=300)
plt.clf()
plt.close()
plt.clf()
plt.cla()
plt.close()"""
######################################
# w2-w3
#
Template_colors = True
templates = sorted(
glob.glob('/Users/graysonpetter/Desktop/Dartmouth/HIZEA/hizea-VLA-SFRs/Comprehensive_library/*.txt'))
# wise bandpasses
bandpass = sorted(glob.glob('/Users/graysonpetter/Desktop/Dartmouth/HIZEA/hizea-VLA-SFRs/bandpass/*.txt'))
template_names = []
# corrections to go from AB mags to WISE Vega mags. first entry is 0 so that W1 correction corresponds to 1st index
wise_corr = [0, 2.699, 3.339, 5.174, 6.620]
w_one_two_AB, w_two_three_AB, w_three_four_AB = [], [], []
w_one_two, w_two_three, w_three_four, w_four = [], [], [], []
# Simulate WISE galaxy colors for different types of templates
if Template_colors:
simulation = Templates.simulate_wise_fluxes_for_colors(0.6, templates, bandpass, False)
lums_for_all = simulation[0]
template_names = simulation[1]
for set in lums_for_all:
w_one_two.append((-2.5 * np.log10(set[0] / set[1])) - wise_corr[1] + wise_corr[2])
w_two_three.append((-2.5 * np.log10(set[1] / set[2])) - wise_corr[2] + wise_corr[3])
w_three_four.append(-2.5 * np.log10(set[2]/ set[3]) - wise_corr[3] + wise_corr[4])
w_one_two_AB.append(-2.5 * np.log10(set[0] / set[1]))
w_two_three_AB.append(-2.5 * np.log10(set[1] / set[2]))
w_three_four_AB.append(-2.5 * np.log10(set[2]/ set[3]))
w_four.append(set[3])
t_fine = t[np.where((t['21 cm SFR'] < 1000))[0]]
one_two, two_three, one_two_err, two_three_err = [], [], [], []
names = t_fine['Name']
ir_rad_ratio = np.array(np.array(t_fine[sfr_to_use]/t_fine['21 cm SFR']))
ir_rad_detect = np.array(np.array(t_ok[sfr_to_use] / t_ok['21 cm SFR']))
ir_rad_non = np.array(np.array(t_nondetect[sfr_to_use] / t_nondetect['21 cm SFR']))
for name in names:
wisecolrs = WISE.colors(name[:5])
one_two.append(wisecolrs[0])
one_two_err.append(wisecolrs[3])
two_three.append(wisecolrs[2])
two_three_err.append(wisecolrs[5])
names_detect = t_ok['Name']
names_non = t_nondetect['Name']
onetwo_detect, twothree_detect = [], []
for name in names_detect:
wisecolrs = WISE.colors(name[:5])
onetwo_detect.append(wisecolrs[0])
twothree_detect.append(wisecolrs[2])
onetwo_non, twothree_non = [], []
for name in names_non:
wisecolrs = WISE.colors(name[:5])
onetwo_non.append(wisecolrs[0])
twothree_non.append(wisecolrs[2])
badcolors = WISE.colors('J0827')
onetwo_bad = badcolors[0]
two_three_bad = badcolors[2]
print(one_two_err, two_three_err)
avg_one_two_err = np.median(one_two_err)
avg_two_three_err = np.median(two_three_err)
fig = plt.figure(82)
plt.style.use('default')
plt.rcParams["font.family"] = "serif"
plt.rcParams["mathtext.fontset"] = "dejavuserif"
cmap = matcol.ListedColormap(['#CE03CE', '#D588D5', '#75D77D', '#5AC162', '#45AD4D', '#309A38', '#1E8526', '#13741B', '#0B6011', '#044D0A'])
boundaries = [0, 0.5, 1., 1.5, 2., 2.5, 3, 3.5, 4., 4.5]
norm = matcol.BoundaryNorm(boundaries, cmap.N, clip=True)
colors_detect = plt.scatter(twothree_detect, onetwo_detect, c=ir_rad_detect, cmap=cmap, norm=norm, s=(marker_size*6))
colors_non = plt.scatter(twothree_non, onetwo_non, c=ir_rad_non, cmap=cmap, norm=norm, s=(marker_size * 6))
colors_bad = plt.scatter(two_three_bad, onetwo_bad, c='r', marker='x', s=marker_size*4)
colors_non.set_facecolor('none')
std_errbar = plt.errorbar(2.0, 0.7, yerr=avg_one_two_err, xerr=avg_two_three_err, ecolor='gray', elinewidth=0.5, capsize=2)
cbar = plt.colorbar(colors_detect)
cbar.set_label('$\mathrm{SFR_{IR}/SFR_{1.5\mathrm{GHz}}}$', size=12)
agn_model = [w_two_three[:4], w_one_two[:4], template_names[:4]]
comp_model = [w_two_three[4:8], w_one_two[4:8], template_names[4:8]]
sfg_model = [w_two_three[8:11], w_one_two[8:11], template_names[8:11]]
m1, = plt.plot([], [], c='magenta', marker='o', markersize=10,
fillstyle='left', linestyle='none', markeredgecolor='none')
m2, = plt.plot([], [], c='g', marker='o', markersize=10,
fillstyle='right', linestyle='none', markeredgecolor='none')
agn = plt.scatter(agn_model[0], agn_model[1], c='r', marker='+', alpha=0.5, s=30)
comp = plt.scatter(comp_model[0], comp_model[1], c='#FF9E00', marker='D', alpha=0.5, s=15)
sfg = plt.scatter(sfg_model[0], sfg_model[1], c='b', marker='*', s=40, alpha=0.5)
plt.xlabel('W2-W3 (mag)', size=12)
plt.ylabel('W1-W2 (mag)', size=12)
plt.legend(((m2, m1), colors_bad, agn, comp, sfg), ('This sample', 'Radio-loud AGN', 'AGN Templates', 'Composite Templates', 'SFG Templates'))
#ax = plt.gca()
#legend = ax.get_legend()
#legend.legendHandles[0].set_color(plt.cm.Reds(.8))
"""if label_points:
for x in range(len(one_two)):
plt.annotate((names[x].split('.')[0])[:5], (two_three[x], one_two[x]), xytext=(0, 2),
textcoords='offset points',
ha='right', va='bottom')
#for x in range(len(w_two_three)):
#plt.annotate(template_names[x], (w_two_three[x], w_one_two[x]), xytext=(0, 2), textcoords='offset points',
# ha='right', va='bottom')"""
plt.savefig('wisecolors.pdf', overwrite=True, bbox_inches='tight', dpi=400)
plt.clf()
plt.close()
plt.clf()
plt.cla()
plt.close()
plt.close()
plt.clf()
plt.cla()
plt.close('all')
"""sofia_colors = True
######################################
# sofia c-e vs w4-c
sofia_bands = sorted(glob.glob('/Users/graysonpetter/Desktop/Dartmouth/HIZEA/hizea-VLA-SFRs/SOFIA/HAWC*.csv'))
# templates.extend(sorted(glob.glob('/Users/graysonpetter/Desktop/Dartmouth/HIZEA/hizea-VLA-SFRs/swire_lib/*.sed')))
examps = sorted(glob.glob('/Users/graysonpetter/Desktop/Dartmouth/HIZEA/hizea-VLA-SFRs/swire_lib/*.sed'))
if sofia_colors:
simulation_sof = simulate_colors(templates, sofia_bands, True)
lums_for_all = simulation_sof[0]
template_names = simulation_sof[1]
sof_c_e, w_four_c = [], []
for b in range(len(lums_for_all)):
sof_c_e.append(-2.5 * np.log10(lums_for_all[b][0] / lums_for_all[b][1]))
w_four_c.append(-2.5 * np.log10(w_four[b] / lums_for_all[b][0]))
"simulation_ex_wise = simulate_colors(examps, bandpass, False)
wise_exs = simulation_ex_wise[0]
template_names.extend(simulation_ex_wise[1])
simulation_ex_sof = simulate_colors(examps, sofia_bands, True)
sof_exs = simulation_ex_sof[0]
print wise_exs, sof_exs
for b in range(len(sof_exs)):
sof_c_e.append(-2.5 * np.log10(sof_exs[b][0] / sof_exs[b][1]))
w_four_c.append(-2.5 * np.log10(wise_exs[b][3] / sof_exs[b][0]))"
# HAWC C-E vs W4-C
fig = plt.figure(37)
sof_wise = plt.scatter(sof_c_e, w_four_c, c='k')
plt.xlabel('HAWC C-E')
plt.ylabel('W4-C')
sofia_observed = pd.read_csv('/Users/graysonpetter/Desktop/Dartmouth/HIZEA/hizea-VLA-SFRs/SOFIA/SOFIA_observed.csv', header=None, engine='python')
obs_y = np.array(sofia_observed.iloc[:, 0])
obs_mag = np.array(sofia_observed.iloc[:, 1])
hawc_c_e = obs_mag[len(obs_mag)-2]-obs_mag[len(obs_mag)-1]
y_w_c = obs_mag[len(obs_mag)-3] - obs_mag[len(obs_mag)-2]
obs_point = plt.scatter(hawc_c_e, y_w_c, c='g')
if label_points:
for x in range(len(template_names)):
plt.annotate(template_names[x], (sof_c_e[x], w_four_c[x]), xytext=(0, 2),
textcoords='offset points',
ha='right', va='bottom')
plt.annotate('J1613', (hawc_c_e, y_w_c), xytext=(0, 2),
textcoords='offset points',
ha='right', va='bottom')
plt.savefig('sofia_colors.png', overwrite=True, bbox_inches='tight', dpi=300)
plt.clf()
plt.close()
plt.clf()
plt.cla()
plt.close()
"del sof_c_e[-1]
del sof_c_e[-1]
del template_names[-1]
del template_names[-1]
# HAWC C-E vs W2-W3
fig = plt.figure(178)
plt.scatter(sof_c_e, w_two_three_AB, c='k')
plt.xlabel('HAWC C-E')
plt.ylabel('W2-W3')
if label_points:
for x in range(len(template_names)):
plt.annotate(template_names[x], (sof_c_e[x], w_two_three_AB[x]), xytext=(0, 2),
textcoords='offset points',
ha='right', va='bottom')
plt.savefig('sofia_colors2.png', overwrite=True, bbox_inches='tight', dpi=300)
plt.clf()
plt.close()
plt.clf()
plt.cla()
plt.close()
# HAWC C-E vs W3-W4
fig = plt.figure(6969)
plt.scatter(sof_c_e, w_three_four_AB, c='k')
plt.xlabel('HAWC C-E')
plt.ylabel('W3-W4')
w_three_four_obs = obs_mag[len(obs_mag)-4] - obs_mag[len(obs_mag)-3]
plt.scatter(hawc_c_e, w_three_four_obs, c='g')
if label_points:
for x in range(len(template_names)):
plt.annotate(template_names[x], (sof_c_e[x], w_three_four_AB[x]), xytext=(0, 2),
textcoords='offset points',
ha='right', va='bottom')
plt.savefig('sofia_colors3.png', overwrite=True, bbox_inches='tight', dpi=300)
plt.clf()
plt.close()
plt.clf()
plt.cla()
plt.close()"
#################################
# ir/radio vs w2-w3
devi = np.array(t_shifto['IR SFR'] / t_shifto['21 cm SFR']).astype(float)
col = np.array(t_shifto['w2-w3']).astype(float)
namex = t_shifto['Name']
devio = np.array(abs(t_elseo['IR SFR'] / t_elseo['21 cm SFR'])).astype(float)
colo = np.array(t_elseo['w2-w3']).astype(float)
else_namex = t_elseo['Name']
fig = plt.figure(87)
shiftedini = plt.scatter(col, devi, c='g')
othelo = plt.scatter(colo, devio, c='m')
plt.xlabel('W2-W3')
plt.ylabel('IR SFR/Radio SFR')
plt.legend((shiftedini, othelo), ('Shifted', 'Other'))
if label_points:
for x in range(len(devi)):
plt.annotate((namex[x].split('.')[0])[:5], (col[x], devi[x]), xytext=(0, 2), textcoords='offset points',
ha='right', va='bottom')
for x in range(len(devio)):
plt.annotate((else_namex[x].split('.')[0])[:5], (colo[x], devio[x]), xytext=(0, 2),
textcoords='offset points',
ha='right', va='bottom')
plt.savefig('wisecolors3.png', overwrite=True, bbox_inches='tight', dpi=300)
plt.clf()
plt.close()
plt.clf()
plt.cla()
plt.close()
##############################
# ir/radio vs z
deviat = np.array(abs(t_shifto['IR SFR'] / t_shifto['21 cm SFR'])).astype(float)
coli = np.array(t_shifto['Z']).astype(float)
nameu = t_shifto['Name']
deviato = np.array(abs(t_elseo['IR SFR'] / t_elseo['21 cm SFR'])).astype(float)
colio = np.array(t_elseo['Z']).astype(float)
else_nameu = t_elseo['Name']
fig = plt.figure(88)
linguini = plt.scatter(coli, deviat, c='g')
oreo = plt.scatter(colio, deviato, c='m')
plt.xlabel('Z')
plt.ylabel('IR SFR/Radio SFR')
plt.legend((linguini, oreo), ('Shifted', 'Other'))
if label_points:
for x in range(len(deviat)):
plt.annotate((nameu[x].split('.')[0])[:5], (coli[x], deviat[x]), xytext=(0, 2), textcoords='offset points',
ha='right', va='bottom')
for x in range(len(deviato)):
plt.annotate((else_nameu[x].split('.')[0])[:5], (colio[x], deviato[x]), xytext=(0, 2),
textcoords='offset points',
ha='right', va='bottom')
plt.savefig('wisecolors4.png', overwrite=True, bbox_inches='tight', dpi=300)
plt.clf()
plt.close()
plt.clf()
plt.cla()
plt.close()"""
def sed():
# separate galaxies which lie significantly to the right of 1-to-1 line from remainder of sample
t_shift = t[np.where(t[sfr_to_use] > (1.5 * t['21 cm SFR']))[0]]
t_else = t[np.where(t[sfr_to_use] < (1.5 * t['21 cm SFR']))[0]]
# wavelengths of SDSS UGRIZ + WISE 1,2,3,4
waves = [.3543, .4770, .6231, .7625, .9134, 3.3680, 4.6180, 12.0820, 22.1940]
plt.clf()
plt.cla()
plt.close()
plt.close()
plt.close()
plt.close()
fig = plt.figure(274)
# WISE corrections from VEGA mags to AB
vega_to_ab = [2.699, 3.339, 5.174, 6.620]
standard = 0
magtrack = []
colors = ['r', 'g', 'b', 'k', 'y', 'c', 'm', 'teal', 'orange', 'gold', 'pink', 'lime', 'dimgray', 'seagreen', 'olive', 'saddlebrown', 'lightgray', 'purple', 'tan', 'darkblue']
# Normalize all
for x in range(len(t['Name'])): #for x in range(len(t_shift['Name'])):
wise = Table.read('unWISE/%s.fits' % (t['Name'][x][:5])) #wise = Table.read('unWISE/%s.fits' % (t_shift['Name'][x][:5]))
SDSS = Table.read('SDSS/%s.fits' % (t['Name'][x][:5])) #SDSS = Table.read('SDSS/%s.fits' % (t_shift['Name'][x][:5]))
# normalizing
if x == 0:
standard = wise['w1_mag'] #standard = SDSS['I']
diff = float(standard) - float(wise['w1_mag']) #diff = float(standard) - float(SDSS['I'])
if np.isnan(wise['w4_mag']):
mags = ([SDSS['u'], SDSS['g'], SDSS['r'], SDSS['I'], SDSS['z'], (wise['w1_mag'] + vega_to_ab[0]),
(wise['w2_mag'] + vega_to_ab[1]), (wise['w3_mag'] + vega_to_ab[2]), np.nan])
else:
mags = ([SDSS['u'], SDSS['g'], SDSS['r'], SDSS['I'], SDSS['z'], (wise['w1_mag'] + vega_to_ab[0]),
(wise['w2_mag'] + vega_to_ab[1]), (wise['w3_mag'] + vega_to_ab[2]),
(wise['w4_mag'] + vega_to_ab[3])])
mags = [y + diff for y in mags]
magtrack.append(list(np.array(mags).astype(float).flatten()))
plt.plot(waves[5:9], list(np.array(mags).astype(float).flatten())[5:9], c=colors[x], linewidth=1, label=t['Name'][x][:5])
plt.legend(loc=2)
"""median_mag = []
shift_std = []
median_w_one = 0
for p in range(0, 9):
scoop = [item[p] for item in magtrack]
scoop[:] = [b for b in scoop if b > 0]
median_mag.append(np.median(np.array(scoop)))
if p == 5: