/
SDSS_ML_UMAP.py
2737 lines (2199 loc) · 139 KB
/
SDSS_ML_UMAP.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
# Written by Alex Clarke - https://github.com/informationcake/SDSS-ML
# It will perform dimension reduction with UMAP, and generate plots.
# Pre-requisits: Run SDSS_ML.py to obtain the clean df.
# Version numbers
# python: 3.6.1
# pandas: 0.25.0
# numpy: 1.17.0
# scipy: 1.3.1
# matplotlib: 3.1.1
# sklearn: 0.20.0
# datashader: 0.7.0
# Import functions
import os, sys, glob
import pandas as pd
import numpy as np
import matplotlib as mpl
mpl.use('TKAgg',warn=False, force=True) #set MPL backend.
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import pickle #save/load python data objects (dictionaries/arrays)
import multiprocessing
import itertools
from sklearn import preprocessing
from sklearn.neighbors import NearestNeighbors
import datetime
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
from mpl_toolkits.axes_grid1.colorbar import colorbar
# Previous functions from SDSS_ML_analysis.py
from SDSS_ML_analysis import load_obj, save_obj, histvals, make_cmap
from SDSS_ML import metrics, prepare_data
#from sklearn.manifold import TSNE #single core TSNE, sklearn.
#from MulticoreTSNE import MulticoreTSNE as multiTSNE #multicore TSNE, not sklearn implementation. Must be installed separately. # not used here since UMAP is far better.
import umap
import datashader as ds
import datashader.transfer_functions as tf
from datashader.transfer_functions import shade, stack
from functools import partial
from datashader.utils import export_image
from datashader.colors import *
# list of functions:
# run_umap_spec
# run_umap_photo
# make_cmap
# reverse_colourmap
# plot_umap_ds_SpecObjs_classes
# plot_umap_ds_SpecObjs_probs
# plot_umap_ds_SpecObjs_resolvedr
# plot_umap_ds_SpecObjs_uz
# plot_umap_ds_SpecObjs_w1w2
# plot_umap_ds_PhotoObjs_classes
# plot_umap_ds_PhotoObjs_probs
# plot_umap_ds_PhotoObjs_resolvedr
# plot_umap_ds_PhotoObjs_uz
# plot_umap_ds_PhotoObjs_w1w2
# ------ ------ ------ ------ ------ ------ ------ ------ ------ ------
def run_umap_spec(df, feature_columns, label='unknown', n_neighbors=15, supervised=True, sample_train=True):
# training fraction is hardcoded to whatever was done with the random forest (from predicted data column)
# get rows which were used in the RF training - will not have entries in class_pred
df_train = df.loc[df['class_pred'].isnull()]
df_test = df.loc[df['class_pred'].notnull()]
# training on too much data can cause umap to loose global structures
if sample_train==True:
print('Selecting half the training data...')
# downsample galaxies, there too many, it confuse UMAP
#df_train_g = df_train[df_train['class']=='GALAXY'].sample(frac=0.5)
#df_train_q = df_train[df_train['class']=='QSO']
#df_train_s = df_train[df_train['class']=='STAR']
#df_train = df_train[0::2] # half as much data
df_train = df_train.sample(frac=0.5)
#df_train = pd.concat([df_train_g, df_train_q, df_train_s])
print('Clustering with UMAP')
if supervised==False:
print('Doing unsupervised UMAP')
print('Fitting to {0} data points...'.format(len(df_train)))
u_model = umap.UMAP(random_state=42, n_neighbors=n_neighbors).fit(df_train[feature_columns])
save_obj(u_model, 'umap_model_unsup'+label) # save for use on photometric objects
if supervised==True:
print('Doing supervised UMAP')
print('Fitting to {0} data points...'.format(len(df_train)))
u_model = umap.UMAP(random_state=42, n_neighbors=n_neighbors).fit(df_train[feature_columns], y=df_train['class_i'])
save_obj(u_model, 'umap_model_sup'+label) # save for use on photometric objects
u_train = u_model.transform(df_train[feature_columns])
u_test = u_model.transform(df_test[feature_columns])
#u = pd.DataFrame(u, columns=['x', 'y'], index=data_prep_dict_all['features_train'].index) # index must match original df, particularly if sub-sampled
u_train_df = pd.DataFrame(u_train, columns=['x', 'y'], index=df_train.index) # index must match original df, particularly if sub-sampled
u_test_df = pd.DataFrame(u_test, columns=['x', 'y'], index=df_test.index) # index must match original df, particularly if sub-sampled
u = pd.concat([u_train_df, u_test_df]) # joins the two dfs together
df = df.join(u, how='left') # join UMAP projection to original df
df['class_cat'] = df['class'].astype('category') # datashader requires catagorical type for colour labels.
return df
# ------ ------ ------ ------ ------ ------ ------ ------ ------ ------
def run_umap_photo(df, feature_columns, label='unknown', n_neighbors=15, labels=False):
print('Clustering with UMAP')
print('Fitting to {0} data points...'.format(len(df)))
if labels==False:
print('Doing unsup umap...')
u_model = umap.UMAP(random_state=42, n_neighbors=n_neighbors).fit(df[feature_columns])
if labels==True:
print('Doing sup umap...')
u_model = umap.UMAP(random_state=42, n_neighbors=n_neighbors).fit(df[feature_columns], y=df['class_i'])
print('Transforming sources from fitted model...')
u_train = u_model.transform(df[feature_columns])
u_train_df = pd.DataFrame(u_train, columns=['x_', 'y_'], index=df.index) # index must match original df, particularly if sub-sampled
df = df.join(u_train_df, how='left') # join UMAP projection to original df
df['class_cat'] = df['class_pred'].astype('category') # datashader requires catagorical type for colour labels.
return df
# ------ ------ ------ ------ ------ ------ ------ ------ ------ ------
# custom function to make sequential cmaps from individual colours - some internet person's lovely code:
# http://schubert.atmos.colostate.edu/~cslocum/custom_cmap.html
def make_cmap(colors, position=None, bit=False):
'''
make_cmap takes a list of tuples which contain RGB values. The RGB
values may either be in 8-bit [0 to 255] (in which bit must be set to
True when called) or arithmetic [0 to 1] (default). make_cmap returns
a cmap with equally spaced colors.
Arrange your tuples so that the first color is the lowest value for the
colorbar and the last is the highest.
position contains values from 0 to 1 to dictate the location of each color.
'''
bit_rgb = np.linspace(0,1,256)
if position == None:
position = np.linspace(0,1,len(colors))
else:
if len(position) != len(colors):
sys.exit("position length must be the same as colors")
elif position[0] != 0 or position[-1] != 1:
sys.exit("position must start with 0 and end with 1")
if bit:
for i in range(len(colors)):
colors[i] = (bit_rgb[colors[i][0]],
bit_rgb[colors[i][1]],
bit_rgb[colors[i][2]])
cdict = {'red':[], 'green':[], 'blue':[]}
for pos, color in zip(position, colors):
cdict['red'].append((pos, color[0], color[0]))
cdict['green'].append((pos, color[1], color[1]))
cdict['blue'].append((pos, color[2], color[2]))
cmap = mpl.colors.LinearSegmentedColormap('my_colormap',cdict,256)
return cmap
# ------ ------ ------ ------ ------ ------ ------ ------ ------ ------
def reverse_colourmap(cmap, name = 'my_cmap_r'):
"""
In:
cmap, name
Out:
my_cmap_r
Explanation:
t[0] goes from 0 to 1
row i: x y0 y1 -> t[0] t[1] t[2]
/
/
row i+1: x y0 y1 -> t[n] t[1] t[2]
so the inverse should do the same:
row i+1: x y1 y0 -> 1-t[0] t[2] t[1]
/
/
row i: x y1 y0 -> 1-t[n] t[2] t[1]
"""
reverse = []
k = []
for key in cmap._segmentdata:
k.append(key)
channel = cmap._segmentdata[key]
data = []
for t in channel:
data.append((1-t[0],t[2],t[1]))
reverse.append(sorted(data))
LinearL = dict(zip(k,reverse))
my_cmap_r = mpl.colors.LinearSegmentedColormap(name, LinearL)
return my_cmap_r
#greenyellow springgreen
# ------ ------ ------ ------ ------ ------ ------ ------ ------ ------
def plot_umap_ds_SpecObjs_classes(df, sup, label='unknown'):
# Plotting: use datashader
df_train = df.loc[df['class_pred'].isnull()] # get rows which were used in the RF training - will not have entries in class_pred\
#df_train = df_train[df_train.psf_r>0]
df_test = df.loc[df['class_pred'].notnull()]
#df_test = df_test[df_test.psf_r>0]
# Plot main figure. Save images for both train and test sets
for dfs, label2 in zip([df_train, df_test], ['train', 'test']):
# create png
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
agg = cvs.points(dfs, 'x', 'y', ds.count_cat('class_cat'))
ckey = dict(GALAXY=(101,236,101), QSO='hotpink', STAR='dodgerblue')
#cm = partial(colormap_select, reverse=('black'!="black"))
img = tf.shade(agg, color_key=ckey, how='log')
export_image(img, 'UMAP-'+label+'-'+label2+'-RFclasslabels', fmt='.png', background='black')
# generate figure with png created and append colourbar axis
fig = plt.figure(figsize=(10,10)) # y axis larger to fit cbar in
img = mpimg.imread('UMAP-'+label+'-'+label2+'-RFclasslabels.png')
plt.imshow(img)
plt.gca().set_axis_off()
plt.tick_params(axis='both', which='both', right=False, left=False, top=False, bottom=False)
'''
# create new axis below main axis for colourbar
ax_divider = make_axes_locatable(plt.gca())
cax = ax_divider.append_axes("bottom", size="3%", pad="1%")
# get min and max values from the data binned by datashader to use as limits for the colourbar
a = agg.data[np.nonzero(agg.data)] # remove zeros to stop log colour scale going wrong
vmin = a[np.isfinite(a)].min() # isfinite to ignore nans
vmax = a[np.isfinite(a)].max()
cbar = mpl.pyplot.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax), cmap=mpl.cm.Greys), orientation='horizontal', label='Number of sources', pad=0.01, cax=cax)
cax.tick_params(which='both', labelbottom='off')
'''
# legend for class labels
g_leg = plt.Line2D((0,0),(0,0), color='lightgreen', marker='', linestyle='', label='Galaxies')
q_leg = plt.Line2D((0,0),(0,0), color='hotpink', marker='', linestyle='', label='Quasars')
s_leg = plt.Line2D((0,0),(0,0), color='dodgerblue', marker='', linestyle='', label='Stars')
leg = plt.legend([g_leg, q_leg, s_leg], ['Galaxies', 'Quasars', 'Stars'], frameon=False)
leg_texts = leg.get_texts()
leg_texts[0].set_color('lightgreen')
leg_texts[1].set_color('hotpink')
leg_texts[2].set_color('dodgerblue')
fig.tight_layout()
fig.savefig('UMAP-'+label+'-'+label2+'-RFclasslabels.pdf', bbox_inches='tight')
plt.close(fig)
# ------ ------ ------ ------ ------ ------ ------ ------ ------ ------
def plot_umap_ds_SpecObjs_probs(df, sup, label='unknown', GQSsplit=False):
# Plotting: use datashader
#df_train = df.loc[df['class_pred'].isnull()] # get rows which were used in the RF training - will not have entries in class_pred\
df_test = df.loc[df['class_pred'].notnull()]
#df_test = df_test[df_test.psf_r>0]
# Plot probability mean
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
agg = cvs.points(df_test, 'x', 'y', ds.mean('prob_best'))
img = tf.shade(agg, cmap=prob_mean_c, how='log')
export_image(img, 'UMAP-'+label+'-probs-mean', fmt='.png', background='black')
# generate figure with png created and append colourbar axis
fig = plt.figure(figsize=(10,fheight)) # y axis larger to fit cbar in
img = mpimg.imread('UMAP-'+label+'-probs-mean.png')
plt.imshow(img)
plt.gca().set_axis_off()
plt.tick_params(axis='both', which='both', right=False, left=False, top=False, bottom=False)
# create new axis below main axis for colourbar
ax_divider = make_axes_locatable(plt.gca())
cax = ax_divider.append_axes("bottom", size="3%", pad="1%")
# get min and max values from the data binned by datashader to use as limits for the colourbar
vmin = agg.data[np.isfinite(agg.data)].min() # isfinite to ignore nans
vmax = agg.data[np.isfinite(agg.data)].max()
cbar = mpl.pyplot.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax), cmap=prob_mean_c), orientation='horizontal', label='Mean probability for predicted sources (test dataset)', pad=0.01, cax=cax)
formatter = mpl.ticker.FuncFormatter(lambda y, _: '{:g}'.format(y)) # format cbar labels as decimals, not exponents
cax.xaxis.set_major_formatter(formatter) # apply formatter to major and minor axes
cax.xaxis.set_minor_formatter(formatter)
fig.tight_layout()
fig.savefig('UMAP-'+label+'-probs-mean.pdf', bbox_inches='tight')
plt.close(fig)
# Plot probability STD
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
agg = cvs.points(df_test, 'x', 'y', ds.std('prob_best'))
img = tf.shade(agg, cmap=prob_std_c, how='log')
export_image(img, 'UMAP-'+label+'-probs-std', fmt='.png', background='black')
# generate figure with png created and append colourbar axis
fig = plt.figure(figsize=(10,fheight)) # y axis larger to fit cbar in
img = mpimg.imread('UMAP-'+label+'-probs-std.png')
plt.imshow(img)
plt.gca().set_axis_off()
plt.tick_params(axis='both', which='both', right=False, left=False, top=False, bottom=False)
# create new axis below main axis for colourbar
ax_divider = make_axes_locatable(plt.gca())
cax = ax_divider.append_axes("bottom", size="3%", pad="1%")
# get min and max values from the data binned by datashader to use as limits for the colourbar
a = agg.data[np.nonzero(agg.data)] # remove zeros to stop log colour scale going wrong
vmin = a[np.isfinite(a.data)].min() # drop nans
vmax = a[np.isfinite(a.data)].max()
#vmin=9e-4 # min value is 0.001 so set a little smaller for cbar ticks to be clearer. can't be zero for cbar scale.
print(vmin, vmax)
cbar = mpl.pyplot.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax), cmap=prob_std_c), orientation='horizontal', label='Standard deviation of probabilities for predicted sources (test dataset)', pad=0.01, cax=cax)
cax.tick_params(which='both', labelbottom='off')
#cax.tick_params(which='major', direction='out', length=4)
fig.tight_layout()
fig.savefig('UMAP-'+label+'-probs-std.pdf', bbox_inches='tight')
plt.close(fig)
'''
# Plot mean stack image
# Can i edit this colour select out?
#colors_g = [(1,1,1), (112/255,128/255,144/255)]
#cmap_g = make_cmap(colors_g)
colors_g = [(1,1,1), (144/255,238/255,144/255)]
cmap_g = make_cmap(colors_g)
colors_q = [(1,1,1), (255/255,105/255,180/255)]
cmap_q = make_cmap(colors_q)
colors_s = [(1,1,1), (30/255,144/255,255/255)]
cmap_s = make_cmap(colors_s)
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
agg = cvs.points(df_test, 'x', 'y', ds.mean('prob_best'))
agg_g = cvs.points(df_test, 'x', 'y', ds.mean('prob_g'))
agg_q = cvs.points(df_test, 'x', 'y', ds.mean('prob_q'))
agg_s = cvs.points(df_test, 'x', 'y', ds.mean('prob_s'))
img = stack( tf.shade(agg_g, cmap=cmap_g, how='log', alpha=100),
tf.shade(agg_q, cmap=cmap_q, how='log', alpha=100),
tf.shade(agg_s, cmap=cmap_s, how='log', alpha=100))
export_image(img, 'UMAP'+label+'-meanstack', fmt='.png', background='black')
'''
if GQSsplit==True:
# ------ GALAXIES ------
# Plot mean prob
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
agg = cvs.points(df_test[ (df_test.class_pred=='GALAXY') ], 'x', 'y', ds.mean('prob_g'))
img = tf.shade(agg, cmap=prob_mean_c, how='log')
img = tf.dynspread(img, threshold=threshold_g, max_px=max_px, shape='square', how='over')
export_image(img, 'UMAP-'+label+'-probs-mean-galaxies', fmt='.png', background='black')
# generate figure with png created and append colourbar axis
fig = plt.figure(figsize=(10,fheight)) # y axis larger to fit cbar in
img = mpimg.imread('UMAP-'+label+'-probs-mean-galaxies.png')
plt.imshow(img)
plt.gca().set_axis_off()
plt.tick_params(axis='both', which='both', right=False, left=False, top=False, bottom=False)
# create new axis below main axis for colourbar
ax_divider = make_axes_locatable(plt.gca())
cax = ax_divider.append_axes("bottom", size="3%", pad="1%")
# get min and max values from the data binned by datashader to use as limits for the colourbar
a = agg.data[np.nonzero(agg.data)] # remove zeros to stop log colour scale going wrong
vmin = a[np.isfinite(a)].min() # isfinite to ignore nans
vmax = a[np.isfinite(a)].max()
cbar = mpl.pyplot.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax), cmap=prob_mean_c), orientation='horizontal', label='Mean probability for predicted galaxies (test dataset)', pad=0.01, cax=cax)
formatter = mpl.ticker.FuncFormatter(lambda y, _: '{:g}'.format(y)) # format cbar labels as decimals, not exponents
cax.xaxis.set_major_formatter(formatter) # apply formatter to major and minor axes
cax.xaxis.set_minor_formatter(formatter)
fig.tight_layout()
fig.savefig('UMAP-'+label+'-probs-mean-galaxies.pdf', bbox_inches='tight')
plt.close(fig)
# Plot galaxy std
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
agg = cvs.points(df_test[ (df_test.class_pred=='GALAXY') ], 'x', 'y', ds.std('prob_g'))
img = tf.shade(agg, cmap=prob_std_c, how='log')
img = tf.dynspread(img, threshold=threshold_g, max_px=max_px, shape='square', how='over')
export_image(img, 'UMAP-'+label+'-probs-std-galaxies', fmt='.png', background='black')
# generate figure with png created and append colourbar axis
fig = plt.figure(figsize=(10,fheight)) # y axis larger to fit cbar in
img = mpimg.imread('UMAP-'+label+'-probs-std-galaxies.png')
plt.imshow(img)
plt.gca().set_axis_off()
plt.tick_params(axis='both', which='both', right=False, left=False, top=False, bottom=False)
# create new axis below main axis for colourbar
ax_divider = make_axes_locatable(plt.gca())
cax = ax_divider.append_axes("bottom", size="3%", pad="1%")
# get min and max values from the data binned by datashader to use as limits for the colourbar
a = agg.data[np.nonzero(agg.data)] # remove zeros to stop log colour scale going wrong
vmin = a[np.isfinite(a)].min() # isfinite to ignore nans
vmax = a[np.isfinite(a)].max()
cbar = mpl.pyplot.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax), cmap=prob_std_c), orientation='horizontal', label='Standard deviation of probabilities for predicted galaxies (test dataset)', pad=0.01, cax=cax)
cax.tick_params(which='both', labelbottom='off')
fig.tight_layout()
fig.savefig('UMAP-'+label+'-probs-std-galaxies.pdf', bbox_inches='tight')
plt.close(fig)
# ------ QUASARS ------
# Plot quasar mean probs
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
agg = cvs.points(df[df.class_pred=='QSO'], 'x', 'y', ds.mean('prob_q'))
img = tf.shade(agg, cmap=prob_mean_c, how='log')
img = tf.dynspread(img, threshold=threshold_q, max_px=max_px, shape='square', how='over')
export_image(img, 'UMAP-'+label+'-probs-mean-quasars', fmt='.png', background='black')
# generate figure with png created and append colourbar axis
fig = plt.figure(figsize=(10,fheight)) # y axis larger to fit cbar in
img = mpimg.imread('UMAP-'+label+'-probs-mean-quasars.png')
plt.imshow(img)
plt.gca().set_axis_off()
plt.tick_params(axis='both', which='both', right=False, left=False, top=False, bottom=False)
# create new axis below main axis for colourbar
ax_divider = make_axes_locatable(plt.gca())
cax = ax_divider.append_axes("bottom", size="3%", pad="1%")
# get min and max values from the data binned by datashader to use as limits for the colourbar
a = agg.data[np.nonzero(agg.data)] # remove zeros to stop log colour scale going wrong
vmin = a[np.isfinite(a)].min() # isfinite to ignore nans
vmax = a[np.isfinite(a)].max()
cbar = mpl.pyplot.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax), cmap=prob_mean_c), orientation='horizontal', label='Mean probability for predicted quasars (test dataset)', pad=0.01, cax=cax)
formatter = mpl.ticker.FuncFormatter(lambda y, _: '{:g}'.format(y)) # format cbar labels as decimals, not exponents
cax.xaxis.set_major_formatter(formatter) # apply formatter to major and minor axes
cax.xaxis.set_minor_formatter(formatter)
#cax.tick_params(which='both', labelbottom='off')
fig.tight_layout()
fig.savefig('UMAP-'+label+'-probs-mean-quasars.pdf', bbox_inches='tight')
plt.close(fig)
# Plot quasar std
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
agg = cvs.points(df[df.class_pred=='QSO'], 'x', 'y', ds.std('prob_q'))
img = tf.shade(agg, cmap=prob_std_c, how='log')
img = tf.dynspread(img, threshold=threshold_q, max_px=max_px, shape='square', how='over')
export_image(img, 'UMAP-'+label+'-probs-std-quasars', fmt='.png', background='black')
# generate figure with png created and append colourbar axis
fig = plt.figure(figsize=(10,fheight)) # y axis larger to fit cbar in
img = mpimg.imread('UMAP-'+label+'-probs-std-quasars.png')
plt.imshow(img)
plt.gca().set_axis_off()
plt.tick_params(axis='both', which='both', right=False, left=False, top=False, bottom=False)
# create new axis below main axis for colourbar
ax_divider = make_axes_locatable(plt.gca())
cax = ax_divider.append_axes("bottom", size="3%", pad="1%")
# get min and max values from the data binned by datashader to use as limits for the colourbar
a = agg.data[np.nonzero(agg.data)] # remove zeros to stop log colour scale going wrong
vmin = a[np.isfinite(a)].min() # isfinite to ignore nans
vmax = a[np.isfinite(a)].max()
cbar = mpl.pyplot.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax), cmap=prob_std_c), orientation='horizontal', label='Standard deviation of probabilities for predicted quasars (test dataset)', pad=0.01, cax=cax)
cax.tick_params(which='both', labelbottom='off')
fig.tight_layout()
fig.savefig('UMAP-'+label+'-probs-std-quasars.pdf', bbox_inches='tight')
plt.close(fig)
# ------ STARS ------
# Plot star probs
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
agg = cvs.points(df[df.class_pred=='STAR'], 'x', 'y', ds.mean('prob_s'))
img = tf.shade(agg, cmap=prob_mean_c, how='log')
img = tf.dynspread(img, threshold=threshold_s, max_px=max_px, shape='square', how='over')
export_image(img, 'UMAP-'+label+'-probs-mean-stars', fmt='.png', background='black')
# generate figure with png created and append colourbar axis
fig = plt.figure(figsize=(10,fheight)) # y axis larger to fit cbar in
img = mpimg.imread('UMAP-'+label+'-probs-mean-stars.png')
plt.imshow(img)
plt.gca().set_axis_off()
plt.tick_params(axis='both', which='both', right=False, left=False, top=False, bottom=False)
# create new axis below main axis for colourbar
ax_divider = make_axes_locatable(plt.gca())
cax = ax_divider.append_axes("bottom", size="3%", pad="1%")
# get min and max values from the data binned by datashader to use as limits for the colourbar
a = agg.data[np.nonzero(agg.data)] # remove zeros to stop log colour scale going wrong
vmin = a[np.isfinite(a)].min() # isfinite to ignore nans
vmax = a[np.isfinite(a)].max()
cbar = mpl.pyplot.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax), cmap=prob_mean_c), orientation='horizontal', label='Mean probability for predicted stars (test dataset)', pad=0.01, cax=cax)
formatter = mpl.ticker.FuncFormatter(lambda y, _: '{:g}'.format(y)) # format cbar labels as decimals, not exponents
cax.xaxis.set_major_formatter(formatter) # apply formatter to major and minor axes
cax.xaxis.set_minor_formatter(formatter)
#cax.tick_params(which='both', labelbottom='off')
fig.tight_layout()
fig.savefig('UMAP-'+label+'-probs-mean-stars.pdf', bbox_inches='tight')
plt.close(fig)
# Plot star std
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
agg = cvs.points(df[df.class_pred=='STAR'], 'x', 'y', ds.std('prob_s'))
img = tf.shade(agg, cmap=prob_std_c, how='log')
img = tf.dynspread(img, threshold=threshold_s, max_px=max_px, shape='square', how='over')
export_image(img, 'UMAP-'+label+'-probs-std-stars', fmt='.png', background='black')
# generate figure with png created and append colourbar axis
fig = plt.figure(figsize=(10,fheight)) # y axis larger to fit cbar in
img = mpimg.imread('UMAP-'+label+'-probs-std-stars.png')
plt.imshow(img)
plt.gca().set_axis_off()
plt.tick_params(axis='both', which='both', right=False, left=False, top=False, bottom=False)
# create new axis below main axis for colourbar
ax_divider = make_axes_locatable(plt.gca())
cax = ax_divider.append_axes("bottom", size="3%", pad="1%")
# get min and max values from the data binned by datashader to use as limits for the colourbar
a = agg.data[np.nonzero(agg.data)] # remove zeros to stop log colour scale going wrong
vmin = a[np.isfinite(a)].min() # isfinite to ignore nans
vmax = a[np.isfinite(a)].max()
vmin = 1.01e-3
cbar = mpl.pyplot.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax), cmap=prob_std_c), orientation='horizontal', label='Standard deviation of probabilities for predicted stars (test dataset)', pad=0.01, cax=cax)
cax.tick_params(which='both', labelbottom='off')
fig.tight_layout()
fig.savefig('UMAP-'+label+'-probs-std-stars.pdf', bbox_inches='tight')
plt.close(fig)
# ------ ------ ------ ------ ------ ------ ------ ------ ------ ------
def plot_umap_ds_SpecObjs_resolvedr(df, sup, label='unknown', GQSsplit=False):
# Plotting: use datashader
df_train = df.loc[df['class_pred'].isnull()] # get rows which were used in the RF training - will not have entries in class_pred\
df_test = df.loc[df['class_pred'].notnull()]
#df_test = df_test[df_test.psf_r>0]
# ------ ALL SOURCES ------
# Plot resolvedr MEAN
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
agg = cvs.points(df_test, 'x', 'y', ds.mean('resolvedr'))
img = tf.shade(agg, cmap=(mpl.cm.YlOrBr), how='log')
export_image(img, 'UMAP-'+label+'-resolvedr-mean', fmt='.png', background='black')
# generate figure with png created and append colourbar axis
fig = plt.figure(figsize=(10,fheight)) # y axis larger to fit cbar in
img = mpimg.imread('UMAP-'+label+'-resolvedr-mean.png')
plt.imshow(img)
plt.gca().set_axis_off()
plt.tick_params(axis='both', which='both', right=False, left=False, top=False, bottom=False)
# create new axis below main axis for colourbar
ax_divider = make_axes_locatable(plt.gca())
cax = ax_divider.append_axes("bottom", size="3%", pad="1%")
# get min and max values from the data binned by datashader to use as limits for the colourbar
a = agg.data[np.nonzero(agg.data)] # remove zeros to stop log colour scale going wrong
vmin = a[np.isfinite(a)].min() # isfinite to ignore nans
vmax = a[np.isfinite(a)].max()
vmin=7e-6 # keep cbar neat in boundary otherwise labels overlap
print(vmin,vmax)
cbar = mpl.pyplot.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax), cmap=mpl.cm.YlOrBr), orientation='horizontal', label='Mean resolvedr parameter for predicted sources (test dataset)', pad=0.01, cax=cax)
cax.tick_params(which='both', labelbottom='off')
fig.tight_layout()
fig.savefig('UMAP-'+label+'-resolvedr-mean.pdf', bbox_inches='tight')
plt.close(fig)
# Plot resolvedr STD
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
agg = cvs.points(df_test, 'x', 'y', ds.std('resolvedr'))
img = tf.shade(agg, cmap=(mpl.cm.YlOrBr), how='log')
export_image(img, 'UMAP-'+label+'-resolvedr-std', fmt='.png', background='black')
# generate figure with png created and append colourbar axis
fig = plt.figure(figsize=(10,fheight)) # y axis larger to fit cbar in
img = mpimg.imread('UMAP-'+label+'-resolvedr-std.png')
plt.imshow(img)
plt.gca().set_axis_off()
plt.tick_params(axis='both', which='both', right=False, left=False, top=False, bottom=False)
# create new axis below main axis for colourbar
ax_divider = make_axes_locatable(plt.gca())
cax = ax_divider.append_axes("bottom", size="3%", pad="1%")
# get min and max values from the data binned by datashader to use as limits for the colourbar
a = agg.data[np.nonzero(agg.data)] # remove zeros to stop log colour scale going wrong
vmin = a[np.isfinite(a)].min() # isfinite to ignore nans
vmax = a[np.isfinite(a)].max()
print(vmin,vmax)
cbar = mpl.pyplot.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax), cmap=mpl.cm.YlOrBr), orientation='horizontal', label='Standard deviation of resolvedr parameter for predicted sources (test dataset)', pad=0.01, cax=cax)
cax.tick_params(which='both', labelbottom='off')
fig.tight_layout()
fig.savefig('UMAP-'+label+'-resolvedr-std.pdf', bbox_inches='tight')
plt.close(fig)
if GQSsplit==True:
# ------ GALAXIES ------
# Plot resolvedr MEAN for galaxies
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
agg = cvs.points(df_test[df_test.class_pred=='GALAXY'], 'x', 'y', ds.mean('resolvedr'))
img = tf.shade(agg, cmap=(mpl.cm.YlOrBr), how='log')
img = tf.dynspread(img, threshold=threshold_g, max_px=max_px, shape='square', how='over')
export_image(img, 'UMAP-'+label+'-resolvedr-mean-galaxies', fmt='.png', background='black')
# generate figure with png created and append colourbar axis
fig = plt.figure(figsize=(10,fheight)) # y axis larger to fit cbar in
img = mpimg.imread('UMAP-'+label+'-resolvedr-mean-galaxies.png')
plt.imshow(img)
plt.gca().set_axis_off()
plt.tick_params(axis='both', which='both', right=False, left=False, top=False, bottom=False)
# create new axis below main axis for colourbar
ax_divider = make_axes_locatable(plt.gca())
cax = ax_divider.append_axes("bottom", size="3%", pad="1%")
# get min and max values from the data binned by datashader to use as limits for the colourbar
a = agg.data[np.nonzero(agg.data)] # remove zeros to stop log colour scale going wrong
vmin = a[np.isfinite(a)].min() # isfinite to ignore nans
vmax = a[np.isfinite(a)].max()
vmin = 1.01e-5
print(vmin,vmax)
cbar = mpl.pyplot.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax), cmap=mpl.cm.YlOrBr), orientation='horizontal', label='Mean resolvedr parameter for predicted galaxies (test dataset)', pad=0.01, cax=cax)
cax.tick_params(which='both', labelbottom='off')
fig.tight_layout()
fig.savefig('UMAP-'+label+'-resolvedr-mean-galaxies.pdf', bbox_inches='tight')
plt.close(fig)
# Plot resolvedr STD for galaxies
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
agg = cvs.points(df_test[df_test.class_pred=='GALAXY'], 'x', 'y', ds.std('resolvedr'))
img = tf.shade(agg, cmap=(mpl.cm.YlOrBr), how='log')
img = tf.dynspread(img, threshold=threshold_g, max_px=max_px, shape='square', how='over')
export_image(img, 'UMAP-'+label+'-resolvedr-std-galaxies', fmt='.png', background='black')
# generate figure with png created and append colourbar axis
fig = plt.figure(figsize=(10,fheight)) # y axis larger to fit cbar in
img = mpimg.imread('UMAP-'+label+'-resolvedr-std-galaxies.png')
plt.imshow(img)
plt.gca().set_axis_off()
plt.tick_params(axis='both', which='both', right=False, left=False, top=False, bottom=False)
# create new axis below main axis for colourbar
ax_divider = make_axes_locatable(plt.gca())
cax = ax_divider.append_axes("bottom", size="3%", pad="1%")
# get min and max values from the data binned by datashader to use as limits for the colourbar
a = agg.data[np.nonzero(agg.data)] # remove zeros to stop log colour scale going wrong
vmin = a[np.isfinite(a)].min() # isfinite to ignore nans
vmax = a[np.isfinite(a)].max()
vmin = 1.01e-5
print(vmin,vmax)
cbar = mpl.pyplot.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax), cmap=mpl.cm.YlOrBr), orientation='horizontal', label='Standard deviation of resolvedr parameter for predicted galaxies (test dataset)', pad=0.01, cax=cax)
cax.tick_params(which='both', labelbottom='off')
fig.tight_layout()
fig.savefig('UMAP-'+label+'-resolvedr-std-galaxies.pdf', bbox_inches='tight')
plt.close(fig)
# ------ QUASARS ------
# Plot resolvedr MEAN for quasars
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
agg = cvs.points(df_test[df_test.class_pred=='QSO'], 'x', 'y', ds.mean('resolvedr'))
img = tf.shade(agg, cmap=(mpl.cm.YlOrBr), how='log')
img = tf.dynspread(img, threshold=threshold_q, max_px=max_px, shape='square', how='over')
export_image(img, 'UMAP-'+label+'-resolvedr-mean-quasars', fmt='.png', background='black')
# generate figure with png created and append colourbar axis
fig = plt.figure(figsize=(10,fheight)) # y axis larger to fit cbar in
img = mpimg.imread('UMAP-'+label+'-resolvedr-mean-quasars.png')
plt.imshow(img)
plt.gca().set_axis_off()
plt.tick_params(axis='both', which='both', right=False, left=False, top=False, bottom=False)
# create new axis below main axis for colourbar
ax_divider = make_axes_locatable(plt.gca())
cax = ax_divider.append_axes("bottom", size="3%", pad="1%")
# get min and max values from the data binned by datashader to use as limits for the colourbar
a = agg.data[np.nonzero(agg.data)] # remove zeros to stop log colour scale going wrong
vmin = a[np.isfinite(a)].min() # isfinite to ignore nans
vmax = a[np.isfinite(a)].max()
vmin = 7e-6
print(vmin,vmax)
cbar = mpl.pyplot.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax), cmap=mpl.cm.YlOrBr), orientation='horizontal', label='Mean resolvedr parameter for predicted quasars (test dataset)', pad=0.01, cax=cax)
cax.tick_params(which='both', labelbottom='off')
fig.tight_layout()
fig.savefig('UMAP-'+label+'-resolvedr-mean-quasars.pdf', bbox_inches='tight')
plt.close(fig)
# Plot resolvedr STD for quasars
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
agg = cvs.points(df_test[df_test.class_pred=='QSO'], 'x', 'y', ds.std('resolvedr'))
img = tf.shade(agg, cmap=(mpl.cm.YlOrBr), how='log')
img = tf.dynspread(img, threshold=threshold_q, max_px=max_px, shape='square', how='over')
export_image(img, 'UMAP-'+label+'-resolvedr-std-quasars', fmt='.png', background='black')
# generate figure with png created and append colourbar axis
fig = plt.figure(figsize=(10,fheight)) # y axis larger to fit cbar in
img = mpimg.imread('UMAP-'+label+'-resolvedr-std-quasars.png')
plt.imshow(img)
plt.gca().set_axis_off()
plt.tick_params(axis='both', which='both', right=False, left=False, top=False, bottom=False)
# create new axis below main axis for colourbar
ax_divider = make_axes_locatable(plt.gca())
cax = ax_divider.append_axes("bottom", size="3%", pad="1%")
# get min and max values from the data binned by datashader to use as limits for the colourbar
a = agg.data[np.nonzero(agg.data)] # remove zeros to stop log colour scale going wrong
vmin = a[np.isfinite(a)].min() # isfinite to ignore nans
vmax = a[np.isfinite(a)].max()
print(vmin,vmax)
cbar = mpl.pyplot.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax), cmap=mpl.cm.YlOrBr), orientation='horizontal', label='Standard deviation of resolvedr parameter for predicted quasars (test dataset)', pad=0.01, cax=cax)
cax.tick_params(which='both', labelbottom='off')
fig.tight_layout()
fig.savefig('UMAP-'+label+'-resolvedr-std-quasars.pdf', bbox_inches='tight')
plt.close(fig)
# ------ STARS ------
# Plot resolvedr MEAN for stars
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
agg = cvs.points(df_test[df_test.class_pred=='STAR'], 'x', 'y', ds.mean('resolvedr'))
img = tf.shade(agg, cmap=(mpl.cm.YlOrBr), how='log')
img = tf.dynspread(img, threshold=threshold_s, max_px=max_px, shape='square', how='over')
export_image(img, 'UMAP-'+label+'-resolvedr-mean-stars', fmt='.png', background='black')
# generate figure with png created and append colourbar axis
fig = plt.figure(figsize=(10,fheight)) # y axis larger to fit cbar in
img = mpimg.imread('UMAP-'+label+'-resolvedr-mean-stars.png')
plt.imshow(img)
plt.gca().set_axis_off()
plt.tick_params(axis='both', which='both', right=False, left=False, top=False, bottom=False)
# create new axis below main axis for colourbar
ax_divider = make_axes_locatable(plt.gca())
cax = ax_divider.append_axes("bottom", size="3%", pad="1%")
# get min and max values from the data binned by datashader to use as limits for the colourbar
a = agg.data[np.nonzero(agg.data)] # remove zeros to stop log colour scale going wrong
vmin = a[np.isfinite(a)].min() # isfinite to ignore nans
vmax = a[np.isfinite(a)].max()
vmin = 7e-6
print(vmin,vmax)
cbar = mpl.pyplot.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax), cmap=mpl.cm.YlOrBr), orientation='horizontal', label='Mean resolvedr parameter for predicted stars (test dataset)', pad=0.01, cax=cax)
cax.tick_params(which='both', labelbottom='off')
fig.tight_layout()
fig.savefig('UMAP-'+label+'-resolvedr-mean-stars.pdf', bbox_inches='tight')
plt.close(fig)
# Plot resolvedr STD for stars
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
agg = cvs.points(df_test[df_test.class_pred=='STAR'], 'x', 'y', ds.std('resolvedr'))
img = tf.shade(agg, cmap=(mpl.cm.YlOrBr), how='log')
img = tf.dynspread(img, threshold=threshold_s, max_px=max_px, shape='square', how='over')
export_image(img, 'UMAP-'+label+'-resolvedr-std-stars', fmt='.png', background='black')
# generate figure with png created and append colourbar axis
fig = plt.figure(figsize=(10,fheight)) # y axis larger to fit cbar in
img = mpimg.imread('UMAP-'+label+'-resolvedr-std-stars.png')
plt.imshow(img)
plt.gca().set_axis_off()
plt.tick_params(axis='both', which='both', right=False, left=False, top=False, bottom=False)
# create new axis below main axis for colourbar
ax_divider = make_axes_locatable(plt.gca())
cax = ax_divider.append_axes("bottom", size="3%", pad="1%")
# get min and max values from the data binned by datashader to use as limits for the colourbar
a = agg.data[np.nonzero(agg.data)] # remove zeros to stop log colour scale going wrong
vmin = a[np.isfinite(a)].min() # isfinite to ignore nans
vmax = a[np.isfinite(a)].max()
print(vmin,vmax)
cbar = mpl.pyplot.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax), cmap=mpl.cm.YlOrBr), orientation='horizontal', label='Standard deviation of resolvedr parameter for predicted stars (test dataset)', pad=0.01, cax=cax)
cax.tick_params(which='both', labelbottom='off')
fig.tight_layout()
fig.savefig('UMAP-'+label+'-resolvedr-std-stars.pdf', bbox_inches='tight')
plt.close(fig)
# ------ ------ ------ ------ ------ ------ ------ ------ ------ ------
def plot_umap_ds_SpecObjs_uz(df, sup, label='unknown', GQSsplit=False):
# Plotting: use datashader
#df_train = df.loc[df['class_pred'].isnull()] # get rows which were used in the RF training - will not have entries in class_pred\
df_test = df.loc[df['class_pred'].notnull()]
#df_test = df_test[df_test.psf_r>0]
# ------ ALL SOURCES ------
# Plot uz mean
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
df_test['SDSS_si'] = np.sqrt( (df_test['psf_u'] - df_test['psf_z'])**2 )
agg = cvs.points(df_test, 'x', 'y', ds.mean('SDSS_si'))
img = tf.shade(agg, cmap=(mpl.cm.YlOrBr), how='log')
export_image(img, 'UMAP-'+label+'-uz-mean', fmt='.png', background='black')
# generate figure with png created and append colourbar axis
fig = plt.figure(figsize=(10,fheight)) # y axis larger to fit cbar in
img = mpimg.imread('UMAP-'+label+'-uz-mean.png')
plt.imshow(img)
plt.gca().set_axis_off()
plt.tick_params(axis='both', which='both', right=False, left=False, top=False, bottom=False)
# create new axis below main axis for colourbar
ax_divider = make_axes_locatable(plt.gca())
cax = ax_divider.append_axes("bottom", size="3%", pad="1%")
# get min and max values from the data binned by datashader to use as limits for the colourbar
a = agg.data[np.nonzero(agg.data)] # remove zeros to stop log colour scale going wrong
vmin = a[np.isfinite(a)].min() # isfinite to ignore nans
vmax = a[np.isfinite(a)].max()
print(vmin,vmax)
cbar = mpl.pyplot.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax), cmap=mpl.cm.YlOrBr), orientation='horizontal', label='Mean |PSF u - PSF z| magnitude for predicted sources (test dataset)', pad=0.01, cax=cax)
cax.tick_params(which='both', labelbottom='off')
fig.tight_layout()
fig.savefig('UMAP-'+label+'-uz-mean.pdf', bbox_inches='tight')
plt.close(fig)
# Plot uz STD
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
df_test['SDSS_si'] = np.sqrt( (df_test['psf_u'] - df_test['psf_z'])**2 )
agg = cvs.points(df_test, 'x', 'y', ds.std('SDSS_si'))
img = tf.shade(agg, cmap=(mpl.cm.YlOrBr), how='log')
export_image(img, 'UMAP-'+label+'-uz-std', fmt='.png', background='black')
# generate figure with png created and append colourbar axis
fig = plt.figure(figsize=(10,fheight)) # y axis larger to fit cbar in
img = mpimg.imread('UMAP-'+label+'-uz-std.png')
plt.imshow(img)
plt.gca().set_axis_off()
plt.tick_params(axis='both', which='both', right=False, left=False, top=False, bottom=False)
# create new axis below main axis for colourbar
ax_divider = make_axes_locatable(plt.gca())
cax = ax_divider.append_axes("bottom", size="3%", pad="1%")
# get min and max values from the data binned by datashader to use as limits for the colourbar
a = agg.data[np.nonzero(agg.data)] # remove zeros to stop log colour scale going wrong
vmin = a[np.isfinite(a)].min() # isfinite to ignore nans
vmax = a[np.isfinite(a)].max()
vmin=7e-6 # keep fig neat
print(vmin,vmax)
cbar = mpl.pyplot.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax), cmap=mpl.cm.YlOrBr), orientation='horizontal', label='Standard deviation of |PSF u - PSF z| magnitude for predicted sources (test dataset)', pad=0.01, cax=cax)
cax.tick_params(which='both', labelbottom='off')
fig.tight_layout()
fig.savefig('UMAP-'+label+'-uz-std.pdf', bbox_inches='tight')
plt.close(fig)
if GQSsplit==True:
# ----- GALAXIES -----
# Plot uz MEAN
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
df_test['SDSS_si'] = np.sqrt( (df_test['psf_u'] - df_test['psf_z'])**2 )
agg = cvs.points(df_test[df_test.class_pred == 'GALAXY'], 'x', 'y', ds.mean('SDSS_si'))
img = tf.shade(agg, cmap=(mpl.cm.YlOrBr), how='log')
img = tf.dynspread(img, threshold=threshold_g, max_px=max_px, shape='square', how='over')
export_image(img, 'UMAP-'+label+'-uz-mean-galaxies', fmt='.png', background='black')
# generate figure with png created and append colourbar axis
fig = plt.figure(figsize=(10,fheight)) # y axis larger to fit cbar in
img = mpimg.imread('UMAP-'+label+'-uz-mean-galaxies.png')
plt.imshow(img)
plt.gca().set_axis_off()
plt.tick_params(axis='both', which='both', right=False, left=False, top=False, bottom=False)
# create new axis below main axis for colourbar
ax_divider = make_axes_locatable(plt.gca())
cax = ax_divider.append_axes("bottom", size="3%", pad="1%")
# get min and max values from the data binned by datashader to use as limits for the colourbar
a = agg.data[np.nonzero(agg.data)] # remove zeros to stop log colour scale going wrong
vmin = a[np.isfinite(a)].min() # isfinite to ignore nans
vmax = a[np.isfinite(a)].max()
print(vmin,vmax)
cbar = mpl.pyplot.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax), cmap=mpl.cm.YlOrBr), orientation='horizontal', label='Mean |PSF u - PSF z| magnitude for predicted galaxies (test dataset)', pad=0.01, cax=cax)
cax.tick_params(which='both', labelbottom='off')
fig.tight_layout()
fig.savefig('UMAP-'+label+'-uz-mean-galaxies.pdf', bbox_inches='tight')
plt.close(fig)
# Plot uz STD
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
df_test['SDSS_si'] = np.sqrt( (df_test['psf_u'] - df_test['psf_z'])**2 )
agg = cvs.points(df_test[df_test.class_pred == 'GALAXY'], 'x', 'y', ds.std('SDSS_si'))
img = tf.shade(agg, cmap=(mpl.cm.YlOrBr), how='log')
img = tf.dynspread(img, threshold=threshold_g, max_px=max_px, shape='square', how='over')
export_image(img, 'UMAP-'+label+'-uz-std-galaxies', fmt='.png', background='black')
# generate figure with png created and append colourbar axis
fig = plt.figure(figsize=(10,fheight)) # y axis larger to fit cbar in
img = mpimg.imread('UMAP-'+label+'-uz-std-galaxies.png')
plt.imshow(img)
plt.gca().set_axis_off()
plt.tick_params(axis='both', which='both', right=False, left=False, top=False, bottom=False)
# create new axis below main axis for colourbar
ax_divider = make_axes_locatable(plt.gca())
cax = ax_divider.append_axes("bottom", size="3%", pad="1%")
# get min and max values from the data binned by datashader to use as limits for the colourbar
a = agg.data[np.nonzero(agg.data)] # remove zeros to stop log colour scale going wrong
vmin = a[np.isfinite(a)].min() # isfinite to ignore nans
vmax = a[np.isfinite(a)].max()
print(vmin,vmax)
cbar = mpl.pyplot.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax), cmap=mpl.cm.YlOrBr), orientation='horizontal', label='Standard deviation of |PSF u - PSF z| for predicted galaxies (test dataset)', pad=0.01, cax=cax)
cax.tick_params(which='both', labelbottom='off')
fig.tight_layout()
fig.savefig('UMAP-'+label+'-uz-std-galaxies.pdf', bbox_inches='tight')
plt.close(fig)
# ----- QUASARS -----
# Plot uz mean
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
df_test['SDSS_si'] = np.sqrt( (df_test['psf_u'] - df_test['psf_z'])**2 )
agg = cvs.points(df_test[df_test.class_pred == 'QSO'], 'x', 'y', ds.mean('SDSS_si'))
img = tf.shade(agg, cmap=(mpl.cm.YlOrBr), how='log')
img = tf.dynspread(img, threshold=threshold_q, max_px=max_px, shape='square', how='over')
export_image(img, 'UMAP-'+label+'-uz-mean-quasars', fmt='.png', background='black')
# generate figure with png created and append colourbar axis
fig = plt.figure(figsize=(10,fheight)) # y axis larger to fit cbar in
img = mpimg.imread('UMAP-'+label+'-uz-mean-quasars.png')
plt.imshow(img)
plt.gca().set_axis_off()
plt.tick_params(axis='both', which='both', right=False, left=False, top=False, bottom=False)
# create new axis below main axis for colourbar
ax_divider = make_axes_locatable(plt.gca())
cax = ax_divider.append_axes("bottom", size="3%", pad="1%")
# get min and max values from the data binned by datashader to use as limits for the colourbar
a = agg.data[np.nonzero(agg.data)] # remove zeros to stop log colour scale going wrong
vmin = a[np.isfinite(a)].min() # isfinite to ignore nans
vmax = a[np.isfinite(a)].max()
print(vmin,vmax)
cbar = mpl.pyplot.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax), cmap=mpl.cm.YlOrBr), orientation='horizontal', label='Mean |PSF u - PSF z| magnitude for predicted quasars (test dataset)', pad=0.01, cax=cax)
cax.tick_params(which='both', labelbottom='off')
fig.tight_layout()
fig.savefig('UMAP-'+label+'-uz-mean-quasars.pdf', bbox_inches='tight')
plt.close(fig)
# Plot uz std