-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbending_analysis.py
2559 lines (2191 loc) · 100 KB
/
bending_analysis.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 logging, urllib2, time, json, os
import pymongo, bson
import numpy as np
import StringIO, gzip
import csv
import pandas as pd
from astropy.io import fits
from astropy import wcs, coordinates as coord, units as u
from astropy.cosmology import Planck13 as cosmo
from scipy.optimize import brentq, curve_fit, leastsq
from scipy.interpolate import interp1d
from scipy.integrate import simps
from scipy import stats
from skgof import ad_test
from sklearn.metrics import r2_score
from processing import SDSS_select
from consensus import rgz_path, data_path, db, version
from processing import *
import contour_path_object as cpo
completed_file = '%s/bending_completed%s.txt' % (rgz_path, version)
# For internal use
from pprint import pprint
import itertools
from sklearn.decomposition import PCA
from corner import corner
import matplotlib.pyplot as plt
from matplotlib import rc
plt.ion()
rc('text', usetex=True)
# Connect to Mongo database
version = '_bending'
subjects = db['radio_subjects']
consensus = db['consensus{}'.format(version)]
catalog = db['catalog{}'.format(version)]
whl = db['WHL15']
rm_m = db['redmapper_members']
rm_c = db['redmapper_clusters']
amf = db['AMFDR9']
version = ''
bent_sources = db['bent_sources{}'.format(version)]
bending_15 = db['bending_15{}'.format(version)]
bending_control = db['bending_control{}'.format(version)]
sdss_sample = db['sdss_sample']
xmatch = db['sdss_whl_xmatch']
distant_sources = db['distant_sources']
# Final sample cuts
total_cuts = {'RGZ.size_arcmin':{'$lte':1.5}, 'RGZ.overedge':0, 'RGZ.radio_consensus':{'$gte':0.65}, 'using_peaks.bending_corrected':{'$lte':135.}, 'best':{'$exists':True}}
# Get dictionary for finding the path to FITS files and WCS headers
with open('%s/first_fits.txt' % rgz_path) as f:
lines = f.readlines()
pathdict = {}
for l in lines:
spl = l.split(' ')
pathdict[spl[1].strip()] = '%s/rgz/raw_images/RGZ-full.%i/FIRST-IMGS/%s.fits' % (data_path, int(spl[0]), spl[1].strip())
### Functions ###
def get_data(subject):
'''
Returns the radio contours belonging to a single subject field
'''
link = subject['location']['contours'] # Gets url as Unicode string
# Use local file if available
jsonfile = link.split("/")[-1]
jsonfile_path = "{0}/rgz/contours/{1}".format(data_path,jsonfile)
if os.path.exists(jsonfile_path):
with open(jsonfile_path,'r') as jf:
data = json.load(jf)
# Otherwise, read from web
else:
# Reform weblink to point to the direct S3 URL, which will work even with older SSLv3
link_s3 = "http://zooniverse-static.s3.amazonaws.com/"+link.split('http://')[-1]
tryCount = 0
while(True): # In case of error, wait 10 sec and try again; give up after 5 tries
tryCount += 1
try:
compressed = urllib2.urlopen(str(link_s3)).read() #reads contents of url to str
break
except (urllib2.URLError, urllib2.HTTPError) as e:
if tryCount>5:
output('Unable to connect to Amazon Web Services; trying again in 10 min', logging.exception)
raise fn.DataAccessError(message)
logging.exception(e)
time.sleep(10)
tempfile = StringIO.StringIO(compressed) # Temporarily stores contents as file (emptied after unzipping)
uncompressed = gzip.GzipFile(fileobj=tempfile, mode='r').read() # Unzips contents to str
data = json.loads(uncompressed) # Loads JSON object
return data
def get_contours(w, ir_pos, peak_pos, data, peak_count):
'''
Returns a list of Path objects corresponding to each outer contour in the data, in RA and dec coordinates
Removes outer layers until there are two components and a disjoint IR
Removes any contours that aren't in this source
'''
assert (peak_count in [2,3]), 'Not a valid morphology'
# Assemble the contour trees
contour_trees = []
for contour in data['contours']:
tree = cpo.Node(w, contour=contour)
contour_trees.append(tree)
# Remove each contour that doesn't contain a peak from this source
contains_peak = []
for ix, tree in enumerate(contour_trees):
if any(tree.contains(peak_pos)):
contains_peak.append(ix)
contour_trees[:] = [tree for ix, tree in enumerate(contour_trees) if ix in contains_peak]
# Combine the entire source into a single tree
value_at_inf = {'arr':[{'x':-1,'y':-1}, {'x':w._naxis1+1,'y':-1}, {'x':w._naxis1+1,'y':w._naxis2+1}, {'x':-1,'y':w._naxis2+1}, {'x':-1,'y':-1}], 'k':-1}
source_tree = cpo.Node(w)
source_tree.insert(cpo.Node(w, value=value_at_inf))
source_tree.children = contour_trees
# Remove the BCG source if it's a triple
if peak_count == 3:
source_tree.remove_triple_center(ir_pos, peak_pos)
# Increase the contour level until the IR position is outside all the contours
roots = []
source_tree.get_equal_disjoint(ir_pos, roots)
source_tree.children = roots
return source_tree
def get_pos_angle(w, ir, method, method_data):
'''
Determines the position angle between the IR position and the given comparison object
Method:
Contour: from the IR position to the most distant part of the radio contour (data is contour_list)
Peak: from the IR position to the peak of each component (data is source['radio']['peaks'])
'''
if method == 'contour':
contour_sky = coord.SkyCoord(w.wcs_pix2world(method_data.vertices,1), unit=(u.deg,u.deg), frame='icrs')
separation = ir.separation(contour_sky)
pos_angle = ir.position_angle(contour_sky)[separation==np.max(separation)][0]
elif method == 'peak':
pos_angle = ir.position_angle(coord.SkyCoord(method_data['ra'], method_data['dec'], unit=(u.deg,u.deg), frame='icrs'))
return pos_angle
def get_angles(w, ir, method, method_data):
'''
Determines the opening angle of the radio tail and the position angle of the angle bisector
Method:
Contour: from the IR position to the most distant part of the radio contour (data is contour_list)
Peak: from the IR position to the peak of each component (data is source['radio']['peaks'])
'''
assert (method in ['contour', 'peak']), 'Not a valid method'
pos_angle_0 = get_pos_angle(w, ir, method, method_data[0])
pos_angle_1 = get_pos_angle(w, ir, method, method_data[1])
opening_angle = np.abs(pos_angle_1-pos_angle_0).wrap_at(2*np.pi*u.rad)
bending_angle = coord.Angle(np.abs(np.pi*u.rad - opening_angle))
bisector = (pos_angle_1+pos_angle_0)/2.
if np.abs(bisector-pos_angle_0) > np.pi/2*u.rad:
bisector += np.pi*u.rad
bending_angles = {'pos_angle_0':pos_angle_0, 'pos_angle_1':pos_angle_1, 'bending_angle':bending_angle, 'bisector':bisector.wrap_at(2*np.pi*u.rad)}
return bending_angles
def get_global_peaks(w, peak_pos, peaks, contour_tree):
'''
Determines the position of the global maximum for each component in the contour
'''
global_peaks = []
for child in contour_tree.children:
global_peak = {'flux':0}
for peak in [peaks[ix] for ix, elem in enumerate(child.contains(peak_pos)) if elem]:
if peak['flux'] > global_peak['flux']:
global_peak = peak
if global_peak['flux'] > 0:
global_peaks.append(global_peak)
return global_peaks
def curve_intersect(fun1, fun2, xmin, xmax):
'''
Finds the intersection of two curves, bounded in [xmin, xmax]
Returns an array of x values
'''
diff = lambda x: fun1(x)-fun2(x)
x_range = np.linspace(xmin, xmax, 100)
m_sign = np.sign(diff(x_range)).astype(int)
roots = x_range[np.where(m_sign[1:] - m_sign[:-1] != 0)[0] + 1]
# If they don't cross, return None
if len(roots) == 0:
return np.array([])
# If they cross exactly once, find thcone global solution
elif len(roots) == 1:
return np.array([brentq(diff, xmin, xmax)])
# If they cross multiple times, find the local solution between each root
else:
limits = np.concatenate(([xmin], roots, [xmax]))
intersections = np.empty(len(limits)-2)
for ix in range(len(intersections)):
intersections[ix] = brentq(diff, limits[ix], limits[ix+1])
return intersections
def get_colinear_separation(w, ir, peak, contour):
'''
Finds the distance from the host to the edge of the contour, passing through the peak
'''
ir_pos = w.wcs_world2pix(np.array([[ir.ra.deg,ir.dec.deg]]), 1)[0]
peak_pos = w.wcs_world2pix(np.array([[peak['ra'], peak['dec']]]), 1)[0]
# Extrapolate the line connecting the peak to the IR position
slope = (peak_pos[1]-ir_pos[1])/(peak_pos[0]-ir_pos[0])
extrap_pos = ir_pos + w._naxis1*np.array([1.,slope])
extrap_neg = ir_pos - w._naxis1*np.array([1.,slope])
# Split the contours into well-behaved functions
# Roll the array until the first index is the minimum value
x, y = contour.vertices.T
xmin_loc = np.where(x==min(x))[0][0]
x_rot = np.append(np.roll(x[:-1], len(x)-xmin_loc-1), min(x))
y_rot = np.append(np.roll(y[:-1], len(x)-xmin_loc-1), y[xmin_loc])
# Find where the contour doubles back on itself along the x-axis
m_sign = np.sign(x_rot[1:]-x_rot[:-1])
roots = np.where(m_sign[1:] - m_sign[:-1] != 0)[0] + 1
limits = np.concatenate(([0], roots, [len(x_rot)-1]))
# Split the contours at the double-back positions
domains = []
ranges = []
for ix in range(len(limits)-1):
domains.append(x_rot[limits[ix]:limits[ix+1]+1])
ranges.append(y_rot[limits[ix]:limits[ix+1]+1])
# Interpolate the contour segments
c_interps = []
for x_seg, y_seg in zip(domains, ranges):
c_interp = interp1d(x_seg, y_seg, 'linear')
c_interps.append(c_interp)
if peak_pos[0] > ir_pos[0]:
tail = np.vstack((extrap_neg, ir_pos, peak_pos, extrap_pos))
else:
tail = np.vstack((extrap_pos, ir_pos, peak_pos, extrap_neg))
tail_interp = interp1d(tail.T[0], tail.T[1], 'linear')
# Find the intersections of the contours and tail
x_intersects, y_intersects = [], []
for ix, c_interp in enumerate(c_interps):
x_intersect = curve_intersect(tail_interp, c_interp, domains[ix][0], domains[ix][-1])
y_intersect = c_interp(x_intersect)
x_intersects.append(x_intersect)
y_intersects.append(y_intersect)
intersects = np.vstack((np.hstack(x_intersects), np.hstack(y_intersects))).T
# Return the maximum separation between host and edge
intersects_sky = coord.SkyCoord(w.wcs_pix2world(intersects,1), unit=(u.deg,u.deg), frame='icrs')
return max(ir.separation(intersects_sky))
def get_tail_lengths(w, ir, method, contour_list, peaks=None):
'''
Determines angular separation between the IR position and the given comparison object
Method:
Contour: from the IR position to the most distant part of the radio contour
Peak: from the IR position to the peak of the component
'''
tail_lengths = []
if method == 'contour':
for contour in contour_list:
contour_sky = coord.SkyCoord(w.wcs_pix2world(contour.vertices,1), unit=(u.deg,u.deg), frame='icrs')
separation = ir.separation(contour_sky)
tail_lengths.append(np.max(separation))
elif method == 'peak':
assert (peaks is not None), 'No radio peaks provided'
for contour, peak in zip(contour_list, peaks):
tail_lengths.append(get_colinear_separation(w, ir, peak, contour))
return tail_lengths
def peak_edge_ratio(w, ir, peaks, tails):
'''
Calculate the ratio of the distance to the peak and to the edge of each tail (measured on the sky)
'''
ratios = []
for peak, tail in zip(peaks, tails):
peak_pos = coord.SkyCoord(peak['ra'], peak['dec'], unit=(u.deg,u.deg), frame=('icrs'))
ratios.append(ir.separation(peak_pos).deg/tail.deg)
return ratios
def get_z(source):
'''
Returns the best redshift value and uncertainty for the source (only if SDSS)
'''
if 'SDSS' in source and 'spec_redshift' in source['SDSS']:
return source['SDSS']['spec_redshift'], source['SDSS']['spec_redshift_err']
elif 'SDSS' in source and 'photo_redshift' in source['SDSS']:
return source['SDSS']['photo_redshift'], source['SDSS']['photo_redshift_err']
else:
return 0, 0
# elif 'AllWISE' in source and 'photo_redshift' in source['AllWISE']:
# return source['AllWISE']['photo_redshift'], 0
def get_whl(ir, z, z_err, transverse, dz):
'''
Find the corresponding galaxy cluster in the WHL15 catalog
If multiple clusters match, choose the one with least angular separation
'''
# If the galaxy is too close, physical separations become too great on the sky
# Restrict redshifts to at least 0.01
if z < 0.01:
return None
# Maximum separation
max_sep = float(transverse * u.Mpc / cosmo.angular_diameter_distance(z) * u.rad / u.deg)
best_sep = np.inf
cluster = None
for temp_c in whl.find({'RAdeg':{'$gt':ir.ra.deg-max_sep, '$lt':ir.ra.deg+max_sep}, 'DEdeg':{'$gt':ir.dec.deg-max_sep, '$lt':ir.dec.deg+max_sep}, \
'$or':[{'zspec':{'$gt':z-dz, '$lt':z+dz}}, {'zphot':{'$gt':z-dz, '$lt':z+dz}}]}):
current_sep = ir.separation( coord.SkyCoord(temp_c['RAdeg'], temp_c['DEdeg'], unit=(u.deg,u.deg), frame='icrs') )
if (current_sep < best_sep) and (current_sep < max_sep*u.deg):
best_sep = current_sep
cluster = temp_c
return cluster
def get_redmapper(objID, ir, z, z_err, transverse, dz):
'''
Find the corresponding galaxy cluster in the redMaPPer catalog
First check against member catalog, then check radially
If multiple clusters match, choose the one with least angular separation
'''
# If the galaxy is too close, physical separations become too great on the sky
# Restrict redshifts to at least 0.01
if z < 0.01:
return None
member = rm_m.find_one({'ObjID':objID})
if member is not None:
return rm_c.find_one({'ID':member['ID']})
# Maximum separation
max_sep = float(transverse * u.Mpc / cosmo.angular_diameter_distance(z) * u.rad / u.deg)
best_sep = np.inf
cluster = None
for temp_c in rm_c.find({'RAdeg':{'$gt':ir.ra.deg-max_sep, '$lt':ir.ra.deg+max_sep}, 'DEdeg':{'$gt':ir.dec.deg-max_sep, '$lt':ir.dec.deg+max_sep}, \
'$or':[{'zspec':{'$gt':z-dz, '$lt':z+dz}}, {'zlambda':{'$gt':z-dz, '$lt':z+dz}}]}):
current_sep = ir.separation( coord.SkyCoord(temp_c['RAdeg'], temp_c['DEdeg'], unit=(u.deg,u.deg), frame='icrs') )
if (current_sep < best_sep) and (current_sep < max_sep*u.deg):
best_sep = current_sep
cluster = temp_c
return cluster
def get_amf(ir, z, z_err, transverse, dz):
'''
Find the corresponding galaxy cluster in the WHL15 catalog
If multiple clusters match, choose the one with least angular separation
'''
# If the galaxy is too close, physical separations become too great on the sky
# Restrict redshifts to at least 0.01
if z < 0.01:
return None
# Maximum separation
max_sep = float(transverse * u.Mpc / cosmo.angular_diameter_distance(z) * u.rad / u.deg)
best_sep = np.inf
cluster = None
for temp_c in amf.find({'ra':{'$gt':ir.ra.deg-max_sep, '$lt':ir.ra.deg+max_sep}, 'dec':{'$gt':ir.dec.deg-max_sep, '$lt':ir.dec.deg+max_sep}, \
'z':{'$gt':z-dz, '$lt':z+dz}}):
current_sep = ir.separation( coord.SkyCoord(temp_c['ra'], temp_c['dec'], unit=(u.deg,u.deg), frame='icrs') )
if (current_sep < best_sep) and (current_sep < max_sep*u.deg):
best_sep = current_sep
cluster = temp_c
return cluster
def get_bending(source, peak_count):
'''
Calculate all the bending parameters that don't depend on the cluster
'''
assert (peak_count in [2, 3]), 'Not a valid morphology'
subject = subjects.find_one({'zooniverse_id':source['zooniverse_id']})
# Get pixel-to-WCS conversion
fid = subject['metadata']['source']
fits_loc = pathdict[fid]
w = wcs.WCS(fits.getheader(fits_loc, 0))
# Get the location of the source
ir = coord.SkyCoord(source['SDSS']['ra'], source['SDSS']['dec'], unit=(u.deg,u.deg), frame='icrs') if 'SDSS' in source else coord.SkyCoord(source['AllWISE']['ra'], source['AllWISE']['dec'], unit=(u.deg,u.deg), frame='icrs')
ir_pos = w.wcs_world2pix(np.array([[ir.ra.deg,ir.dec.deg]]), 1)
z, z_err = get_z(source)
peaks = source['radio']['peaks']
peak_pos = w.wcs_world2pix(np.array([ [peak['ra'],peak['dec']] for peak in peaks ]), 1)
# Get image parameters for this source
data = get_data(subject)
contour_tree = get_contours(w, ir_pos, peak_pos, data, peak_count)
peaks = get_global_peaks(w, peak_pos, peaks, contour_tree)
if len(peaks) != 2:
output("%s didn't have 2 tails" % source['zooniverse_id'])
return
contour_list = [child.path for child in contour_tree.children if any(child.contains(peak_pos))]
# Using the 'contour' method
# bending_angles = get_angles(w, ir, 'contour', contour_list)
# tail_lengths_apparent = get_tail_lengths(w, ir, 'contour', contour_list)
# tail_lengths_physical = []
# for tail in tail_lengths_apparent:
# tail_lengths_physical.append(cosmo.angular_diameter_distance(z) * tail.to(u.rad)/u.rad)
# ratios = peak_edge_ratio(w, ir, peaks, tail_lengths_apparent)
# asymmetry = ratios[1]/ratios[0]
# using_contour = {'tail_deg_0':tail_lengths_apparent[0], 'tail_deg_1':tail_lengths_apparent[1], 'size_deg':sum(tail_lengths_apparent), 'tail_kpc_0':float(tail_lengths_physical[0]/u.kpc), 'tail_kpc_1':float(tail_lengths_physical[1]/u.kpc), 'size_kpc':float(sum(tail_lengths_physical)/u.kpc), 'ratio_0':ratios[0], 'ratio_1':ratios[1], 'asymmetry':max(asymmetry,1./asymmetry)}
# using_contour.update(bending_angles)
# for key in using_contour.keys():
# if type(using_contour[key]) is coord.angles.Angle:
# using_contour[key] = using_contour[key].deg
# Using the 'peak' method
bending_angles = get_angles(w, ir, 'peak', peaks)
# tail_lengths_apparent = get_tail_lengths(w, ir, 'peak', contour_list, peaks)
# tail_lengths_physical = []
# for tail in tail_lengths_apparent:
# tail_lengths_physical.append(cosmo.angular_diameter_distance(z) * tail.to(u.rad)/u.rad)
# ratios = peak_edge_ratio(w, ir, peaks, tail_lengths_apparent)
# asymmetry = ratios[1]/ratios[0]
# using_peaks = {'tail_deg_0':tail_lengths_apparent[0], 'tail_deg_1':tail_lengths_apparent[1], 'size_deg':sum(tail_lengths_apparent), 'tail_kpc_0':float(tail_lengths_physical[0]/u.kpc), 'tail_kpc_1':float(tail_lengths_physical[1]/u.kpc), 'size_kpc':float(sum(tail_lengths_physical)/u.kpc), 'ratio_0':ratios[0], 'ratio_1':ratios[1], 'asymmetry':max(asymmetry,1./asymmetry)}
# using_peaks.update(bending_angles)
# for key in using_peaks.keys():
# if type(using_peaks[key]) is coord.angles.Angle:
# using_peaks[key] = using_peaks[key].deg
morphology = 'double' if peak_count == 2 else 'triple'
rgz = {'RGZ_id':source['catalog_id'], 'zooniverse_id':source['zooniverse_id'], 'ir_consensus':source['consensus']['ir_level'], 'radio_consensus':source['consensus']['radio_level'], 'peaks':peaks, 'components':source['radio']['components'], 'morphology':morphology, 'size_arcmin':source['radio']['max_angular_extent']/60., 'size_kpc':float((cosmo.angular_diameter_distance(z)*source['radio']['max_angular_extent']*np.pi/180.)/u.kpc)}
# entry = {'RGZ':rgz, 'using_contour':using_contour, 'using_peaks':using_peaks}
entry = {'RGZ':rgz, 'using_peaks':{}}
if 'SDSS' in source:
entry['SDSS'] = source['SDSS']
if 'AllWISE' in source:
entry['AllWISE'] = source['AllWISE']
best_ra = entry['SDSS']['ra'] if 'SDSS' in entry else entry['AllWISE']['ra']
best_dec = entry['SDSS']['dec'] if 'SDSS' in entry else entry['AllWISE']['dec']
entry['best'] = {'ra':best_ra, 'dec':best_dec, 'redshift':z}
return entry
def make_bent_sources():
'''
Generate a collection of radio sources with bending parameters that don't depend on the cluster
Once generated, various matching schemes to the clusters can be tried efficiently
'''
# Determine which sources have already been processed
completed = []
if os.path.exists(completed_file):
with open(completed_file, 'r') as f:
lines = f.readlines()
for line in lines:
completed.append(int(line))
z_range = [0.01, 0.8]
# 'ignore_bending':False
double_args = {'$and': [{'overedge':0, 'catalog_id':{'$nin':completed}}, \
{'$or': [{'radio.number_peaks':2, 'radio.number_components':1}, \
{'radio.number_components':2}]}, \
{'$or': [{'SDSS.photo_redshift':{'$gte':z_range[0], '$lt':z_range[1]}}, \
{'SDSS.spec_redshift':{'$gte':z_range[0], '$lt':z_range[1]}}, \
{'AllWISE.photo_redshift':{'$gte':z_range[0], '$lt':z_range[1]}}] }]}
triple_args = {'$and': [{'overedge':0, 'catalog_id':{'$nin':completed}}, \
{'$or': [{'radio.number_peaks':3, 'radio.number_components':{'$in':[1,2]}}, \
{'radio.number_components':3}]}, \
{'$or': [{'SDSS.photo_redshift':{'$gte':z_range[0], '$lt':z_range[1]}}, \
{'SDSS.spec_redshift':{'$gte':z_range[0], '$lt':z_range[1]}}, \
{'AllWISE.photo_redshift':{'$gte':z_range[0], '$lt':z_range[1]}}] }]}
# Find the bending parameters for each source that matches
for args,peak_count,morphology in zip([double_args,triple_args], [2,3], ['double','triple']):
count = bent_sources.find({'RGZ.morphology':morphology}).count()
with open(completed_file, 'a') as f:
for source in catalog.find(args).batch_size(50):
entry = get_bending(source, peak_count)
if entry is not None:
count += 1
output('%i %s' % (count, source['zooniverse_id']))
bent_sources.insert(entry)
print >> f, source['catalog_id']
def get_cluster_match(source):
'''
Given a source from RGZ, match it to a cluster and calculate the redshift-dependent bending parameters
'''
ir = coord.SkyCoord(source['SDSS']['ra'], source['SDSS']['dec'], unit=(u.deg,u.deg), frame='icrs') if 'SDSS' in source else \
coord.SkyCoord(source['AllWISE']['ra'], source['AllWISE']['dec'], unit=(u.deg,u.deg), frame='icrs')
z, z_err = get_z(source)
# Match to cluster catalogs
cluster_w = get_whl(ir, z, z_err, 15, 0.04*(1+z))
whl_prop = {}
if cluster_w is not None:
c_pos = coord.SkyCoord(cluster_w['RAdeg'], cluster_w['DEdeg'], unit=(u.deg,u.deg), frame='icrs')
c_sep_arc = c_pos.separation(ir)
c_sep_mpc = float(cosmo.angular_diameter_distance(cluster_w['zspec'] if 'zspec' in cluster_w else cluster_w['zphot'])/u.Mpc * c_sep_arc.to(u.rad)/u.rad)
c_pos_angle = c_pos.position_angle(ir)
if c_sep_mpc/cluster_w['r500'] < 0.01:
pop = 'BCG'
elif c_sep_mpc/cluster_w['r500'] >= 1.5:
pop = 'outer'
else:
pop = 'inner'
whl_prop = {'ra':c_pos.ra.deg, 'dec':c_pos.dec.deg, 'separation_deg':c_sep_arc.deg, 'separation_Mpc':c_sep_mpc, 'position_angle':c_pos_angle.wrap_at(2*np.pi*u.rad).deg, 'r/r500':c_sep_mpc/cluster_w['r500'], 'population':pop, 'zbest':cluster_w['zspec'] if 'zspec' in cluster_w else cluster_w['zphot']}
for key in ['_id', 'N500', 'N500sp', 'RL*500', 'name', 'r500', 'zphot', 'zspec', 'M500']:
if key in cluster_w:
whl_prop[key] = cluster_w[key]
# Only continue if a cluster was matched
if cluster_w is None: #and cluster_r is None and cluster_a is None:
output("%s didn't match to a cluster" % source['RGZ']['zooniverse_id'])
return
else:
z = cluster_w['zspec'] if 'zspec' in cluster_w else cluster_w['zphot']
# Using the 'contour' method
# tail_lengths_apparent = [source['using_contour']['tail_deg_0']*u.deg, source['using_contour']['tail_deg_1']*u.deg]
# tail_lengths_physical = []
# for tail in tail_lengths_apparent:
# tail_lengths_physical.append(cosmo.angular_diameter_distance(z) * tail.to(u.rad)/u.rad)
# using_contour = {'tail_kpc_0':float(tail_lengths_physical[0]/u.kpc), 'tail_kpc_1':float(tail_lengths_physical[1]/u.kpc), 'size_kpc':float(sum(tail_lengths_physical)/u.kpc)}
# source['using_contour'].update(using_contour)
# Using the 'peak' method
# tail_lengths_apparent = [source['using_peaks']['tail_deg_0']*u.deg, source['using_peaks']['tail_deg_1']*u.deg]
# tail_lengths_physical = []
# for tail in tail_lengths_apparent:
# tail_lengths_physical.append(cosmo.angular_diameter_distance(z) * tail.to(u.rad)/u.rad)
# using_peaks = {'tail_kpc_0':float(tail_lengths_physical[0]/u.kpc), 'tail_kpc_1':float(tail_lengths_physical[1]/u.kpc), 'size_kpc':float(sum(tail_lengths_physical)/u.kpc)}
# source['using_peaks'].update(using_peaks)
# Calculate the orientation angle
# for cluster,prop in zip([cluster_w,cluster_r,cluster_a], [whl_prop,rm_prop,amf_prop]):
# if cluster is not None:
cluster, prop = cluster_w, whl_prop
# for method,using in zip(['contour','peaks'], [source['using_contour'],source['using_peaks']]):
for method,using in zip(['peaks'], [source['using_peaks']]):
orientation = coord.angles.Angle(prop['position_angle'] - using['bisector'], unit=u.deg).wrap_at(360.*u.deg).deg
if orientation > 180.:
orientation = 360. - orientation
prop['orientation_%s' % method] = orientation
if orientation > 90.:
orientation = 180. - orientation
prop['orientation_folded'] = orientation
# Compile all results
if cluster_w is not None:
source['WHL'] = whl_prop
# if cluster_r is not None:
# source['redMaPPer'] = rm_prop
# if cluster_a is not None:
# source['AMFDR9'] = amf_prop
return source
def make_catalog():
'''
Find the sources matching the given search parameters and morphology and run the processing pipeline
'''
# Determine which sources have already been processed
completed = []
if os.path.exists(completed_file):
with open(completed_file, 'r') as f:
lines = f.readlines()
for line in lines:
completed.append(int(line))
# Find the bending and cluster results for each source that matches
for peak_count,morphology in zip([2,3], ['double','triple']):
count = bending_15.find({'RGZ.morphology':morphology}).count()
with open(completed_file, 'a') as f:
for source in bent_sources.find({'RGZ.RGZ_id': {'$nin':completed}, 'RGZ.morphology':morphology}).batch_size(50):
entry = get_cluster_match(source)
if entry is not None:
count += 1
output('%i %s' % (count, source['RGZ']['zooniverse_id']))
bending_15.insert(entry)
print >> f, source['RGZ']['RGZ_id']
# Apply the bending correction
bending_correct(plot=False, update=True, methods=['using_peaks'])
def random_control():
'''
Generate a control sample by randomizing the positions and redshifts of all the sources meeting the radio morphology requirements
'''
# Get the original location values
ras1, ras2, decs1, decs2 = [], [], [], []
for source in bent_sources.find():
ra = source['SDSS']['ra'] if 'SDSS' in source else source['AllWISE']['ra']
dec = source['SDSS']['dec'] if 'SDSS' in source else source['AllWISE']['dec']
if 90 < ra < 290:
ras1.append(ra)
decs1.append(dec)
else:
ras2.append(ra)
decs2.append(dec)
# Shuffle the location values
np.random.shuffle(ras1)
np.random.shuffle(ras2)
np.random.shuffle(decs1)
np.random.shuffle(decs2)
loc = np.vstack([ np.append(ras1,ras2), np.append(decs1,decs2) ]).T
np.random.shuffle(loc)
# Find the bending and cluster results for each source that matches
for ix, source in enumerate(bent_sources.find().batch_size(50)):
# Assign the randomized values
if 'SDSS' in source:
source['SDSS'].update({'ra':loc[ix][0], 'dec':loc[ix][1]})
else:
source['SDSS'] = {'ra':loc[ix][0], 'dec':loc[ix][1]}
entry = get_cluster_match(source)
if entry is not None:
output('%i %s' % (ix, source['RGZ']['zooniverse_id']))
bending_control.insert(entry)
def output(string, fn=logging.info):
'''
Print a string to screen and the logfile
'''
fn(string)
print string
def to_file(filename, coll, params={}):
'''
Print the bending collection to a csv file for analysis
'''
rgz_keys = ['RGZ_id', 'zooniverse_id', 'first_id', 'morphology', 'radio_consensus', 'ir_consensus', 'size_arcmin', 'size_kpc', 'solid_angle']
best_keys = ['ra', 'ra_err', 'dec', 'dec_err', 'redshift']
sdss_keys = ['ra', 'dec', 'objID', 'photo_redshift', 'photo_redshift_err', 'spec_redshift', 'spec_redshift_err', 'u', 'u_err', 'g', 'g_err', 'r', 'r_err', 'i', 'i_err', 'z', 'z_err', 'morphological_class', 'spectral_class', 'number_matches']
wise_keys = ['ra', 'dec', 'designation', 'photo_redshift', 'w1mpro', 'w1sigmpro', 'w1snr', 'w2mpro', 'w2sigmpro', 'w2snr', 'w3mpro', 'w3sigmpro', 'w3snr', 'w4mpro', 'w4sigmpro', 'w4snr']
whl_keys = ['name', 'ra', 'dec', 'zphot', 'zspec', 'N500', 'N500sp', 'RL*500', 'M500', 'r500', 'separation_deg', 'separation_Mpc', 'r/r500', 'population', 'position_angle', 'orientation_contour', 'orientation_peaks', 'orientation_folded', 'P', 'P500', 'grad_P', 'alignment']
rm_keys = ['name', 'ra', 'dec', 'zlambda', 'zspec', 'S', 'lambda', 'separation_deg', 'separation_Mpc', 'position_angle', 'orientation_contour', 'orientation_peaks']
amf_keys = ['AMF_id', 'ra', 'dec', 'z', 'r200', 'richness', 'core_radius', 'concentration', 'likelihood', 'separation_deg', 'separation_Mpc', 'position_angle', 'orientation_contour', 'orientation_peaks']
bending_keys = ['pos_angle_0', 'pos_angle_1', 'bending_angle', 'bending_corrected', 'bending_err', 'bending_excess', 'bisector', 'asymmetry'] #, 'tail_deg_0', 'tail_deg_1', 'size_deg', 'tail_kpc_0', 'tail_kpc_1', 'size_kpc', 'ratio_1', 'ratio_0']
all_keys = [rgz_keys, best_keys, sdss_keys, whl_keys, bending_keys, bending_keys]
dict_names = ['RGZ', 'best', 'SDSS', 'WHL', 'using_contour', 'using_peaks']
success = 0
with open(filename, 'w') as f:
header = 'final_sample'
for superkey, key_list in zip(dict_names, all_keys):
for key in key_list:
header += ',%s.%s' % (str(superkey), str(key))
print >> f, header
for entry in coll.find(params):
try:
row = str(entry['final_sample'])
for superkey, key_list in zip(dict_names, all_keys):
for key in key_list:
if superkey in entry and key in entry[superkey]:
if type(entry[superkey][key]) is long or type(entry[superkey][key]) is bson.int64.Int64:
row += ",'%s'" % str(entry[superkey][key])
else:
row += ',%s' % str(entry[superkey][key])
else:
row += ',-99'
print >> f, row
success += 1
except BaseException as e:
output(e, logging.exception)
output('%i/%i successfully printed to %s' % (success, coll.find(params).count(), filename))
def plot_running(x_param, y_param, coll=bending_15, morph=None, pop=None, bin_by=None, bin_count=0, logx=False, logy=False, square=False, bent_cut=0, align=None, combined=False, title=True):
'''
Plot the running 1st, 2nd, and 3rd quartiles averaged over window data points
x_param, y_param, and (optional) bin_by need to be 'category.key' to search for coll[category][key]
morph can be 'double' or 'triple' to select only that morphology
pop can be 'BCG', 'non-BCG', 'inner', or 'outer' to select only that population
When selecting 'non-BCG', combined=True will combine the 'inner' and 'outer' sources before smoothing
align can be 'radial' or 'tangential' to select only that alignment
The axes can be plotted on a log scale by specifying logx and logy to True or False
Also select square=True when plotting log-log plots
Data can be binned with bin_by and bin_count
bent_cut applies a minimum corrected bending angle
'''
assert morph in [None, 'double', 'triple'], "morph must be 'double' or 'triple'"
assert pop in [None, 'BCG', 'inner', 'outer', 'separate', 'non-BCG'], "pop must be 'BCG', 'inner', 'outer', 'separate', or 'non-BCG'"
assert align in [None, 'radial', 'tangential'], "align must be 'radial' or 'tangential'"
if bin_by is not None:
assert type(bin_count) is int and bin_count>0, 'bin_count must be positive int'
# Prepare parameters for search
params = total_cuts.copy()
x_param_list = x_param.split('.')
y_param_list = y_param.split('.')
for param in [x_param, y_param]:
if param in params:
params[param]['$exists'] = True
else:
params[param] = {'$exists':True}
if morph is not None:
params['RGZ.morphology'] = morph
if align is not None:
params['WHL.alignment'] = align
if pop == 'separate':
pop_list = ['inner', 'outer', 'BCG']
elif pop == 'non-BCG':
if combined:
pop_list = [{'$ne':'BCG'}]
else:
pop_list = ['inner', 'outer']
else:
pop_list = [pop]
params['using_peaks.bending_corrected']['$gte'] = bent_cut
# Open the plotting window
fig, ax = plt.subplots()
box = ax.get_position()
# Plot trends for each population of interest
needs_labels = True
windows = set()
if bin_by is not None:
plot_params = {'RGZ.size_arcmin': {'name':"Size (')", 'fmt':'%.2f\n - %.2f', 'width':0.91}, \
'best.redshift': {'name':'Redshift', 'fmt':'%.2f\n - %.2f', 'width':0.89}, \
'WHL.M500': {'name':'Mass', 'fmt':'%.1f\n - %.1f', 'width':0.91}}
bin_by_list = bin_by.split('.')
bins = np.arange(bin_count+1) * 100. / bin_count
vals = []
for i in coll.find(params):
vals.append(i[bin_by_list[0]][bin_by_list[1]])
samples = np.percentile(vals, bins)
ax.plot(0, 0, c='w', label=plot_params[bin_by]['name'])
for pop2 in pop_list:
if pop2 is not None:
params['WHL.population'] = pop2
for i in range(len(samples)-1):
params[bin_by] = {'$gte':samples[i], '$lt':samples[i+1]}
window_size, run_x_50, run_y_50 = get_trends(params, x_param, y_param, coll, True, pop!='BCG')
windows.add(window_size)
if needs_labels:
ax.plot(run_x_50, run_y_50, label=plot_params[bin_by]['fmt'] % (samples[i], samples[i+1]), color='C%i'%i)
ax.set_position([box.x0, box.y0, box.width * plot_params[bin_by]['width'], box.height])
else:
ax.plot(run_x_50, run_y_50, color='C%i'%i)
needs_labels = False
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
else:
for pop2 in pop_list:
if pop2 is not None:
params['WHL.population'] = pop2
window_size, run_x_50, run_y_25, run_y_50, run_y_75 = get_trends(params, x_param, y_param, coll, False, pop!='BCG')
windows.add(window_size)
if needs_labels:
#ax.plot(run_x_50, run_y_75, label='75\%', color='C0')
ax.plot(run_x_50, run_y_50, label='50\%', color='C0')
#ax.plot(run_x_50, run_y_25, label='25\%', color='C2')
ax.fill_between(run_x_50, run_y_25, run_y_75, color='C0', alpha=.5)
#ax.set_position([box.x0, box.y0, box.width * 0.94, box.height])
needs_labels = False
else:
#ax.plot(run_x_50, run_y_75, color='C0')
ax.plot(run_x_50, run_y_50, color='C0')
#ax.plot(run_x_50, run_y_25, color='C2')
ax.fill_between(run_x_50, run_y_25, run_y_75, color='C0', alpha=.5)
# Make the plot pretty
ax.set_xlabel(get_label(x_param))
ax.set_ylabel(get_label(y_param))
windows_txt = str(min(windows))
if len(windows) > 1:
windows_txt += str(-1*max(windows))
titletxt = '%s%s%ssources (window size: %s)' % (morph+' ' if type(morph) is str else '', align+' ' if type(align) is str else '', pop+' ' if type(pop) is str and pop!='separate' else '', windows_txt)
if title:
ax.set_title('All '+titletxt if titletxt[0:7]=='sources' else titletxt[0].upper()+titletxt[1:])
#ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
if logx:
ax.set_xscale('log')
if logy:
ax.set_yscale('log')
if square:
ax.set_aspect('equal', adjustable='box')
if y_param == 'using_peaks.bending_corrected':
params['WHL.population'] = 'outer'
bend = []
for i in coll.find(params):
bend.append(i['using_peaks']['bending_corrected'])
ax.axhline(np.median(bend), ls=':', c='k')
elif y_param == 'using_peaks.bending_excess':
ax.axhline(0, ls=':', c='k')
plt.tight_layout()
def get_trends(params, x_param, y_param, coll, binned, combine_bcg=True):
x_param_list = x_param.split('.')
y_param_list = y_param.split('.')
x, y = [], []
for i in coll.find(params).sort(x_param, 1):
x.append(i[x_param_list[0]][x_param_list[1]])
y.append(i[y_param_list[0]][y_param_list[1]])
x = np.array(x)
y = np.array(y)
window_size = min(len(x)/10, 100)
if 'WHL.population' in params and params['WHL.population'] == 'BCG' and combine_bcg:
run_x_50 = [0.01, 0.011]
run_y_25 = 2*[np.percentile(y, 25)]
run_y_50 = 2*[np.percentile(y, 50)]
run_y_75 = 2*[np.percentile(y, 75)]
else:
run_x_50 = np.array([np.percentile(x[ix:ix+window_size], 50) for ix in np.arange(len(x)-window_size+1)])
run_y_25 = np.array([np.percentile(y[ix:ix+window_size], 25) for ix in np.arange(len(y)-window_size+1)])
run_y_50 = np.array([np.percentile(y[ix:ix+window_size], 50) for ix in np.arange(len(y)-window_size+1)])
run_y_75 = np.array([np.percentile(y[ix:ix+window_size], 75) for ix in np.arange(len(y)-window_size+1)])
if binned:
return window_size, run_x_50, run_y_50
else:
return window_size, run_x_50, run_y_25, run_y_50, run_y_75
def get_label(param):
if param == 'WHL.r/r500':
return 'Separation ($r_{500}$)'
elif param == 'WHL.M500':
return 'Cluster mass ($10^{14}~M_\odot$)'
elif param == 'WHL.P':
return 'ICM pressure (keV cm$^{-3}$)'
elif 'bending_angle' in param:
return 'Bending angle (deg)'
elif 'bending_corrected' in param:
return 'Corrected bending angle (deg)'
elif 'bending_excess' in param:
return 'Excess bending angle (deg)'
elif 'asymmetry' in param:
return 'Asymmetry'
elif param == 'RGZ.size_arcmin':
return 'Size (armin)'
elif param == 'RGZ.size_kpc':
return 'Size (kpc)'
elif param == 'WHL.grad_P':
return 'Pressure gradient (keV cm$^{-3}$ kpc$^{-1}$)'
else:
return param.replace('_', '\_')
def get_params(param_list, coll=bending_15, morph=None, pop=None):
'''
Returns an array of data containing the values of the specified paramters for all sources in the sample
'''
assert morph in [None, 'double', 'triple'], "morph must be 'double' or 'triple'"
assert pop in [None, 'BCG', 'inner', 'outer'], "pop must be 'BCG', 'inner', or 'outer'"
params = total_cuts.copy()
if morph is not None:
params['RGZ.morphology'] = morph
if pop is not None:
params['WHL.population'] = pop
data = np.zeros([len(param_list), coll.find(params).count()])
for jx, gal in enumerate(coll.find(params)):
for ix, param in enumerate(param_list):
datum = gal[param[0]][param[1]]
if datum=='double':
datum = 2
elif datum=='triple':
datum = 3
elif datum=='BCG':
datum = 0
elif datum=='inner':
datum = 1
elif datum=='outer':
datum = 2
data[ix,jx] = datum
return data
def custom_exp(x, a, b):
return a*np.exp(b*x)
def bending_correct(coll=bending_15, window_size=100, plot=False, update=False, methods=None):
'''
Apply a pre-determined correction for the angular size dependence to the bending angle
'''
if methods is None:
methods = ['using_peaks', 'using_contour']
elif type(methods) is str:
methods = [methods]
# Repeat for both morphologies and angle-measuring methods separately
for morph in ['double', 'triple']:
for method in methods:
# Print progress
print morph, method
# Collect data from outer region
sizes, angles, separations = [], [], []
params = total_cuts.copy()
del params['using_peaks.bending_corrected']
params['RGZ.morphology'] = morph
params[method+'.bending_angle'] = total_cuts['using_peaks.bending_corrected']
params['WHL.population'] = 'outer'
for gal in bending_15.find(params).sort('RGZ.size_arcmin', 1):
sizes.append(gal['RGZ']['size_arcmin'])
angles.append(gal[method]['bending_angle'])
separations.append(gal['WHL']['r/r500'])
sizes = np.array(sizes)
angles = np.array(angles)
separations = np.array(separations)
# Find running trend
sizes_running = np.array([np.median(sizes[ix:ix+window_size]) for ix in np.arange(len(sizes)-window_size+1)])
angles_running = np.array([np.median(angles[ix:ix+window_size]) for ix in np.arange(len(angles)-window_size+1)])
# Find best fit
med_size = np.median(sizes)
popt, pcov = curve_fit(custom_exp, sizes_running-med_size, angles_running)
angles_best = custom_exp(sizes-med_size, *popt)
angles_best_running = np.array([np.median(angles_best[ix:ix+window_size]) for ix in np.arange(len(angles_best)-window_size+1)])
# Save fits for comparison
if method == 'using_peaks':
if morph == 'double':
d_x = sizes
d_popt = popt
d_x0 = med_size
else:
t_x = sizes
t_popt = popt
t_x0 = med_size
# Plot fits
if plot:
fig, (ax1, ax2) = plt.subplots(2, sharex=True, gridspec_kw={'height_ratios':[3,1]})
ax1.plot(sizes_running, angles_running, label='Running median')
ax1.plot(sizes_running, angles_best_running, ls='--', label='$%.1fe^{%+.1f(x-%.2f)}$\n$R^2 = %.3f$' % (popt[0], popt[1], med_size, r2_score(angles_running, angles_best_running)))
ax1.legend(loc='upper right')
ax1.set_ylabel('Bending angle (deg)')#('$\\mathrm{%s.bending_angle}$' % method).replace('_', '\_'))
#ax1.set_title('Best fit %s sources' % morph)
ax2.plot(sizes_running, angles_running-angles_best_running, label='residual')
ax2.axhline(0, color='k', lw=1)
ax2.set_xlabel('Size (arcmin)')
ax2.set_ylabel('Residual')
fig.tight_layout()
plt.subplots_adjust(hspace=0.05)
# Insert to Mongo
if update:
for gal in coll.find():
best_angle = custom_exp(gal['RGZ']['size_arcmin']-med_size, *popt)
corr_angle = popt[0] * gal[method]['bending_angle'] / best_angle
coll.update({'_id':gal['_id']}, {'$set': {method+'.bending_corrected':corr_angle}})
get_bending_excess()