-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbc03_comp.py
476 lines (378 loc) · 15.7 KB
/
bc03_comp.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
from glob import glob
import os
import re
import numpy as np
import pyfits
from yanny import yanny
from pyraf import iraf
import time
import prep_balmer as pb
import scipy.stats as ss
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages as PDF
plt.ioff()
iraf.noao(_doprint=0)
iraf.onedspec(_doprint=0)
def bc03_prep():
fraclist = np.array([1,0.2,0.02,0.005,0.4,2.5])
modellist = ['/d/monk/eigenbrot/WIYN/14B-0456/anal/models/bc03_{}_ChabIMF.fits'.format(i) for i in ['solarZ','004Z','0004Z','0001Z','008Z','05Z']]
for i, model in enumerate(modellist):
h = pyfits.open(model)[1]
linwave = np.arange(h.data['WAVE'].min(),h.data['WAVE'].max(),2.1)
numage = h.data['FLUX'].shape[1]
out = np.zeros((numage,linwave.size))
for j in range(numage):
out[j,:] = np.interp(linwave,h.data['WAVE'][0],
h.data['FLUX'][0,j])
outhdu = pyfits.PrimaryHDU(out)
outhdu.header.update('Z',fraclist[i])
outhdu.header.update('CTYPE1','LINEAR')
outhdu.header.update('CRPIX1',1)
outhdu.header.update('CRVAL1',linwave.min())
outhdu.header.update('CDELT1',np.mean(np.diff(linwave)))
outhdu.header.update('CTYPE2','LINEAR')
outhdu.header.update('CRPIX2',1)
outhdu.header.update('CRVAL2',numage)
outhdu.header.update('CDELT2',1)
outhdu.writeto('BC03_Z{:04n}.fits'.format(fraclist[i]*1000),clobber=True)
return
def data_prep(datafile, velocity, output, isdata=True):
wavemin=3800.
wavemax=6800.
vel = np.loadtxt(velocity,usecols=(1,),unpack=True)
hdu = pyfits.open(datafile)[0]
data = hdu.data
header = hdu.header
if isdata:
cdelt = header['CDELT1']
crpix = header['CRPIX1']
crval = header['CRVAL1']
base = os.path.basename(datafile)
dirn = os.path.dirname(datafile)
pointing = int(re.search('_P([1-6])_',base).groups()[0])
fitfile = '{}/{}_allz2.fit.fits'.format(dirn,base.split('.')[0])
contsub = '{}/{}_contsub.ms.fits'.format(dirn,base.split('.')[0])
pb.prep_spectra(datafile, fitfile, contsub, velocity)
pb.do_fitprof(contsub, pointing)
emline = pyfits.open('{}/P{}_HB_fits.fits'.format(dirn,pointing))[0].data
else:
#Hacky hack for fit files. These values should not really change, so I think it's OK
cdelt = 2.1
crpix = 1
crval = 3800.
header.update('CDELT1',cdelt)
header.update('CRPIX',crpix)
wave = (np.arange(data.shape[1]) + crpix-1)*cdelt + crval
idx = np.where((wave >= wavemin) & (wave <= wavemax))[0]
wave = wave[idx]
data = data[:,idx]
shift = np.vstack([np.interp(wave,wave*(1 - vel[i]/3e5),data[i,:]) for i in range(data.shape[0])])
if isdata:
# emline = emline[:,idx]
print shift.shape
print emline.shape
shift -= emline/1e17
header.update('CRVAL1', 3800.)
pyfits.PrimaryHDU(shift,header).writeto(output,clobber=True)
return
def prep_all_data():
for i in range(6):
output = 'NGC_891_P{}_bin30.msz.fits'.format(i+1)
data_prep('NGC_891_P{}_bin30.ms.fits'.format(i+1),
'NGC_891_P{}_bin30_velocities.dat'.format(i+1),output)
return
def run_sbands(findstr, bands, clobber=True):
inputlist = glob(findstr)
for data in inputlist:
output = data.split('.fits')[0]+'.bands.dat'
print '{} -> {}'.format(data,output)
if clobber and os.path.exists(output):
os.system('rm {}'.format(output))
iraf.sbands(data,output,bands,
normali=True,
mag=False,
verbose=True,
_save=0)
return
def combine_sbands(output,numaps=10):
numbands = 7
fraclist = np.array([1,0.2,0.02,0.005,0.4,2.5])
fraclist = np.sort(fraclist)
results = np.zeros((numaps, fraclist.size, numbands))
for f, frac in enumerate(fraclist):
fracfile = 'BC03_Z{:04n}.bands.dat'.format(frac*1000)
data = np.loadtxt(fracfile,usecols=(0,1,5,6),
dtype={'names':('aps','bands','index','eqwidth'),
'formats':('S26','S11','f4','f4')})
aps = np.unique(data['aps'])
sar = [int(s.split(',')[-1].split(']')[0]) for s in aps]
sidx = np.argsort(sar)
print aps[sidx]
for a, ap in enumerate(aps[sidx]):
idx = np.where(data['aps'] == ap)
results[a,f,:] = eat_index(data['eqwidth'][idx])
outhdu = pyfits.PrimaryHDU(results)
outhdu.header.update('d0','aperture')
outhdu.header.update('d1','Z')
outhdu.header.update('d2','index')
outhdu.header.update('i0','HB')
outhdu.header.update('i1','HdA')
outhdu.header.update('i2','HgA')
outhdu.header.update('i3','HdF')
outhdu.header.update('i4','HgF')
outhdu.header.update('i5','FeAvg')
outhdu.header.update('i6','MgFe')
outhdu.writeto(output,clobber=True)
return
def quick_eat(datafile, numbands=7):
data = np.loadtxt(datafile,usecols=(0,1,5,6),
dtype={'names':('aps','bands','index','eqwidth'),
'formats':('S80','S11','f4','f4')},
converters={5: eat_indef, 6: eat_indef})
aps = np.unique(data['aps'])
sar = [int(s.split(',')[-1].split(']')[0]) for s in aps]
sidx = np.argsort(sar)
numaps = aps.size
results = np.zeros((numaps,numbands))
for a, ap in enumerate(aps[sidx]):
idx = np.where(data['aps'] == ap)
results[a,:] = eat_index(data['eqwidth'][idx])
return results
def eat_indef(s):
try:
res = np.float(s)
except ValueError:
res = np.nan
return res
def bc03_compare(databands, bc03bands, outputprefix):
pp = PDF('{}.pdf'.format(outputprefix))
f = open('{}.dat'.format(outputprefix), 'w')
f.write('#{:>7}{:>10}{:>10}\n'.format('Apnum','Age [Gyr]','Z/Z_sol'))
fraclist = np.array([1,0.2,0.02,0.005,0.4,2.5])
fraclist = np.sort(fraclist)
agelist = np.array([ 5.01186000e+06, 2.51188000e+07, 1.01518000e+08,
2.86119008e+08, 6.40542976e+08, 9.04792000e+08,
1.43400000e+09, 2.50000000e+09, 5.00000000e+09,
1.00000000e+10])/1e9
bc03data = pyfits.open(bc03bands)[0].data
numages, numZ, numindex = bc03data.shape
galdata = np.loadtxt(databands,usecols=(0,1,5,6),
dtype={'names':('aps','bands','index','eqwidth'),
'formats':('S50','S11','f4','f4')})
aps = np.unique(galdata['aps'])
sar = [int(s.split('(')[-1].split(')')[0]) for s in aps]
sidx = np.argsort(sar)
outdata = np.zeros((aps.size,2))
for a, ap in enumerate(aps[sidx]):
idx = np.where(galdata['aps'] == ap)
bands = eat_index(galdata['eqwidth'][idx])
compdata = np.tile(bands,(numages,numZ,1))
chigrid = np.sum((compdata - bc03data)**2/bc03data,axis=2)
bestage, bestZ = np.unravel_index(np.argmin(chigrid),chigrid.shape)
outdata[a,0] = agelist[bestage]
outdata[a,1] = fraclist[bestZ]
f.write('{:8n}{:10.2f}{:10.0e}\n'.format(a+1,agelist[bestage],fraclist[bestZ]))
fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(111)
I = ax.imshow(chigrid,cmap=plt.cm.gnuplot,interpolation='nearest',
origin='lower')
ax.set_title('Aperture {:}\nZ = {:5.2e} Z/Z$_{{\odot}}$\nAge = {:5.3f} Gyr'.format(a,outdata[a,1],outdata[a,0]))
ax.set_yticks(np.arange(agelist.size))
ax.set_yticklabels(['{:3.3f}'.format(a) for a in agelist])
ax.set_xlabel('Z/Z$_{\odot}$')
ax.set_xticks(np.arange(fraclist.size))
ax.set_xticklabels(fraclist)
ax.set_ylabel('SSP Age [Gyr]')
ax.axvline(x=bestZ,color='white')
ax.axhline(y=bestage,color='white')
pp.savefig(fig)
plt.close(fig)
f.close()
pp.close()
return outdata
def eat_index(index):
#Assumes order is:
#0 HdA
#1 HgA
#2 HdF
#3 HgF
#4 Mgb
#5 Fe5270
#6 Fe5335
#7 HB
#
# Output is:
# 0 HB
# 1 HdA
# 2 HgA
# 3 HdF
# 4 HgF
# 5 <Fe>
# 6 <MgFe>
FeAvg = 0.5*(index[5] + index[6])
MgFe = np.sqrt(index[4]*(0.72*index[5] + 0.28*index[6]))
return np.array([index[7], index[0], index[1],
index[2], index[3],
FeAvg, MgFe])
def plot_bc03_grid(bc03_data_file, ax, band1, band2):
fraclist = np.array([1,0.2,0.02,0.005,0.4,2.5])
fraclist = np.sort(fraclist)
agelist = np.array([ 5.01186000e+06, 2.51188000e+07, 1.01518000e+08,
2.86119008e+08, 6.40542976e+08, 9.04792000e+08,
1.43400000e+09, 2.50000000e+09, 5.00000000e+09,
1.00000000e+10])/1e9
bc03data = pyfits.open(bc03_data_file)[0].data
numages, numZ, numindex = bc03data.shape
idx = np.where(agelist >= 0.3)[0]
for a in range(numages - 3):
# ax.plot(np.log10(bc03data[a+3,:,band1]),
# np.log10(bc03data[a+3,:,band2]),
# '-k')
# ax.text(np.log10(bc03data[a+3,-1,band1]),
# np.log10(bc03data[a+3,-1,band2]),
# '{:4.1f} Gyr'.format(agelist[a+3]),fontsize=6,ha='right')
ax.plot(bc03data[a+3,:,band1],
bc03data[a+3,:,band2],
'-k')
ax.text(bc03data[a+3,-1,band1],
bc03data[a+3,-1,band2],
'{:4.1f} Gyr'.format(agelist[a+3]),fontsize=6,ha='left')
for z in range(numZ):
# ax.plot(np.log10(bc03data[idx,z,band1]),
# np.log10(bc03data[idx,z,band2]),
# ':k')
# ax.text(np.log10(bc03data[idx[-1],z,band1]),
# np.log10(bc03data[idx[-1],z,band2]),
# '{:4.1f} Z/Z$_{{\odot}}$'.format(fraclist[z]),fontsize=6)
ax.plot(bc03data[idx,z,band1],
bc03data[idx,z,band2],
':k')
ax.text(bc03data[idx[-1],z,band1],
bc03data[idx[-1],z,band2],
'{:4.2f} Z/Z$_{{\odot}}$'.format(fraclist[z]),fontsize=6,ha='center',va='top')
return
def plot_yanny_on_grid(parfile, ax, band1, band2):
par = yanny(parfile,np=True)
scat = ax.scatter(par['APINFO'][band1], par['APINFO'][band2],
c=np.abs(par['APINFO']['z']), s=40, linewidths=0,
alpha=0.7, cmap=plt.cm.gnuplot2)
return scat
def plot_index_grid(bc03_data_file,data_file,output):
fig = plt.figure(figsize=(12,11))
bandlist = ['Hb','HdA','HgA','HdF','HgF','Fe','MgFe']
ab = ['<Fe>','<MgFe>']
o = [r'$H\beta$',r'$H_{\delta,A}$','$H_{\gamma,A}$']
axes = []
for p in range(6):
ax = fig.add_subplot(3,2,p+1)
axes.append(ax)
plot_bc03_grid(bc03_data_file,ax,
5 + (p % 2),
p/2)
scat = plot_yanny_on_grid(data_file,ax,
bandlist[5 + (p % 2)],
bandlist[p/2])
ax.set_xlabel(ab[p%2])
ax.set_ylabel(o[p/2])
# ax.set_xlim(0.87,1.05)
# ax.set_ylim(0.728,1.197)
# ax.set_xlim(-0.060,0.021)
# ax.set_ylim(-0.138,0.078)
if p < 4:
ax.set_xticklabels([])
ax.set_xlabel('')
if p % 2 == 1:
ax.set_yticklabels([])
ax.set_ylabel('')
fig.subplots_adjust(hspace=0.0001,wspace=0.0001)
cb = fig.colorbar(scat,ax=axes)
cb.set_label('z [kpc]')
fig.suptitle('{}\nGenerated on {}'.format(data_file,time.asctime()))
pp = PDF(output)
pp.savefig(fig)
pp.close()
plt.close(fig)
return
def model_compare(dataloc, modellist, output, prep=True, sband=True):
pp = PDF(output)
bandlist = ['Hb','HdA','HgA','HdF','HgF','Fe','MgFe']
plotbands = [0, 1, 2, 5, 6]
axlims = [[1,6], [-5,9],[-7,7],[0,3.5],[0,4]]
for p in range(6):
fig = plt.figure(figsize=(6,8))
lax = fig.add_subplot(111)
lax.set_axis_off()
lax.set_ylabel('Data')
lax.set_title('P{}\n{}'.format(p+1,time.asctime()),fontsize=8)
#First, get the actual data
datafile = glob('{}/NGC_891_P{}*.ms.fits'.format(dataloc,p+1))[0]
velfile = glob('{}/NGC_891_P{}*velocities.dat'.format(dataloc,p+1))[0]
preppedfile = '{}/NGC_891_P{}_bin30.ms.bp.fits'.format(dataloc,p+1)
print 'Grabbing', datafile
if prep:
data_prep(datafile, velfile, preppedfile)
if sband:
try:
run_sbands(preppedfile, 'LICK.bands'.format(dataloc))
except Exception as e:
print e
run_sbands(preppedfile, 'LICK.bands'.format(dataloc))
bandfile = '{}/NGC_891_P{}_bin30.ms.bp.bands.dat'.format(dataloc,p+1)
data = quick_eat(bandfile)
#Now the different models
linelist = []
leglist = []
axlist = []
for axn, band in enumerate(plotbands):
ax = fig.add_subplot(3,2,axn+2,aspect='equal')
ax.text(0.1,0.85,bandlist[band],transform=ax.transAxes)
ax.tick_params(axis='both',labelsize=8)
axlist.append(ax)
for mnum, mloc in enumerate(modellist):
lax.set_xlabel(mloc)
print '{}/NGC_891_P{}*.fit.fits'.format(mloc,p+1)
modelfile = glob('{}/NGC_891_P{}*.fit.fits'.format(mloc,p+1))[0]
Mvelfile = glob('{}/NGC_891_P{}*velocities.dat'.format(mloc,p+1))[0]
Mpreppedfile = '{}/NGC_891_P{}_bin30_allz2.fit.bp.fits'.format(mloc,p+1)
print 'Grabbing', modelfile
if prep:
data_prep(modelfile, Mvelfile, Mpreppedfile, isdata=False)
if sband:
try:
run_sbands(Mpreppedfile, 'LICK.bands'.format(dataloc))
except Exception as e:
#Fuck you, IRAF
print e
run_sbands(Mpreppedfile, 'LICK.bands'.format(dataloc))
Mbandfile = '{}/NGC_891_P{}_bin30_allz2.fit.bp.bands.dat'.format(mloc,p+1)
model = quick_eat(Mbandfile)
print data.shape
print model.shape
for axn, band in enumerate(plotbands):
l = axlist[axn].plot(data[:,band],model[:,band],'.')[0]
tau, pval = ss.kendalltau(data[:,band], model[:,band])
CI = (1-ss.norm.cdf(ss.norm.isf(tau)))*100
axlist[axn].text(0.9,0.9-mnum*0.05,'{:4.2f}'.format(tau),color=l.get_color(),
transform=axlist[axn].transAxes,fontsize=5)
axlist[axn].set_xlim(*axlims[axn])
axlist[axn].set_ylim(*axlims[axn])
# if axn != 0 and axn %2 == 0:
# ax.set_yticklabels([])
# if axn < 3:
# ax.set_xticklabels([])
linelist.append(l)
leglist.append(os.path.basename(mloc))
for ax in axlist:
ax.autoscale(False)
ax.plot([-100,100],[-100,100],':k',alpha=0.3)
kax = fig.add_axes([0.2,0.7,0.2,0.2])
kax.set_xlabel('Data')
kax.set_ylabel('Best Fit Model')
kax.set_xticklabels([])
kax.set_yticklabels([])
kax.legend(linelist, leglist, loc='center',fontsize=8, numpoints=1,frameon=False)
# fig.subplots_adjust(hspace=0.0001, wspace=0.0001)
fig.tight_layout(h_pad=0.2,w_pad=1.2)
pp.savefig(fig)
plt.close(fig)
pp.close()