-
Notifications
You must be signed in to change notification settings - Fork 0
/
ediscs_catalog.py
1527 lines (1278 loc) · 82.4 KB
/
ediscs_catalog.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
from statsmodels.formula.api import ols,rlm
from astropy import coordinates
from astropy.table import Table
from astropy import units as u
import pdb, shlex, os, shutil, pandas, statsmodels.api as sm, numpy as np
import matplotlib.pyplot as plt, matplotlib.cm as cm, photcheck as pc, re
import subprocess as sp, labbe_depth as lb, pyfits as pf, random, pandas as pd
from astropysics import obstools as obs
from astropy.stats.funcs import biweight_location as bl
from scipy.optimize import curve_fit
import threedhst.eazyPy as eazy
megaLocation='/Volumes/BAHAMUT/megacat.v5.7.fits'
plt.rcParams['text.latex.preamble']=[r"\usepackage{amsmath}"]
#plt.rc('ps',usedistiller='xpdf')
#-----------------------------------
# GENERAL NOTES
#
# Required files:
# Photometry from SExtractor for the WFI, MOSAIC, and
# NEWFIRM observations
#
# Dennis Just's "VLT.starflag.dat" file for each cluster
#
# FORS photometry to solve for WFI zeropoints
#-----------------------------------
#Constants
vega2AB={'bctio':-0.09949,'bkpno':-0.10712,'v':0.01850,'r':0.19895,'i':0.42143,'k':1.84244}
medCterms={'VRv':-0.151,'VRr':0.0245,'VIv':-0.0725,'VIi':0.1465,'RIr':0.015,'RIi':0.238}
#Fields for FITS catalogs
colNames=('field','ids','ra','dec','x','y','ebv','fwhmR','fB1','fB1err','fB2','fB2err','fB3','fB3err','fBiso',
'fBisoerr','fBauto','fBautoerr','fV1','fV1err','fV2','fV2err','fV3','fV3err','fViso','fVisoerr',
'fVauto','fVautoerr','fR1','fR1err','fR2','fR2err','fR3','fR3err','fRiso','fRisoerr','fRauto',
'fRautoerr','fI1','fI1err','fI2','fI2err','fI3','fI3err','fIiso','fIisoerr','fIauto','fIautoerr',
'fz1','fz1err','fz2','fz2err','fz3','fz3err','fziso','fzisoerr','fzauto','fzautoerr','fK1','fK1err',
'fK2','fK2err','fK3','fK3err','fKiso','fKisoerr','fKauto','fKautoerr','zLDP5_7','Q5_7',
'class_StarR','iso_area','major_ax','minor_ax','theta','sexflagB','sexflagV','sexflagR','sexflagI',
'sexflagz','sexflagK','wK')
colNames70=('field','ids','ra','dec','x','y','ebv','fwhmR','fB1','fB1err','fB2','fB2err','fB3','fB3err','fBiso',
'fBisoerr','fBauto','fBautoerr','fV1','fV1err','fV2','fV2err','fV3','fV3err','fViso','fVisoerr',
'fVauto','fVautoerr','fR1','fR1err','fR2','fR2err','fR3','fR3err','fRiso','fRisoerr','fRauto',
'fRautoerr','fI1','fI1err','fI2','fI2err','fI3','fI3err','fIiso','fIisoerr','fIauto','fIautoerr',
'fz1','fz1err','fz2','fz2err','fz3','fz3err','fziso','fzisoerr','fzauto','fzautoerr','fK1','fK1err',
'fK2','fK2err','fK3','fK3err','fKiso','fKisoerr','fKauto','fKautoerr','zLDP5_7','Q5_7','zphot',
'zphot_errUP','zphot_errLO','class_StarR','iso_area','major_ax','minor_ax','theta','sexflagB',
'sexflagV','sexflagR','sexflagI','sexflagz','sexflagK','wK')
#Flux and error column names
fluxNames = [x for x in list(colNames) if re.match('(?!.*err)f[BVRIzK].',x)]
errNames = [x for x in list(colNames) if re.match('(?=.*err)f[BVRIzK].',x)]
#Set up data types for FITS catalogs. All values should be floats except the SExtractor flags (int), LDP quality (int)
#field names (str), and WFI ID names (str)
Fdtype=('f;'*len(colNames)).split(';')[:-1]
for x in range(len(Fdtype)):
if ('field' in colNames[x]) or ('ids' in colNames[x]):
Fdtype[x] = 'S'
if (colNames[x] == 'Q5_7') or ('sexflag' in colNames[x]):
Fdtype[x] = 'i'
Fdtype = tuple(Fdtype)
Fdtype70=('f;'*len(colNames70)).split(';')[:-1]
for x in range(len(Fdtype70)):
if ('field' in colNames70[x]) or ('ids' in colNames70[x]):
Fdtype70[x] = 'S'
if (colNames70[x] == 'Q5_7') or ('sexflag' in colNames70[x]):
Fdtype70[x] = 'i'
Fdtype70 = tuple(Fdtype70)
#-----------------------------------
#Define a series of functions that are for fitting the zeropoints by comparing the WFI and FORS observations
#of stars using a constant color term, but allowing the zeropoint to vary. A separate function was necessary
#for each color (e.g., V-R, R-I, etc.) to fix the slope to different values unique to each color.
def fixedVRv(x,zp):
return (medCterms['VRv']*x)+zp
def fixedVRr(x,zp):
return (medCterms['VRr']*x)+zp
def fixedVIv(x,zp):
return (medCterms['VIv']*x)+zp
def fixedVIi(x,zp):
return (medCterms['VIi']*x)+zp
def fixedRIr(x,zp):
return (medCterms['RIr']*x)+zp
def fixedRIi(x,zp):
return (medCterms['RIi']*x)+zp
#-----------------------------------
def randomSample(catalog,filters,output1='randomFirst.fits',output2='randomSecond.fits',
classStar=0.3,Q=4):
"""
PURPOSE: Generate a random sample of galaxies from the photometric catalog of a single cluster.
\tAlso generate a second FITS file of the other galaxies not in the random sample.'
INPUTS:
\tcatalog - FITS photometric catalog
\tfilters - string list of the filter names (e.g., BVRIzK)
\toutput1 - Name of random sample FITS catalog
\toutput2 - Name of FITS catalog with galaxies NOT in the random sample
\tclassStar - SExtractor class_star value to perform cut on (selects objects with class_star < this value)
\tQ - LDP quality flag for selecting sources
RETURNS: None.
"""
select = 'class_StarR < '+str(classStar)+' & Q5_7 == '+str(Q)+' & '+' & '.join(['sexflag'+x+' == 0' for x in filters])
data = Table.read(catalog).to_pandas()
trimData = data.query(select)
idx=xrange(len(trimData))
sample = random.sample(idx,int(np.ceil(len(trimData)/2.)))
inverse = []
for x in idx:
if x not in sample:
inverse.append(x)
first = trimData.iloc[sample]
second = trimData.iloc[inverse]
fitsCols = list(trimData.columns.values)
firstDict = {colNames[x]:first[fitsCols[x]].values for x in range(len(fitsCols))}
secondDict = {colNames[x]:second[fitsCols[x]].values for x in range(len(fitsCols))}
galsDict = {colNames[x]:trimData[fitsCols[x]].values for x in range(len(fitsCols))}
Table(firstDict, names=colNames, dtype=Fdtype).write(output1,format='fits',overwrite=True)
Table(secondDict, names=colNames, dtype=Fdtype).write(output2,format='fits',overwrite=True)
Table(galsDict, names=colNames, dtype=Fdtype).write('galaxies.fits',format='fits',overwrite=True)
#-----------------------------------
def mkZPoffs(b=0.0,v=0.0,r=0.0,i=0.0,z=0.0,k=0.0,kpno=False):
f=open('zphot.zeropoint','w')
bvrizk=[b,v,r,i,z,k]
fcodes=['F','F3','F4','F5','F6','F7']
if kpno == False:
fcodes[0]=fcodes[0]+'1'
else:
fcodes[0]=fcodes[0]+'2'
for x in range(len(bvrizk)):
if bvrizk[x] > 0.0:
offset = 10.0**(-0.4*bvrizk[x])
f.write(fcodes[x]+'\t'+str(offset)+'\n')
f.close()
#-----------------------------------
def update70(fitscat,clname,zphot='OUTPUT/photz.zout',output='v7.0.fits',zpvoff=0.0,zproff=0.0,zpioff=0.0,best=True,
offFile=''):
if best == True:
if offFile == '':
offFile=os.environ['EDISCS']+'/files/images/wfi_zeropoints.dat'
offsets=pd.read_table(offFile,delim_whitespace=True,
header=None,names=['CLUSTER','FILTER','C1','S1','C2','S2','FLAG','OFFSET','KEEP'],
comment='#',index_col=None)
(zpvoff, zproff, zpioff) = (offsets[offsets['CLUSTER'].str.contains('CL1301') & offsets['FILTER'].str.contains('V')]['OFFSET'].values[0],
offsets[offsets['CLUSTER'].str.contains('CL1301') & offsets['FILTER'].str.contains('R')]['OFFSET'].values[0],
offsets[offsets['CLUSTER'].str.contains('CL1301') & offsets['FILTER'].str.contains('I')]['OFFSET'].values[0])
catalog = Table.read(fitscat).to_pandas()
z=eazy.catIO.Readfile(zphot)
#Add in the zphot values and their associated uncertainties
index=range(len(catalog))
catalog['index']=index
catalog['zphot']=z.z_m2[catalog['index']].tolist()
catalog['zphot_errUP']=z.u68[catalog['index']].tolist()-catalog['zphot']
catalog['zphot_errLO']=catalog['zphot']-z.l68[catalog['index']].tolist()
catalog.drop('index', axis=1, inplace=True)
#Update the VRI photometry with the offsets (if necessary) and preserve the
#signal-to-noise ratio
offsets=[zpvoff,zproff,zpioff]
filters=['V','R','I']
apertures=['1','2','3','auto','iso']
for x in range(len(offsets)):
if offsets[x] != 0.0:
for y in apertures:
filtap = filters[x]+y
snratio = catalog['f'+filtap]/catalog['f'+filtap+'err']
catalog['f'+filtap] = catalog['f'+filtap] * (10.0**(-0.4*offsets[x]))
catalog['f'+filtap+'err'] = catalog['f'+filtap] / snratio
#Write the final FITS file
final = {colNames70[x]:catalog[colNames70[x]].values for x in range(len(colNames70))}
Table(final, names=colNames70, dtype=Fdtype70).write(output,format='fits',overwrite=True)
#-----------------------------------
#def updatecat(catalog,fieldName,outname,megacat='/Volumes/BAHAMUT/megacat.v5.7.fits'):
#
# hdu = pf.open(catalog)
# oldData = hdu[1].data
# field=[fieldName for x in range(len(oldData))]
#
# (filters, apertures) = (['B','V','R','I','z','K'], ['1','2','3','iso','auto'])
# for filt in filters:
# for ap in apertures:
# fluxes = 'f'+filt+ap
# bad = np.where(np.log10(np.abs(oldData[fluxes])) < -6.)
# oldData[fluxes][bad] = -77
#
# (zLDP,Q)=(np.zeros(len(oldData))-99,np.zeros(len(oldData))-99)
#
# megatab=pf.open('/Users/tyler/megacat.v5.7.fits')
# megadat=megatab[1].data
# (mzldp,mq,megaRA,megaDec)=(megadat['zldp'],megadat['q'],megadat['RA'],megadat['DEC'])
#
# wfiSky=coordinates.SkyCoord(ra=oldData['ra']*u.degree, dec=oldData['dec']*u.degree)
# megaSky=coordinates.SkyCoord(ra=megaRA*u.degree, dec=megaDec*u.degree)
# (idx,d2d,_)=wfiSky.match_to_catalog_sky(megaSky)
# match=np.where(d2d.arcsec < 0.5)
# zLDP[match]=mzldp[idx][match]
# Q[match]=mq[idx][match]
#
# final={'field':field,'ids':oldData['ids'],'ra':oldData['ra'],'dec':oldData['dec'],'x':oldData['x'],'y':oldData['y'],'ebv':oldData['ebv'],
# 'fwhmR':oldData['fwhmR'],
# 'fB1':oldData['fB1'],'fB1err':oldData['fB1err'],'fB2':oldData['fB2'],'fB2err':oldData['fB2err'],'fB3':oldData['fB3'],'fB3err':oldData['fB3err'],
# 'fBiso':oldData['fBiso'],'fBisoerr':oldData['fBisoerr'],'fBauto':oldData['fBauto'],'fBautoerr':oldData['fBautoerr'],'fV1':oldData['fV1'],
# 'fV1err':oldData['fV1err'],'fV2':oldData['fV2'],'fV2err':oldData['fV2err'],'fV3':oldData['fV3'],'fV3err':oldData['fV3err'],'fViso':oldData['fViso'],
# 'fVisoerr':oldData['fVisoerr'],'fVauto':oldData['fVauto'],'fVautoerr':oldData['fVautoerr'],'fR1':oldData['fR1'],'fR1err':oldData['fR1err'],
# 'fR2':oldData['fR2'],'fR2err':oldData['fR2err'],'fR3':oldData['fR3'],'fR3err':oldData['fR3err'],'fRiso':oldData['fRiso'],'fRisoerr':oldData['fRisoerr']
# ,'fRauto':oldData['fRauto'],'fRautoerr':oldData['fRautoerr'],'fI1':oldData['fI1'],'fI1err':oldData['fI1err'],'fI2':oldData['fI2'],
# 'fI2err':oldData['fI2err'],'fI3':oldData['fI3'],'fI3err':oldData['fI3err'],'fIiso':oldData['fIiso'],'fIisoerr':oldData['fIisoerr'],
# 'fIauto':oldData['fIauto'],'fIautoerr':oldData['fIautoerr'],'fz1':oldData['fz1'],'fz1err':oldData['fz1err'],'fz2':oldData['fz2'],
# 'fz2err':oldData['fz2err'],'fz3':oldData['fz3'],'fz3err':oldData['fz3err'],'fziso':oldData['fziso'],'fzisoerr':oldData['fzisoerr'],
# 'fzauto':oldData['fzauto'],'fzautoerr':oldData['fzautoerr'],'fK1':oldData['fK1'],'fK1err':oldData['fK1err'],'fK2':oldData['fK2'],
# 'fK2err':oldData['fK2err'],'fK3':oldData['fK3'],'fK3err':oldData['fK3err'],'fKiso':oldData['fKiso'],'fKisoerr':oldData['fKisoerr'],
# 'fKauto':oldData['fKauto'],'fKautoerr':oldData['fKautoerr'],'zLDP':zLDP,'Q':Q,'starB':oldData['starB'],'starV':oldData['starV'],
# 'starR':oldData['starR'],
# 'starI':oldData['starI'],'starz':oldData['starz'],'starK':oldData['starK'],'sexflagB':oldData['sexflagB'],'sexflagV':oldData['sexflagV'],
# 'sexflagR':oldData['sexflagR'],'sexflagI':oldData['sexflagI'],'sexflagz':oldData['sexflagz'],'sexflagK':oldData['sexflagK']}
#
# tab = Table(final, names=('field','ids','ra','dec','x','y','ebv','fwhmR','fB1','fB1err','fB2',
# 'fB2err','fB3','fB3err','fBiso','fBisoerr',
# 'fBauto','fBautoerr','fV1','fV1err','fV2','fV2err','fV3','fV3err','fViso','fVisoerr','fVauto',
# 'fVautoerr','fR1','fR1err','fR2','fR2err','fR3','fR3err','fRiso','fRisoerr','fRauto',
# 'fRautoerr','fI1','fI1err','fI2','fI2err','fI3','fI3err','fIiso','fIisoerr','fIauto',
# 'fIautoerr','fz1','fz1err','fz2','fz2err','fz3','fz3err','fziso','fzisoerr','fzauto',
# 'fzautoerr','fK1','fK1err','fK2','fK2err','fK3','fK3err','fKiso','fKisoerr','fKauto',
# 'fKautoerr','zLDP','Q','starB','starV','starR','starI','starz','starK','sexflagB','sexflagV','sexflagR','sexflagI',
# 'sexflagz','sexflagK'))
# tab.write(outname, format='fits', overwrite=True)
#-----------------------------------
def matchxy(x1,y1,x2,y2,tol=0.1):
match=[]
for i in range(len(x1)):
cdt=(x1[i],y1[i])
dist=np.sqrt((cdt[0]-x2)**2.+(cdt[1]-y2)**2.)
if np.min(dist) <= tol:
match.append(np.where(dist == np.min(dist))[0][0])
return np.array(match)
#-----------------------------------
def backZP(flux,mag):
"""PURPOSE: Backout the zeropoint for a source knowing its flux in detector units and its physical magnitude
INPUTS:
\tflux - flux in detector units (counts or counts/second)
\tmag - magnitude in physical units (note that if this is in AB mag, the result includes the AB conversion factor)
RETURNS: The zeropoint to convert between detector flux and physical magnitude
"""
return 2.5*np.log10(flux)+mag
#-----------------------------------
#def getSmoothFactor(rcat,xcat,class_star=0.0,border=1500.,pixscale=0.238,save=False):
#
# rangeMagR=[-15.,-12.]
# rangeMagX=[-10.,-5.]
#
# (rflux,rfwhm,starR)=np.loadtxt(rcat,usecols=(6,9,14),unpack=True,comments='#')
# (xcdt,ycdt,xflux,xfwhm,starX)=np.loadtxt(xcat,usecols=(2,3,6,9,14),unpack=True,comments='#')
#
# (rmags,xmags)=(-2.5*np.log10(rflux),-2.5*np.log10(xflux))
# goodX=np.where((xfwhm > 0.) & (xcdt < np.max(xcdt)-border) &
# (xcdt > np.min(xcdt)+border) & (ycdt < np.max(ycdt)-border) &
# (ycdt > np.min(ycdt)+border))
# goodR=np.where(starR >= class_star)
#
# plt.scatter(rmags,rfwhm*3600.,alpha=0.05,color='r')
# plt.scatter(xmags[goodX],xfwhm[goodX]*3600.,alpha=0.05,color='b')
#
# (rfwhm,xfwhm)=(rfwhm*3600.,xfwhm*3600.)
# (rfwhmSub,xfwhmSub)=(rfwhm[np.where((rmags >= rangeMagR[0]) & (rmags <= rangeMagR[1]) & (starR >= class_star))],
# xfwhm[np.where((xmags >= rangeMagX[0]) & (xmags <= rangeMagX[1]) & (starX >= class_star) & (xcdt < np.max(xcdt)-border) &
# (xcdt > np.min(xcdt)+border) & (ycdt < np.max(ycdt)-border) &
# (ycdt > np.min(ycdt)+border))])
#
# (avgR,avgX)=(bl(rfwhmSub),bl(xfwhmSub))
#
# xx=[-100,100]
# yy1=[avgR,avgR]
# yy2=[avgX,avgX]
# plt.plot(xx,yy1,'k-')
# plt.plot(xx,yy2,'k--')
# plt.axis([-20,-1,0.5,15])
#
# (pR,pX)=(avgR/pixscale,avgX/pixscale)
# sig=np.sqrt((pX**2.)-(pR**2.))/2.355
# print 'Avg. R = '+str(avgR)+' arcsec\nAvg. X = '+str(avgX)+' arcsec\nSigma smooth factor: '+str(sig)+' pixels'
#
# if save == True:
# plt.savefig('seeing_comp.pdf',format='pdf',dpi=6000.)
# else:
# plt.show()
#-----------------------------------
def addquad(xerr,orerr,nrerr,xflux,orflux,nrflux):
value=(xflux/nrflux)*orflux
return np.abs(value*np.sqrt((xerr/xflux)**2. + (nrerr/nrflux)**2. + (orerr/orflux)**2.))
#-----------------------------------
def photscript(listfile,clname,photfile='photscript'):
"""
PURPOSE: Generate a script (to be called on with source from the command line) that will run SExtractor on
\tall input images in dual-image mode (using the R-band for detection) for a cluster.
INPUTS:
\tlistfile - two columns of ?img (where ? is the filter letter) and image file names
\tclname - name of the cluster (e.g., cl1354)
\tphotfile - name of the output script file (optional)
RETURNS: None.
"""
(keys,files)=np.loadtxt(listfile,usecols=(0,1),unpack=True,dtype={'names':('keys','files'), 'formats':('S5','S30')})
imgs={}
for x in range(len(keys)):
imgs[keys[x]]=files[x]
outfile=open('photscript','w')
string1='sex -c ediscs.sex -BACKPHOTO_TYPE "GLOBAL" -CATALOG_NAME '
string2=' -CHECKIMAGE_TYPE "-BACKGROUND" -CHECKIMAGE_NAME '
finalString=''
finalString=finalString+string1+clname+'_r.cat'+' -CHECKIMAGE_TYPE "-BACKGROUND,SEGMENTATION" -CHECKIMAGE_NAME "' \
+imgs['rimg'][:-5]+'_bkgsub.fits'+','+imgs['rimg'][:-5]+'_segmap.fits" '+imgs['rimg']+','+imgs['rimg']+'\n'
if 'bimg' in keys:
finalString=finalString+string1+clname+'_b.cat'+string2+imgs['bimg'][:-5]+'_bkgsub.fits '+imgs['rimg']+','+imgs['bimg']+'\n'
if 'vimg' in keys:
finalString=finalString+string1+clname+'_v.cat'+string2+imgs['vimg'][:-5]+'_bkgsub.fits '+imgs['rimg']+','+imgs['vimg']+'\n'
if 'iimg' in keys:
finalString=finalString+string1+clname+'_i.cat'+string2+imgs['iimg'][:-5]+'_bkgsub.fits '+imgs['rimg']+','+imgs['iimg']+'\n'
if 'zimg' in keys:
finalString=finalString+string1+clname+'_z.cat'+string2+imgs['zimg'][:-5]+'_bkgsub.fits '+imgs['rimg']+','+imgs['zimg']+'\n'
if 'kimg' in keys:
finalString=finalString+string1+clname+'_k.cat'+string2+imgs['kimg'][:-5]+'_bkgsub.fits '+imgs['rimg']+','+imgs['kimg']+'\n'
if 'rbimg' in keys:
finalString=finalString+string1+clname+'_rb.cat'+string2+imgs['rbimg'][:-5]+'_bkgsub.fits '+imgs['rimg']+','+imgs['rbimg']+'\n'
if 'rkimg' in keys:
finalString=finalString+string1+clname+'_rk.cat'+string2+imgs['rkimg'][:-5]+'_bkgsub.fits '+imgs['rimg']+','+imgs['rkimg']+'\n'
out=open(photfile,'w')
out.write(finalString)
out.close()
#-----------------------------------
#def flags(flux,err,x,y,xmin=0,xmax=1e6,ymin=0,ymax=1e6):
#
# for j in range(len(flux)):
# if flux[j] == -99.0:
# err[j] = -99.0
# if np.log10(np.abs(flux[j])) > 4.0:
# flux[j] = -77.0
# err[j] = -77.0
# if np.log10(np.abs(flux[j])) < -8.0:
# flux[j] = -66.0
# err[j] = -66.0
# if x[j] < xmin:
# flux[j] = -55.0
# err[j] = -55.0
# if x[j] > xmax:
# flux[j] = -55.0
# err[j] = -55.0
# if y[j] < ymin:
# flux[j] = -55.0
# err[j] = -55.0
# if y[j] > ymax:
# flux[j] = -55.0
# err[j] = -55.0
#
# return flux,err
#-----------------------------------
#def fixData(data,flag=-88.0):
#
# keys=data.keys()
# for x in keys:
# if x != 'ids':
# nan=np.where(np.isnan(data[x]))
# inf=np.where(np.isinf(data[x]))
# data[x][nan]=flag
# data[x][inf]=flag
#
# return data
#-----------------------------------
def sigfunc(N,s,a,b):
"""
PURPOSE: Function from qquation 3 from Labbe et al. (2003), ApJ, 125, 1107.
"""
return (N*s*(a+(b*N)))
#-----------------------------------
#def binAvgData(x, y, npts, minimum = -999999.0, maximum = 9999999.0):
#
# use = np.where((x > minimum) & (x < maximum))
# x, y = x[use], y[use]
# sort = np.argsort(x)
# xs, ys = x[sort], y[sort]
# xm, ym = np.array([]), np.array([])
# i = 0
# for j in range(int(np.ceil(len(x)/npts))):
# if i+npts <= len(x):
# xm = np.append(xm, np.mean(xs[i:i+npts]))
# ym = np.append(ym, np.mean(ys[i:i+npts]))
# else:
# xm = np.append(xm, np.mean(xs[i:]))
# ym = np.append(ym, np.mean(ys[i:]))
# i = i + npts
#
# return (xm, ym)
#-----------------------------------
#def binAvgDataFixed(x, y, width, minimum = -999999.0, maximum = 9999999.0):
#
# use = np.where((x > minimum) & (x < maximum))
# x, y = x[use], y[use]
# sort = np.argsort(x)
# xs, ys = x[sort], y[sort]
# xm, ym = np.array([]), np.array([])
# i = np.min(x)
# while i + width < np.max(x):
# xm = np.append(xm, np.mean(xs[np.where((xs > i) & (xs <= i+width))]))
# ym = np.append(ym, np.mean(ys[np.where((xs > i) & (xs <= i+width))]))
# i = i + width
#
# return (xm, ym)
#-----------------------------------
def getEBV(ra,dec,path='/Users/tyler/Downloads/'):
"""
PURPOSE: For a given RA and Dec, lookup the E(B-V) value from the Schlegel dust maps.
INPUTS:
\tra - Right ascension (deg; J2000)
\tdec - Declination (deg; J2000)
RETURNS: E(B-V)
"""
if os.path.exists('SFD_dust_4096_ngp.fits') == False:
shutil.copy(path+'SFD_dust_4096_ngp.fits','.')
if os.path.exists('SFD_dust_4096_sgp.fits') == False:
shutil.copy(path+'SFD_dust_4096_sgp.fits','.')
galcoord = coordinates.SkyCoord(ra=ra*u.degree, dec=dec*u.degree, frame='fk5').galactic
(latitude, longitude) = (galcoord.l.degree, galcoord.b.degree)
ebv = obs.get_SFD_dust(latitude, longitude)
return ebv
#-----------------------------------
def calflux(flux, zp, abconv = 0.0):
"""
PURPOSE: Converts an instrumental flux into a physical one in flux space to preserve negative values.
INPUTS:
\tflux - instrumental flux
\tzp - zeropoint to convert instrumental to calibrated flux
\tabconv - conversion factor from Vega to AB magnitudes (optional)
RETURNS: Flux in uJy
"""
return ((flux)/(10.0**(0.4*(zp + abconv)))) * 3631.0 * 1e6
#-----------------------------------
def flux2mag(flux, zp, abconv = 0.0):
return -2.5 * np.log10(flux) + zp + abconv
#-----------------------------------
def mag2flux(mag, ab2ujy=False):
if ab2ujy == False:
return 10.0**(-0.4 * mag)
else:
return 10.0**(-0.4 * mag) * 3631.0 * 1e6
#-----------------------------------
#def ab2ujy(mag):
#
# jy = 10.0**(-0.4 * mag) * 3631.0
#
# return jy * 1e6
#-----------------------------------
#def ujy2abmag(flux):
#
# return -2.5 * np.log10(flux) + 23.9
#-----------------------------------
def seeingCorr(rr, rm, mm, outfile='seeingcorr.dat'):
res=(mm*rr)/rm
if outfile != '':
out=open(outfile,'w')
for x in range(len(mm)):
out.write(str(mm[x])+'\t'+str(res[x])+'\n')
out.close()
return res
#-----------------------------------
def zpWFI(ra, dec, v, r, i, v3, r3, i3, starR, photref = 'fors.dat', tol=0.01, synth=False, plot=False,
vr1=-99, vi1=-99, ri1=-99, show=False, classStar=0.9):
"""
Notes: Adapted from Dennis Just's "bvriz.pro" IDL code
"""
# (wmin, starflag) = np.loadtxt('VLT.starflag.dat', usecols=(0, 1), unpack = True, comments = '#')
(forsRA, forsDec, forsV, forsR, forsI, wmin, starflag) = np.loadtxt(photref, usecols = (1, 2, 9, 10, 11, 16, 17),
unpack = True, comments = '#')
#Identify stars based on Dennis's criteria. Create new arrays of only the coordinates
#and photometry of the stars from the FORS and WFI data. Convert the FORS RA from hours
#to degrees for matching. (starflag = 0 = galaxies, 1 = stars)
stars_fors = np.where((wmin > 0.2) & (starflag == 1) & (forsR <= 22.0) & (forsR > 16.5)
& (forsV > 16.5) & (forsI > 16.5))
star_wfi = np.where((starR >= classStar))
(sforsRA, sforsDec, sforsV, sforsR, sforsI) = (forsRA[stars_fors], forsDec[stars_fors],
forsV[stars_fors], forsR[stars_fors],
forsI[stars_fors])
(swfiRA, swfiDec, swfiV, swfiR, swfiI) = (ra[star_wfi], dec[star_wfi], v3[star_wfi],
r3[star_wfi], i3[star_wfi])
sforsRAh = sforsRA*15.0
#Match coords here!
forsCat=coordinates.SkyCoord(ra=sforsRAh*u.degree, dec=sforsDec*u.degree)
wfiCat=coordinates.SkyCoord(ra=swfiRA*u.degree, dec=swfiDec*u.degree)
idx, d2d, _ = wfiCat.match_to_catalog_sky(forsCat)
match = np.where(d2d.arcsec <= 1.0)
(sforsVmatch,sforsRmatch,sforsImatch)=(sforsV[idx][match], sforsR[idx][match],
sforsI[idx][match])
#Create initial guesses of the zeropoints, then fit the zeropoints to the
#(V-R) and (R-I) colors using an orthogonal least squares (OLS) regression
#to protect against outliers.
(zpV, zpR, zpI) = (sforsVmatch + (2.5 * np.log10(swfiV[match])),
sforsRmatch + (2.5 * np.log10(swfiR[match])),
sforsImatch + (2.5 * np.log10(swfiI[match])))
vicolor=sforsVmatch-sforsImatch
vrcolor=sforsVmatch-sforsRmatch
ricolor=sforsRmatch-sforsImatch
#For the V-R color, exclude stars with V-R >= 0.7 for clusters with synthesized R-band magnitudes
(vrrange,virange,rirange)=(np.where((vrcolor > 0.) & (vrcolor < 2.5) & (zpV > 22.5) & (zpR > 22.5) & (zpI > 22.5)),
np.where((vicolor > 0.) & (vicolor < 2.5) & (zpV > 22.5) & (zpR > 22.5) & (zpI > 22.5)),
np.where((ricolor > 0.) & (ricolor < 2.5) & (zpV > 22.5) & (zpR > 22.5) & (zpI > 22.5)))
# if synth == True:
# goodvr = np.where((vrcolor > 0.0) & (vrcolor < 2.5))
# (zpVvr, zpRvr, vr) = (zpV[goodvr], zpR[goodvr], vrcolor[goodvr])
# vfit0=curve_fit(fixedVRv,vr,zpVvr)[0][0]
# rfit0=curve_fit(fixedVRr,vr,zpRvr)[0][0]
# else:
# goodvr = np.where((vrcolor > 0.) & (vrcolor < 2.5))
# (zpVvr, zpRvr, vr) = (zpV[goodvr], zpR[goodvr], vrcolor[goodvr])
# vfit0=curve_fit(fixedVRv,vr,zpVvr)[0][0]
# rfit0=curve_fit(fixedVRr,vr,zpRvr)[0][0]
(zpVvi, zpVvr, zpRri, zpRvr, zpIri, zpIvi) = (zpV[virange], zpV[vrrange], zpR[rirange], zpR[vrrange], zpI[rirange], zpI[virange])
(vr,ri,vi) = (vrcolor[vrrange],ricolor[rirange],vicolor[virange])
vfit0=curve_fit(fixedVRv,vr,zpVvr)[0][0]
rfit0=curve_fit(fixedVRr,vr,zpRvr)[0][0]
vfit20=curve_fit(fixedVIv,vi,zpVvi)[0][0]
rfit20=curve_fit(fixedRIr,ri,zpRri)[0][0]
ifit0=curve_fit(fixedVIi,vi,zpIvi)[0][0]
ifit20=curve_fit(fixedRIi,ri,zpIri)[0][0]
if show == True:
print '\n\tFITTED SLOPES:\n'
print '\tV (vr) slope: '+str(vfit0)
print '\tR (vr) slope: '+str(rfit0)
print '\tV (vi) slope: '+str(vfit20)
print '\tI (vi) slope: '+str(ifit0)
print '\tR (ri) slope: '+str(rfit20)
print '\tI (ri) slope: '+str(ifit20)+'\n'
pdb.set_trace()
if plot == True:
plt.plot(vi,zpIvi,'ro')
plt.plot(vi,zpVvi,'bo')
plt.plot(vr,zpRvr,'ko')
xx=np.array([-100.0,100.0])
yy=ifit0+(xx*medCterms['VIi'])
yy2=vfit20+(xx*medCterms['VIv'])
yy3=rfit0+(xx*medCterms['VRr'])
plt.plot(xx,yy,'r--')
plt.plot(xx,yy2,'b--')
plt.plot(xx,yy3,'k--')
plt.axis([0,2.5,np.min([ifit0,vfit20,rfit0])-0.5,np.max([ifit0,vfit20,rfit0])+1.])
plt.xlabel('(V-I)')
plt.ylabel('ZP')
plt.savefig('slopecheck.pdf', format='pdf', dpi=6000)
plt.close()
if ((type(vr1) is int) | (type(vi1) is int) | (type(ri1) is int)):
#Iterate over the WFI photometry (used 20 iterations from Dennis's code) to
#sovle for the zeropoint for each source. When there is no V-band data, use
#the (R-I) color (and the assosciated fit), otherwise use the (V-R) and (V-I)
#colors.
(nv,nr,ni)=(0,0,0)
(zpV0,zpR0,zpI0)=(vfit0+(0.5*medCterms['VRv']), rfit0+(0.5*medCterms['VRr']), ifit0+(0.5*medCterms['VIi']))
(vmag,rmag,imag)=(np.empty(len(starR)),np.empty(len(starR)),np.empty(len(starR)))
(zpv,zpr,zpi)=(np.empty(len(starR)),np.empty(len(starR)),np.empty(len(starR)))
rpflag=np.empty(len(starR))
for j in range(len(starR)):
(zpv[j], zpr[j], zpi[j]) = (zpV0, zpR0, zpI0)
(ii, rdiff, vdiff, idiff) = (0, 1.0, 1.0, 1.0)
if v[j] > 0:
(zpcomp,compmag) = (zpV0,flux2mag(v[j],zpV0))
else:
(zpcomp,compmag) = (zpI0,flux2mag(i[j],zpI0))
oldr=flux2mag(r[j],zpr[j])
rmag[j]=oldr
while (ii <= 20) and (np.abs(rdiff) > tol):
if v[j] > 0:
rpflag[j]=ii
zpr[j]=medCterms['VRr']*(compmag-rmag[j])+rfit0
zpcomp=medCterms['VRv']*(compmag-rmag[j])+vfit0
rmag[j]=flux2mag(r[j],zpr[j])
compmag=flux2mag(v[j],zpcomp)
elif ((v[j] <= 0) & (i[j] > 0)):
rpflag[j]=-1
zpr[j]=medCterms['RIr']*(rmag[j]-compmag)+rfit20
zpcomp=medCterms['RIi']*(rmag[j]-compmag)+ifit20
rmag[j]=flux2mag(r[j],zpr[j])
compmag=flux2mag(i[j],zpcomp)
else:
rpflag[j]=-1
rmag[j]=flux2mag(r[j],zpr[j])
rdiff=oldr-rmag[j]
oldr=rmag[j]
ii += 1
ii = 0
if v[j] > 0:
oldv=flux2mag(v[j],zpv[j])
vmag[j]=oldv
compmag=rmag[j]
while (ii <= 20) and (np.abs(vdiff) > tol):
zpv[j]=medCterms['VRv']*(vmag[j]-compmag)+vfit0
vmag[j]=flux2mag(v[j],zpv[j])
vdiff=oldv-vmag[j]
oldv=vmag[j]
ii += 1
else:
vmag[j]=-99
ii = 0
if i[j] > 0:
oldi=flux2mag(i[j],zpi[j])
imag[j]=oldi
if v[j] > 0:
(fit0, fit1, compmag, cfit0, cfit1) = (ifit0, medCterms['VIi'], vmag[j], vfit20, medCterms['VIv'])
else:
(fit0, fit1, compmag, cfit0, cfit1) = (ifit20, medCterms['RIi'], rmag[j], rfit20, medCterms['RIr'])
while (ii <= 20) and (np.abs(idiff) > tol):
zpi[j]=fit1*(compmag-imag[j])+fit0
imag[j]=flux2mag(i[j],zpi[j])
idiff=oldi-imag[j]
oldi=imag[j]
ii += 1
else:
imag[j]=-99
else:
(vmag,rmag,imag)=(np.empty(len(starR)),np.empty(len(starR)),np.empty(len(starR)))
(zpv,zpr,zpi)=(np.empty(len(starR)),np.empty(len(starR)),np.empty(len(starR)))
#For if the color is supplied (e.g., the 1" colors are supplied for larger apertures so the colors are uniform
#for the zeropoint calculations)
for j in range(len(starR)):
if ((v[j] > 0) & (i[j] > 0)):
zpv[j]=fixedVRv(vr1[j],vfit0)
zpr[j]=fixedVRr(vr1[j],rfit0)
zpi[j]=fixedVIi(vi1[j],ifit0)
vmag[j]=flux2mag(v[j],zpv[j])
rmag[j]=flux2mag(r[j],zpr[j])
imag[j]=flux2mag(i[j],zpi[j])
elif ((v[j] <= 0) & (i[j] > 0)):
vmag[j]=-99
zpr[j]=fixedRIr(ri1[j],rfit20)
zpi[j]=fixedRIi(ri1[j],ifit20)
rmag[j]=flux2mag(r[j],zpr[j])
imag[j]=flux2mag(i[j],zpi[j])
elif ((v[j] <= 0) & (i[j] <= 0)):
vmag[j]=-99
imag[j]=-99
zpr[j]=fixedVRr(0.5,rfit0)
rmag[j]=flux2mag(r[j],zpr[j])
#Convert the Vega magnitudes to AB magnitudes and uJy fluxes. Return the uJy fluxes
#and the AB magnitude zeropoints.
(vmagab, rmagab, imagab) = (vmag + vega2AB['v'], rmag + vega2AB['r'], imag + vega2AB['i'])
(vab, rab, iab) = (mag2flux(vmagab, ab2ujy=True), mag2flux(rmagab, ab2ujy=True), mag2flux(imagab, ab2ujy=True))
return (vab, rab, iab, zpv + vega2AB['v'], zpr + vega2AB['r'], zpi + vega2AB['i'])
#-----------------------------------
def mergeLists(b="",v="",r="",i="",z="",k="",rimg="",zpb=0.0,zpk=0.0,null=-99):
"""
"""
(foo1,foo2)=np.loadtxt(r, usecols = (0,1), unpack=True, comments= '#')
nsrcs=len(foo1)
nullArr = np.zeros(nsrcs) + null
columnsR = (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
columnsX = (4, 5, 6, 7, 8, 15)
if b != "":
(b1, b2, b3, biso, bauto, sexflagB) = np.loadtxt(b, usecols = columnsX,
unpack = True, comments = '#')
else:
(b1, b2, b3, biso, bauto, sexflagB) = (np.zeros(nsrcs)+null, np.zeros(nsrcs)+null, np.zeros(nsrcs)+null,
np.zeros(nsrcs)+null, np.zeros(nsrcs)+null, np.zeros(nsrcs)+null)
if v != "":
(v1, v2, v3, viso, vauto, sexflagV) = np.loadtxt(v, usecols = columnsX, unpack = True, comments = '#')
else:
(v1, v2, v3, viso, vauto, sexflagV) = (np.zeros(nsrcs)+null, np.zeros(nsrcs)+null, np.zeros(nsrcs)+null,
np.zeros(nsrcs)+null, np.zeros(nsrcs)+null, np.zeros(nsrcs)+null)
(x, y, r1, r2, r3, riso, rauto, fwhmR, kronR, aimage,
bimage, theta, isoarea, starR, sexflagR) = np.loadtxt(r, usecols = columnsR, unpack = True, comments = '#')
fwhmR = fwhmR * 3600.0
majorax = kronR * aimage
minorax = kronR * bimage
if i != "":
(i1, i2, i3, iiso, iauto, sexflagI) = np.loadtxt(i, usecols = columnsX, unpack = True, comments = '#')
else:
(i1, i2, i3, iiso, iauto, sexflagI) = (np.zeros(nsrcs)+null, np.zeros(nsrcs)+null, np.zeros(nsrcs)+null,
np.zeros(nsrcs)+null, np.zeros(nsrcs)+null, np.zeros(nsrcs)+null)
if z != "":
(z1, z2, z3, ziso, zauto, sexflagz) = np.loadtxt(z, usecols = columnsX, unpack = True, comments = '#')
else:
(z1, z2, z3, ziso, zauto, sexflagz) = (np.zeros(nsrcs)+null, np.zeros(nsrcs)+null, np.zeros(nsrcs)+null,
np.zeros(nsrcs)+null, np.zeros(nsrcs)+null, np.zeros(nsrcs)+null)
if k != "":
(k1, k2, k3, kiso, kauto, sexflagK) = np.loadtxt(k, usecols = columnsX, unpack = True, comments = '#')
else:
(k1, k2, k3, kiso, kauto, sexflagK) = (np.zeros(nsrcs)+null, np.zeros(nsrcs)+null, np.zeros(nsrcs)+null,
np.zeros(nsrcs)+null, np.zeros(nsrcs)+null, np.zeros(nsrcs)+null)
#Convert (x,y) into RA and Dec
np.savetxt('dummy.foobar', np.c_[(x, y)])
sp.Popen('xy2sky -d '+rimg+' @dummy.foobar > dummy2.foobar', shell=True).wait()
(ra, dec) = np.loadtxt('dummy2.foobar', usecols = (0, 1), unpack = True)
os.remove('dummy.foobar')
os.remove('dummy2.foobar')
data = {'ra':ra, 'dec':dec, 'x':x, 'y':y, 'b1':b1, 'b2':b2, 'b3':b3, 'biso':biso, 'bauto':bauto,
'sexflagB':sexflagB, 'v1':v1, 'v2':v2, 'v3':v3, 'viso':viso, 'vauto':vauto, 'sexflagV':sexflagV,
'r1':r1, 'r2':r2, 'r3':r3, 'riso':riso, 'rauto':rauto, 'starR':starR, 'sexflagR':sexflagR, 'i1':i1, 'i2':i2,
'i3':i3, 'iiso':iiso, 'iauto':iauto, 'sexflagI':sexflagI, 'z1':z1, 'z2':z2, 'z3':z3, 'ziso':ziso,
'zauto':zauto, 'sexflagz':sexflagz, 'k1':k1, 'k2':k2, 'k3':k3, 'kiso':kiso, 'kauto':kauto,
'sexflagK':sexflagK, 'fwhmR':fwhmR, 'kron_a':majorax, 'kron_b':minorax, 'isoarea':isoarea,
'theta':theta}
return data
#-----------------------------------
def updateBCat(b='',r='',rb='',zpb='',imglist='imglist',rsegmap='',oldcat='',null=-99,xmin=0.,xmax=1e6,
ymin=0.,ymax=1e6,clname='',pixscale=0.238,errborder=50.,includeLDP=False):
abconvb = vega2AB['bkpno']
(foo1,foo2)=np.loadtxt(r, usecols = (0,1), unpack=True, comments= '#')
nsrcs=len(foo1)
nullArr = np.zeros(nsrcs) + null
(keys,files)=np.loadtxt(imglist,usecols=(0,1),unpack=True,dtype={'names':('keys','files'), 'formats':('S4','S30')})
imgs={}
for x in range(len(keys)):
imgs[keys[x]]=files[x]
bbkgsub=imgs['bimg'][:-5]+'_bkgsub.fits'
hdu = pf.open(oldcat)
oldData = hdu[1].data
if includeLDP == True:
#Add in LDP redshifts
megatab=pf.open('/Users/tyler/megacat.v5.7.fits')
megadat=megatab[1].data
(mzldp,mq)=(megadat['zldp'],megadat['q'])
wfiSky=coordinates.SkyCoord(ra=oldData['ra']*u.degree, dec=oldData['dec']*u.degree)
megaSky=coordinates.SkyCoord(ra=megadat['ra']*u.degree, dec=megadat['dec']*u.degree)
idx, d2d, _ = megaSky.match_to_catalog_sky(wfiSky)
match = np.where(d2d.arcsec <= 0.5)
(oldData['zLDP'][idx][match],oldData['Q'][idx][match])=(mzldp[match],mq[match])
(oldRx,oldRy) = (oldData['x'],oldData['y'])
tmpData = mergeLists(b=b,r=r,zpb=zpb,null=null,rimg=imgs['rimg'])
res=matchxy(tmpData['x'],tmpData['y'],oldRx,oldRy)
newData = {'b1':tmpData['b1'][res], 'b2':tmpData['b2'][res], 'b3':tmpData['b3'][res],
'biso':tmpData['biso'][res], 'bauto':tmpData['bauto'][res],
'r1':tmpData['r1'][res], 'r2':tmpData['r2'][res], 'r3':tmpData['r3'][res],
'riso':tmpData['riso'][res], 'rauto':tmpData['rauto'][res],
'starB':tmpData['starB'][res], 'sexflagB':tmpData['sexflagB'][res],
'fwhmB':tmpData['fwhmB'][res]}
#Convert the B-band fluxes from SExtractor into uJy fluxes.
#Update the dictionary appropriately. Correct
#the B-band data for seeing if its seeing is worse than the worst
#WFI seeing image.
photcols = (4, 5, 6, 7, 8)
(b1m, b2m, b3m, bisom, bautom) = (calflux(newData['b1'], zpb, abconv = abconvb),
calflux(newData['b2'], zpb, abconv = abconvb),
calflux(newData['b3'], zpb, abconv = abconvb),
calflux(newData['biso'], zpb, abconv = abconvb),
calflux(newData['bauto'], zpb, abconv = abconvb))
(b1c, b2c, b3c, bisoc, bautoc) = (newData['b1'], newData['b2'], newData['b3'],
newData['biso'], newData['bauto'])
# pdb.set_trace()
#Calculate uncertainties
print '\n\tCalculating uncertainties...\n'
(auton,ison,n1,n2,n3)=(np.sqrt(np.pi*tmpData['kron_a'][res]*tmpData['kron_b'][res]),
np.sqrt(tmpData['isoarea'][res]),np.sqrt(np.pi*(1.0/pixscale)**2.0),
np.sqrt(np.pi*(2.0/pixscale)**2.0),np.sqrt(np.pi*(3.0/pixscale)**2.0))
berrpars = lb.main(bbkgsub, rsegmap, outplot='bdepth.pdf', clname=clname, pixscale=pixscale,
border=errborder, persec=False, aprange=[0.5,2.0],maxrange=500.)
bautoerr=(sigfunc(auton,berrpars[0],berrpars[1],berrpars[2])/bautoc)
bisoerr=(sigfunc(ison,berrpars[0],berrpars[1],berrpars[2])/bisoc)
b1err=(sigfunc(n1,berrpars[0],berrpars[1],berrpars[2])/b1c)
b2err=(sigfunc(n2,berrpars[0],berrpars[1],berrpars[2])/b2c)
b3err=(sigfunc(n3,berrpars[0],berrpars[1],berrpars[2])/b3c)
print '\tB-band done\n'
#Correct for seeing (if necessary)
if rb != "":
(rb1, rb2, rb3, rbiso, rbauto) = np.loadtxt(rb, usecols = photcols, unpack = True, comments = '#')
(r1zp, r2zp, r3zp, risozp, rautozp) = (backZP(newData['r1'],flux2mag(oldData['fR1'],23.9)),
backZP(newData['r2'],flux2mag(oldData['fR2'],23.9)),
backZP(newData['r3'],flux2mag(oldData['fR3'],23.9)),
backZP(newData['riso'],flux2mag(oldData['fRiso'],23.9)),
backZP(newData['rauto'],flux2mag(oldData['fRauto'],23.9)))
(rb1m, rb2m , rb3m, rbisom, rbautom) = (calflux(rb1[res], r1zp), calflux(rb2[res], r2zp),calflux(rb3[res], r3zp),
calflux(rbiso[res], risozp),calflux(rbauto[res], rautozp))
#Calculate erorrs again! >_<
rbkgsub=imgs['simg'][:-5]+'_bkgsub.fits'
rerrpars = lb.main(rbkgsub, rsegmap, outplot='r_smooth_depth.pdf', clname=clname, pixscale=pixscale,
border=errborder, persec=False, aprange=[0.5,2.0],maxrange=500.)
rautoerr=(sigfunc(auton,rerrpars[0],rerrpars[1],rerrpars[2])/rb1[res])*rbautom
risoerr=(sigfunc(ison,rerrpars[0],rerrpars[1],rerrpars[2])/rbiso[res])*rbisom
r1err=(sigfunc(n1,rerrpars[0],rerrpars[1],rerrpars[2])/rb1[res])*rb1m
r2err=(sigfunc(n2,rerrpars[0],rerrpars[1],rerrpars[2])/rb2[res])*rb2m
r3err=(sigfunc(n3,rerrpars[0],rerrpars[1],rerrpars[2])/rb3[res])*rb3m
print '\tSmoothed R-band done\n'
# pdb.set_trace()
(b1mc, b2mc, b3mc, bisomc, bautomc) = (seeingCorr(oldData['fR1'], rb1m, b1m), seeingCorr(oldData['fR2'], rb2m, b1m),
seeingCorr(oldData['fR3'], rb3m, b3m), seeingCorr(oldData['fRiso'], rbisom, bisom),
seeingCorr(oldData['fRauto'], rbautom, bautom))
(b1ecorr,b2ecorr,b3ecorr,bisoecorr,bautoecorr) = (b1err*b1mc, b2err*b2mc, b3err*b3mc,
bisoerr*bisomc, bautoerr*bautomc)
(newData['b1e'],newData['b2e'],newData['b3e'],
newData['bisoe'],newData['bautoe']) = (addquad(b1ecorr,oldData['fR1err'],r1err,b1mc,oldData['fR1'],rb1m),
addquad(b2ecorr,oldData['fR2err'],r2err,b2mc,oldData['fR2'],rb2m),
addquad(b3ecorr,oldData['fR3err'],r3err,b3mc,oldData['fR3'],rb3m),
addquad(bisoecorr,oldData['fRisoerr'],risoerr,bisomc,oldData['fRiso'],rbisom),
addquad(bautoecorr,oldData['fRautoerr'],rautoerr,bautomc,oldData['fRauto'],rbautom))
else:
(newData['b1e'], newData['b2e'], newData['b3e'],
newData['bisoe'], newData['bautoe']) = (b1err*newData['b1'], b2err*newData['b2'],
b3err*newData['b3'], bisoerr*newData['biso'],
bautoerr*newData['bauto'])
(b1mc, b2mc, b3mc, bisomc, bautomc) = (b1m, b2m, b3m, bisom, bautom)
(newData['b1'], newData['b2'], newData['b3'],
newData['biso'], newData['bauto']) = (b1mc, b2mc, b3mc, bisomc, bautomc)
outname=clname+'_catalogB_v7.0.fits'
# final=oldData
# (final['fwhmB'],final['fB1'],final['fB1err'],final['fB2'],
# final['fB2err'],final['fB3'],final['fB3err'],final['fBiso'],
# final['fBisoerr'],final['fBauto'],final['fBautoerr'],
# final['starB'],final['sexflagB']) = (newData['fwhmB'],newData['b1'],newData['b1e'],newData['b2'],newData['b2e'],
# newData['b3'],newData['b3e'],newData['biso'],newData['bisoe'],
# newData['bauto'],newData['bautoe'],newData['starB'],newData['sexflagB'])
final={'ids':oldData['ids'],'ra':oldData['ra'],'dec':oldData['dec'],'x':oldData['x'],'y':oldData['y'],'ebv':oldData['ebv'],'fwhmB':oldData['fwhmB'],
'fwhmV':oldData['fwhmV'],'fwhmR':oldData['fwhmR'],'fwhmI':oldData['fwhmI'],'fwhmz':oldData['fwhmz'],'fwhmK':oldData['fwhmK'],
'fB1':newData['b1'],'fB1err':newData['b1e'],'fB2':newData['b2'],'fB2err':newData['b2e'],'fB3':newData['b3'],'fB3err':newData['b3e'],
'fBiso':newData['biso'],'fBisoerr':newData['bisoe'],'fBauto':newData['bauto'],'fBautoerr':newData['bautoe'],'fV1':oldData['fV1'],
'fV1err':oldData['fV1err'],'fV2':oldData['fV2'],'fV2err':oldData['fV2err'],'fV3':oldData['fV3'],'fV3err':oldData['fV3err'],'fViso':oldData['fViso'],
'fVisoerr':oldData['fVisoerr'],'fVauto':oldData['fVauto'],'fVautoerr':oldData['fVautoerr'],'fR1':oldData['fR1'],'fR1err':oldData['fR1err'],
'fR2':oldData['fR2'],'fR2err':oldData['fR2err'],'fR3':oldData['fR3'],'fR3err':oldData['fR3err'],'fRiso':oldData['fRiso'],'fRisoerr':oldData['fRisoerr']
,'fRauto':oldData['fRauto'],'fRautoerr':oldData['fRautoerr'],'fI1':oldData['fI1'],'fI1err':oldData['fI1err'],'fI2':oldData['fI2'],
'fI2err':oldData['fI2err'],'fI3':oldData['fI3'],'fI3err':oldData['fI3err'],'fIiso':oldData['fIiso'],'fIisoerr':oldData['fIisoerr'],
'fIauto':oldData['fIauto'],'fIautoerr':oldData['fIautoerr'],'fz1':oldData['fz1'],'fz1err':oldData['fz1err'],'fz2':oldData['fz2'],
'fz2err':oldData['fz2err'],'fz3':oldData['fz3'],'fz3err':oldData['fz3err'],'fziso':oldData['fziso'],'fzisoerr':oldData['fzisoerr'],
'fzauto':oldData['fzauto'],'fzautoerr':oldData['fzautoerr'],'fK1':oldData['fK1'],'fK1err':oldData['fK1err'],'fK2':oldData['fK2'],
'fK2err':oldData['fK2err'],'fK3':oldData['fK3'],'fK3err':oldData['fK3err'],'fKiso':oldData['fKiso'],'fKisoerr':oldData['fKisoerr'],
'fKauto':oldData['fKauto'],'fKautoerr':oldData['fKautoerr'],'zLDP':oldData['zLDP'],'Q':oldData['Q'],'starB':newData['starB'],'starV':oldData['starV'],
'starR':oldData['starR'],
'starI':oldData['starI'],'starz':oldData['starz'],'starK':oldData['starK'],'sexflagB':newData['sexflagB'],'sexflagV':oldData['sexflagV'],
'sexflagR':oldData['sexflagR'],'sexflagI':oldData['sexflagI'],'sexflagz':oldData['sexflagz'],'sexflagK':oldData['sexflagK']}
# s=['ids','ra','dec','x','y','ebv','fwhmB','fwhmV','fwhmR','fwhmI','fwhmz','fwhmK','fB1','fB1err','fB2',
# 'fB2err','fB3','fB3err','fBiso','fBisoerr',
# 'fBauto','fBautoerr','fV1','fV1err','fV2','fV2err','fV3','fV3err','fViso','fVisoerr','fVauto',
# 'fVautoerr','fR1','fR1err','fR2','fR2err','fR3','fR3err','fRiso','fRisoerr','fRauto',
# 'fRautoerr','fI1','fI1err','fI2','fI2err','fI3','fI3err','fIiso','fIisoerr','fIauto',
# 'fIautoerr','fz1','fz1err','fz2','fz2err','fz3','fz3err','fziso','fzisoerr','fzauto',
# 'fzautoerr','fK1','fK1err','fK2','fK2err','fK3','fK3err','fKiso','fKisoerr','fKauto',
# 'fKautoerr','zLDP','Q','starB','starV','starR','starI','starz','starK','sexflagB','sexflagV','sexflagR','sexflagI',
# 'sexflagz','sexflagK']
# pdb.set_trace()
#Save the dictionary as a FITS table
tab = Table(final, names=('ids','ra','dec','x','y','ebv','fwhmB','fwhmV','fwhmR','fwhmI','fwhmz','fwhmK','fB1','fB1err','fB2',
'fB2err','fB3','fB3err','fBiso','fBisoerr',
'fBauto','fBautoerr','fV1','fV1err','fV2','fV2err','fV3','fV3err','fViso','fVisoerr','fVauto',
'fVautoerr','fR1','fR1err','fR2','fR2err','fR3','fR3err','fRiso','fRisoerr','fRauto',
'fRautoerr','fI1','fI1err','fI2','fI2err','fI3','fI3err','fIiso','fIisoerr','fIauto',
'fIautoerr','fz1','fz1err','fz2','fz2err','fz3','fz3err','fziso','fzisoerr','fzauto',
'fzautoerr','fK1','fK1err','fK2','fK2err','fK3','fK3err','fKiso','fKisoerr','fKauto',
'fKautoerr','zLDP','Q','starB','starV','starR','starI','starz','starK','sexflagB','sexflagV','sexflagR','sexflagI',
'sexflagz','sexflagK'))
tab.write(outname, format='fits', overwrite=True)
#-----------------------------------
def updateKCat(k='',r='',rk='',zpk='',imglist='imglist',rsegmap='',oldcat='',null=-99,xmin=0.,xmax=1e6,
ymin=0.,ymax=1e6,clname='',pixscale=0.238,errborder=50.,expmap=''):
abconvk = vega2AB['k']
(foo1,foo2)=np.loadtxt(r, usecols = (0,1), unpack=True, comments= '#')
nsrcs=len(foo1)
nullArr = np.zeros(nsrcs) + null
(keys,files)=np.loadtxt(imglist,usecols=(0,1),unpack=True,dtype={'names':('keys','files'), 'formats':('S4','S30')})
imgs={}