-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmakefakecmd.py
2490 lines (1918 loc) · 93 KB
/
makefakecmd.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
## to deal with display when running as background jobs
from matplotlib import use
use('Agg')
import pyfits
from numpy import *
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import pylab
import PIL
import time
import ezfig # morgan's plotting code
import read_brick_data as rbd
import isolatelowAV as iAV
import analysis as analysis
from scipy import ndimage
from scipy.stats import norm
from scipy.ndimage import filters as filt
import scipy.special as special
import string
import os.path as op
import random as rnd
import numpy as np
from astropy.io import fits
from astropy import wcs
# Principle: "rotate" to frame where all "colors" are along reddening
# vector. Rotate the -data- into this frame, once. Rotate the original
# unreddened CMD -once-. Then all convolutions are fast 1-d.
############# code for generating foreground CMD ###############
def split_ra_dec(ra, dec, d_arcsec=10.0, ra_bins='', dec_bins=''):
"""
indices, ra_bins, dec_bins = split_ra_dec(ra, dec, d_arcsec=10.0, ra_bins=0, dec_bins=0)
Takes lists of ra and dec, divides the list into pixels of width
d_arcsec, and returns an array, where each entry is a list of the
indices from the original ra, dec list whose ra and dec fell into
that pixel. Also returns the boundaries of the bins used to
generate the index array. (Functions like reverse indices in IDL's
histogram function)
OR
if ra_bins and dec_bins are provided as arguments, uses those, overriding d_arcsec
To setup:
filename = '../../Data/12056_M31-B15-F09-IR_F110W_F160W.st.fits'
fitstab = pyfits.open(filename)
ra = fitstab[1].data.field('RA')
dec = fitstab[1].data.field('DEC')
fitstab.close()
"""
if (len(dec_bins) == 0):
print 'Generating new bins for declination '
# figure out ranges
dec_min = nanmin(dec)
dec_max = nanmax(dec)
# find center
dec_cen = (dec_max + dec_min) / 2.0
print 'dec_cen: ', dec_cen
# figure out number of bins, rounding up to nearest integer
d_dec = d_arcsec / 3600.0
print 'd_dec: ',d_dec
n_dec = int((dec_max - dec_min) / d_dec + 1.0)
# calculate histogram bin edges
dec_bins = linspace(dec_min,dec_min + n_dec*d_dec, num=n_dec+1)
print 'Dec Range: ', dec_bins.min(), dec_bins.max()
else:
print 'Using user-provided declination bins: ',[dec_bins.min(), dec_bins.max()]
# recalculate maximums and center, since range is not necessarily
# an integer multiple of d_arcsec
n_dec = len(dec_bins) - 1
dec_min = dec_bins.min()
dec_max = dec_bins.max()
dec_cen = (dec_max + dec_min) / 2.0
if (len(ra_bins) == 0):
print 'Generating new bins for RA '
# figure out ranges
ra_min = nanmin(ra)
ra_max = nanmax(ra)
# figure out number of bins, rounding up to nearest integer
d_ra = (d_arcsec / cos(math.pi * dec_cen / 180.0)) / 3600.0
print 'd_ra: ',d_ra
n_ra = int((ra_max - ra_min) / d_ra + 1.0)
# calculate histogram bin edges
ra_bins = linspace(ra_min, ra_min + n_ra*d_ra, num=n_ra+1)
print 'RA Range: ',ra_bins.min(), ra_bins.max()
else:
print 'Using user-provided RA bins: ',[ra_bins.min(), ra_bins.max()]
# recalculate maximums and center, since range is not necessarily
# an integer multiple of d_arcsec
n_ra = len(ra_bins) - 1
ra_min = ra_bins.min()
ra_max = ra_bins.max()
ra_cen = (ra_max + ra_min) / 2.0
# get indices falling into each pixel in ra, dec bins
raindex = digitize(ra, ra_bins) - 1
decindex = digitize(dec, dec_bins) - 1
# generate n_ra by n_dec array of lists, giving indices in each bin
indices = empty( (n_ra,n_dec), dtype=object )
for (i,j), value in ndenumerate(indices):
indices[i,j]=[]
# populate the array with the indices in each bin
for k in range(len(ra)):
indices[raindex[k],decindex[k]].append(k)
print 'Generated indices in array of dimensions', indices.shape
print 'Median number of stars per bin: ', median([len(indices[x,y]) for
(x,y),v in ndenumerate(indices) if (len(indices[x,y]) > 1)])
return indices, ra_bins, dec_bins
def median_rgb_color_map(indices,c,m,mrange=[18.8,22.5],crange=[0.3,2.5],
rgbparam=[22.0, 0.74, -0.13, -0.012]):
"""
Return array of median NIR color of RGB in range, and standard
deviation, relative to fiducial curve, and list of the good pixel
values.
indices = array of indices in RA, Dec bins (from split_ra_dec())
c, m = list of colors,magnitudes referred to by indices in i
mrange = restrict to range of magnitudes
rgbparam = 2nd order polynomial of RGB location [magref, a0, a1, a2]
cmap, cmapgoodvals, cstdmap, cstdmapgoodvals, cmean, cmeanlist =
median_rgb_color_map(indices,c,m,mrange=[19,21.5])
to display:
plt.imshow(cmap,interpolation='nearest')
plt.hist(cmapgoodvals, cumulative=True,histtype='step',normed=1)
"""
# fiducial approximation of isochrone to flatten RGB to constant color
magref = rgbparam[0]
a = rgbparam[1:4]
cref = a[0] + a[1]*(m-magref) + a[2]*(m-magref)**2
dc = c - cref
# initialize color map
emptyval = -1
cmap = empty( indices.shape, dtype=float )
cmeanmap = empty( indices.shape, dtype=float )
cstdmap = empty( indices.shape, dtype=float )
nstarmap = empty( indices.shape, dtype=float )
# calculate median number of stars per bin, to set threshold for
# ignoring partially filled ra-dec pixels.
n_per_bin = median([len(indices[x,y]) for (x,y),v in ndenumerate(indices)
if (len(indices[x,y]) > 1)])
n_thresh = n_per_bin - 7*sqrt(n_per_bin)
print 'Dimension of Color Map: ',cmap.shape
for (i,j), value in ndenumerate(indices):
if (len(indices[i,j]) > n_thresh):
dctmp = dc[indices[i,j]]
ctmp = c[indices[i,j]]
mtmp = m[indices[i,j]]
cmap[i,j] = median(dctmp.compress(((mtmp > mrange[0]) &
(mtmp<mrange[1]) &
(ctmp > crange[0]) &
(ctmp<crange[1])).flat))
cmeanmap[i,j] = mean(dctmp.compress(((mtmp > mrange[0]) &
(mtmp<mrange[1]) &
(ctmp > crange[0]) &
(ctmp<crange[1])).flat))
cstdmap[i,j] = std(dctmp.compress(((mtmp > mrange[0]) &
(mtmp<mrange[1]) &
(ctmp > crange[0]) &
(ctmp<crange[1])).flat))
nstarmap[i,j] = len(dctmp.compress(((mtmp > mrange[0]) &
(mtmp<mrange[1]) &
(ctmp > crange[0]) &
(ctmp<crange[1])).flat))
else:
cmap[i,j] = emptyval
cmeanmap[i,j] = emptyval
cstdmap[i,j] = emptyval
nstarmap[i,j] = emptyval
# calculate list of good values
igood = where(cmap > -1)
print 'Median Color offset:', median(cmap[igood])
return cmap, cmap[igood], cstdmap, cstdmap[igood], cmeanmap, cmeanmap[igood], nstarmap, nstarmap[igood]
def isolate_low_AV_color_mag(filename = '../../Data/12056_M31-B15-F09-IR_F110W_F160W.st.fits',
frac=0.2, mrange=[19,21.5],
rgbparam=[22.0, 0.74, -0.13, -0.012],
d_arcsec=10):
"""
Return a list of color and magnitude for stars in the frac of low
extinction pixels defined by either blueness or narrowness of RGB.
cblue,mblue,iblue,cnarrow,mnarrow,inarrow,cmap,cstdmap =
isolate_low_AV_color_mag(filename, fraction, mrange, rgbparam)
filename = FITS file of stellar parameters
fraction = return stars that fall in the fraction of pixels with bluest RGB
mrange = F160W magnitude range for evaluating color of RGB
rgbparam = polynomial approximation of color of RGB = [magref,a0,a1,a2]
cblue,mblue,iblue = color, magnitude, and indices of stars in the
bluest bins
cnarrow,mnarrow,inarrow = same, but for narrowest RGB bins
cmap = 2d array of RGB color
cstd = 2d array of RGB width
"""
m1, m2, ra, dec = rbd.read_mag_position_gst(filename)
c = array(m1 - m2)
m = array(m2)
# cut out main sequence stars
crange = [0.3, 2.0]
indices, rabins, decbins = split_ra_dec(ra, dec, d_arcsec)
cm,cmlist,cstd,cstdlist,cmean,cmeanlist = median_rgb_color_map(indices, c, m,
mrange, crange, rgbparam)
print 'Number of valid areas in color map: ', len(cmlist)
# find bluest elements
cmlist.sort()
n_cm_thresh = int(frac * (len(cmlist) + 1))
cmthresh = cmlist[n_cm_thresh]
cmnodataval = -1
# find elements with the narrowest color sequence
cstdlist.sort()
n_cstd_thresh = int(frac * (len(cstdlist) + 1))
cstdthresh = cstdlist[n_cstd_thresh]
cstdnodataval = -1
ikeep_blue = []
for (x,y), value in ndenumerate(cm):
if ((cm[x,y] < cmthresh) & (cm[x,y] > cmnodataval)) :
ikeep_blue.extend(indices[x,y])
ikeep_narrow = []
for (x,y), value in ndenumerate(cm):
if ((cstd[x,y] < cstdthresh) & (cm[x,y] > cmnodataval)) :
ikeep_narrow.extend(indices[x,y])
print 'Blue: Returning ', len(ikeep_blue),' out of ', len(c),' stars from ',n_cm_thresh,' bins.'
print 'Narrow: Returning ', len(ikeep_narrow),' out of ',len(c),' stars from ',n_cstd_thresh,' bins.'
return c[ikeep_blue], m[ikeep_blue], ikeep_blue, c[ikeep_narrow], m[ikeep_narrow], ikeep_narrow, cm, cstd
def color_sigma_vs_mag(c, m, magrange=[18.5,24.0], nperbin=50):
"""
Return color dispersion vs magnitude, calculated in bins with
constant numbers of stars, limited to magrange
cdisp, mbins_disp = color_sigma_vs_mag(colorlist,maglist,magrange,nperbin)
"""
# sort into ascending magnitude
isort = argsort(m)
# take groups of nperbin, and calculate the interquartile range in
# color, and the median magnitude of the group.
nout = int(len(c)/nperbin)
mmed = empty(nout,dtype=float)
cvar = empty(nout,dtype=float)
for i in range(nout):
k = i * nperbin + arange(nperbin)
mmed[i] = median(m[isort[k]])
ctmp = array(c[isort[k]]) # make numpy array
cmed = median(ctmp)
c25 = median(ctmp.compress(ctmp <= cmed))
c75 = median(ctmp.compress(ctmp > cmed))
cvar[i] = (c75 - c25) / (2.0 * 0.6745)
return cvar, mmed
def clean_fg_cmd(fg_cmd, nsigvec, niter=4, showplot=0):
"""
Line by line, fit for mean color and width of RGB, then mask
outside of nsig[0] on blue and nsig[1] on red.
Fit iteratively, using rejection.
Return mask (same dimensions as fg_cmd), and vector of mean
color and width of RGB
"""
mask = 1.0 + zeros(fg_cmd.shape)
# Record size of array, in preparation for looping through magnitude bins
nmag = fg_cmd.shape[0]
ncol = fg_cmd.shape[1]
nsig_clip = 2.5
nanfix = 0.0000000000001
for j in range(niter):
# Get mean color and width of each line
meancol = array([sum(arange(ncol) * fg_cmd[i,:] * mask[i,:]) /
sum(fg_cmd[i,:] * (mask[i,:] + nanfix)) for i in range(nmag)])
sigcol = array([sqrt(sum(fg_cmd[i,:]*mask[i,:] *
(range(ncol) - meancol[i])**2) /
sum(fg_cmd[i,:]*mask[i,:] + nanfix))
for i in range(nmag)])
if showplot != 0:
plt.plot(meancol,range(nmag),color='blue')
plt.plot(meancol-nsigvec[0]*sigcol,range(nmag),color='red')
plt.plot(meancol+nsigvec[1]*sigcol,range(nmag),color='red')
# Mask the region near the RGB
mask = array([where(abs(range(ncol) - meancol[i]) <
nsig_clip*sigcol[i], 1.0, 0.0)
for i in range(nmag)])
# Regenerate mask using requested sigma clip
mask = array([where((range(ncol) - meancol[i] > -nsigvec[0] * sigcol[i]) &
(range(ncol) - meancol[i] < nsigvec[1] * sigcol[i]),
1.0, 0.0)
for i in range(nmag)])
return mask, meancol, sigcol
def display_CM_diagram(c, m, crange=[-1,3], mrange=[26,16], nbins=[50,50],
alpha=1.0):
"""
Plot binned CMD, and return the binned histogram, extent vector,
cbins, mbins
"""
h, xedges, yedges = histogram2d(m, c, range=[sort(mrange), crange],
bins=nbins)
extent = [yedges[0], yedges[-1], xedges[-1], xedges[0]]
plt.imshow(log(h), extent=extent, origin='upper', aspect='auto',
interpolation='nearest',alpha=alpha)
plt.xlabel('F110W - F160W')
plt.ylabel('F160W')
return h, extent, yedges, xedges
########## CODE TO DEAL WITH INPUT DATA #################
def get_star_indices(c_star, m_star, cedges, medges):
"""
Input: list of star colors and magnitudes, and vectors of the
edges returned by 2d histogram of the comparison CMD
Return: i_color and i_magnitude -- indices giving location within
the comparison CMD
"""
# calculate indices in image of star locations
dcol = cedges[1] - cedges[0]
dmag = medges[1] - medges[0]
i_c = floor((array(c_star) - cedges[0])/dcol)
i_m = floor((array(m_star) - medges[0])/dmag)
return i_c.astype(int), i_m.astype(int)
def make_data_mask(fg_cmd, cedges, medges, m1range, m2range, clim, useq=0):
"""
fg_cmd = image to make mask for
cedges, medges = values of color and magnitude along array sides
m1lims = 2 element vector for blue filter [bright,faint]
m2lims = 2 element vector for red filter [bright,faint]
useq = if set, assume fg_cmd is rotated to reddening free mags,
and translate mag limits accordingly. Assume value = [c0=reference_color]
clim = color to cut on blue side
Returns mask of 1's where data falls within magnitude limits
"""
mask = 1.0 + zeros(fg_cmd.shape)
# Define reddening parameters
#print 'Defining reddening parameters'
Amag_AV = 0.20443
Acol_AV = 0.33669 - 0.20443
#t = np.arctan(-Amag_AV / Acol_AV)
if useq != 0:
c0 = useq[0]
#t = useq[1]
mlim2_faint = m2range[1] + (cedges[:-1] - c0)*(-Amag_AV / Acol_AV)
mlim2_bright = m2range[0] + (cedges[:-1] - c0)*(-Amag_AV / Acol_AV)
mlim1_faint = ((m1range[1] - cedges[:-1]) +
(cedges[:-1] - c0)*(-Amag_AV / Acol_AV))
mlim1_bright = ((m1range[0] - cedges[:-1]) +
(cedges[:-1] - c0)*(-Amag_AV / Acol_AV))
else:
mlim2_faint = m2range[1] + 0.0*cedges[:-1]
mlim2_bright = m2range[0] + 0.0*cedges[:-1]
mlim1_faint = (m1range[1] - cedges[:-1])
mlim1_bright = (m1range[0] - cedges[:-1])
nmag = fg_cmd.shape[0]
ncol = fg_cmd.shape[1]
dm = medges[1] - medges[0]
mask = array([where((cedges[:-1] > clim[i]) &
(medges[i] > mlim2_bright) & (medges[i] < mlim2_faint) &
(medges[i] > mlim1_bright) & (medges[i] < mlim1_faint),
#(medges[i] > mlim2_bright) & (mlim2_faint- medges[i] > -dm) &
#(medges[i] > mlim1_bright) & (mlim1_faint - medges[i] > -dm),
1.0, 0.0) for i in range(nmag)])
return mask
############# CODE TO GENERATE MODEL CMD #######################
def makefakecmd(fg_cmd, cvec, mvec, AVparam, floorfrac=0.0,
mask = 1.0, SHOWPLOT=True,
noise_model=0.0, noise_frac=0.0, frac_red_mean=0.5, print_fred=False):
"""
fg_cmd, cvec, mvec = 2-d binned CMD of lowreddening stars, binned
in color c & DEREDDENED magnitude m' =
m+(c-c0)*[A_1/(A_1-A_2)], and the bin coordinates. c0 is
arbitrary color coordinate around which the rotation such
that reddening is purely horizontal occured. Inputs
calculated as fg_cmd, extent, cvec, mvec =
display_CM_diagram(c, m') with c, m derived from cnar,
mnar outputs of isolate_low_AV_color_mag, and cleaned of
points with unreasonable colors, and m' =
m+(c-c0)*[A_1/(A_1-A_2)].
(write second function to generate a mask of where to compare data)
"""
# vectors defining mapping from array location to color and magnitude
crange = [cvec[0],cvec[-1]]
mrange = [mvec[0],mvec[-1]]
dcol = cvec[1] - cvec[0]
dmag = mvec[1] - mvec[0]
# set up reddening parameters
#fracred = AVparam[0]
alpha = log(0.5) / log(frac_red_mean)
fracred = (exp(AVparam[0]) / (1. + exp(AVparam[0])))**(1./alpha) # x = ln(f/(1-f))
if (print_fred):
print 'In makefakecmd: f_red = ', fracred
medianAV = AVparam[1]
#stddev = AVparam[2] * medianAV
#sigma_squared = log((1. + sqrt(1. + 4. * (stddev/medianAV)**2)) / 2.)
#sigma = sqrt(sigma_squared)
sigma = AVparam[2]
stddev_squared = (exp(sigma**2)-1.0)*exp(sigma**2)*(medianAV**2)
stddev = sqrt(stddev_squared)
Amag_AV = AVparam[3]
Acol_AV = AVparam[4]
# translate color shifts into equivalent AV
dAV = dcol / Acol_AV
# make log-normal convolution kernel in color, based on lg-normal
# in A_V (Note, currently does not integrate lg-normal over bin
# width. Could make the kernel with color spacing of dcol/4, and
# then sum every 4 bins back down to normal dcol width to
# approximate integration.)
nstddev = 5.0 # set range based on width of log normal
nresamp = 4.0
#kernmaxcolor = Acol_AV * exp(nstddev * sigma + log(medianAV))
kernmaxcolor = Acol_AV * (medianAV + nstddev * stddev)
nkern = int(kernmaxcolor / dcol)
# make sure kernel size is <= size of array and > 0
nkern = minimum(len(cvec), nkern)
nkern = maximum(1, nkern)
nkernresamp = nkern * nresamp
kernmaxcolor = nkern * dcol # recalculate maximum
#colorkern = arange(int(nkern), dtype=float) * dcol
#AVkern = colorkern / Acol_AV
resampcolorkern = arange(int(nkernresamp), dtype=float) * (dcol/nresamp)
AVkern = resampcolorkern / Acol_AV
AVkern[0] = 1.0e-17
pAVkernresamp = ((1.0 / (AVkern * sigma * sqrt(2.0 * 3.1415926))) *
exp(-0.5 * (log(AVkern / medianAV) / sigma)**2))
# undo resampling by adding up bins
pAVkern = array([(pAVkernresamp[i*nresamp:(i+1)*nresamp-1]).sum() / nresamp
for i in range(nkern)])
# normalize the kernels
pAVkernnorm = pAVkern.sum()
pAVkern = pAVkern / pAVkernnorm
# zero out where not finite
i = where (isfinite(pAVkern) == False)
if len(i) > 0:
pAVkern[i] = 0.0
# generate combined foreground + reddened CMD
cmdorig = fg_cmd.copy()
# sequentially shift cmd and co-add, weighted by pEBV
dmagshift = dAV * Amag_AV / dmag
dcolshift = dAV * Acol_AV / dcol
cmdred = pAVkern[0] * fg_cmd.copy()
for i in range(1, len(pAVkern)):
cmdred[:,i:] += cmdorig[:,0:-i] * pAVkern[i]
# combination of unreddened and unreddend cmd
cmdcombo = (1.0-fracred)*fg_cmd + fracred*cmdred
# add in noise model
cmdcombo = (1.0 - noise_frac)*cmdcombo + noise_frac*noise_model
# display commands
if SHOWPLOT:
plt.imshow(cmdcombo,extent=[crange[0],crange[1],mrange[1],mrange[0]],
origin='upper',aspect='auto', interpolation='nearest')
plt.xlabel('F110W - F160W')
plt.ylabel('Extinction Corrected F160W')
# mask regions (defaults to *1 if mask not set in function call)
cmdcombo = cmdcombo * mask
# renormalize the entire PDF
norm = cmdcombo.sum()
cmdcombo = cmdcombo / norm
# permit a constant offset in unmasked regions, to give non-zero probability
# of a random star.
if floorfrac > 0:
if len(array(mask).shape) == 0:
masknorm = len(cmdcombo)
else:
masknorm = mask.sum()
cmdcombo = mask*((1.0 - floorfrac) * cmdcombo +
floorfrac * (mask / masknorm))
# return cmd
return cmdcombo
def makefakecmd_AVparamsonly(param):
"""
Same as makefakecmd, but uses global parameters for most input
"""
return makefakecmd(foreground_cmd, color_boundary, qmag_boundary,
[param[0], param[1], param[2], 0.20443,
(0.33669 - 0.20443)],
floorfrac=floorfrac_value,
mask=color_qmag_datamask, SHOWPLOT=False,
noise_model = noise_model,
frac_red_mean = frac_red_mean)
def cmdlikelihoodfunc(param, i_star_color, i_star_magnitude):
"""
Return likelihood compared to dust model using param.
Passes parameters for dust model, and the color and magnitude
indices of stars (i.e., figure out which pixel of dusty CMD all
stars fall in before the call -- do the masking in advance as well)
"""
if (ln_priors(param) == False):
return -inf
# calculate probability distribution
img = makefakecmd_AVparamsonly(param)
# calculate log likelihood
pval = img[i_star_magnitude, i_star_color]
lnp = (log(pval[where(pval > 0)])).sum()
return lnp
################################################
# global parameters setting up foreground CMD
datadir = '/astro/store/angst4/dstn/v8/' # bagel
datadir = '/mnt/angst4/dstn/v8/' # chex
datadir = '../../Data/' # poptart
resultsdir = '../Results/'
# Set up input data file and appropriate magnitude cuts
fnroot = 'ir-sf-b21-v8-st'
m110range = [16.0,25.0]
m160range = [18.4,23.25] # just above RC -- worse constraints on AV
m160range = [18.4,24.5] # just below RC
m160range = [18.4,24.0] # middle of RC
fnroot = 'ir-sf-b17-v8-st'
m110range = [16.0,24.0]
m160range = [18.4,24.0]
fnroot = 'ir-sf-b14-v8-st'
m110range = [16.0,23.5]
m160range = [18.4,24.0]
fnroot = 'ir-sf-b16-v8-st'
m110range = [16.0,23.5]
m160range = [18.4,24.0]
fnroot = 'ir-sf-b18-v8-st'
m110range = [16.0,24.0]
m160range = [18.4,24.0]
fnroot = 'ir-sf-b19-v8-st'
m110range = [16.0,24.0]
m160range = [18.4,24.0]
fnroot = 'ir-sf-b22-v8-st'
m110range = [16.0,24.5]
m160range = [18.4,24.0]
fnroot = 'ir-sf-b12-v8-st'
m110range = [16.0,23.5]
m160range = [18.4,23.25]
fn = datadir + fnroot + '.fits'
mfitrange = [18.7,21.3] # range for doing selection for "narrow" RGB
# Set up color range and binning for color and magnitude
#crange = [0.3,3.0]
crange = [0.3,2.5]
deltapix_approx = [0.025,0.3]
nbins = [int((m160range[1] - m160range[0]) / deltapix_approx[1]),
int((crange[1] - crange[0]) / deltapix_approx[0])]
# Define reddening parameters
Amag_AV = 0.20443
Acol_AV = 0.33669 - 0.20443
t = arctan(-Amag_AV / Acol_AV)
reference_color = 1.0
# define fraction of uniform "noise" to include in data model
floorfrac_value = 0.05
# generate foreground CMD in reddening free magnitudes
#clo, mlo, ilo, cnar, mnar, inr, cm, cstd = isolate_low_AV_color_mag(
# filename=fn, frac=0.025, mrange=mfitrange, d_arcsec=10.)
#qnar = mnar + (cnar-reference_color)*(-Amag_AV / Acol_AV)
#foreground_cmd_orig, qmag_boundary, color_boundary = histogram2d(qnar, cnar,
# range=[sort(m160range), crange], bins=nbins)
#foregroundmask, meancol, sigcol = clean_fg_cmd(foreground_cmd_orig, [3.0,3.5],
# niter=4, showplot=0)
#foreground_cmd = foreground_cmd_orig * foregroundmask
# make the noise model by masking out foreground and smoothing
#noisemask, meancol, sigcol = clean_fg_cmd(foreground_cmd_orig, [4.5,4.5],
# niter=5, showplot=0)
#noisemask = abs(noisemask - 1)
#noise_smooth = [3, 10] # mag, color, in pixels
#noise_model_orig = foreground_cmd_orig * noisemask
#noise_model = ndimage.filters.uniform_filter(noise_model_orig,
# size=noise_smooth)
# generate mask of data regions to ignore
#nsig_blue_color_cut = 2.0
#bluecolorlim = color_boundary[maximum(rint(meancol - nsig_blue_color_cut *
# sigcol).astype(int),0)]
#color_qmag_datamask = make_data_mask(foreground_cmd, color_boundary,
# qmag_boundary, m110range, m160range,
# bluecolorlim, useq=[reference_color])
# relative normalization of foreground model and noise model
#nfg = (foreground_cmd * color_qmag_datamask).sum()
#nnoise = (noise_model * color_qmag_datamask).sum()
#frac_noise = nnoise / (nnoise + nfg)
#print 'Noise fraction: ', frac_noise
# read in main data file
#m1, m2, ra, dec = rbd.read_mag_position_gst(fn)
#m = array(m2)
#c = array(m1 - m2)
#q = m + (c-reference_color)*(-Amag_AV / Acol_AV)
#ra = array(ra)
#dec = array(dec)
# exclude data outside the color-magnitude range
#igood = where((c > color_boundary[0]) & (c < color_boundary[-1]) &
# (q > qmag_boundary[0]) & (q < qmag_boundary[-1]))
#m = m[igood]
#c = c[igood]
#q = q[igood]
#ra = ra[igood]
#dec = dec[igood]
# exclude data outside the data mask
#i_c, i_q = get_star_indices(c, q, color_boundary, qmag_boundary)
#igood = where(color_qmag_datamask[i_q, i_c] != 0)
#m = m[igood]
#c = c[igood]
#q = q[igood]
#ra = ra[igood]
#dec = dec[igood]
#i_c = i_c[igood]
#i_q = i_q[igood]
# split into RA-Dec
#binarcsec = 10.0
#i_ra_dec_vals, ra_bins, dec_bins = split_ra_dec(ra, dec, d_arcsec = binarcsec)
# grab data for a test bin, if needed for testing.
#i_test_ra = 60
#i_test_dec = 20
#ctest = c[i_ra_dec_vals[i_test_ra,i_test_dec]]
#mtest = m[i_ra_dec_vals[i_test_ra,i_test_dec]]
#qtest = q[i_ra_dec_vals[i_test_ra,i_test_dec]]
#i_ctest, i_qtest = get_star_indices(ctest, qtest, color_boundary, qmag_boundary)
########### CODE FOR LOOPING THROUGH RA-DEC BINS, RUNNING EMCEE ########
def generate_global_ra_dec_grid(d_arcsec=7.5):
filename = 'radius_range_of_bricks.npz' # generated by get_radius_range_of_all_bricks in isolatelowAV.py
dat = load(filename)
r_range_brick_array = dat['r_range_brick_array']
ra_min = min(r_range_brick_array[:,3])
ra_max = max(r_range_brick_array[:,4])
dec_min = min(r_range_brick_array[:,5])
dec_max = max(r_range_brick_array[:,6])
# default M31 parameters (see also compleness.py)
m31ra = 10.6847929
m31dec = 41.2690650 # use as tangent point
# figure out number of bins, rounding up to nearest integer
d_ra = (d_arcsec / cos(math.pi * m31dec / 180.0)) / 3600.0
d_dec = d_arcsec / 3600.0
print 'd_ra: ',d_ra
print 'd_dec: ',d_dec
n_ra = int((ra_max - ra_min) / d_ra + 1.0)
n_dec = int((dec_max - dec_min) / d_dec + 1.0)
# calculate histogram bin edges
ra_bins = linspace(ra_min, ra_min + n_ra*d_ra, num=n_ra+1)
dec_bins = linspace(dec_min, dec_min + n_dec*d_dec, num=n_dec+1)
print 'RA Range: ', ra_bins.min(), ra_bins.max()
print 'Dec Range: ', dec_bins.min(), dec_bins.max()
# recalculate maximums and center, since range is not necessarily
# an integer multiple of d_arcsec
ra_max = ra_bins.max()
dec_max = dec_bins.max()
ra_cen = (ra_max + ra_min) / 2.0
dec_cen = (dec_max + dec_min) / 2.0
return ra_bins, dec_bins
def extract_local_subgrid(ra_range, dec_range,
ra_bins_global, dec_bins_global):
"""
For a given range in ra and dec (rarange=[ramin, ramax], decrange
= [decmin, decmax]), extract only the relevant subgrid of the
global ra, dec grid defined by ra_bins_global and dec_bins_global
(evenly spaced boundaries of global grid).
Returns ra_bins_local, dec_bins_local and [iramin, iramax],
[idecmin, idecmax] to show where resulting local array should be
placed back in the global array:
array_global[iramin:iramax, idecmin:idecmax] = array_local
"""
dra = ra_bins_global[1] - ra_bins_global[0]
ddec = dec_bins_global[1] - dec_bins_global[0]
i_ra = (array(ra_range) - ra_bins_global[0]) / dra
i_dec = (array(dec_range) - dec_bins_global[0]) / ddec
i_ra[0] = max((floor(i_ra[0])).astype(int), 0) # prevent negatives
i_dec[0] = max((floor(i_dec[0])).astype(int), 0)
i_ra[1] = (ceil(i_ra[1] + 1)).astype(int) # add 1 for slicing to work
i_dec[1] = (ceil(i_dec[1] + 1)).astype(int) # add 1 for slicing to work
print 'Extracting RA Global points between ',i_ra[0], ' and ', i_ra[1]
print 'Extracting Dec Global points between ',i_dec[0], ' and ', i_dec[1]
return ra_bins_global[i_ra[0]:i_ra[1]], dec_bins_global[i_dec[0]:i_dec[1]], i_ra, i_dec
def get_ra_dec_bin(i_ra=60, i_dec=20):
i_ctest, i_qtest = get_star_indices(c[i_ra_dec_vals[i_ra,i_dec]],
q[i_ra_dec_vals[i_ra,i_dec]],
color_boundary, qmag_boundary)
return i_ctest, i_qtest
class lnpriorobj(object):
def __init__(self, f_mean):
self.f_mean = f_mean
def __call__(self, param, **kwargs):
return ln_priors_function(param, f_mean = self.f_mean, **kwargs)
def map_call(self, args):
return self(*args)
class likelihoodobj(object):
def __init__(self, foreground_cmd, noise_model, datamask, color_boundary, mag_boundary,
noise_frac, floorfrac_value, f_mean):
self.foreground_cmd = foreground_cmd
self.noise_model = noise_model
self.datamask = datamask
self.color_boundary = color_boundary
self.mag_boundary = mag_boundary
self.noise_frac = noise_frac
self.floorfrac_value = floorfrac_value
self.f_mean = f_mean
def __call__(self, param, i_star_color, i_star_magnitude):
ln_priors = lnpriorobj(self.f_mean)
lnp = ln_priors(param)
if (lnp == -Inf): # parameters out of range
return -Inf
# calculate probability distribution
img = makefakecmd(self.foreground_cmd, self.color_boundary, self.mag_boundary,
[param[0], param[1], param[2], 0.20443,
(0.33669 - 0.20443)],
floorfrac=self.floorfrac_value,
mask=self.datamask, SHOWPLOT=False,
noise_model = self.noise_model,
noise_frac = self.noise_frac,
frac_red_mean = self.f_mean)
# calculate log likelihood
pval = img[i_star_magnitude, i_star_color]
lnlikelihood = (log(pval[where(pval > 0)])).sum()
return lnp + lnlikelihood
def map_call(self, args):
return self(*args)
def test_run_one_brick(pix='', datadir='../../Data/', results_extension = '', AV_fitsfile=''):
"""
Test code using single pixel
"""
#datadir = '../../Data/'
#results_extension = ''
nwalkers = 50
nsamp = 15
nburn = 150
#nburn = 300
fileroot = 'ir-sf-b15-v8-st'
d_arcsec = 6.64515
grab_ira_idec = [7, 59] # high extinction, high f_red
grab_ira_idec = [45, 63] # high extinction, moderate f_red
grab_ira_idec = [45, 60] # high extinction, moderate f_red
grab_ira_idec = [49, 56] # high extinction, moderate f_red
grab_ira_idec = [16, 18] # high extinction, loweish f_red
grab_ira_idec = [59, 35] # lowish extinction, loweish f_red
grab_ira_idec = [61, 42] # lowish extinction, loweish f_red
grab_ira_idec = [61, 59] # very high extinction, loweish f_red
grab_ira_idec = [95, 12] # low extinction, loweish f_red
grab_ira_idec = [95, 13] # low extinction, loweish f_red
fileroot = 'ir-sf-b16-v8-st'
d_arcsec = 6.64515
grab_ira_idec = [90, 28] # low extinction, low f_red
grab_ira_idec = [90, 29] # low extinction, low f_red
fileroot = 'ir-sf-b17-v8-st'
d_arcsec = 6.64515
grab_ira_idec = [10, 76] # moderate extinction, high f_red, low N
grab_ira_idec = [12, 62] # moderate extinction, high f_red
grab_ira_idec = [11, 76] # moderate extinction, high f_red
grab_ira_idec = [13, 74] # moderate extinction, high f_red
grab_ira_idec = [29, 67] # moderate extinction, high f_red
grab_ira_idec = [45, 71] # moderate extinction, high f_red
grab_ira_idec = [45, 70] # moderate extinction, high f_red
fileroot = 'ir-sf-b16-v8-st'
d_arcsec = 6.64515
grab_ira_idec = [103, 52] # moderate extinction, high f_red, low N
grab_ira_idec = [104, 1] # moderate extinction, high f_red, low N
grab_ira_idec = [104, 24] # moderate extinction, high f_red, low N
grab_ira_idec = [110, 19] # big outlier
grab_ira_idec = [110, 42] # modest outlier
grab_ira_idec = [114, 44] # modest outlier
fileroot = 'ir-sf-b02-v8-st'
d_arcsec = 25.0
grab_ira_idec = [25, 0] # high sigma in low res
grab_ira_idec = [28, 4] # high sigma in low res
fileroot = 'ir-sf-b12-v8-st'