def ngc3100_NI_Hb(): galaxy = 'ngc3100' opt='pop' instrument='vimos' from plot_results import add_ from errors2 import get_dataCubeDirectory Prefig(size=(8,8)) fig, ax = plt.subplots() f = fits.open(get_dataCubeDirectory(galaxy)) header = f[0].header f.close() D = Data(galaxy, instrument=instrument, opt=opt) ax = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, D.components['[NI]d'].flux/D.components['Hbeta'].flux, header, nodots=True, flux_unbinned=D.unbinned_flux, colorbar=True, ax=ax, label=r'$\mathrm{\frac{[NI]\lambda\lambda5197,5200}{H\beta}}$', label_size=1.4) for o, color in {'radio':'g','CO':'w'}.iteritems(): scale = 'log' if o == 'radio' else 'lin' add_(o, color, ax, galaxy, nolegend=True, scale=scale) ax.ax_dis.tick_params(top=True, bottom=True, left=True, right=True, direction='in', which='major', length=20, width=3, labelsize='large') ax.ax_dis.tick_params(top=True, bottom=True, left=True, right=True, direction='in', which='minor', length=10, width=3) fig.savefig('%s/Documents/paper/vimos/ngc3100_NI_Hb.png' % ( cc.home_dir), dpi=300, bbox_inches='tight')
def get_specFromAperture(galaxy, app_size=1.0, inside=True): f = fits.open(get_dataCubeDirectory(galaxy)) s = f[0].data.shape res = f[0].header['CDELT1'] galaxy_gals = np.loadtxt('%s/Data/vimos/analysis/galaxies.txt' % (cc.base_dir), unpack=True, skiprows=1, usecols=(0,), dtype=str) x_cent, y_cent = np.loadtxt('%s/Data/vimos/analysis/galaxies.txt' % (cc.base_dir), unpack=True, skiprows=1, usecols=(4,5), dtype=int) i_gal = np.where(galaxy_gals==galaxy)[0][0] x_cent = x_cent[i_gal] y_cent = y_cent[i_gal] # area = get_areaInAperture(s[1], s[2], x_cent, y_cent, app_size/res) area = in_aperture(x_cent, y_cent, app_size/res, instrument='vimos') if not inside: area = 1 - area # Deal with NaN d = f[0].data d[np.isnan(d)] = 0 n = f[1].data n[np.isnan(n)] = 0 return np.einsum('ijk,jk->i', d, area), \ np.sqrt(np.einsum('ijk,jk->i', n**2, area)), \ np.arange(s[0])*f[0].header['CDELT3'] + f[0].header['CRVAL3']
def __init__(self, galaxy, slit_h=4.5*60, slit_w=2, slit_pa=30, method='aperture', r1=0.0, r2=1.0, debug=False): self.galaxy = galaxy self.slit_w = float(slit_w) self.slit_h = float(slit_h) self.slit_pa = float(slit_pa) self.debug = debug self.method = method self.r1 = float(r1) self.r2 = float(r2) ## ----------============== Load galaxy info ================--------- data_file = "%s/Data/vimos/analysis/galaxies.txt" % (cc.base_dir) # different data types need to be read separetly z_gals, vel_gals, sig_gals, x_gals, y_gals = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=(1,2,3,4,5)) galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0,),dtype=str) self.i_gal = np.where(galaxy_gals==galaxy)[0][0] self.vel = vel_gals[self.i_gal] self.sig = sig_gals[self.i_gal] self.z = z_gals[self.i_gal] data_file = "%s/Data/vimos/analysis/galaxies2.txt" % (cc.base_dir) # different data types need to be read separetly ellip = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=(2,)) galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0,),dtype=str) i_gal2 = np.where(galaxy_gals==galaxy)[0][0] self.ellip = ellip[i_gal2] self.f = fits.open(get_dataCubeDirectory(galaxy)) self.lam = np.arange(self.f[0].header['NAXIS3'])*self.f[0].header['CDELT3'] + \ self.f[0].header['CRVAL3'] self.x_cent = x_gals[self.i_gal] * self.f[0].header['CDELT1'] self.y_cent = y_gals[self.i_gal] * self.f[0].header['CDELT2'] self.cube = self.f[0].data self.cube /= np.nanmedian(self.cube, axis=0) # Noramlise cube self.cube[self.f[3].data==1] = 0 self.noise_cube = self.f[1].data self.noise_cube[self.f[3].data==1] = 0.000000001 self.cube[~np.isfinite(self.noise_cube)] = 0 self.noise_cube[~np.isfinite(self.noise_cube)] = 0.000000001 ## ----------============ Find data within slit =============--------- self.x = (np.arange(self.f[0].header['NAXIS1']) * self.f[0].header['CDELT1'] ).repeat(self.f[0].header['NAXIS2']) self.y = np.tile(np.arange(self.f[0].header['NAXIS2']) * self.f[0].header['CDELT2'], self.f[0].header['NAXIS1']) self.slit_res = 0.82 # "/px
def __init__(self, galaxy): self.f = fits.open(get_dataCubeDirectory(galaxy)) s = self.f[0].data.shape self.gal_spec = np.nansum(self.f[0].data, axis=(1,2)) self.gal_noise = np.sqrt(np.nansum(self.f[1].data**2, axis=(1,2))) data_file = "%s/Data/vimos/analysis/galaxies.txt" % (cc.base_dir) # different data types need to be read separetly z_gals, vel_gals, sig_gals, x_gals, y_gals = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=(1,2,3,4,5)) galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0,),dtype=str) i_gal = np.where(galaxy_gals==galaxy)[0][0] self.vel = vel_gals[i_gal] self.sig = sig_gals[i_gal] self.z = z_gals[i_gal] self.lam = np.arange(s[0])*self.f[0].header['CDELT3'] + self.f[0].header['CRVAL3']
def __init__(self, galaxy, slit_h=4.1, slit_w=2.5, slit_pa=30, debug=False): self.debug = debug ## ----------============== Load galaxy info ================--------- data_file = "%s/Data/vimos/analysis/galaxies.txt" % (cc.base_dir) # different data types need to be read separetly z_gals, vel_gals, sig_gals, x_gals, y_gals = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=(1,2,3,4,5)) galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0,),dtype=str) i_gal = np.where(galaxy_gals==galaxy)[0][0] self.vel = vel_gals[i_gal] self.sig = sig_gals[i_gal] self.z = z_gals[i_gal] self.f = fits.open(get_dataCubeDirectory(galaxy)) self.lam = np.arange(self.f[0].header['NAXIS3'])*self.f[0].header['CDELT3'] + self.f[0].header['CRVAL3'] ## ----------============ Find data within slit =============--------- x = (np.arange(self.f[0].header['NAXIS1']) * self.f[0].header['CDELT1']).repeat( self.f[0].header['NAXIS2']) y = np.tile(np.arange(self.f[0].header['NAXIS2']) * self.f[0].header['CDELT2'], self.f[0].header['NAXIS1']) slit_x, slit_y = get_slit(galaxy, slit_h, slit_w, slit_pa) frac_image = np.zeros((self.f[0].header['NAXIS1'], self.f[0].header['NAXIS2'])) if self.debug: frac = funccontains(slit, (slit_x,slit_y), x=x, y=y).contains.astype(int) else: frac = funccontains(slit, (slit_x,slit_y), x=x, y=y).fraction frac_image[np.arange(self.f[0].header['NAXIS1']).repeat(self.f[0].header['NAXIS2']), np.tile(np.arange(self.f[0].header['NAXIS2']),self.f[0].header['NAXIS1'])] = frac cube = self.f[0].data # Cube cannot be normalised due to removing heavier weighting for brighter # central bins. cube[self.f[3].data==1] = 0 noise_cube = self.f[1].data noise_cube[self.f[3].data==1] = 0.000000001 cube[~np.isfinite(noise_cube)] = 0 noise_cube[~np.isfinite(noise_cube)] = 0.000000001 self.gal_spec = np.einsum('ijk,jk->i', cube, frac_image) self.gal_noise = np.sqrt(np.einsum('ijk,jk->i', noise_cube**2, frac_image**2))
def compare_absortion(galaxy, O_sig=False, corr_lines='all'): f = fits.open(get_dataCubeDirectory(galaxy)) header = f[0].header # Load VIMOS values data_file = "%s/Data/vimos/analysis/galaxies.txt" % (cc.base_dir) z_gals, x_cent_gals, y_cent_gals = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=(1,4,5), dtype='float,int,int') galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0,),dtype=str) i_gal = np.where(galaxy_gals==galaxy)[0][0] z = z_gals[i_gal] center = np.array([x_cent_gals[i_gal], y_cent_gals[i_gal]]) data_file = "%s/Data/vimos/analysis/galaxies2.txt" % (cc.base_dir) pa_gals = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=(3,)) galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0,),dtype=str) i_gal = np.where(galaxy_gals==galaxy)[0][0] pa = pa_gals[i_gal] lines = ['H_beta', 'Fe5015', 'Mg_b'] e_lines = ['e_H_beta', 'e_Fe5015', 'e_Mg_b'] # load Ogando values cols = Ogando_data = np.loadtxt('%s/Data/lit_absorption/Ogando.txt' % ( cc.base_dir), dtype=str)[0] cols = [i for i, co in enumerate(cols) if co in lines or co in e_lines] Ogando_data = np.loadtxt('%s/Data/lit_absorption/Ogando.txt' % ( cc.base_dir), unpack=True, skiprows=2, usecols=np.append([1,2],cols)) galaxies = np.loadtxt('%s/Data/lit_absorption/Ogando.txt' % ( cc.base_dir), unpack=True, skiprows=2, usecols=(0,), dtype=str) i_gal = np.where(galaxies==galaxy)[0][0] O_sigma, O_sigma_err = 10**Ogando_data[0, i_gal], np.abs( 10**Ogando_data[0, i_gal] * Ogando_data[0, i_gal] * Ogando_data[1, i_gal]/10) O_val = {} O_err = {} for i in range(0, 2*len(lines), 2): O_val[lines[i/2]] = Ogando_data[i, i_gal] O_err[lines[i/2]] = Ogando_data[i+1, i_gal] params = set_params(reps=0, opt='pop', gas=1, lines=corr_lines, produce_plot=False) mask = slitFoV(center, 4.1/header['CDELT1'], 2.5/header['CDELT2'], pa, instrument='vimos') ifu = np.array(f[0].data) ifu[np.isnan(ifu)] = 0 spec = np.einsum('ijk,jk->i',ifu, mask) ifu = np.array(f[1].data) ifu[np.isnan(ifu)] = 0 noise = np.sqrt(np.einsum('ijk,jk->i',ifu**2, mask)) lam = np.arange(len(spec))*header['CDELT3'] + header['CRVAL3'] spec, lam, cut = apply_range(spec, lam=lam, set_range=params.set_range, return_cuts=True) lamRange = np.array([lam[0],lam[-1]]) noise = noise[cut] pp = run_ppxf(galaxy, spec, noise, lamRange, header['CDELT3'], params) if O_sig: if isinstance(O_sig, bool): absorp, uncert = get_absorption(lines, pp=pp, sigma=O_sigma(a), instrument='vimos') sigma = O_sigma(a) else: absorp, uncert = get_absorption(lines, pp=pp, instrument='vimos', sigma=O_sigma(a)+O_sig*(pp.sol[0][1]-O_sigma(a))) sigma = O_sigma(a)+O_sig*(pp.sol[0][1]-O_sigma(a)) else: absorp, uncert = get_absorption(lines, pp=pp, instrument='vimos') sigma = pp.sol[0][1] my = [] e_my = [] og = [] e_og = [] sig = [] lin = [] for i, l in enumerate(lines): lin = np.append(lin, l) sig = np.append(sig, sigma) # Aperture correction: r_ab = 1.025*np.sqrt(4.1 * 2.5 / np.pi) # arcsec r_ab = np.radians(r_ab/60**2) * z * c / H * 1000 # kpc if l=='H_beta' or l=='Hbeta': l2='hb' beta = 0.002 # from table 5 in Ogando '08 e_beta = 0.027 elif l == 'Fe5015': l2 = l beta = -0.012 e_beta = 0.027 elif l=='Mg_b': l2='mgb' beta = -0.031 e_beta = 0.034 elif l=='NaD': l2='nad' beta = -0.034 e_beta = 0.022 # elif l=='TiO1': # l2='tio1' # elif l=='TiO2': # l2='tio2' elif l=='Fe5270': l2='fe52' beta = -0.016 e_beta = 0.025 elif l=='Fe5335': l2='fe53' beta = -0.012 e_beta = 0.027 elif l=='Fe5406': l2=l beta = -0.015 e_beta = 0.029 elif l=='Fe5702': l2=l beta = 0 e_beta = 0.036 # Change to mag units s = spectrum(lam=pp.lam, lamspec=pp.galaxy) I = -2.5 * np.log10(1 - absorp[l]/np.diff(getattr(s,l2))[0]) e_I = np.abs(2.5/np.log(10) * uncert[l]/(np.diff(getattr(s,l2))[0] - absorp[l])) I = I - beta * np.log10(r_ab/1.19) # Choosen from Davies 1987 e_I = np.sqrt(e_I**2 + (e_beta**2 * np.log10(r_ab/1.19))) absorp[l] = (1 - 10**(-I/2.5))*np.diff(getattr(s,l2))[0] # Back to A uncert[l] = np.abs(2.5 * absorp[l] * np.log(10) * e_I) lit_value = Ogando_data[i*2+2, i_gal] e_lit_value = Ogando_data[i*2+3, i_gal] e_lit_value = np.mean([np.abs(Lick_to_LIS(l, lit_value + e_lit_value) - Lick_to_LIS(l, lit_value)), np.abs(Lick_to_LIS(l, lit_value - e_lit_value) - Lick_to_LIS(l, lit_value))]) lit_value = Lick_to_LIS(l, lit_value) my.append(absorp[l]) e_my.append(uncert[l]) og.append(lit_value) e_og.append(e_lit_value) return my, e_my, og, e_og, lin
def whole_image(galaxy, verbose=True): print galaxy if cc.device == 'glamdring': data_file = "%s/analysis/galaxies.txt" % (cc.base_dir) else: data_file = "%s/Data/vimos/analysis/galaxies.txt" % (cc.base_dir) z_gals, x_gals, y_gals = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=(1, 4, 5), dtype='float,int,int') galaxy_gals = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=(0,), dtype=str) i_gal = np.where(galaxy_gals==galaxy)[0][0] z = z_gals[i_gal] D = z*c/H0 # Mpc centre = (x_gals[i_gal], y_gals[i_gal]) limits_file = '%s/Data/vimos/analysis/galaxies_gasMass.txt' %(cc.base_dir) galaxy_gals, mass, e_mass = np.loadtxt(limits_file, unpack=True, dtype=str, skiprows=1) i_gal = np.where(galaxy_gals==galaxy)[0][0] max_radius = 29 # in spaxels radius = float(max_radius) Mass_sav = 0 f = fits.open(get_dataCubeDirectory(galaxy)) while radius > 2: mask = in_aperture(centre[0], centre[1], radius, instrument='vimos') spec = f[0].data noise = f[1].data spec[np.isnan(spec)] = 0 noise[np.isnan(noise)] = 0 spec = np.einsum('ijk,jk->i', spec, mask)#/np.sum(mask) noise = np.sqrt(np.einsum('ijk,jk->i', noise**2, mask))#/np.sum(mask) params = set_params(opt='pop', reps=4, temp_mismatch=True, produce_plot=False, gas=1) lam = (np.arange(len(spec)) - (f[0].header['CRPIX3'] - 1)) * \ f[0].header['CDELT3'] + f[0].header['CRVAL3'] spec, lam, cut = apply_range(spec, lam=lam, return_cuts=True, set_range=params.set_range) lamRange = np.array([lam[0],lam[-1]]) noise = noise[cut] pp = run_ppxf(galaxy, spec, noise, lamRange, f[0].header['CDELT3'], params) # pp.noise = np.min([pp.noise, np.abs(pp.galaxy-pp.bestfit)],axis=0) residuals = pp.galaxy - pp.bestfit _, residuals, _ = moving_weighted_average(pp.lam, residuals, step_size=3., interp=True) noise = np.sqrt(residuals**2 + pp.noise**2) OIII_spec = pp.matrix[:, pp.templatesToUse==\ '[OIII]5007d'].flatten()*\ pp.weights[pp.templatesToUse=='[OIII]5007d'] Hb_spec = pp.matrix[:, pp.templatesToUse=='Hbeta'].flatten() * \ pp.weights[pp.templatesToUse=='Hbeta'] Hb_flux = np.trapz(Hb_spec, x=pp.lam) Ha_flux = 2.86 * Hb_flux Hb_spec_uncert = pp.MCgas_uncert_spec[ pp.templatesToUse[pp.component!=0]=='Hbeta', :].flatten() Hb_flux_uncert = trapz_uncert(Hb_spec_uncert, x=pp.lam) Ha_flux_uncert = 2.86 * Hb_flux_uncert Mass = get_Mass(Ha_flux, D) e_Mass = get_Mass(Ha_flux_uncert, D) Hb_spec2 = pp.matrix[:, pp.templatesToUse=='Hbeta'].flatten() \ / np.max(pp.matrix[:, pp.templatesToUse=='Hbeta']) \ * np.median(noise[(pp.lam < 4861./(1 + (pp.sol[1][0] - 300)/c)) * (pp.lam > 4861./(1 + (pp.sol[1][0] + 300)/c))]) Hb_flux2 = np.trapz(Hb_spec2, x=pp.lam) Ha_flux2 = 2.86 * Hb_flux2 Mass2 = get_Mass(Ha_flux2, D) if max(OIII_spec)/np.median(noise[ (pp.lam < 5007./(1 + (pp.sol[1][0] - 300)/c)) * (pp.lam > 5007./(1 + (pp.sol[1][0] + 300)/c))]) > 4: if max(Hb_spec)/np.median(noise[ (pp.lam < 4861./(1 + (pp.sol[1][0] - 300)/c)) * (pp.lam > 4861./(1 + (pp.sol[1][0] + 300)/c))]) > 2.5: mass[i_gal] = str(round(np.log10(Mass),4)) e_mass[i_gal] = str(round(np.abs(e_Mass/Mass/ np.log(10)), 4)) if verbose: print '%s +/- %s log10(Solar Masses)' % ( mass[i_gal], e_mass[i_gal]) from ppxf import create_plot fig, ax = create_plot(pp).produce ax.set_xlim([4800, 4900]) ax.legend() fig1, ax1 = create_plot(pp).produce ax1.legend() import matplotlib.pyplot as plt plt.show() radius = -1 else: Mass_sav = max(Mass, Mass2, Mass_sav) if Mass_sav == Mass2: e_Mass = np.nan # if radius == max_radius: mass[i_gal] = '<'+str(round(np.log10(Mass_sav),4)) e_mass[i_gal] = str(round(np.abs(e_Mass/Mass/ np.log(10)), 4)) if verbose: print '<%s +/- %s log10(Solar Masses)' % ( mass[i_gal], e_mass[i_gal]) from ppxf import create_plot fig, ax = create_plot(pp).produce ax.set_xlim([4800, 4900]) ax.legend() import matplotlib.pyplot as plt plt.show() else: Mass_sav = max(Mass, Mass2, Mass_sav) if Mass_sav == Mass2: e_Mass = np.nan # if radius == max_radius: mass[i_gal] = '<'+str(round(np.log10(Mass_sav),4)) e_mass[i_gal] = str(round(np.abs(e_Mass/Mass/ np.log(10)), 4)) if verbose: print '<%s +/- %s log10(Solar Masses)' % ( mass[i_gal], e_mass[i_gal]) from ppxf import create_plot fig, ax = create_plot(pp).produce ax.set_xlim([4800, 4900]) ax.legend() import matplotlib.pyplot as plt plt.show() radius -= 1 temp = "{0:12}{1:10}{2:10}\n" with open(limits_file, 'w') as l: l.write(temp.format('Galaxy', 'Mass', 'e_Mass')) for i in range(len(galaxy_gals)): l.write(temp.format(galaxy_gals[i], mass[i], e_mass[i]))
def H_profile(instrument='vimos'): from matplotlib import ticker if instrument=='vimos': galaxies = np.array(['ic1459', 'ngc0612', 'ngc3100']) str_galaxies = np.array(['IC 1459', 'NGC 612', 'NGC 3100']) cols = (4, 5) line = 'Hbeta' res = 0.67 # arcsec/pix elif instrument=='muse': galaxies = np.array(['ic1459', 'ngc1316']) str_galaxies = np.array(['IC 1459', 'NGC 1316']) cols = (1, 2) line = 'Halpha' res = 0.2 # arcsec/pix Prefig(size=np.array((len(galaxies), 0.43*len(galaxies)))*7) # if instrument=='vimos': # plt.rc('axes', labelsize='x-large') # facecolor='w' # plt.rc('xtick.major', size=10, width=2) # plt.rc('xtick.minor', size=10, width=2) # plt.rc('ytick.major', size=10, width=2) # plt.rc('ytick.minor', size=10, width=2) plt.rc('font', size=10*len(galaxies)) fig, ax = plt.subplots(1, len(galaxies), sharey=True) analysis_dir = "%s/Data/%s/analysis" % (cc.base_dir, instrument) galaxiesFile = "%s/galaxies.txt" % (analysis_dir) x_cent_gals, y_cent_gals = np.loadtxt(galaxiesFile, unpack=True, skiprows=1, usecols=cols, dtype=int) galaxy_gals = np.loadtxt(galaxiesFile, skiprows=1, usecols=(0,), dtype=str) for i, galaxy in enumerate(galaxies): print 'H profile:', galaxy if galaxy == 'ngc1316': D = Data(galaxy, instrument=instrument, opt='pop_test', overide=True) else: D = Data(galaxy, instrument=instrument, opt='pop') if instrument=='vimos': if galaxy=='ic1459': seeing_sigma = np.mean([0.82,0.84,1.20,1.26,1.10,1.27]) * 2.5 norm_r = 2.4 norm_y = 0.1 elif galaxy=='ngc0612': seeing_sigma = np.mean([0.72,0.78,1.45,1.46,1.08,1.11]) * 2.5 norm_r = 5 norm_y = 0.2 elif galaxy=='ngc3100': seeing_sigma = np.mean([0.76,0.82,0.75,0.82,1.16,1.20]) * 2.5 norm_r = 2.9 norm_y = 0.2 elif instrument=='muse': from errors2_muse import get_dataCubeDirectory f=fits.open(get_dataCubeDirectory(galaxy)) seeing_sigma = np.mean([f[0].header['ESO TEL AMBI FWHM START'], f[0].header['ESO TEL AMBI FWHM START']]) * 2.5 if galaxy=='ic1459': norm_r = 1.7 norm_y = 0.1 elif galaxy=='ngc1316': norm_r = 3 norm_y = 0.1 i_gal = np.where(galaxy_gals==galaxy)[0][0] center = (x_cent_gals[i_gal], y_cent_gals[i_gal]) r = np.sqrt((D.xBar - center[0])**2 + (D.yBar - center[1])**2) * res if line in D.e_components: H = D.e_line[line].flux ax[i].errorbar(r, H/np.nanmax(H), yerr=H.uncert/np.nanmax(H), fmt='.', color='k') o = np.argsort(r) lim = ax[i].get_xlim() ax[i].set_xlim(0, min(lim[1], 22)) lim = ax[i].get_xlim() x = np.arange(-seeing_sigma, lim[1], 0.01) y = 1/x**2 y = ndimage.gaussian_filter1d(y, seeing_sigma) # convolve with seeing y = norm_y * norm_r**2 * y # normalised by eye ax[i].plot(x[x>=0], y[x>=0], zorder=10, color='r') ax[i].set_xlim(lim) ax[i].text(0.93*lim[1], 0.7, str_galaxies[i], ha='right') ax[i].set_ylim([0.01, 1.1]) ax[i].set_yscale('log') ax[i].tick_params(which='major', direction='in', length=10, width=2) ax[i].tick_params(axis='y', which='minor', direction='in', length=6, width=2) for axis in [ax[i].xaxis, ax[i].yaxis]: axis.set_major_formatter( ticker.FuncFormatter(lambda y, _: '{:g}'.format(y))) if instrument == 'vimos': ax[0].set_ylabel(r'H$\,\beta$ normalised flux') if instrument == 'muse': ax[0].set_ylabel(r'H$\,\alpha$ normalised flux') for a in ax: a.set_xlabel('Radius (arcsec)') fig.subplots_adjust(wspace=0,hspace=0) fig.savefig('%s/Documents/paper/%s_profile.png' % ( cc.home_dir, line), dpi=240, bbox_inches='tight') plt.close('all')
def plot(galaxy, instrument='vimos', debug=True): print galaxy, instrument # opt = 'kin' overplot={'CO':'c', 'radio':'g'} if instrument=='vimos': from plot_results import add_, set_lims from errors2 import get_dataCubeDirectory ext = 0 rows = 5 plots = [[ 'D.flux', "D2.components['[OIII]5007d'].flux", "D.components['stellar'].plot['vel']", "D.components['stellar'].plot['vel'].uncert", "D.components['stellar'].plot['sigma']", "D.components['stellar'].plot['sigma'].uncert" ],[ "D2.absorption_line('G4300')", "D2.absorption_line('G4300',uncert=True)[1]", "D2.absorption_line('Fe4383')", "D2.absorption_line('Fe4383',uncert=True)[1]", "D2.absorption_line('Ca4455')", "D2.absorption_line('Ca4455',uncert=True)[1]" ],[ "D2.absorption_line('Fe4531')", "D2.absorption_line('Fe4531',uncert=True)[1]", "D2.absorption_line('H_beta')", "D2.absorption_line('H_beta',uncert=True)[1]", "D2.absorption_line('Fe5015')", "D2.absorption_line('Fe5015',uncert=True)[1]" ],[ "D2.absorption_line('Mg_b')", "D2.absorption_line('Mg_b',uncert=True)[1]", '', '', '', '' ]] str_plots = [[ 'Flux', r'[OIII]$\lambda\lambda$4959,5007 Flux', "Stellar mean velocity", "Stellar mean velocity\nuncertainty", "Stellar velocity dispersion", "Stellar velocity dispersion\nuncertainty" ],[ "G4300", "G4300 uncertainty", "Fe4383", "Fe4383 uncertainty", "Ca4455", "Ca4455 uncertainty" ],[ "Fe4531", "Fe4531 uncertainty", r'H$\,\beta$', r'H$\,\beta$ uncertainty', "Fe5015", "Fe5015 uncertainty" ],[ r'Mg$\,$b', r'Mg$\,$b uncertainty', '', '', '', '' ]] units = [[ '', '', r'km s$^{-1}$', r'km s$^{-1}$', r'km s$^{-1}$', r'km s$^{-1}$' ],[ r'$\AA$', r'$\AA$', r'$\AA$', r'$\AA$', r'$\AA$', r'$\AA$' ],[ r'$\AA$', r'$\AA$', r'$\AA$', r'$\AA$', r'$\AA$', r'$\AA$' ],[ r'$\AA$', r'$\AA$', '', '', '', '' ]] elif instrument == 'muse': from plot_results_muse import add_, set_lims from errors2_muse import get_dataCubeDirectory ext = 1 rows = 6 plots = [[ 'D.flux', "D2.components['[OIII]5007d'].flux", "D.components['stellar'].plot['vel']", "D.components['stellar'].plot['vel'].uncert", "D.components['stellar'].plot['sigma']", "D.components['stellar'].plot['sigma'].uncert" ],[ "D2.absorption_line('H_beta')", "D2.absorption_line('H_beta',uncert=True)[1]", "D2.absorption_line('Fe5015')", "D2.absorption_line('Fe5015',uncert=True)[1]", "D2.absorption_line('Mg_b')", "D2.absorption_line('Mg_b',uncert=True)[1]" ],[ "D2.absorption_line('Fe5270')", "D2.absorption_line('Fe5270',uncert=True)[1]", "D2.absorption_line('Fe5335')", "D2.absorption_line('Fe5335',uncert=True)[1]", "D2.absorption_line('Fe5406')", "D2.absorption_line('Fe5406',uncert=True)[1]" ],[ "D2.absorption_line('Fe5709')", "D2.absorption_line('Fe5709',uncert=True)[1]", "D2.absorption_line('Fe5782')", "D2.absorption_line('Fe5782',uncert=True)[1]", "D2.absorption_line('NaD')", "D2.absorption_line('NaD',uncert=True)[1]" ],[ "D2.absorption_line('TiO1',remove_badpix=True)", "D2.absorption_line('TiO1',uncert=True,remove_badpix=True)[1]", "D2.absorption_line('TiO2',remove_badpix=True)", "D2.absorption_line('TiO2',uncert=True,remove_badpix=True)[1]", '', '' ]] str_plots = [[ 'Flux', r'[OIII]$\lambda\lambda$4959,5007 Flux', "Stellar mean velocity", "Stellar mean velocity\nuncertainty", "Stellar velocity dispersion", "Stellar velocity dispersion\nuncertainty" ],[ r'H$\,\beta$', r'H$\,\beta$ uncertainty', "Fe5015", "Fe5015 uncertainty", r'Mg$\,$b', r'Mg$\,$b uncertainty' ],[ 'Fe5270', 'Fe5270 uncertainty', 'Fe5335', 'Fe5335 uncertainty', 'Fe5406', 'Fe5406 uncertainty' ],[ 'Fe5709', 'Fe5709 uncertainty', 'Fe5782', 'Fe5782 uncertainty', 'NaD', 'NaD uncertainty' ],[ 'TiO1', 'TiO1 uncertainty', 'TiO2', 'TiO2 uncertainty', '', '' ]] units = [[ '', '', r'km s$^{-1}$', r'km s$^{-1}$', r'km s$^{-1}$', r'km s$^{-1}$' ],[ r'$\AA$', r'$\AA$', r'$\AA$', r'$\AA$', r'$\AA$', r'$\AA$' ],[ r'$\AA$', r'$\AA$', r'$\AA$', r'$\AA$', r'$\AA$', r'$\AA$' ],[ r'$\AA$', r'$\AA$', r'$\AA$', r'$\AA$', r'$\AA$', r'$\AA$' ],[ 'mag', 'mag', 'mag', 'mag', '', '' ]] if galaxy in ['ngc0612', 'pks0718-34']: rows -= 1 # No Mgb if galaxy in ['ic1459', 'ngc0612', 'ngc1316', 'ngc3100']: rows += 1 plots.insert(1, [ "D2.components['[OIII]5007d'].plot['vel']", "D2.components['[OIII]5007d'].plot['vel'].uncert", "D2.components['[OIII]5007d'].plot['sigma']", "D2.components['[OIII]5007d'].plot['sigma'].uncert", '', '' ]) str_plots.insert(1, [ r"[OIII]$\lambda\lambda$4959,5007"+"\nmean velocity", r"[OIII]$\lambda\lambda$4959,5007"+"\nmean velocity uncertainty", r"[OIII]$\lambda\lambda$4959,5007"+"\nvelocity dispersion", r"[OIII]$\lambda\lambda$4959,5007"+"\nvelocity dispersion\nuncertainty", '', '' ]) units.insert(1,[ r'km s$^{-1}$', r'km s$^{-1}$', r'km s$^{-1}$', r'km s$^{-1}$', '', '' ]) Prefig(size=np.array((6, rows))*6) fig, axs = plt.subplots(rows, 6) out_dir = '%s/Documents/paper/' % (cc.home_dir) f = fits.open(get_dataCubeDirectory(galaxy)) header = f[ext].header f.close() if debug: D = Ds() D2 = Ds() vin_dir = '%s/Data/%s/analysis' % (cc.base_dir, instrument) data_file = "%s/galaxies.txt" % (vin_dir) file_headings = np.loadtxt(data_file, dtype=str)[0] col = np.where(file_headings=='SN_kin')[0][0] col2 = np.where(file_headings=='SN_pop')[0][0] SN_target_kin_gals, SN_target_pop_gals = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=(col,col2)) galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0,),dtype=str) i_gal = np.where(galaxy_gals==galaxy)[0][0] SN_target_kin=SN_target_kin_gals[i_gal] SN_target_pop=SN_target_pop_gals[i_gal] # attr, vmin, vmax = np.loadtxt('%s/lims.txt' % (vin_dir), dtype=str, # usecols=(0,1,2), skiprows=1, unpack=True) # vmin, vmax = vmin.astype(float), vmax.astype(float) vin_dir2 = str(vin_dir + '/%s/pop' % (galaxy)) vin_dir += '/%s/kin' % (galaxy) if not debug: # pickle_file = '%s/pickled' % (vin_dir) # pickleFile = open("%s/dataObj.pkl" % (pickle_file), 'rb') # D = pickle.load(pickleFile) # pickleFile.close() # pickle_file2 = '%s/pickled' % (vin_dir2) # pickleFile2 = open("%s/dataObj.pkl" % (pickle_file2), 'rb') # D2 = pickle.load(pickleFile2) # pickleFile2.close() D = Data(galaxy, instrument=instrument, opt='kin') D2 = Data(galaxy, instrument=instrument, opt='pop') for i, row in enumerate(plots): for j, p in enumerate(row): # print i, j, p if galaxy in ['ngc0612', 'pks0718-34'] and 'Mg_b' in p: break # break out of for-loop elif galaxy in ['ngc1399', 'pks0718-34'] and 'OIII' in p: axs[i,j].remove() elif 'flux' in p: if p == 'D.flux': axs[i,j] = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, eval(p), header, cmap='gist_yarg', flux_unbinned=D.unbinned_flux, galaxy=str_plots[i][j], ax=axs[i,j]) elif p == "D2.components['[OIII]5007d'].flux": axs[i,j] = plot_velfield_nointerp(D2.x, D2.y, D2.bin_num, D2.xBar, D2.yBar, eval(p), header, cmap='gist_yarg', flux_unbinned=D2.unbinned_flux, galaxy=str_plots[i][j], ax=axs[i,j]) if overplot and p != '' and 'uncert' not in p: for o, color in overplot.iteritems(): scale = 'log' if o == 'radio' else 'lin' add_(o, color, axs[i,j], galaxy, nolegend=True, scale=scale) if i > 0: if plots[i-1][j] != '' and hasattr(axs[i-1,j], 'ax_dis'): axs[i-1,j].ax_dis.set_xticklabels([]) axs[i-1,j].ax_dis.set_xlabel('') if j > 0: if plots[i][j-1] != '' and hasattr(axs[i,j-1], 'ax_dis'): axs[i,j].ax_dis.set_yticklabels([]) axs[i,j].ax_dis.set_ylabel('') elif p != '': vmin, vmax = set_lims(eval(p), symmetric = 'vel' in p and 'uncert' not in p, positive = not ('vel' in p and 'uncert' not in p)) if 'D2' in p: axs[i,j] = plot_velfield_nointerp(D2.x, D2.y, D2.bin_num, D2.xBar, D2.yBar, eval(p), header, vmin=vmin, vmax=vmax, flux_unbinned=D2.unbinned_flux, galaxy=str_plots[i][j], signal_noise=D2.SNRatio, signal_noise_target=SN_target_pop, ax=axs[i,j], lim_labels=True, lim_labels_units=units[i][j]) else: axs[i,j] = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, eval(p), header, vmin=vmin, vmax=vmax, flux_unbinned=D.unbinned_flux, galaxy=str_plots[i][j], signal_noise=D.SNRatio, signal_noise_target=SN_target_kin, ax=axs[i,j], lim_labels=True, lim_labels_units=units[i][j]) if overplot and p != '' and 'uncert' not in p: for o, color in overplot.iteritems(): scale = 'log' if o == 'radio' else 'lin' add_(o, color, axs[i,j], galaxy, nolegend=True, scale=scale) if i > 0: if plots[i-1][j] != '' and hasattr(axs[i-1,j], 'ax_dis'): axs[i-1,j].ax_dis.set_xticklabels([]) axs[i-1,j].ax_dis.set_xlabel('') if j > 0: if plots[i][j-1] != '' and hasattr(axs[i,j-1], 'ax_dis'): axs[i,j].ax_dis.set_yticklabels([]) axs[i,j].ax_dis.set_ylabel('') else: axs[i,j].remove() # age = np.zeros(D2.number_of_bins) # met = np.zeros(D2.number_of_bins) # alp = np.zeros(D2.number_of_bins) # unc_age = np.zeros(D2.number_of_bins) # unc_met = np.zeros(D2.number_of_bins) # unc_alp = np.zeros(D2.number_of_bins) # if not debug: # for j in xrange(D2.number_of_bins): # ag, me, al = np.loadtxt('%s/pop/distribution/%i.dat' % ( # vin_dir2, j), unpack=True) # for plot, unc_plot, pop in zip([age,met,alp], # [unc_age,unc_met,unc_alp], [ag,me,al]): # hist = np.histogram(pop, bins=40) # x = (hist[1][0:-1]+hist[1][1:])/2 # hist = hist[0] # plot[j] = x[np.argmax(hist)] # gt_fwhm = hist >= np.max(hist)/2 # unc_plot[j] = np.max(x[gt_fwhm]) - np.min(x[gt_fwhm]) str_plots = ['Age', 'Age uncertainty', 'Metallicity', 'Metallicity uncertainty', 'Alpha enhancement', 'Alpha enhancement\nuncertainty'] units = ['Gyr', 'Gyr', None, None, None, None] vmin = [0, 0, -2.25, 0, -0.3, 0] vmax = [15, 2, 0.67, 0.4, 0.5, 0.25] for j, p in enumerate(['age', 'age.uncert', 'metalicity', 'metalicity.uncert', 'alpha', 'alpha.uncert']): axs[-1, j] = plot_velfield_nointerp(D2.x, D2.y, D2.bin_num, D2.xBar, D2.yBar, eval("D2.components['stellar']."+p), header, vmin=vmin[j], vmax=vmax[j], # cmap='inferno', flux_unbinned=D2.unbinned_flux, galaxy=str_plots[j], signal_noise=D2.SNRatio, signal_noise_target=SN_target_pop, ax=axs[-1,j], lim_labels=True, lim_labels_units=units[j]) if j > 0: axs[-1,j].ax_dis.set_yticklabels([]) axs[-1,j].ax_dis.set_ylabel('') if plots[-1][j] != '' or galaxy in ['ngc0612', 'pks0718-34']: axs[-2, j].ax_dis.set_xticklabels([]) axs[-2, j].ax_dis.set_xlabel('') if overplot and 'unc' not in p: for o, color in overplot.iteritems(): scale = 'log' if o == 'radio' else 'lin' add_(o, color, axs[-1,j], galaxy, nolegend=True, scale=scale) for i, a in enumerate(axs.flatten()): # if galaxy in ['ngc1399', 'pks0718-34'] and i==1: # break if hasattr(a, 'ax_dis'): a.ax_dis.tick_params(top=True, bottom=True, left=True, right=True, direction='in', which='major', length=20, width=3, labelsize='large', zorder=10) a.ax_dis.tick_params(top=True, bottom=True, left=True, right=True, direction='in', which='minor', length=10, width=3, zorder=10) a.ax_dis.xaxis.label.set_size(22) a.ax_dis.yaxis.label.set_size(22) # Create gap between pairs of columns for j in range(1, 6, 2): for a in axs[:, j].flatten(): ax_loc = a.get_position() ax_loc.x0 -= 0.007 ax_loc.x1 -= 0.007 a.set_position(ax_loc) if hasattr(a, 'ax_dis'): a.ax_dis.set_position(ax_loc) # for j in range(0, 6, 2): # for a in axs[:, j+1].flatten(): # ax_loc = a.get_position() # ax_loc.x0 += 0.01 # ax_loc.x1 += 0.01 # a.set_position(ax_loc) # if hasattr(a, 'ax_dis'): # a.ax_dis.set_position(ax_loc) # fig.text(0.24, 0.9, r'Flux', va='top', ha='center', size='xx-large') # fig.text(0.51, 0.9, r'Velocty', va='top', ha='center', size='xx-large') # fig.text(0.8, 0.9, r'Velocty Dispersion', va='top', ha='center', # size='xx-large') # Add colorbar ax_loc = axs[0,-1].get_position() cax = fig.add_axes([ax_loc.x1+0.03, ax_loc.y0, 0.02, ax_loc.height]) cbar = plt.colorbar(axs[1,1].cs, cax=cax) cbar.ax.set_yticklabels([]) # plt.show() fig.savefig('%s/%s.png' % (out_dir, galaxy), bbox_inches='tight', dpi=200)
def stellar_pop_grad(galaxy, method='median', opt='pop'): print 'Finding population gradients' vin_dir = '%s/Data/vimos/analysis/%s/%s/pop' % (cc.base_dir, galaxy, opt) # Load pickle file from pickler.py out_dir = '%s/Data/vimos/analysis' % (cc.base_dir) output = "%s/%s/%s" % (out_dir, galaxy, opt) out_plots = "%s/plots/pop_distributions" % (output) if not os.path.exists(out_plots): os.makedirs(out_plots) f = fits.open(get_dataCubeDirectory(galaxy)) header = f[0].header data_file = "%s/galaxies.txt" % (out_dir) x_cent_gals, y_cent_gals = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=(4,5), dtype=int) galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0,),dtype=str) i_gal = np.where(galaxy_gals==galaxy)[0][0] center = (x_cent_gals[i_gal], y_cent_gals[i_gal]) R_e = get_R_e(galaxy) apertures = np.array([R_e/8, R_e/2, R_e]) str_ap = ['R_e_8', 'R_e_2', 'R_e'] for i, a in enumerate(apertures): params = set_params(reps=100, opt='pop', gas=1, produce_plot=False) mask = in_aperture(center[0], center[1], a/header['CDELT1'], instrument='vimos') spec = np.einsum('ijk,jk->ijk', f[0].data, mask) noise = np.einsum('ijk,jk->ijk', f[1].data**2, mask) spec = np.nansum(spec, axis=(1,2)) noise = np.sqrt(np.nansum(noise, axis=(1,2))) lam = np.arange(len(spec))*header['CDELT3'] + header['CRVAL3'] spec, lam, cut = apply_range(spec, lam=lam, set_range=params.set_range, return_cuts=True) lamRange = np.array([lam[0],lam[-1]]) noise = noise[cut] pp = run_ppxf(galaxy, spec, noise, lamRange, header['CDELT3'], params) pop = population(pp=pp, instrument='vimos', method=method) pop.plot_probability_distribution(saveTo='%s/%s.png' % ( out_plots, str_ap[i])) file = '%s/pop_sigma.txt' % (out_dir) value = np.loadtxt(file, unpack=True, skiprows=2, dtype=str) i_gal = np.where(value[0]==galaxy)[0][0] value[i*9+1, i_gal] = str(round(pp.sol[0][1], 2)) value[i*9+2, i_gal] = str(round(np.std(pp.MCstellar_kin[:,1]), 2)) value[i*9+3, i_gal] = str(round(pop.age, 2)) value[i*9+4, i_gal] = str(round(pop.unc_age, 2)) value[i*9+5, i_gal] = str(round(pop.metallicity, 2)) value[i*9+6, i_gal] = str(round(pop.unc_met, 2)) value[i*9+7, i_gal] = str(round(pop.alpha, 2)) value[i*9+8, i_gal] = str(round(pop.unc_alp, 2)) value[i*9+9, i_gal] = str(round(pop.prob, 2)) temp = '{0:12}{1:7}{2:7}{3:7}{4:7}{5:7}{6:7}{7:7}{8:7}{9:7}{10:7}'+\ '{11:7}{12:7}{13:7}{14:7}{15:7}{16:7}{17:7}{18:7}{19:7}{20:7}'+\ '{21:7}{22:7}{23:7}{24:7}{25:7}{26:7}{27:7}\n' with open(file, 'w') as out: out.write(temp.format('Galaxy', 'sig', 'e_sig', 'age', 'e_age', 'met', 'e_met', 'alpha', 'e_alpha', 'prob', 'sig', 'e_sig', 'age', 'e_age', 'met', 'e_met', 'alpha', 'e_alpha', 'prob', 'sig', 'e_sig', 'age', 'e_age', 'met', 'e_met', 'alpha', 'e_alpha', 'prob')) out.write(temp.format('', 'R_e/8', 'R_e/8', 'R_e/8', 'R_e/8', 'R_e/8', 'R_e/8', 'R_e/8', 'R_e/8', 'R_e/8', 'R_e/2', 'R_e/2', 'R_e/2', 'R_e/2', 'R_e/2', 'R_e/2', 'R_e/2', 'R_e/2', 'R_e', 'R_e', 'R_e/2', 'R_e', 'R_e', 'R_e', 'R_e', 'R_e', 'R_e', 'R_e')) for j in range(len(value[0])): out.write(temp.format(*value[:,j]))
def plot_results(galaxy, discard=0, norm="lwv", plots=False, residual=False, overplot={}, show_bin_num=False, D=None, mapping=None, opt='kin'): s = set_ax_y_object() data_file = "%s/galaxies.txt" % (vin_dir) file_headings = np.loadtxt(data_file, dtype=str)[0] col = np.where(file_headings=='SN_%s' % (opt))[0][0] # different data types need to be read separetly z_gals, x_cent_gals, y_cent_gals, SN_target_gals = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=(1,4,5,col), dtype='float,int,int,float') galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0,),dtype=str) i_gal = np.where(galaxy_gals==galaxy)[0][0] z = z_gals[i_gal] SN_target=SN_target_gals[i_gal] center = (x_cent_gals[i_gal], y_cent_gals[i_gal]) output = "%s/%s/%s" % (out_dir, galaxy, opt) out_plots = "%s/plots" % (output) out_nointerp = "%s/notinterpolated" % (out_plots) vin_dir_gasMC = "%s/%s/%s/MC" % (vin_dir, galaxy, opt) out_pickle = '%s/pickled' % (output) cubeFile = fits.open(get_dataCubeDirectory(galaxy)) header = cubeFile[0].header cubeFile.close() # ------------== Reading pickle file and create plot ===---------- # Load pickle file from pickler.py if D is None: pickleFile = open("%s/dataObj.pkl" % (out_pickle), 'rb') D = pickle.load(pickleFile) pickleFile.close() # for bin in D.bin: # for l in bin.e_line.keys(): # bin.components[l].__threshold__ = 3 if D.norm_method != norm: D.norm_method = norm D.find_restFrame() # Create figure and array for axes n_rows = 2+2*len(D.e_components) + int(np.ceil(len(D.e_components)* (len(D.e_components)-1)/6.0)) f = plt.figure()#frameon=False) ax_array = [] if mapping.SNR or mapping is None: saveTo = "%s/SNR.png" % (out_nointerp) ax1 = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, D.SNRatio, header, colorbar=True, nodots=True, title='SNR', save=saveTo, close=True, flux_unbinned=D.unbinned_flux, center=center, show_bin_num=show_bin_num, galaxy=galaxy.upper(), redshift=z) # ------------=============== Plot image ================---------- if mapping.image or mapping is None: print " Image" title = "Total Flux" CBLabel = r"Flux ($\sim 10^{-15}$ erg s$^{-1}$ cm$^{-2}$)" ax = f.add_subplot(111, aspect='equal') saveTo = "%s/total_image.png" % (out_nointerp) ax.saveTo = saveTo ax.figx, ax.figy = 0, 0 fmin, fmax = set_lims(D.flux, positive=True) ax = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, D.flux, header, vmin=fmin, vmax=fmax, nodots=True, colorbar=True, label=CBLabel, title=title, cmap='gist_yarg', ax=ax, flux_unbinned=D.unbinned_flux, center=center, galaxy=galaxy.upper()) if plots: plt.show() ax_array.append(ax) f.delaxes(ax) f.delaxes(ax.cax) if hasattr(ax,'ax2'): f.delaxes(ax.ax2) if hasattr(ax,'ax3'): f.delaxes(ax.ax3) # ------------========= Plot intensity (& EW) ===========---------- if mapping.equivalent_width or mapping is None: print " gas map(s) and equivalent widths" for c in D.e_components: print " " + c if 'OIII' in c: c_title = '[OIII]' elif 'Hbeta' in c: c_title = r'H$_\beta$' elif 'Hgamma' in c: c_title = r'H$_\gamma$' else: c_title = c f_title = "%s Flux" % (c_title) fh_title = "%s Flux Histogram" % (c_title) # from header fCBtitle = r"Flux ($\sim 10^{-15}$ erg s$^{-1}$ cm$^{-2}$)" f_min, f_max = set_lims(D.e_line[c].flux, positive=True) saveTo = "%s/%s_flux_hist.png" % (out_plots, c) plot_histogram(D.e_line[c].flux, galaxy=galaxy.upper(), redshift=z, vmin=f_min,vmax=f_max, weights=D.n_spaxels_in_bin, title=fh_title, xaxis=fCBtitle, save=saveTo) ax_y = s.set_ax_y(c) ax = f.add_subplot(111, aspect='equal') saveTo = "%s/%s_img.png" % (out_nointerp, c) ax.saveTo = saveTo ax.figx, ax.figy = 0, ax_y ax = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, D.e_line[c].flux, header, vmin=f_min, vmax=f_max, colorbar=True, nodots=True, label=fCBtitle, title=f_title, ax=ax, flux_unbinned=D.unbinned_flux, center=center, galaxy=galaxy.upper(), signal_noise=D.e_line[c].amp_noise, signal_noise_target=4, redshift=z) ax_array.append(ax) f.delaxes(ax) f.delaxes(ax.cax) if hasattr(ax,'ax2'): f.delaxes(ax.ax2) if hasattr(ax,'ax3'): f.delaxes(ax.ax3) if plots: plt.show() # Uncertainy in flux fu_title = "%s Flux Uncertainty" % (c_title) f_uncert_min, f_uncert_max = set_lims(D.e_line[c].flux.uncert, positive=True) saveTo = "%s/%s_img_uncert.png" % (out_nointerp, c) ax1 = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, D.e_line[c].flux.uncert, header, vmin=f_uncert_min, vmax=f_uncert_max, flux_unbinned=D.unbinned_flux, nodots=True, colorbar=True, label=fCBtitle, galaxy = galaxy.upper(), title=fu_title, save=saveTo, close=True, center=center) eq_title = "%s Equivalent Width" % (c_title) eqh_title = "%s Equivalent Width Histogram" % (c_title) eqCBtitle = r"Equivalent Width ($\AA$)" eq_min, eq_max = set_lims(D.e_line[c].equiv_width, positive=True) saveTo = "%s/%s_eqWidth_hist.png" % (out_plots, c) plot_histogram(D.e_line[c].equiv_width, galaxy=galaxy.upper(), redshift=z, vmin=eq_min,vmax=eq_max, weights=D.n_spaxels_in_bin, title=eqh_title, xaxis=eqCBtitle, save=saveTo) ax = f.add_subplot(111, aspect='equal') saveTo = "%s/%s_equiv_width.png" % (out_nointerp, c) ax.saveTo = saveTo ax.figx, ax.figy = 0, ax_y+1 ax = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, D.e_line[c].equiv_width, header, vmin=eq_min, vmax=eq_max, colorbar=True, nodots=True, label=eqCBtitle, title=eq_title, ax=ax, flux_unbinned=D.unbinned_flux, center=center, galaxy=galaxy.upper(), signal_noise=D.e_line[c].amp_noise, signal_noise_target=4, redshift=z) ax_array.append(ax) f.delaxes(ax) f.delaxes(ax.cax) if hasattr(ax,'ax2'): f.delaxes(ax.ax2) if hasattr(ax,'ax3'): f.delaxes(ax.ax3) # Uncertainy in EW equ_title = "%s Equivalent Width Uncertainty" % (c_title) eq_uncert_min, eq_uncert_max = set_lims(D.e_line[c].equiv_width.uncert, positive=True) saveTo = "%s/%s_equiv_width_uncert.png" % (out_nointerp, c) ax1 = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, D.e_line[c].equiv_width.uncert, header, vmin=eq_uncert_min, vmax=eq_uncert_max, flux_unbinned=D.unbinned_flux, nodots=True, colorbar=True, label=eqCBtitle, galaxy = galaxy.upper(), title=equ_title, save=saveTo, close=True, center=center) # ------------============ Amplitude/Noise ==============---------- if mapping.amp_noise or mapping is None: for c in D.e_components: if 'OIII' in c: c_title = '[OIII]' elif 'Hbeta' in c: c_title = r'H$_\beta$' elif 'Hgamma' in c: c_title = r'H$_\gamma$' else: c_title = c amp_title = '%s Amplitude to Noise ratio' % (c_title) amp_min, amp_max = set_lims(D.e_line[c].amp_noise, positive=True) saveTo = "%s/%s_amp_noise.png" % (out_nointerp, c) ax1 = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, D.e_line[c].amp_noise, header, vmin=amp_min, vmax=amp_max, colorbar=True, nodots=True, title=amp_title, save=saveTo, close=True, flux_unbinned=D.unbinned_flux, center=center) # ------------=========== Setting titles etc ============---------- if mapping.kinematics or mapping is None: print ' Kinematics' # for c in ['stellar']: # For debugging for c in D.independent_components: print ' %s' % (c) im_type = c pl = c if im_type == "gas": im_type="" pl = '[OIII]5007d' elif im_type == "SF": im_type=" (Star Forming)" pl = '[OIII]5007d' elif im_type == "Shocks": im_type=" (Shocking)" pl = 'Hbeta' elif 'Hbeta' in im_type: im_type=" ("+r'H$_\beta$'+")" elif 'Hgamma' in im_type: im_type=" ("+r'H$_\gamma$'+")" elif 'OIII' in im_type: im_type=" (OIII)" else: im_type=" (" + im_type + ")" for k in D.components[pl].plot.keys(): ax_y = s.set_ax_y(c) symmetric=False positive=False CBLabel = None if k == "vel": ax_x=1 title = 'Velocity' CBLabel = "V (km s$^{-1}$)" symmetric=True if k == "sigma": ax_x=2 title = 'Velocity Dispersion' CBLabel = r'$\mathrm{\sigma}$ (km s$^{-1}$)' positive = True if k == "h3": ax_x=1 ax_y+=1 title = 'h3' symmetric = True if k == "h4": ax_x=2 ax_y+=1 title = 'h4' SNR = D.SNRatio SN_target_kine = SN_target if pl != 'stellar': SNR = D.gas_dynamics_SN SN_target_kine = 5 if c == "stellar": utitle = "Stellar Uncertainty " + title + " Map" htitle = "Stellar " + title + " Histogram" uhtitle = "Stellar Uncertainty " + title + " Histogram" title = "Stellar " + title + " Map" else: utitle = "Ionised" + im_type + " Gas Uncertainty " + title + " Map" htitle = "Ionised" + im_type + " Gas " + title + " Histogram" uhtitle = "Ionised" + im_type + " Gas Uncertainty " + title + \ " Histogram" title = "Ionised" + im_type + " Gas\n" + title + " Map" # ------------============ Setting v range ==============---------- vmin, vmax = set_lims(D.components[pl].plot[k][D.SNRatio > 0.75*SN_target], positive=positive, symmetric=symmetric) v_uncert_min, v_uncert_max = set_lims(D.components[pl].plot[k].uncert, positive=True) # # ------------============== Plot Histogram =============---------- # Field histogram # saveTo = "%s/%s_hist_%s.png" % (out_plots, plot_title, wav_range) # plot_histogram(D.components[c].plot[k], galaxy=galaxy.upper(), redshift=z, # vmin=vmin,vmax=vmax, weights=D.n_spaxels_in_bin, title=htitle, # xaxis=CBLabel, save=saveTo) # # Uncertainty histogram # saveTo = "%s/%s_hist_%s.png" % (out_plots, plot_title+'_uncert', wav_range) # plot_histogram(D.components[c].plot[k].uncert, galaxy=galaxy.upper(), # redshift=z, vmin=v_uncert_min,vmax=v_uncert_max, # weights=D.n_spaxels_in_bin, title=uhtitle, xaxis=CBLabel, save=saveTo) # if plots: # plt.show() # ------------==== Plot velfield - no interperlation ====---------- # Field plot ax = f.add_subplot(111, aspect='equal') saveTo = ("%s/%s_%s_field.png" % (out_nointerp, c, k)) ax.saveTo = saveTo ax.figx, ax.figy = ax_x, ax_y ax = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, D.components[pl].plot[k], header, vmin=vmin, vmax=vmax, nodots=True, colorbar=True, label=CBLabel,galaxy = galaxy.upper(), redshift = z, title=title, ax=ax, signal_noise=D.SNRatio, signal_noise_target=SN_target_kine, flux_unbinned=D.unbinned_flux, center=center) # plots=True if plots: plt.show() ax_array.append(ax) f.delaxes(ax) f.delaxes(ax.cax) if hasattr(ax,'ax2'): f.delaxes(ax.ax2) if hasattr(ax,'ax3'): f.delaxes(ax.ax3) # Uncertainty plot saveTo = "%s/%s_%s_uncert_field.png" % (out_nointerp, c, k) ax1 = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, D.components[pl].plot[k].uncert, header, vmin=v_uncert_min, vmax=v_uncert_max, nodots=True, colorbar=True, label=CBLabel, galaxy=galaxy.upper(), title=utitle, save=saveTo, close=True, flux_unbinned=D.unbinned_flux, center=center) #plots=False if plots: plt.show() # ------------============= Plot residuals ==============---------- if residual and (mapping.plot_resid or mapping is None): print " " + residual + " residuals" average_residuals = np.zeros(D.number_of_bins) for i, bin in enumerate(D.bin): residuals = (bin.spectrum - bin.bestfit)/bin.spectrum # remove edge pixels residuals = np.delete(residuals, [np.arange(5), len(residuals)+np.arange(-5,0)], axis=0) if residual=="mean": average_residuals[i] = np.mean(residuals) elif residual=="median": average_residuals[i] = np.median(residuals) elif residual=="max": average_residuals[i] = np.max(np.abs(residuals)) minres, maxres = set_lims(average_residuals, positive=True) #mean_centered=True, CBLabel = "Residuals" title = "Fractional " + str.capitalize(residual) + " Residuals" saveTo = "%s/%s_residual.png" % (out_nointerp, residual) ax1 = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, average_residuals, header, vmin=minres, vmax=maxres, nodots=True, colorbar=True, label=CBLabel, flux_unbinned=D.unbinned_flux, galaxy = galaxy.upper(), title=title, save=saveTo, close=True, center=center) if plots: plt.show() # ------------============ Line ratio maps ==============---------- if len(D.list_components)>2 and (mapping.line_ratios or mapping is None): print " line ratios" t_num = (len(D.e_components)-1)*len(D.e_components)/2 for n in range(t_num): i = 0 m = t_num while m > n: i += 1 m -= i cA = D.e_components[len(D.e_components)-i-1] cB = D.e_components[len(D.e_components)-i+n-m] # Always put Balmer lines on the denominator if ('[' in cA) and ('H' in cB): cA, cB = cB, cA line_ratio = np.log10(D.e_line[cB].flux/D.e_line[cA].flux) if 'OIII' in cA: cA_title = '[OIII]' elif 'Hbeta' in cA: cA_title = r'H$_\beta$' elif 'Hdelta' in cA: cA_title = r'H$_\delta$' elif 'Hgamma' in cA: cA_title = r'H$_\gamma$' else: cA_title = cA if 'OIII' in cB: cB_title = '[OIII]' elif 'Hbeta' in cB: cB_title = r'H$_\beta$' elif 'Hdelta' in cB: cB_title = r'H$_\delta$' elif 'Hgamma' in cB: cB_title = r'H$_\gamma$' else: cB_title = cB lr_title = "%s/%s Line Ratio" % (cB_title, cA_title) lrCBtitle = r"log$_{10}$ (%s/%s)" %(cB_title,cA_title) lr_min, lr_max = set_lims(line_ratio) ax = f.add_subplot(111, aspect='equal') saveTo = "%s/lineratio/%s_%s_line_ratio.png" % (out_nointerp, cB, cA) ax.saveTo = saveTo ax.figx, ax.figy = n%3, n_rows - int(np.ceil(t_num/3.0)) + int(np.ceil(n/3)) ANRatio = np.min([D.e_line[cB].amp_noise, D.e_line[cA].amp_noise], axis=0) ax = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, line_ratio, header, vmin=lr_min, vmax=lr_max, colorbar=True, nodots=True, title=lr_title, label=lrCBtitle, ax=ax, galaxy=galaxy.upper(), redshift=z, flux_unbinned=D.unbinned_flux, center=center, signal_noise=ANRatio, signal_noise_target=5) ax_array.append(ax) f.delaxes(ax) f.delaxes(ax.cax) if hasattr(ax,'ax2'): f.delaxes(ax.ax2) if hasattr(ax,'ax3'): f.delaxes(ax.ax3) # ------------============= Plot and save ===============---------- print " Plotting and saving" cbar_position = [] for i, a in enumerate(ax_array): f.add_axes(a) #a.axis('tight') f.add_axes(a.cax) if hasattr(a,'ax2'): f.add_axes(a.ax2) if hasattr(a,'ax3'): f.add_axes(a.ax3) if not os.path.exists(os.path.dirname(a.saveTo)): os.makedirs(os.path.dirname(a.saveTo)) f.savefig(a.saveTo, bbox_inches="tight") if overplot: for o, color in overplot.iteritems(): add_(o, color, a, galaxy) # Make lines thinner for pdf by finding the line objects for o in a.get_children(): if type(o) is LineCollection: o.set_linewidth(0.3) cbar_position.append(a.cax.get_position()) f.delaxes(a) f.delaxes(a.cax) if hasattr(a,'ax2'): f.delaxes(a.ax2) if hasattr(a,'ax3'): f.delaxes(a.ax3) # a.change_geometry(n_rows, 3, a.figy*3+a.figx+1) # if mapping.all or mapping is None: # for i, a in enumerate(ax_array): # if not np.isnan(a.figy): # a2 = f.add_axes(a) # # cax2 = f.add_axes(a.cax, position=cbar_position[i]) # p = a2.get_position() # c = f.add_axes([p.x1,p.y0, 0.01, p.height]) # # c = f.add_axes([p.x1,p.y0*1.06-0.004,0.005, p.height*1.05]) # cb = plt.colorbar(a.images[0], cax=c) # cb.outline.set_visible(False) # cb.ax.tick_params(labelsize='x-small') # a.set_title(a.get_title(), fontdict={'fontsize':'small'}) # a.xaxis.set_visible(False) # a.yaxis.set_visible(False) # a.axis('off') # # a.autoscale(False) # # c.autoscale(False) # if hasattr(a,'gal_name'): a.gal_name.remove() # if hasattr(a, 'gal_z'): a.gal_z.remove() # f.set_size_inches(8.5,n_rows*1.8) # # f.tight_layout(h_pad=0.5)#pad=0.4, w_pad=0.5, h_pad=1.0) # # f.subplots_adjust(top=0.94) # f.suptitle(galaxy.upper()) # saveTo = "%s/grid.pdf" % (out_plots) # f.savefig(saveTo)#, bbox_inches="tight",format='pdf') return D
def add_(overplot, color, ax, galaxy, scale='lin', close=False, radio_band=None, debug=False, FoV=None, nolegend=False): image_dir=getattr(get_dataCubeDirectory(galaxy, radio_band=radio_band), overplot) if scale is None: if image_dir.default_scale is not None: scale = image_dir.default_scale else: scale = 'lin' if os.path.exists(image_dir): f = fits.open(image_dir)[0] # ****** NB: NOTE THE -VE SIGN ON CDELT1 ****** x = (np.arange(f.header['NAXIS1']) - f.header['CRPIX1']) *\ -abs(f.header['CDELT1']) + f.header['CRVAL1'] + (image_dir.RAoffset/(60.**2)) y = (np.arange(f.header['NAXIS2']) - f.header['CRPIX2']) *\ -f.header['CDELT2'] + f.header['CRVAL2'] + (image_dir.decoffset/(60.**2)) x, y = np.meshgrid(x,y) #remove random extra dimenisons. s = np.array(f.data.shape) if any(s==1): image = np.sum(f.data, axis=tuple(np.where(s==1)[0])) else: image = f.data xlim = ax.get_xlim() ylim = ax.get_ylim() # Discard noise from outer parts of the galaxy - for radio if overplot == 'radio' or scale =='lin': lim = np.nanmean(image) + np.nanstd(image) image[image < lim] = lim if scale == 'log': image = np.log10(image) elif scale == 'lin': pass # m = np.nanmean(image) # s = np.nanstd(image) # image[image<m+s] = np.nan elif scale == 'sqrt': image = np.sqrt(image) else: raise ValueError("'scale' keyword has invaild value: %s" % (scale)) # Plot cs = ax.contour(x, y, image, colors=color, linestyles='solid', linewidth=1) # cs = ax.contour(image, colors=color, linestyles='solid', linewidth=1) if not nolegend: if overplot == 'radio': if scale != 'lin': cs.collections[0].set_label(scale+' '+image_dir.band) else: cs.collections[0].set_label(image_dir.band) else: if scale != 'lin': cs.collections[0].set_label(scale+' '+overplot) else: cs.collections[0].set_label(overplot) if not debug: ax.set_xlim(xlim) ax.set_ylim(ylim) elif FoV is not None: xdiff = xlim[1] - xlim[0] xcent = np.mean(xlim) ax.set_xlim(np.array([-1,1])*xdiff*FoV/2. + xcent) ydiff = ylim[1] - ylim[0] ycent = np.mean(ylim) ax.set_ylim(np.array([-1,1])*ydiff*FoV/2. + ycent) if not nolegend: leg = ax.legend(facecolor='w') # Save if hasattr(ax, 'saveTo'): saveTo = os.path.dirname(ax.saveTo)+"/Overplot/" + \ os.path.basename(ax.saveTo) if not os.path.exists(os.path.dirname(saveTo)): os.makedirs(os.path.dirname(saveTo)) plt.savefig(saveTo, bbox_inches="tight") if close: plt.close() elif not nolegend: leg.remove()
def use_kinemetry(gal, opt='kin'): out_dir = '%s/Data/vimos/analysis' % (cc.base_dir) colors=['b','y','g'] fig, ax = plt.subplots() pl_ob=[] # array for the plot objects missing=0 # number of missing plots (out of 3) # Plot all avaliable types for i, type in enumerate(['flux','vel','sigma']): f = '%s/%s/%s/kinemetry/kinemetry_gas_%s.txt' % (out_dir, gal, opt, type) if os.path.exists(f): rad, pa, er_pa, q, er_q, k1, erk1 = np.loadtxt(f, unpack=True, skiprows=1) # rad*=0.67 # Change to arcsec pa = rollmed(pa, 7) # smooth with rolling median k1 = rollmed(k1, 7) # Align pa[0] as closely as possible with flux pa[0] by +/- 360 deg if type == 'flux': pa0 = pa[0] else: a = np.argmin(np.abs(pa[0]-pa0+[-360,0,360])) if a == 0: pa -= 360 elif a == 2: pa += 360 # Optimizing PA # cut = np.arange(360,0,-10) # r = np.array([list(pa)]*len(cut)) # for j, c in enumerate(cut): # r[j, np.where(r[j,:] > c)[0]] -=360 # l = np.argmin(np.ptp(r,axis=1)) # pa = r[l] # Finding smoothest pa by add or subtracting 360 deg for j in range(1,len(pa)): test = np.array([pa[j]-360, pa[j], pa[j]+360]) a = np.argmin(np.abs(test-pa[j-1])) if a==0: pa[j:]-=360 elif a==2: pa[j:]+=360 pl = ax.plot(rad,pa,colors[i],label='%s PA' % (type)) pl_ob.append(pl) # Plot k1 from velocity fit. if type == 'vel': ax2=ax.twinx() b=ax2.plot(rad,k1,'r', label='k1') ax2.spines['right'].set_color('red') ax2.yaxis.label.set_color('red') ax2.tick_params(axis='y', colors='red') ax2.set_ylabel('k1',color='r', rotation=270, labelpad=10) ax2.spines['left'].set_color('blue') else: print 'There is no %s KINEMETRY file for %s.' %(type, gal) missing +=1 # If not all missing if missing != 3: # Get redshift of galaxy from data_file data_file = "%s/galaxies.txt" % (out_dir) classify_file = "%s/galaxies_classify.txt" % (out_dir) # different data types need to be read separetly z_gals = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=(1,)) galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0,),dtype=str) i_gal = np.where(galaxy_gals==gal)[0][0] z = z_gals[i_gal] # Set secondary x axis in kpc. ax3=ax.twiny() c = 299792 #km/s #H = 67.8 #(km/s)/Mpc # From Planck H = 70.0 # value used by Bolonga group. r_kpc = np.radians(rad/(60.0*60.0)) * z*c/H *1000 ax3.set_xlim(r_kpc[0],r_kpc[-1]) ax3.set_xlabel('Radius (kpc)') # Mark extent of KDC galaxy_gals2, KDC_size = np.loadtxt(classify_file, unpack=True, usecols=(0,6), dtype=str, skiprows=1) has_KDC = KDC_size!='-' galaxy_gals2 = galaxy_gals2[has_KDC] KDC_size = KDC_size[has_KDC].astype(float) if gal in galaxy_gals2: ax.axvline(KDC_size[galaxy_gals2==gal][0]) #ax.yaxis.label.set_color('blue') #ax.tick_params(axis='y', colors='blue') ax.set_ylabel('PA')#,color='b') ax.set_xlabel('radius (arcsec)') # Legend try: lns = b for l in pl_ob: lns+=l except UnboundLocalError: if missing==1:lns=pl_ob[0]+pl_ob[1] else:lns=pl_ob[0] labs = [l.get_label() for l in lns] ax.legend(lns, labs, loc=0) # Moves title clear of upper x axis plt.subplots_adjust(top=0.85) ax.set_title('%s: KINEMETRY gas output (Smoothed)' % (gal), y=1.12) fig.savefig('%s/%s/%s/kinemetry/kinemetry.png'%(out_dir, gal, opt)) plt.close() Prefig(size=(16*3,12*5), transparent=False) fig, ax = plt.subplots(5,3) fig.set_suptitle('Kinemetry fit to Ionised gas dynamics') f = fits.open(get_dataCubeDirectory(gal)) header = f[0].header f.close() tessellation_File = "%s/%s/%s/setup/voronoi_2d_binning_output.txt" % (out_dir, gal, opt) x,y,bin_num = np.loadtxt(tessellation_File, usecols=(0,1,2), unpack=True, skiprows=1, dtype=int) for i, type in enumerate(['flux','vel','sigma']): f = '%s/%s/%s/kinemetry/kinemetry_gas_%s_2Dmodel.txt' % (out_dir, gal, opt, type) xbin, ybin, velkin, velcirc = np.loadtxt(f, unpack=True, skiprows=1) f = '%s/%s/%s/kinemetry/gas_%s.dat' % (out_dir, gal, opt, type) vel = np.loadtxt(f, usecols=(0,), unpack=True) velkin[velkin==max(velkin)] = np.nan velcirc[velcirc==max(velcirc)] = np.nan # f = '%s/%s/%s/kinemetry/flux.dat' % (out_dir, gal, opt) # flux = np.loadtxt(f) vmin, vmax = set_lims(vel, symmetric=type=='vel', positive=type!='vel') plot_velfield_nointerp(x, y, bin_num, xbin, ybin, vel, header, vmin=vmin, vmax=vmax, nodots=True, title='%s Data'%(type), colorbar=True, ax=ax[0,i])#, flux=flux) plot_velfield_nointerp(x, y, bin_num, xbin, ybin, velkin, header, vmin=vmin, vmax=vmax, nodots=True, title='KINEMETRY %s model' % (type), colorbar=True, ax=ax[1,i])#, flux=flux) plot_velfield_nointerp(x, y, bin_num, xbin, ybin, vel-velkin, header, nodots=True, title='KINEMETRY %s residuals'%(type), colorbar=True, ax=ax[2,i])#, flux=flux) vmin, vmax = set_lims(vel-velkin, symmetric=True) plot_velfield_nointerp(x, y, bin_num, xbin, ybin, vel-velkin, header, vmin=vmin, vmax=vmax, nodots=True, title='KINEMETRY %s vkin residuals'%(type), colorbar=True, ax=ax[2,i])#, flux=flux) vmin, vmax = set_lims(vel-velcirc, symmetric=True) plot_velfield_nointerp(x, y, bin_num, xbin, ybin, vel-velcirc, header, vmin=vmin, vmax=vmax, nodots=True, title='KINEMETRY %s vcirc residuals'%(type), colorbar=True, ax=ax[4,i])#, flux=flux) fig.savefig('%s/%s/%s/kinemetry/kinemetry_models.png'%(out_dir, gal, opt))
def fit_disk(galaxy, D=None, opt='kin'): Prefig(subplots=(3,2)) fig, ax = plt.subplots(2,3) f = fits.open(get_dataCubeDirectory(galaxy)) header = f[0].header f.close() if D is None: pickleFile = open('%s/Data/vimos/analysis/%s/%s/pickled/dataObj.pkl' % (cc.base_dir, galaxy,opt)) D = pickle.load(pickleFile) pickleFile.close() # Use gas disk vel = D.components['[OIII]5007d'].plot['vel'].unbinned vel_err = D.components['[OIII]5007d'].plot['vel'].uncert.unbinned disk,pars=dfn.disk_fit_exp(vel.copy(),vel_err.copy(),sigclip=3.0,leeway=2.) ax[1,0] = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, D.components['[OIII]5007d'].plot['vel'], header, #vmin=vmin, vmax=vmax, flux_unbinned=D.unbinned_flux, nodots=True, colorbar=True, ax=ax[1,0], title=r'Gas observed velocity (v$_\mathrm{gas}$)') ax[1,1].imshow(disk, cmap=sauron) ax[1,1].set_title(r'Gas model velocity (v$_\mathrm{g,mod})$') plot = D.components['[OIII]5007d'].plot['vel']-D.rebin(disk, flux_weighted=True) # vmin,vmax = set_lims(plot) ax[1,2] = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, plot, header, # vmin=vmin, vmax=vmax, flux_unbinned=D.unbinned_flux, nodots=True, colorbar=True, ax=ax[1,2], title=r'Residuals: v$_\mathrm{gas}$ - v$_\mathrm{g,mod}$') # Use stellar disk vel = D.components['stellar'].plot['vel'].unbinned vel_err = D.components['stellar'].plot['vel'].uncert.unbinned disk,pars=dfn.disk_fit_exp(vel.copy(),vel_err.copy(),sigclip=3.0,leeway=2.) ax[0,0] = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, D.components['stellar'].plot['vel'], header, #vmin=vmin, vmax=vmax, flux_unbinned=D.unbinned_flux, nodots=True, colorbar=True, ax=ax[0,0], title=r'Stellar observed velocity (v$_\mathrm{\ast}$)') ax[0,1].imshow(disk, cmap=sauron) ax[0,1].set_title(r'Gas model velocity (v$_\mathrm{\ast,mod}$)') plot = D.components['[OIII]5007d'].plot['vel']-D.rebin(disk, flux_weighted=True) # vmin,vmax = set_lims(plot) ax[0,2] = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, plot, header, # vmin=vmin, vmax=vmax, flux_unbinned=D.unbinned_flux, nodots=True, colorbar=True, ax=ax[0,2], title=r'Residuals: v$_\mathrm{gas}$ - v$_\mathrm{\ast,mod}$') fig.suptitle('Outflows in %s' % (galaxy)) fig.savefig('%s/Data/vimos/analysis/%s/%s/plots/outflows.png' % (cc.base_dir, galaxy, opt)) return D
def pickler(galaxy, discard=0, norm='', opt="kin", override=False): print " Loading D" tessellation_File = "%s/%s/%s/setup/voronoi_2d_binning_output.txt" % (vin_dir, galaxy, opt) tessellation_File2 = "%s/%s/%s/setup/voronoi_2d_binning_output2.txt" %(vin_dir, galaxy, opt) dataCubeDirectory = get_dataCubeDirectory(galaxy) output = "%s/%s/%s" % (out_dir, galaxy, opt) vin_dir_gasMC = "%s/%s/%s/MC" % (vin_dir, galaxy, opt) out_pickle = '%s/pickled' % (output) # Check tessellation file is older than pPXF outputs (checks # vin_dir_gasMC/0.dat only). if not override: if os.path.getmtime(tessellation_File) > os.path.getmtime('%s/0.dat' % ( vin_dir_gasMC)): bin_num = np.loadtxt(tessellation_File, unpack=True, skiprows = 1, usecols=(2,), dtype=int) if os.path.exists('%s/%i.dat' % (vin_dir_gasMC,max(bin_num))) and not \ os.path.exists('%s/%i.dat' % (vin_dir_gasMC, max(bin_num)+1)): # Issue warning, but do not stop. warnings.warn('WANING: The tesselation file '+\ 'voronoi_2d_binning_output.txt may to have been changed.') else: # Stop and raise exception raise UserWarning('WANING: The tesselation file '+\ 'voronoi_2d_binning_output.txt has been overwritten. ' + \ "Use the 'override' keyword to run this routine anyway.") # ------------======== Reading the spectrum ============---------- D = Data(np.loadtxt(tessellation_File, unpack=True, skiprows = 1, usecols=(0,1,2)), sauron=True) galaxy_data, header = pyfits.getdata(dataCubeDirectory, 0, header=True) s = galaxy_data.shape rows_to_remove = range(discard) rows_to_remove.extend([s[1]-1-i for i in range(discard)]) cols_to_remove = range(discard) cols_to_remove.extend([s[2]-1-i for i in range(discard)]) galaxy_data = np.delete(galaxy_data, rows_to_remove, axis=1) galaxy_data = np.delete(galaxy_data, cols_to_remove, axis=2) D.unbinned_flux = np.nansum(galaxy_data, axis=0) temp_wav = np.loadtxt('%s/models/miles_library/m0001V' % (cc.home_dir), usecols=(0,), unpack=True) for i in range(D.number_of_bins): D.bin[i].spectrum = np.loadtxt("%s/input/%d.dat" % (vin_dir_gasMC,i), unpack=True) D.bin[i].noise = np.loadtxt("%s/noise_input/%d.dat" % (vin_dir_gasMC,i), unpack=True) D.bin[i].lam = np.loadtxt("%s/lambda/%d.dat" % (vin_dir_gasMC, i)) # Getting emission templates used lines = {'Hdelta':4101.76, 'Hgamma':4340.47, 'Hbeta':4861.33, '[OIII]5007d':5004.0,'[NI]d':5200.0} matrix = np.loadtxt("%s/bestfit/matrix/%d.dat" % (vin_dir_gasMC, i), dtype=str) ms = matrix.shape for j in range(ms[0]-8, ms[0]): if not matrix[j,0].isdigit(): line = matrix[j,0] D.bin[i].components[line] = emission_line(D.bin[i], line,lines[line],matrix[j,1:].astype(float)) # Skip step if file is empty. with warnings.catch_warnings(): warnings.simplefilter('error') try: D.bin[i].components[line].uncert_spectrum = np.loadtxt( '%s/gas_uncert_spectrum/%s/%i.dat' % (vin_dir_gasMC, line, i)) except:# Warning: pass D.add_e_line(line, lines[line]) D.bin[i].bestfit = np.loadtxt("%s/bestfit/%d.dat" %(vin_dir_gasMC,i), unpack=True) if 'kin' in opt: D.bin[i].apweight = np.loadtxt("%s/apweights/%d.dat" %(vin_dir_gasMC,i), unpack=True) elif 'pop' in opt: D.bin[i].mpweight = np.loadtxt("%s/mpweights/%d.dat" %(vin_dir_gasMC,i), unpack=True) #Setting the weighting given to the gas templates temp_name, temp_weight = np.loadtxt("%s/temp_weights/%d.dat" % ( vin_dir_gasMC, i), unpack=True, dtype='str') # temp_weight = temp_weight.astype(float) D.bin[i].set_templates(temp_name, temp_weight.astype(float)) D.xBar, D.yBar = np.loadtxt(tessellation_File2, unpack=True, skiprows = 1) # ------------=========== Read kinematics results ==============---------- if os.path.isdir(vin_dir_gasMC + "/gas"): components = [d for d in os.listdir(vin_dir_gasMC + "/gas") if \ os.path.isdir(os.path.join(vin_dir_gasMC + "/gas", d))] else: components = [] if len(components) == 0: gas =0 elif 'gas' in components: gas = 1 elif 'Shocks' in components and 'SF' in components: gas = 2 else: gas = 3 D.gas = gas for c in D.list_components_no_mask: dynamics = {'vel':np.zeros(D.number_of_bins)*np.nan, 'sigma':np.zeros(D.number_of_bins)*np.nan, 'h3':np.zeros(D.number_of_bins)*np.nan, 'h4':np.zeros(D.number_of_bins)*np.nan} dynamics_uncert = {'vel':np.zeros(D.number_of_bins)*np.nan, 'sigma':np.zeros(D.number_of_bins)*np.nan, 'h3':np.zeros(D.number_of_bins)*np.nan, 'h4':np.zeros(D.number_of_bins)*np.nan} for bin in range(D.number_of_bins): # Bestfit values glamdring_file = "%s/%i.dat" % (vin_dir_gasMC, bin) c_in_bin = np.loadtxt(glamdring_file, unpack=True, usecols=(0,), dtype=str) # vel, sig, h3s, h4s = np.loadtxt(glamdring_file, unpack=True, # usecols=(1,2,3,4)) if gas == 1 and c != 'stellar': c_type = 'gas' elif gas == 2 and c != 'stellar': if 'H' in c: c_type = 'SF' else: c_type = 'Shocks' else: c_type = c # check componant is in bin if c_type in c_in_bin: i = np.where(c_in_bin == c_type)[0][0] with open(glamdring_file, 'r') as g: rows = g.read().replace('[','').replace(']','').splitlines() row = np.array(rows[i].split()) for j, d in enumerate(['vel', 'sigma', 'h3', 'h4']): try: dynamics[d][bin] = float(row[j+1]) except IndexError: pass # Calculating uncertainties if c_type != "stellar": MC_dir = "%s/gas" % (vin_dir_gasMC) else: MC_dir=vin_dir_gasMC glamdring_file = '%s/%s/%i.dat' % (MC_dir, c_type, bin) # Ignore empty file warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") f = np.loadtxt(glamdring_file, unpack=True) # Check if MC has been run. if len(f) != 0: for j, d in enumerate(['vel', 'sigma', 'h3', 'h4']): try: dynamics_uncert[d][bin] = np.std(f[j,:]) except IndexError: pass else: dynamics_uncert = dynamics for kine in dynamics.keys(): if np.isnan(dynamics[kine]).all(): D.components_no_mask[c].unset(kine) else: D.components_no_mask[c].setkin(kine, dynamics[kine]) D.components_no_mask[c].setkin_uncert(kine, dynamics_uncert[kine]) if norm != '': D.norm_method = norm D.find_restFrame() # ------------================ Pickling =================---------- print " Pickling D" if not os.path.exists(out_pickle): os.makedirs(out_pickle) pickleFile = open("%s/dataObj.pkl" % (out_pickle), 'wb') pickle.dump(D,pickleFile) pickleFile.close() return D
def global_MEx(aperture=3, instrument='vimos'): if instrument == 'vimos': from errors2 import run_ppxf, set_params, get_dataCubeDirectory cen_cols = (4,5) galaxies = np.array(['eso443-g024', 'ic1459', 'ic1531', 'ic4296', 'ngc0612', 'ngc1399', 'ngc3100', 'ngc3557', 'ngc7075', 'pks0718-34']) fits_ext = 0 CDELT1 = 'CDELT1' CDELT3 = 'CDELT3' elif instrument == 'muse': from errors2_muse import run_ppxf, set_params, get_dataCubeDirectory cen_cols = (1,2) galaxies = np.array(['ic1459', 'ic4296', 'ngc1316', 'ngc1399']) fits_ext = 1 CDELT1 = 'CD1_1' CDELT3 = 'CD3_3' data_file = "%s/Data/%s/analysis/galaxies.txt" % (cc.base_dir, instrument) # different data types need to be read separetly x_cent_gals, y_cent_gals = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=cen_cols) galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0,), dtype=str) Prefig() fig, ax = plt.subplots() ax.set_xlabel(r'$\sigma_\ast$') ax.set_ylabel(r'log [OIII]$\lambda$5007/H$\,\beta$') OIII_ew_sav = [] sigma_sav = [] e_sigma_sav = [] excitation_sav = [] e_excitation_sav = [] for galaxy in galaxies: params = set_params(reps=10, produce_plot=False, opt='pop') i_gal = np.where(galaxy_gals==galaxy)[0][0] x_cent_pix = x_cent_gals[i_gal] y_cent_pix = y_cent_gals[i_gal] f = fits.open(get_dataCubeDirectory(galaxy)) galaxy_data = f[fits_ext].data header = f[fits_ext].header # Normalise each spaxel for population pipeline galaxy_noise = f[fits_ext+1].data f.close() ## write key parameters from header - can then be altered in future CRVAL_spec = header['CRVAL3'] CDELT_spec = header[CDELT3] s = galaxy_data.shape if aperture == 'R_e': ap = get_R_e(galaxy)/np.abs(header[CDELT1]) else: ap = aperture/np.abs(header[CDELT1]) frac_in_ap = in_aperture(x_cent_pix, y_cent_pix, ap, instrument=instrument) galaxy_data = np.einsum('ijk,jk->ijk', galaxy_data, frac_in_ap) galaxy_noise = np.einsum('ijk,jk->ijk', galaxy_noise, frac_in_ap)**2 bin_lin = np.nansum(galaxy_data, axis=(1,2)) bin_lin_noise = np.sqrt(np.nansum(galaxy_noise, axis=(1,2))) lam = np.arange(s[0])*CDELT_spec + CRVAL_spec bin_lin, lam, cut = apply_range(bin_lin, lam=lam, set_range=params.set_range, return_cuts=True) lamRange = np.array([lam[0],lam[-1]]) bin_lin_noise = bin_lin_noise[cut] pp = run_ppxf(galaxy, bin_lin, bin_lin_noise, lamRange, CDELT_spec, params) e_lines = pp.component != 0 residuals = pp.galaxy - pp.bestfit _, residuals, _ = moving_weighted_average(pp.lam, residuals, step_size=3., interp=True) noise = np.sqrt(residuals**2 + pp.noise**2) # Only use line if formally detected. OIII = pp.matrix[:,pp.templatesToUse=='[OIII]5007d'].flatten() \ * pp.weights[pp.templatesToUse=='[OIII]5007d'] Hb = pp.matrix[:,pp.templatesToUse=='Hbeta'].flatten() \ * pp.weights[pp.templatesToUse=='Hbeta'] if np.max(OIII)/np.median( noise[(np.log(pp.lam) > np.log(5007) - 300/c) * (np.log(pp.lam) < np.log(5007) + 300/c)]) < 4: OIII[:] = 0 Hb[:] = 0 elif np.max(Hb)/np.median( noise[(np.log(pp.lam) > np.log(4861) - 300/c) * (np.log(pp.lam) < np.log(4861) + 300/c)]) < 3: Hb[:] = 0 OIII_flux = np.trapz(OIII, x=pp.lam)/1.35 # not doublet e_lines = np.array([e for e in pp.templatesToUse if not e.isdigit()]) e_OIII_flux = trapz_uncert( pp.MCgas_uncert_spec[e_lines=='[OIII]5007d',:], x=pp.lam) continuum = pp.galaxy - OIII # only need continuum at 5007A OIII_pix = np.argmin(np.abs(pp.lam / (1 + pp.sol[0][0]/c) - 5007)) OIII_ew = OIII_flux/continuum[OIII_pix] Hb_flux = np.trapz(Hb, x=pp.lam) e_Hb_flux = trapz_uncert( pp.MCgas_uncert_spec[e_lines=='Hbeta',:], x=pp.lam) excitation = np.log10(OIII_flux/Hb_flux) e_excitation = np.sqrt((e_Hb_flux/Hb_flux)**2 + (e_OIII_flux/OIII_flux)**2)/np.log(10) e_excitation = np.sqrt((e_OIII_flux/OIII_flux)**2 + (e_Hb_flux/Hb_flux)**2)/np.log(10) sigma = pp.sol[0][1] e_sigma = np.std(pp.MCstellar_kin[:,1]) if OIII_flux != 0 and Hb_flux != 0: if OIII_ew > 0.8: ax.errorbar(sigma, np.log10(OIII_flux/Hb_flux), xerr=e_sigma, yerr=e_excitation, fmt='x', c='k') else: ax.errorbar(sigma, np.log10(OIII_flux/Hb_flux), xerr=e_sigma, yerr=e_excitation, fmt='o', c='k') ax.text(sigma+2, np.log10(OIII_flux/Hb_flux)+0.02, galaxy, fontsize=12) OIII_ew_sav.append(OIII_ew) sigma_sav.append(sigma) e_sigma_sav.append(e_sigma) excitation_sav.append(excitation) e_excitation_sav.append(e_excitation) ax.axvline(70, c='k') ax.axhline(np.log10(0.5), xmin=70./400, c='k') ax.axhline(np.log10(1), xmin=70./400, c='k') x_line = np.arange(70,1000,1) y_line = 1.6*10**-3 * x_line + 0.33 ax.plot(x_line, y_line, c='k') ax.set_xlim([0, 400]) ax.set_ylim([-1.2, 1.5]) ylim = ax.get_ylim() yrange = ylim[1] - ylim[0] ax.text(50, ylim[0] +0.96 * yrange, 'SF') ax.text(75, 0.55, 'Seyfert 2') ax.text(75, 0.15, 'LINER') ax.text(75, -0.23, 'Transition') ax.text(75, -0.5, 'Passive') # ax.legend() fig.savefig('%s/Data/%s/analysis/global_MEx.png' %(cc.base_dir, instrument)) with open('%s/Data/%s/analysis/global_MEx.txt' %(cc.base_dir, instrument), 'w') as f: f.write('Galaxy sigma e_sigma log(OIII/Hb)'+ ' e_log(OIII/Hb) OIII_ew \n') for i in range(len(galaxies)): f.write('%s \t\t %.4g %.4g %.4g %.4g %.4g \n' % (galaxies[i], sigma_sav[i], e_sigma_sav[i], excitation_sav[i], e_excitation_sav[i], OIII_ew_sav[i]))
def compare_absortion(galaxy, R_sig=False, corr_lines='all'): f = fits.open(get_dataCubeDirectory(galaxy)) header = f[0].header lines = ['G4300', 'Fe4383', 'Ca4455', 'Fe4531', 'H_beta', 'Fe5015', 'Mg_b'] color = ['r', 'b', 'g', 'c', 'purple', 'k', 'orange'] R_e = get_R_e(galaxy) apertures = np.array([1.5, 2.5, 10, R_e/10, R_e/8, R_e/4, R_e/2]) # arcsec Ramp_sigma = {'ngc3557':[265, 247, 220], 'ic1459':[311, 269, 269], 'ic4296':[340, 310, 320]} R_sigma = interp1d([R_e/8, R_e/4, R_e/2], Ramp_sigma[galaxy], fill_value=(Ramp_sigma[galaxy][0], Ramp_sigma[galaxy][2]), bounds_error=False) data_file = "%s/Data/vimos/analysis/galaxies.txt" % (cc.base_dir) z_gals, x_cent_gals, y_cent_gals = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=(1,4,5), dtype='float,int,int') galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0,),dtype=str) i_gal = np.where(galaxy_gals==galaxy)[0][0] z = z_gals[i_gal] center = np.array([x_cent_gals[i_gal], y_cent_gals[i_gal]]) index = np.zeros((40,40,2)) for i in range(40): for j in range(40): index[i,j,:] = np.array([i,j]) - center fig, ax = plt.subplots() fig3, ax3 = plt.subplots() fig4, ax4 = plt.subplots() ax5 = ax4.twinx() my_values = {} my_errors = {} sigma = np.array([]) R_s = np.array([]) t=[] e=[] g=[] h=[] j=[] r=[] w=[] y=[] for a in apertures: params = set_params(reps=0, opt='pop', gas=1, lines=corr_lines, produce_plot=False, res=8.4) mask = np.sqrt(index[:,:,0]**2 + index[:,:,1]**2) * header['CDELT3'] < a spec = np.nansum(f[0].data[:,mask], axis=1) noise = np.sqrt(np.nansum(f[1].data[:,mask]**2, axis=1)) lam = np.arange(len(spec))*header['CDELT3'] + header['CRVAL3'] spec, lam, cut = apply_range(spec, lam=lam, set_range=params.set_range, return_cuts=True) lamRange = np.array([lam[0],lam[-1]]) noise = noise[cut] pp = run_ppxf(galaxy, spec, noise, lamRange, header['CDELT3'], params) plot = create_plot(pp) plot.lam = pp.lam*(1+pp.z)/(1+pp.z+(pp.sol[0][0]/c)) fig2, ax2, = plot.produce s = spectrum(lam=pp.lam, lamspec=pp.galaxy) for i, l in enumerate(lines): if l=='H_beta' or l=='Hbeta': l='hb' elif l=='Mg_b': l='mgb' elif l=='NaD': l='nad' elif l=='TiO1': l='tio1' elif l=='TiO2': l='tio2' elif l=='Fe5270': l='fe52' elif l=='Fe5335': l='fe53' ax2.axvspan(*getattr(s,l),color='b', alpha=0.5) ax2.axvspan(getattr(s,l+'cont')[0], getattr(s,l+'cont')[1], color='r', alpha=0.5) ax2.axvspan(getattr(s,l+'cont')[2], getattr(s,l+'cont')[3], color='r', alpha=0.5) lims = ax2.get_ylim() if i%2==0: ax2.text(np.mean(getattr(s,l)), lims[1] - 0.1*(lims[1]-lims[0]), l, size=8, ha='center') else: ax2.text(np.mean(getattr(s,l)), lims[1] - 0.15*(lims[1]-lims[0]), l, size=8, ha='center') fig2.savefig('/Data/lit_absorption/Rampazzo/%s_rad_%.2f.png'%(galaxy, a)) plt.close(fig2) if R_sig: if isinstance(R_sig, bool): absorp, uncert = get_absorption(lines, pp=pp, sigma=R_sigma(a), instrument='vimos', res=8.4) sigma = np.append(sigma, R_sigma(a)) else: absorp, uncert = get_absorption(lines, pp=pp, instrument='vimos', sigma=R_sigma(a)+R_sig*(pp.sol[0][1]-R_sigma(a)), res=8.4) sigma = np.append(sigma, R_sigma(a)+R_sig*(pp.sol[0][1]-R_sigma(a))) else: absorp, uncert = get_absorption(lines, pp=pp, instrument='vimos', res=8.4) sigma = np.append(sigma, pp.sol[0][1]) for l in lines: if a == min(apertures): my_values[l] = np.array([]) my_errors[l] = np.array([]) my_values[l] = np.append(my_values[l], absorp[l]) my_errors[l] = np.append(my_errors[l], uncert[l]) for i, l in enumerate(lines): ax.errorbar(a, absorp[l], yerr=uncert[l], color=color[i], fmt='x') R_s = np.append(R_s, R_sigma(a)) for i, l in enumerate(lines): ax.errorbar(np.nan, np.nan, color=color[i], fmt='x', label=l) ax.legend(facecolor='w') Rampazzo_file = '%s/Data/lit_absorption/Rampazzo_aperture.txt' % (cc.base_dir) file_headings = np.loadtxt(Rampazzo_file, dtype=str)[0] for i, l in enumerate(lines): col = np.where(file_headings==l)[0][0] try: col2 = np.where(file_headings==l)[0][1] except: try: col2 = np.where(file_headings=='_'+l)[0][0] except: col2 = np.where(file_headings=='e_'+l)[0][0] R_obs, R_err = np.loadtxt(Rampazzo_file, unpack=True, skiprows=1, usecols=(col,col2)) R_galaxies = np.loadtxt(Rampazzo_file, unpack=True, skiprows=1, usecols=(0,), dtype=str) mask = R_galaxies==galaxy order = np.argsort(apertures) lit_value = Lick_to_LIS(l, R_obs[mask][order], res=8.4) err = np.mean([np.abs(Lick_to_LIS(l, R_obs[mask][order] + R_err[mask][order]) - Lick_to_LIS(l, R_obs[mask][order])), np.abs(Lick_to_LIS(l, R_obs[mask][order] - R_err[mask][order]) - Lick_to_LIS(l, R_obs[mask][order]))], axis=0) ax.errorbar(apertures[order], lit_value, yerr=err, color=color[i]) if l=='H_beta' or l=='Hbeta': l2='hb' elif l=='Mg_b': l2='mgb' elif l=='NaD': l2='nad' elif l=='TiO1': l2='tio1' elif l=='TiO2': l2='tio2' elif l=='Fe5270': l2='fe52' elif l=='Fe5335': l2='fe53' else: l2=l ax3.scatter( np.abs(my_values[l][order] - lit_value)/my_values[l][order], np.abs(my_values[l][order] - lit_value)/np.sqrt(err**2 + my_errors[l][order]**2), color=color[i], s=4*apertures[order]**2, label=l) ax4.scatter(sigma[order], np.abs(my_values[l][order] - lit_value)/my_values[l][order], color=color[i], s=4*apertures[order]**2, label=l) ax5.scatter(sigma[order], np.abs(my_values[l][order] - lit_value)/np.sqrt(err**2 + my_errors[l][order]**2), marker='x', color=color[i], s=4*apertures[order]**2, label=l) t.extend(sigma[order]) g.extend(my_values[l][order]) h.extend(lit_value) j.extend(err) e.extend(my_errors[l][order]) r.extend([lines[i]]*len(sigma)) w.extend(4*apertures[order]**2) y.extend(R_s) ax.set_ylabel(r'Index strength, $\AA$') ax.set_xlabel('Radius, arcsec') fig.savefig('%s/Data/lit_absorption/Rampazzo_aperture_%s_%i.png' % ( cc.base_dir, galaxy, params.gas)) plt.close(fig) ax3.set_ylabel(r'Sigma difference ((Mine - Ramp)/Combined Uncert)') ax3.set_xlabel('Fractional difference ((Mine - Ramp)/Mine)') ax3.legend() fig3.savefig('%s/Data/lit_absorption/Rampazzo_aperture_%s_fractional.png' % ( cc.base_dir, galaxy)) plt.close(fig3) ax4.set_xlabel('Vel dispersion') ax3.set_ylabel('Fractional difference ((Mine - Ramp)/Mine)') ax5.set_ylabel(r'Sigma difference ((Mine - Ramp)/Combined Uncert)') ax4.legend() fig4.savefig('%s/Data/lit_absorption/Rampazzo_aperture_%s_sigma.png' % ( cc.base_dir, galaxy)) plt.close(fig4) return t, g, h, j, e, r, w, y
def plot(galaxies, str_galaxies, file_name, instrument, debug=False): if instrument == 'vimos': from plot_results import add_ from errors2 import get_dataCubeDirectory elif instrument == 'muse': from plot_results_muse import add_ from errors2_muse import get_dataCubeDirectory opt = 'pop' overplot={'CO':'w', 'radio':'g'} Prefig(size=np.array((4, len(galaxies)))*7) fig, axs = plt.subplots(len(galaxies), 4)#, sharex=True, sharey=True) out_dir = '%s/Documents/paper/%s' % (cc.home_dir, instrument) for i, galaxy in enumerate(galaxies): if debug: from produce_plots import Ds D = Ds() else: D = Data(galaxy, instrument=instrument, opt=opt) opt = D.opt print galaxy vin_dir = '%s/Data/%s/analysis' % (cc.base_dir, instrument) data_file = "%s/galaxies.txt" % (vin_dir) file_headings = np.loadtxt(data_file, dtype=str)[0] col = np.where(file_headings=='SN_%s' % (opt))[0][0] SN_target_gals = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=(col,)) galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0,), dtype=str) i_gal = np.where(galaxy_gals==galaxy)[0][0] SN_target=SN_target_gals[i_gal] attr, vmin, vmax = np.loadtxt('%s/lims.txt' % (vin_dir), dtype=str, usecols=(0,1,2), skiprows=1, unpack=True) vmin, vmax = vmin.astype(float), vmax.astype(float) f = fits.open(get_dataCubeDirectory(galaxy)) if instrument == 'vimos': header = f[0].header elif instrument == 'muse': header = f[1].header f.close() plots = [ "components['[OIII]5007d'].plot['vel']", "components['[OIII]5007d'].plot['sigma']", "components['[OIII]5007d'].plot['vel'].uncert", "components['[OIII]5007d'].plot['sigma'].uncert" ] # Velocity if galaxy == 'ngc3100': vmin_vel, vmax_vel = -100, 100 #set_lims( # D.components['[OIII]5007d'].plot['vel'], symmetric=True, # n_std=5) print 'NGC 3100 velocity scale:', vmin_vel,'km/s to ', \ vmax_vel, 'km/s' else: vmin_vel=vmin[attr==plots[0]][0] vmax_vel=vmax[attr==plots[0]][0] axs[i,0] = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, D.components['[OIII]5007d'].plot['vel'], header, vmin=vmin_vel, vmax=vmax_vel, cmap=sauron, flux_unbinned=D.unbinned_flux, signal_noise=D.SNRatio, signal_noise_target=SN_target, ax=axs[i,0]) if overplot: for o, color in overplot.iteritems(): scale = 'log' if o == 'radio' else 'lin' add_(o, color, axs[i, 0], galaxy, nolegend=True, scale=scale) axs[i,1] = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, D.components['[OIII]5007d'].plot['vel'].uncert, header, vmin=vmin[attr==plots[2]][0], vmax=vmax[attr==plots[2]][0], cmap=sauron, flux_unbinned=D.unbinned_flux, signal_noise=D.SNRatio, signal_noise_target=SN_target, ax=axs[i,1]) # Velocty dispersion axs[i,2] = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, D.components['[OIII]5007d'].plot['sigma'], header, vmin=vmin[attr==plots[1]][0], vmax=vmax[attr==plots[1]][0], cmap=sauron, flux_unbinned=D.unbinned_flux, signal_noise=D.SNRatio, signal_noise_target=SN_target, ax=axs[i,2]) if overplot: for o, color in overplot.iteritems(): scale = 'log' if o == 'radio' else 'lin' add_(o, color, axs[i, 2], galaxy, nolegend=True, scale=scale) axs[i,3] = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, D.components['[OIII]5007d'].plot['sigma'].uncert, header, vmin=vmin[attr==plots[3]][0], vmax=vmax[attr==plots[3]][0], cmap=sauron, flux_unbinned=D.unbinned_flux, signal_noise=D.SNRatio, signal_noise_target=SN_target, ax=axs[i,3]) for a in axs.flatten(): if hasattr(a, 'ax_dis'): a.ax_dis.tick_params(top=True, bottom=True, left=True, right=True, direction='in', which='major', length=20, width=3, labelsize='large') a.ax_dis.tick_params(top=True, bottom=True, left=True, right=True, direction='in', which='minor', length=10, width=3) a.ax_dis.xaxis.label.set_size(22) a.ax_dis.yaxis.label.set_size(22) for a in axs[:,1:].flatten(): if hasattr(a, 'ax_dis'): a.ax_dis.set_yticklabels([]) a.ax_dis.set_ylabel('') # for a in axs[range(0, len(galaxies), 2), 1:].flatten(): # if hasattr(a, 'ax_dis'): # a.ax_dis.set_yticklabels([]) # a.ax_dis.set_ylabel('') for a in axs[:-1,:].flatten(): if hasattr(a, 'ax_dis'): a.ax_dis.set_xticklabels([]) a.ax_dis.set_xlabel('') # Create gap between galaxies for i in range(1, len(galaxies)): for a in axs[i, :].flatten(): ax_loc = a.get_position() ax_loc.y0 -= i*0.01 ax_loc.y1 -= i*0.01 a.set_position(ax_loc) if hasattr(a, 'ax_dis'): a.ax_dis.set_position(ax_loc) loc = np.mean([axs[0,0].get_position().x0, axs[0,1].get_position().x1]) fig.text(loc, 0.92, r'Mean Velocity', va='top', ha='center', size='xx-large') loc = np.mean([axs[0,2].get_position().x0, axs[0,3].get_position().x1]) fig.text(loc, 0.92, r'Velocity Dispersion', va='top', ha='center', size='xx-large') for i, g in enumerate(str_galaxies): loc = np.mean([axs[i,0].get_position().y0, axs[i,0].get_position().y1]) fig.text(0.07, loc, g, va='center', ha='right', rotation='vertical', size='xx-large') # Add colorbar ticks_sym = ticker.MaxNLocator(nbins=4, symmetric=True, min_n_ticks=6) ticks_pos = ticker.MaxNLocator(nbins=4, min_n_ticks=3) ax_loc = axs[0,3].get_position() # Left cax = fig.add_axes([ax_loc.x1+0.06, ax_loc.y0, 0.02, ax_loc.height]) cbar = plt.colorbar(axs[0,0].cs, cax=cax, ticks=ticks_pos) fig.text(ax_loc.x1+0.02, (ax_loc.y0+ax_loc.y1)/2, r'Velocity (km s$^{-1}$)', rotation=90, va='center', ha='center') # Right fig.text(ax_loc.x1+0.13, (ax_loc.y0+ax_loc.y1)/2, r'Velocity Dispersion (km s$^{-1}$)', rotation=270, va='center', ha='center') cax2 = cax.twinx() cax2.set_ylim(axs[0,2].cs.get_clim()) cax2.yaxis.set_major_locator(ticks_sym) # Colorbar for Uncertainy ax_loc = axs[1,3].get_position() ticks_pos = ticker.MaxNLocator(nbins=4) # Left cax = fig.add_axes([ax_loc.x1+0.06, ax_loc.y0, 0.02, ax_loc.height]) cbar = plt.colorbar(axs[1,1].cs, cax=cax, ticks=ticks_pos) fig.text(ax_loc.x1+0.02, (ax_loc.y0+ax_loc.y1)/2, r'Velocity Uncertainy (km s$^{-1}$)', rotation=90, va='center', ha='center') # Right fig.text(ax_loc.x1+0.13, (ax_loc.y0+ax_loc.y1)/2, r'Velocity Dispersion Uncertainy(km s$^{-1}$)', rotation=270, va='center', ha='center') cax2 = cax.twinx() cax2.set_ylim(axs[1,3].cs.get_clim()) cax2.yaxis.set_major_locator(ticks_pos) # Add extra colorbar for NGC 3100 if 'ngc3100' in galaxies: loc = np.where(np.array(galaxies)=='ngc3100')[0][0] ax_loc = axs[loc, 3].get_position() ticks_sym = ticker.MaxNLocator(nbins=4, min_n_ticks=3) cax = fig.add_axes([ax_loc.x1+0.06, ax_loc.y0, 0.02, ax_loc.height]) cbar = plt.colorbar(axs[loc,1].cs, cax=cax, ticks=ticks_sym) fig.text(ax_loc.x1+0.13, (ax_loc.y0+ax_loc.y1)/2, r'Velocity for NGC 3100 (km s$^{-1}$)', rotation=270, va='center', ha='center') if debug: fig.savefig('%s/%s.png' % (out_dir, 'test'), bbox_inches='tight', dpi=240) else: fig.savefig('%s/%s.png' % (out_dir, file_name), bbox_inches='tight', dpi=240) plt.close('all')
def mg_sigma(galaxy, aperture=1.0): ## ----------===============================================--------- ## ----------============= Input parameters ===============--------- ## ----------===============================================--------- params = set_params(reps=10, produce_plot=False, opt='pop', res=8.4, use_residuals=True) galaxies = np.array(['ngc3557', 'ic1459', 'ic1531', 'ic4296', 'ngc0612', 'ngc1399', 'ngc3100', 'ngc7075', 'pks0718-34', 'eso443-g024']) i_gal = np.where(galaxies == galaxy)[0][0] if cc.device == 'glamdring': dir = cc.base_dir else: dir = '%s/Data/vimos' % (cc.base_dir) data_file = dir + "/analysis/galaxies.txt" # different data types need to be read separetly x_cent_gals, y_cent_gals = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=(4,5)) galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0,),dtype=str) i_gal = np.where(galaxy_gals==galaxy)[0][0] x_cent_pix = x_cent_gals[i_gal] y_cent_pix = y_cent_gals[i_gal] ## ----------===============================================--------- ## ----------=============== Run analysis =================--------- ## ----------===============================================--------- ## ----------========= Reading the spectrum ===============--------- f = fits.open(get_dataCubeDirectory(galaxy)) galaxy_data = f[0].data header = f[0].header # Normalise each spaxel for population pipeline galaxy_noise = f[1].data ## write key parameters from header - can then be altered in future CRVAL_spec = header['CRVAL3'] CDELT_spec = header['CDELT3'] s = galaxy_data.shape if aperture == 'R_e': ap = get_R_e(galaxy)/header['CDELT1'] else: ap = aperture ## ----------========== Spatially Integrating =============--------- frac_in_ap = in_aperture(x_cent_pix, y_cent_pix, ap, instrument='vimos') galaxy_data = np.einsum('ijk,jk->ijk', galaxy_data, frac_in_ap) galaxy_noise = np.einsum('ijk,jk->ijk', galaxy_noise**2, frac_in_ap) bin_lin = np.nansum(galaxy_data, axis=(1,2)) bin_lin_noise = np.sqrt(np.nansum(galaxy_noise, axis=(1,2))) ## ----------========= Calibrating the spectrum ===========--------- lam = np.arange(s[0])*CDELT_spec + CRVAL_spec bin_lin, lam, cut = apply_range(bin_lin, lam=lam, set_range=params.set_range, return_cuts=True) lamRange = np.array([lam[0],lam[-1]]) bin_lin_noise = bin_lin_noise[cut] pp = run_ppxf(galaxy, bin_lin, bin_lin_noise, lamRange, CDELT_spec, params) ## ----------=============== Find sigma_0 =================--------- sigma_0 = pp.sol[0][1] unc_sigma_0 = np.std(pp.MCstellar_kin[:,1]) if aperture == 'R_e': area = np.sum(frac_in_ap)*header['CDELT1']*header['CDELT2'] if area < 0.97 * np.pi * R_e**2: R = np.sqrt(area/np.pi) sigma_0 = sigma_0 * (R_e/R)**-0.066 unc_sigma_0 = np.sqrt(unc_sigma_0**2 + ((R_e/R)**-0.066 * np.log(R_e/R) * 0.035)**2) # ## ----------============ Find dynamical mass ===============--------- # G = 4.302*10**-6 # kpc (km/s)^2 M_odot^-1 # M = 5.0 * R_e * sigma_0**2/G mg, mg_uncert = get_absorption(['Mg_b'], pp=pp, instrument='vimos', res=8.4) return mg['Mg_b'], mg_uncert['Mg_b'], sigma_0, unc_sigma_0
def ngc1316_inflow(): galaxy = 'ngc1316' opt = 'pop' instrument = 'muse' from plot_results_muse import add_ from errors2_muse import get_dataCubeDirectory import disk_fit_functions_binned as dfn Prefig(size=np.array((3.6, 1))*5.5) fig, ax = plt.subplots(1,3) f = fits.open(get_dataCubeDirectory(galaxy)) header = f[1].header f.close() D = Data('ngc1316', instrument=instrument, opt=opt) vel = D.components['[OIII]5007d'].plot['vel'] m = ~np.isnan(vel) d, params = dfn.disk_fit_exp(D.xBar[m], D.yBar[m], np.array(vel).copy()[m], vel.uncert.copy()[m], sigclip=5.0, leeway=0., verbose=False, grid_length=150) d *= -1 # Seems to be slight quirk of the system. params[5:] *= -1 disc = vel.copy() # reinsert nans disc[m] = d vmin, vmax = set_lims(D.components['[OIII]5007d'].plot['vel'], symmetric=True, positive=False) ax[0] = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, vel, header, vmin=vmin, max=vmax, nodots=True, flux_unbinned=D.unbinned_flux, colorbar=False, ax=ax[0]) ax[1] = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, disc, header, vmin=vmin, vmax=vmax, nodots=True, flux_unbinned=D.unbinned_flux, colorbar=False, ax=ax[1]) ax[2] = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, vel - disc, header, vmin=vmin, vmax=vmax, nodots=True, flux_unbinned=D.unbinned_flux, colorbar=False, ax=ax[2]) for a in ax: for o, color in {'radio':'g','CO':'w'}.iteritems(): scale = 'log' if o == 'radio' else 'lin' add_(o, color, a, galaxy, nolegend=True, scale=scale) if hasattr(a, 'ax_dis'): a.ax_dis.tick_params(top=True, bottom=True, left=True, right=True, direction='in', which='major', length=20, width=3, labelsize='large') a.ax_dis.tick_params(top=True, bottom=True, left=True, right=True, direction='in', which='minor', length=10, width=3) # Decrease gap between maps for i in range(len(ax)): for a in ax[i:]: ax_loc = a.get_position() ax_loc.x0 -= 0.03 ax_loc.x1 -= 0.03 a.set_position(ax_loc) if hasattr(a, 'ax_dis'): a.ax_dis.set_position(ax_loc) for i, t in enumerate([r'$V_\mathrm{gas}$', r'$V_\mathrm{model}$', r'$V_\mathrm{residuals} = V_\mathrm{gas} - V_\mathrm{model}$']): fig.text(ax[i].ax_dis.get_position().x0+0.02, ax[i].ax_dis.get_position().y1-0.04, t, va='top', color='w', zorder=15) for a in ax[1:]: if hasattr(a, 'ax_dis'): a.ax_dis.set_yticklabels([]) a.ax_dis.set_ylabel('') ax_loc = ax[2].ax_dis.get_position() cax = fig.add_axes([ax_loc.x1+0.03, ax_loc.y0, 0.02, ax_loc.height]) cbar = plt.colorbar(ax[0].cs, cax=cax) # cbar.ax.set_yticklabels([]) fig.text(ax_loc.x1+0.08, 0.5, r'Mean velocity (km s$^{-1}$)', rotation=270, verticalalignment='center') fig.savefig('%s/Documents/paper/ngc1316_inflow.png' % ( cc.home_dir), dpi=300, bbox_inches='tight')
def plot_absorption(galaxy, D=None, uncert=True, opt='pop', overplot={}, gradient=True): # Find lines: lines = ['G4300', 'Fe4383', 'Ca4455', 'Fe4531', 'H_beta', 'Fe5015', #'Mg_1', 'Mg_2', 'Mg_b'] limits = {#'G4300', 'Fe4383', 'Ca4455', 'Fe4531', 'H_beta':[1.0,2.9], 'Fe5015':[3.5,5.9], 'Mg_b':[3.1,4.7]} print 'Absorption lines' # Load pickle file from pickler.py out_dir = '%s/Data/vimos/analysis' % (cc.base_dir) output = "%s/%s/%s" % (out_dir, galaxy, opt) out_plots = "%s/plots/absorption" % (output) if not os.path.exists(out_plots): os.makedirs(out_plots) if D is None and gradient != 'only': out_pickle = '%s/pickled' % (output) pickleFile = open("%s/dataObj.pkl" % (out_pickle), 'rb') D = pickle.load(pickleFile) pickleFile.close() f = fits.open(get_dataCubeDirectory(galaxy)) header = f[0].header if not gradient: f.close() data_file = "%s/galaxies.txt" % (out_dir) file_headings = np.loadtxt(data_file, dtype=str)[0] col = np.where(file_headings=='SN_%s' % (opt))[0][0] z_gals, x_cent_gals, y_cent_gals, SN_target_gals = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=(1,4,5,col), dtype='float,int,int,float') galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0,),dtype=str) i_gal = np.where(galaxy_gals==galaxy)[0][0] z = z_gals[i_gal] SN_target=SN_target_gals[i_gal] center = (x_cent_gals[i_gal], y_cent_gals[i_gal]) figs = {} axs = {} fig,ax =plt.subplots() figs['Mg_sigma'] = fig axs['Mg_sigma'] = ax # mins = {} # maxs = {} for line in lines: fig,ax =plt.subplots() figs[line] = fig axs[line] = ax # mins[line] = 1000 # maxs[line] = -1000 if gradient !='only': for i, line in enumerate(lines): print " " + line if uncert: ab_line, ab_uncert = D.absorption_line(line, uncert=True) else: ab_line = D.absorption_line(line) abmin, abmax = set_lims(ab_line, positive=True) # if line in limits.keys(): # abmin = limits[line][0] # abmax = limits[line][1] saveTo = '%s/%s.png' % (out_plots, line) ax = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, ab_line, header, vmin=abmin, vmax=abmax, nodots=True, colorbar=True, label='Index strength ('+r'$\AA$'+')', title=line, cmap='gnuplot2', redshift=z, flux_unbinned=D.unbinned_flux, signal_noise=D.SNRatio, signal_noise_target=SN_target, center=center, save=saveTo) ax.saveTo = saveTo count = 0 if overplot: for o, color in overplot.iteritems(): count +=1 add_(o, color, ax, galaxy, close = count==len(overplot)) if uncert: abmin, abmax = set_lims(ab_uncert) ax = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, ab_uncert, header, vmin=abmin, vmax=abmax, nodots=True, colorbar=True, label='Index strength ('+r'$\AA$'+')', title=line, cmap='gnuplot2', flux_unbinned=D.unbinned_flux, signal_noise=D.SNRatio, signal_noise_target=SN_target, center=center, save='%s/%s_uncert.png' % (out_plots, line), close=True) if gradient: r = np.sqrt((D.xBar - center[0])**2 + (D.yBar - center[1])**2) if uncert: axs[line].errorbar(r, ab_line, yerr=ab_uncert, fmt='.', c='k') else: axs[line].scatter(r, ab_line, marker = 'x', c='k') if line == 'Mg_b': x = np.log10(D.components['stellar'].plot['sigma']) xerr = D.components['stellar'].plot['sigma'].uncert/\ D.components['stellar'].plot['sigma']/np.log(10) axs['Mg_sigma'].errorbar(x, ab_line, xerr=xerr, yerr=ab_uncert, fmt='.', c='k') if np.isfinite(ab_line[0]): params, cov = np.polyfit(x,ab_line, 1, w=np.sqrt(1/(xerr)**2 + 1/ab_uncert**2), cov=True) lims = np.array(axs['Mg_sigma'].get_xlim()) axs['Mg_sigma'].plot(lims, np.poly1d(params)(lims), 'k') if gradient: print ' Gradients' index = np.zeros((40,40,2)) for i in range(40): for j in range(40): index[i,j,:] = np.array([i,j]) - center step_size = 2 annuli = np.arange(2, 26, step_size) mg = np.array([]) e_mg = np.array([]) sigma = np.array([]) e_sigma = np.array([]) for a in annuli: params = set_params(reps=10, opt='pop', gas=1, produce_plot=False) mask = (np.sqrt(index[:,:,0]**2 + index[:,:,1]**2) < a) * ( np.sqrt(index[:,:,0]**2 + index[:,:,1]**2) > a - step_size) spec = np.nansum(f[0].data[:,mask], axis=1) noise = np.sqrt(np.nansum(f[1].data[:,mask]**2, axis=1)) lam = np.arange(len(spec))*header['CDELT3'] + header['CRVAL3'] spec, lam, cut = apply_range(spec, lam=lam, set_range=params.set_range, return_cuts=True) lamRange = np.array([lam[0],lam[-1]]) noise = noise[cut] pp = run_ppxf(galaxy, spec, noise, lamRange, header['CDELT3'], params) absorp, uncert = get_absorption(lines, pp=pp, instrument='vimos') for line in lines: axs[line].errorbar(a, absorp[line], yerr=uncert[line], c='r', fmt='.') # mins[line] = min(mins[line], absorp[line]) # maxs[line] = max(maxs[line], absorp[line]) axs['Mg_sigma'].errorbar(np.log10(pp.sol[0][1]), absorp['Mg_b'], xerr=np.std(pp.MCstellar_kin[:,1])/pp.sol[0][1]/np.log(10), yerr=uncert['Mg_b'], c='r', fmt='.') mg = np.append(mg, absorp['Mg_b']) e_mg = np.append(e_mg, uncert['Mg_b']) sigma = np.append(sigma, np.log10(pp.sol[0][1])) e_sigma = np.append(e_sigma, np.std(pp.MCstellar_kin[:,1])/pp.sol[0][1]/np.log(10)) for line in lines: # axs[line].set_ylim(0.9*mins[line], 1.1*maxs[line]) axs[line].set_ylim(0,9) axs[line].set_xlabel('Radius') axs[line].set_ylabel(r'Index \AA') figs[line].savefig('%s/%s_grad.png' %(out_plots, line)) plt.close(figs[line]) if np.isfinite(mg[0]): mask = np.isfinite(mg) params, cov = np.polyfit(sigma[mask], mg[mask], 1, w=np.sqrt(1/(e_sigma)**2 + 1/e_mg**2)[mask], cov=True) lims = np.array(axs['Mg_sigma'].get_xlim()) axs['Mg_sigma'].plot(lims, np.poly1d(params)(lims), 'r') grad = params[0] e_grad = np.sqrt(np.diag(cov))[0] else: grad = np.nan e_grad = np.nan axs['Mg_sigma'].set_xlabel(r'log $\sigma$ [km s$^{-1}$]') axs['Mg_sigma'].set_ylabel(r'Mg$_b \, \AA$') if galaxy not in ['pks0718-34', 'ngc0612']: axs['Mg_sigma'].set_ylim([0.9*min(mg), 1.1*max(mg)]) axs['Mg_sigma'].set_xlim(np.log10(200), np.log10(350)) figs['Mg_sigma'].savefig('%s/Mg_sigma.png' % (out_plots)) plt.close(figs['Mg_sigma']) grad_file = '%s/galaxies_resolved_mg_sigma.txt' % (out_dir) galaxy_gals, grad_gals, e_grad_gals = np.loadtxt(grad_file, unpack=True, dtype=str) i_gal = np.where(galaxy_gals == galaxy)[0][0] grad_gals[i_gal] = str(round(grad, 3)) e_grad_gals[i_gal] = str(round(e_grad, 3)) with open(grad_file, 'w') as f: temp = "{0:12}{1:15}{2:15}\n" for i in range(len(galaxy_gals)): f.write(temp.format(galaxy_gals[i], grad_gals[i], e_grad_gals[i])) return D
def whole_image(galaxy, verbose=True, instrument='vimos'): print galaxy data_file = "%s/Data/vimos/analysis/galaxies.txt" % (cc.base_dir) galaxy_gals = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=(0,), dtype=str) i_gal = np.where(galaxy_gals==galaxy)[0][0] if instrument=='vimos': from errors2 import run_ppxf, apply_range, set_params, get_dataCubeDirectory res = 0.67 # arcsec/pix z_gals, x_gals, y_gals = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=(1, 4, 5), dtype='float,int,int') i_gal2 = i_gal fits_ext = 0 elif instrument == 'muse': from errors2_muse import run_ppxf, apply_range, set_params, \ get_dataCubeDirectory res = 0.2 # arcsec/pix z_gals = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=(1,)) data_file2 = "%s/Data/muse/analysis/galaxies.txt" % (cc.base_dir) x_gals, y_gals = np.loadtxt(data_file2, unpack=True, skiprows=1, usecols=(1,2), dtype=int) galaxy_gals = np.loadtxt(data_file2, unpack=True, skiprows=1, usecols=(0,), dtype=str) i_gal2 = np.where(galaxy_gals==galaxy)[0][0] fits_ext = 1 z = z_gals[i_gal] D = z*c/H0 # Mpc centre = (x_gals[i_gal2], y_gals[i_gal2]) limits_file = '%s/Data/%s/analysis/galaxies_gasMass.txt' %(cc.base_dir, instrument) galaxy_gals, mass, e_mass = np.loadtxt(limits_file, unpack=True, dtype=str, skiprows=1, usecols=(0,1,2)) i_gal = np.where(galaxy_gals==galaxy)[0][0] if instrument == 'muse': bd, e_bd = np.loadtxt(limits_file, unpack=True, dtype=str, skiprows=1, usecols=(3,4)) if 'ic' in galaxy: f = fits.open(get_dataCubeDirectory(galaxy)) elif 'ngc' in galaxy: f = fits.open(get_dataCubeDirectory(galaxy)[:-5]+'2.fits') f[fits_ext].header['CDELT3'] = f[fits_ext].header['CD3_3'] elif instrument == 'vimos': f = fits.open(get_dataCubeDirectory(galaxy)) R_e = get_R_e(galaxy)/res mask = in_aperture(centre[0], centre[1], R_e/2, instrument=instrument) spec = f[fits_ext].data noise = f[fits_ext+1].data spec[np.isnan(spec)] = 0 noise[np.isnan(noise)] = 0 spec = np.einsum('ijk,jk->i', spec, mask) noise = np.sqrt(np.einsum('ijk,jk->i', noise**2, mask)) if galaxy == 'ngc1316': params = set_params(opt='pop', reps=4, temp_mismatch=True, produce_plot=False, gas=1, set_range_star=np.array([2000, 5800])) else: params = set_params(opt='pop', reps=4, temp_mismatch=True, produce_plot=False, gas=1) lam = (np.arange(len(spec)) - (f[fits_ext].header['CRPIX3'] - 1)) * \ f[fits_ext].header['CDELT3'] + f[fits_ext].header['CRVAL3'] spec, lam, cut = apply_range(spec, lam=lam, return_cuts=True, set_range=params.set_range) lamRange = np.array([lam[0],lam[-1]]) noise = noise[cut] if instrument == 'vimos': pp = run_ppxf(galaxy, spec, noise, lamRange, f[fits_ext].header['CDELT3'], params) elif instrument=='muse': pp = run_ppxf(galaxy, spec, noise, f[fits_ext].header['CDELT3'], f[fits_ext].header['CRVAL3'], params) residuals = pp.galaxy - pp.bestfit _, residuals, _ = moving_weighted_average(pp.lam, residuals, step_size=3., interp=True) residuals[np.isnan(residuals)] = 0 noise = np.sqrt(residuals**2 + pp.noise**2) # noise = np.array(residuals) OIII_spec = pp.matrix[:, pp.templatesToUse=='[OIII]5007d'].flatten()*\ pp.weights[pp.templatesToUse=='[OIII]5007d'] # These results for Hb are used later, even for MUSE Hb_spec = pp.matrix[:, pp.templatesToUse=='Hbeta'].flatten() * \ pp.weights[pp.templatesToUse=='Hbeta'] Hb_flux = np.trapz(Hb_spec, x=pp.lam) ANR = max(Hb_spec)/np.median( noise[(pp.lam < 4861./(1 + (pp.sol[1][0] - 300)/c)) * (pp.lam > 4861. /(1 + (pp.sol[1][0] + 300)/c))]) Hb_spec_uncert = pp.MCgas_uncert_spec[ pp.templatesToUse[pp.component!=0]=='Hbeta', :].flatten() Hb_spec_norm = Hb_spec/np.max(Hb_spec) Hb_spec_uncert = np.sqrt(Hb_spec_uncert**2 + (noise*Hb_spec_norm)**2) Hb_spec_uncert_plus = Hb_spec + Hb_spec_uncert Hb_spec_uncert_minus = Hb_spec - Hb_spec_uncert Hb_flux_uncert_plus = np.trapz(Hb_spec_uncert_plus, x=pp.lam) Hb_flux_uncert_minus = np.trapz(Hb_spec_uncert_minus, x=pp.lam) Hb_flux_uncert = np.mean([abs(Hb_flux_uncert_plus - Hb_flux), abs(Hb_flux - Hb_flux_uncert_minus)]) if instrument == 'vimos': Ha_flux = 2.86 * Hb_flux Ha_flux_uncert = 2.86 * Hb_flux_uncert Ha_flux_uncert_plus = 2.86 * Hb_flux_uncert_plus Ha_flux_uncert_minus = 2.86 * Hb_flux_uncert_minus elif instrument == 'muse': Ha_spec = pp.matrix[:, pp.templatesToUse=='Halpha'].flatten() * \ pp.weights[pp.templatesToUse=='Halpha'] Ha_flux = np.trapz(Ha_spec, x=pp.lam) Ha_spec_uncert = pp.MCgas_uncert_spec[ pp.templatesToUse[pp.component!=0]=='Halpha', :].flatten() Ha_spec_norm = Ha_spec/np.max(Ha_spec) Ha_spec_uncert = np.sqrt(Ha_spec_uncert**2 + (noise*Ha_spec_norm)**2) # Ha_flux_uncert = trapz_uncert(Ha_spec_uncert, x=pp.lam) Ha_spec_uncert_plus = Ha_spec + Ha_spec_uncert Ha_spec_uncert_minus = Ha_spec - Ha_spec_uncert Ha_flux_uncert_plus = np.trapz(Ha_spec_uncert_plus, x=pp.lam) Ha_flux_uncert_minus = np.trapz(Ha_spec_uncert_minus, x=pp.lam) Ha_flux_uncert = np.mean([abs(Ha_flux_uncert_plus - Ha_flux), abs(Ha_flux - Ha_flux_uncert_minus)]) Hb_ANR = np.array(ANR) ANR = max(Ha_spec)/np.median( noise[(pp.lam < 6563./(1 + (pp.sol[1][0] - 300)/c)) * (pp.lam > 6563. /(1 + (pp.sol[1][0] + 300)/c))]) Mass = get_Mass(Ha_flux, D, instrument=instrument) e_Mass = get_Mass(Ha_flux_uncert, D, instrument=instrument) OIII_ANR = max(OIII_spec)/np.median(noise[ (pp.lam < 5007./(1 + (pp.sol[1][0] - 300)/c)) * (pp.lam > 5007./(1 + (pp.sol[1][0] + 300)/c))]) if OIII_ANR > 4 and ANR > 2.5: mass[i_gal] = str(round(np.log10(Mass),4)) e_mass[i_gal] = str(round(np.abs(e_Mass/Mass/ np.log(10)), 4)) if verbose: print '%s +/- %s log10(Solar Masses)' % ( mass[i_gal], e_mass[i_gal]) import matplotlib.pyplot as plt fig, ax = plt.subplots(2) from ppxf import create_plot plot = create_plot(pp) plot.ax = ax[0] plot.produce ax[0].set_xlim([4840, 4880]) ax[0].ax2.set_ylim([0,500000]) ax[0].ax2.plot(pp.lam, residuals, 'k') ax[0].legend() plot.ax = ax[1] plt.show() if 'home' in cc.device else fig.savefig('whole_image2.png') else: if instrument == 'vimos': Hb_spec_norm = gaussian(pp.lam, mean=4861., sigma=pp.sol[0][1]) Hb_spec2 = Hb_spec_norm \ * np.median(noise[(pp.lam < 4861./(1 + (pp.sol[1][0] - 300)/c)) * (pp.lam > 4861./(1 + (pp.sol[1][0] + 300)/c))]) * 2.5 Hb_flux2 = np.trapz(Hb_spec2, x=pp.lam) Hb_spec_uncert2 = np.abs(noise*Hb_spec_norm) Hb_spec_uncert_plus2 = Hb_spec2 + Hb_spec_uncert2 Hb_spec_uncert_minus2 = Hb_spec2 - Hb_spec_uncert2 Hb_flux_uncert_plus2 = np.trapz(Hb_spec_uncert_plus2, x=pp.lam) Hb_flux_uncert_minus2 = np.trapz(Hb_spec_uncert_minus2, x=pp.lam) Hb_flux_uncert2 = np.mean([abs(Hb_flux_uncert_plus2 - Hb_flux2), abs(Hb_flux2 - Hb_flux_uncert_minus2)]) Ha_flux2 = 2.86 * Hb_flux2 Ha_flux_uncert2 = 2.86 * Hb_flux_uncert2 elif instrument == 'muse': Ha_spec_norm = gaussian(pp.lam, mean=6563., sigma=pp.sol[0][1]) Ha_spec2 = Ha_spec_norm \ * np.median(noise[(pp.lam < 6563./(1 + (pp.sol[1][0] - 300)/c)) * (pp.lam > 6563./(1 + (pp.sol[1][0] + 300)/c))]) * 2.5 Ha_flux2 = np.trapz(Ha_spec2, x=pp.lam) Ha_spec_uncert2 = np.abs(noise*Ha_spec_norm) Ha_spec_uncert_plus2 = Ha_spec2 + Ha_spec_uncert2 Ha_spec_uncert_minus2 = Ha_spec2 - Ha_spec_uncert2 Ha_flux_uncert_plus2 = np.trapz(Ha_spec_uncert_plus2, x=pp.lam) Ha_flux_uncert_minus2 = np.trapz(Ha_spec_uncert_minus2, x=pp.lam) Ha_flux_uncert2 = np.mean([abs(Ha_flux_uncert_plus2 - Ha_flux2), abs(Ha_flux2 - Ha_flux_uncert_minus2)]) Mass2 = get_Mass(Ha_flux2, D, instrument=instrument) e_Mass2 = get_Mass(Ha_flux_uncert2, D, instrument=instrument) mass[i_gal] = '<'+str(round(np.log10(Mass2),4)) e_mass[i_gal] = str(round(np.abs(e_Mass2/Mass2/ np.log(10)), 4)) if verbose: print '<%s +/- %s log10(Solar Masses)' % ( mass[i_gal], e_mass[i_gal]) import matplotlib.pyplot as plt fig, ax = plt.subplots(2) from ppxf import create_plot plot = create_plot(pp) plot.ax = ax[0] plot.produce ax[0].set_xlim([4800, 4900]) ax[0].ax2.plot(pp.lam, residuals, 'k') ax[0].legend() plot.ax = ax[1] plot.produce plt.show() if 'home' in cc.device else fig.savefig('whole_image2.png') if instrument == 'muse': if OIII_ANR > 4 and ANR > 2.5 and Hb_ANR > 2.5: bd[i_gal] = str(round(Ha_flux/Hb_flux, 4)) e_bd[i_gal] = str(round(Ha_flux/Hb_flux * np.sqrt( (Ha_flux_uncert/Ha_flux)**2 + (Hb_flux_uncert/Hb_flux)**2), 4)) elif OIII_ANR > 4 and ANR > 2.5: Hb_spec_norm = gaussian(pp.lam, mean=4861., sigma=pp.sol[0][1]) Hb_spec2 = Hb_spec_norm \ * np.median(noise[(pp.lam < 4861./(1 + (pp.sol[1][0] - 300)/c)) * (pp.lam > 4861./(1 + (pp.sol[1][0] + 300)/c))]) * 2.5 Hb_flux2 = np.trapz(Hb_spec2, x=pp.lam) Hb_spec_uncert2 = np.abs(noise*Hb_spec_norm) Hb_spec_uncert_plus2 = Hb_spec2 + Hb_spec_uncert2 Hb_spec_uncert_minus2 = Hb_spec2 - Hb_spec_uncert2 Hb_flux_uncert_plus2 = np.trapz(Hb_spec_uncert_plus2, x=pp.lam) Hb_flux_uncert_minus2 = np.trapz(Hb_spec_uncert_minus2, x=pp.lam) Hb_flux_uncert2 = np.mean([abs(Hb_flux_uncert_plus2 - Hb_flux2), abs(Hb_flux2 - Hb_flux_uncert_minus2)]) bd[i_gal] = '>' + str(round(Ha_flux/Hb_flux2, 4)) e_bd[i_gal] = str(round(Ha_flux/Hb_flux2 * np.sqrt( (Ha_flux_uncert/Ha_flux)**2 + (Hb_flux_uncert2/Hb_flux2)**2), 4)) else: #H-beta Hb_spec_norm = gaussian(pp.lam, mean=4861., sigma=pp.sol[0][1]) Hb_spec2 = Hb_spec_norm \ * np.median(noise[(pp.lam < 4861./(1 + (pp.sol[1][0] - 300)/c)) * (pp.lam > 4861./(1 + (pp.sol[1][0] + 300)/c))]) * 2.5 Hb_flux2 = np.trapz(Hb_spec2, x=pp.lam) Hb_spec_uncert2 = np.abs(noise*Hb_spec_norm) Hb_spec_uncert_plus2 = Hb_spec2 + Hb_spec_uncert2 Hb_spec_uncert_minus2 = Hb_spec2 - Hb_spec_uncert2 Hb_flux_uncert_plus2 = np.trapz(Hb_spec_uncert_plus2, x=pp.lam) Hb_flux_uncert_minus2 = np.trapz(Hb_spec_uncert_minus2, x=pp.lam) Hb_flux_uncert2 = np.mean([abs(Hb_flux_uncert_plus2 - Hb_flux2), abs(Hb_flux2 - Hb_flux_uncert_minus2)]) # H-alpha Ha_spec_norm = gaussian(pp.lam, mean=6563., sigma=pp.sol[0][1]) Ha_spec2 = Ha_spec_norm \ * np.median(noise[(pp.lam < 6563./(1 + (pp.sol[1][0] - 300)/c)) * (pp.lam > 6563./(1 + (pp.sol[1][0] + 300)/c))]) * 2.5 Ha_flux2 = np.trapz(Ha_spec2, x=pp.lam) Ha_spec_uncert2 = np.abs(noise*Ha_spec_norm) Ha_spec_uncert_plus2 = Ha_spec2 + Ha_spec_uncert2 Ha_spec_uncert_minus2 = Ha_spec2 - Ha_spec_uncert2 Ha_flux_uncert_plus2 = np.trapz(Ha_spec_uncert_plus2, x=pp.lam) Ha_flux_uncert_minus2 = np.trapz(Ha_spec_uncert_minus2, x=pp.lam) Ha_flux_uncert2 = np.mean([abs(Ha_flux_uncert_plus2 - Ha_flux2), abs(Ha_flux2 - Ha_flux_uncert_minus2)]) bd[i_gal] = '<' + str(round(Ha_flux2/Hb_flux2, 4)) e_bd[i_gal] = str(round(Ha_flux2/Hb_flux2 * np.sqrt( (Ha_flux_uncert2/Ha_flux2)**2 + (Hb_flux_uncert2/Hb_flux2)**2), 4)) if instrument == 'vimos': temp = "{0:12}{1:10}{2:10}\n" with open(limits_file, 'w') as l: l.write(temp.format('Galaxy', 'Mass', 'e_Mass')) for i in range(len(galaxy_gals)): l.write(temp.format(galaxy_gals[i], mass[i], e_mass[i])) elif instrument =='muse': temp = "{0:12}{1:10}{2:10}{3:10}{4:10}\n" with open(limits_file, 'w') as l: l.write(temp.format('Galaxy', 'Mass', 'e_Mass', 'Bul_dec', 'e_Bul_dec')) for i in range(len(galaxy_gals)): l.write(temp.format(galaxy_gals[i], mass[i], e_mass[i], bd[i], e_bd[i]))
def plot_stellar_pop(galaxy, method='median', D=None, opt='pop', overplot={}, gradient=True): print 'Plotting stellar population' if cc.device == 'glamdring': vin_dir = '%s/analysis/%s/%s/pop' % ( cc.base_dir, galaxy, opt) else: vin_dir = '%s/Data/vimos/analysis/%s/%s/pop' % (cc.base_dir, galaxy, opt) # Load pickle file from pickler.py out_dir = '%s/Data/vimos/analysis' % (cc.base_dir) output = "%s/%s/%s" % (out_dir, galaxy, opt) out_plots = "%s/plots/population" % (output) if not os.path.exists(out_plots): os.makedirs(out_plots) if D is None and gradient !='only': pickle_file = '%s/pickled' % (output) pickleFile = open("%s/dataObj.pkl" % (pickle_file), 'rb') D = pickle.load(pickleFile) pickleFile.close() f = fits.open(get_dataCubeDirectory(galaxy)) header = f[0].header if not gradient: f.close() data_file = "%s/galaxies.txt" % (out_dir) file_headings = np.loadtxt(data_file, dtype=str)[0] col = np.where(file_headings=='SN_%s' % (opt))[0][0] z_gals, x_cent_gals, y_cent_gals, SN_target_gals = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=(1,4,5,col), dtype='float,int,int,float') galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0,),dtype=str) i_gal = np.where(galaxy_gals==galaxy)[0][0] z = z_gals[i_gal] SN_target=SN_target_gals[i_gal] center = (x_cent_gals[i_gal], y_cent_gals[i_gal]) if gradient != 'only': age = np.zeros(D.number_of_bins) met = np.zeros(D.number_of_bins) alp = np.zeros(D.number_of_bins) unc_age = np.zeros(D.number_of_bins) unc_met = np.zeros(D.number_of_bins) unc_alp = np.zeros(D.number_of_bins) if method == 'median': for i in xrange(D.number_of_bins): ag, me, al = np.loadtxt('%s/%i.dat' % (vin_dir, i), unpack=True) age[i] = ag[0] unc_age[i] = ag[1] met[i] = me[0] unc_met[i] = me[1] alp[i] = al[0] unc_alp[i] = al[1] title = '%s median and standard deviation' %(galaxy.upper()) elif method == 'mostlikely': for i in xrange(D.number_of_bins): ag, me, al = np.loadtxt('%s/distribution/%i.dat' % ( vin_dir, i), unpack=True) for plot, unc_plot, pop in zip([age,met,alp], [unc_age,unc_met,unc_alp], [ag,me,al]): hist = np.histogram(pop, bins=40) x = (hist[1][0:-1]+hist[1][1:])/2 hist = hist[0] plot[i] = x[np.argmax(hist)] gt_fwhm = hist >= np.max(hist)/2 unc_plot[i] = np.max(x[gt_fwhm]) - np.min(x[gt_fwhm]) title = 'Mostlikely' u_title = 'FWHM' if gradient: figs = {} axs = {} rad = {} rad_err = {} for i in ['age', 'met', 'alp']: fig, ax = plt.subplots() figs[i] = fig axs[i] = ax rad[i] = [] rad_err[i] = [] if gradient != 'only': # Age ax = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, age, header, nodots=True, colorbar=True, label='Age (Gyrs)', vmin=0, vmax=15, title=title + ' Age', cmap='gnuplot2', flux_unbinned=D.unbinned_flux, signal_noise=D.SNRatio, signal_noise_target=SN_target, center=center, redshift=z) if overplot: for o, color in overplot.iteritems(): add_(o, color, ax, galaxy) plt.gcf().savefig('%s/Age.png' % (out_plots)) plt.close() plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, unc_age, header, nodots=True, colorbar=True, label='Age (Gyrs)', vmin=0, vmax=15, title=u_title+' Age', cmap='gnuplot2', flux_unbinned=D.unbinned_flux, signal_noise=D.SNRatio, close=True, signal_noise_target=SN_target, center=center, save='%s/Age_uncert.png'%(out_plots)) # Metalicity ax = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, met, header, nodots=True, colorbar=True, label='Metalicity [Z/H]', vmin=-2.25, vmax=0.67, title=title+' Metalicity', cmap='gnuplot2', flux_unbinned=D.unbinned_flux, signal_noise=D.SNRatio, signal_noise_target=SN_target, center=center) if overplot: for o, color in overplot.iteritems(): add_(o, color, ax, galaxy) plt.gcf().savefig('%s/Metalicity.png' % (out_plots)) plt.close() plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, unc_met, header, nodots=True, colorbar=True, label='Metalicity', vmin=0, vmax=0.67+2.25, title=u_title+' Metalicity [Z/H]', cmap='gnuplot2', flux_unbinned=D.unbinned_flux, signal_noise=D.SNRatio, signal_noise_target=SN_target, center=center, save='%s/Metalicity_uncert.png'%(out_plots), close=True) # Alpha ax = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, alp, header, nodots=True, colorbar=True, label='Element Ratio [alpha/Fe]', vmin=-0.3, vmax=0.5, title=title+' Alpha Enhancement', cmap='gnuplot2', flux_unbinned=D.unbinned_flux, signal_noise=D.SNRatio, signal_noise_target=SN_target, center=center) if overplot: for o, color in overplot.iteritems(): add_(o, color, ax, galaxy) plt.gcf().savefig('%s/Alpha.png' % (out_plots)) plt.close() plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, unc_alp, header, nodots=True, colorbar=True, label='Element Ratio [alpha/Fe]', vmin=0, vmax=0.5+0.3, title=u_title+' Alpha Enhancement', cmap='gnuplot2', flux_unbinned=D.unbinned_flux, signal_noise=D.SNRatio, signal_noise_target=SN_target, center=center, save='%s/Alpha_uncert.png'%(out_plots), close=True) # Moved to produce_pop_plot.py # -----------============ Thesis plots ==========--------------- # thesis_out = '%s/Documents/thesis/chapter4/vimos'%(cc.home_dir) # ax = plot_velfield_nointerp(D.x, D.y, D.bin_num, # D.xBar, D.yBar, age, header, # vmin=0, vmax=15, # cmap='gnuplot2', flux_unbinned=D.unbinned_flux, # signal_noise=D.SNRatio, signal_noise_target=SN_target, # center=center) # if overplot: # for o, color in overplot.iteritems(): # add_(o, color, ax, galaxy) # plt.gcf().savefig('%s/%s_age.png' % (thesis_out, galaxy)) # plt.close() # plot_velfield_nointerp(D.x, D.y, D.bin_num, # D.xBar, D.yBar, unc_age, header, vmin=0, vmax=15, # cmap='gnuplot2', flux_unbinned=D.unbinned_flux, # signal_noise=D.SNRatio, close=True, # signal_noise_target=SN_target, center=center, # save='%s/%s_age_uncert.png'%(thesis_out, galaxy)) # # Metalicity # ax = plot_velfield_nointerp(D.x, D.y, D.bin_num, # D.xBar, D.yBar, met, header, vmin=-2.25, vmax=0.67, # cmap='gnuplot2', # flux_unbinned=D.unbinned_flux, signal_noise=D.SNRatio, # signal_noise_target=SN_target, center=center) # if overplot: # for o, color in overplot.iteritems(): # add_(o, color, ax, galaxy) # plt.gcf().savefig('%s/%s_metallicity.png' % (thesis_out, galaxy)) # plt.close() # plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, # unc_met, header, vmin=0, vmax=0.67+2.25, cmap='gnuplot2', # flux_unbinned=D.unbinned_flux, signal_noise=D.SNRatio, # signal_noise_target=SN_target, center=center, close=True, # save='%s/%s_metallicity_uncert.png' % (thesis_out, galaxy)) # # Alpha # ax = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, # alp, header, vmin=-0.3, vmax=0.5, cmap='gnuplot2', # flux_unbinned=D.unbinned_flux, signal_noise=D.SNRatio, # signal_noise_target=SN_target, center=center) # if overplot: # for o, color in overplot.iteritems(): # add_(o, color, ax, galaxy) # plt.gcf().savefig('%s/%s_alpha.png' % (thesis_out, galaxy)) # plt.close() # plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, # unc_alp, header, vmin=0, vmax=0.5+0.3, cmap='gnuplot2', # flux_unbinned=D.unbinned_flux, signal_noise=D.SNRatio, # signal_noise_target=SN_target, center=center, close=True, # save='%s/%s_alpha_uncert.png'%(thesis_out, galaxy)) # ------=========== Detailed (no clip on color axis) =========--------- out_plots = "%s/plots/population_detail" % (output) if not os.path.exists(out_plots): os.makedirs(out_plots) # Age vmin, vmax = set_lims(age) ax = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, age, header, nodots=True, colorbar=True, label='Age (Gyrs)', title=title + ' Age', cmap='gnuplot2', vmin=vmin, vmax=vmax, flux_unbinned=D.unbinned_flux, signal_noise=D.SNRatio, signal_noise_target=SN_target, center=center, redshift=z) if overplot: for o, color in overplot.iteritems(): add_(o, color, ax, galaxy) plt.gcf().savefig('%s/Age.png' % (out_plots)) plt.close() vmin, vmax = set_lims(unc_age) plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, unc_age, header, nodots=True, colorbar=True, label='Age (Gyrs)', title=u_title+' Age', cmap='gnuplot2', vmin=vmin, vmax=vmax, flux_unbinned=D.unbinned_flux, signal_noise=D.SNRatio, close=True, signal_noise_target=SN_target, center=center, save='%s/Age_uncert.png'%(out_plots)) # Metalicity vmin, vmax = set_lims(met) ax = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, met, header, nodots=True, colorbar=True, label='Metalicity [Z/H]', title=title+' Metalicity', vmin=vmin, vmax=vmax, cmap='gnuplot2', flux_unbinned=D.unbinned_flux, signal_noise=D.SNRatio, signal_noise_target=SN_target, center=center) if overplot: for o, color in overplot.iteritems(): add_(o, color, ax, galaxy) plt.gcf().savefig('%s/Metalicity.png' % (out_plots)) plt.close() vmin, vmax = set_lims(unc_met) plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, unc_met, header, nodots=True, colorbar=True, label='Metalicity', vmin=vmin, vmax=vmax, title=u_title+' Metalicity [Z/H]', cmap='gnuplot2', flux_unbinned=D.unbinned_flux, signal_noise=D.SNRatio, signal_noise_target=SN_target, center=center, save='%s/Metalicity_uncert.png'%(out_plots),close=True) # Alpha vmin, vmax = set_lims(alp) ax = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, alp, header, nodots=True, colorbar=True, label='Element Ratio [alpha/Fe]', vmin=vmin, vmax=vmax, title=title+' Alpha Enhancement', cmap='gnuplot2', flux_unbinned=D.unbinned_flux, signal_noise=D.SNRatio, signal_noise_target=SN_target, center=center) if overplot: for o, color in overplot.iteritems(): add_(o, color, ax, galaxy) plt.gcf().savefig('%s/Alpha.png' % (out_plots)) plt.close() vmin, vmax = set_lims(unc_alp) plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, unc_alp, header, nodots=True, colorbar=True, label='Element Ratio [alpha/Fe]', title=u_title+' Alpha Enhancement', cmap='gnuplot2', vmin=vmin, vmax=vmax, flux_unbinned=D.unbinned_flux, signal_noise=D.SNRatio, signal_noise_target=SN_target, center=center, close=True, save='%s/Alpha_uncert.png'%(out_plots)) if gradient: r = np.sqrt((D.xBar - center[0])**2 + (D.yBar - center[1])**2) for i in ['age', 'met', 'alp']: if i=='age': y = np.log10(eval(i)) y_err = np.abs(eval('unc_'+i)/np.array(eval(i))/ np.log(10)) else: y = eval(i) y_err = eval('unc_'+i) axs[i].errorbar(r, y, yerr=y_err, fmt='.', c='k') params, cov = np.polyfit(r, y, 1, w=1/y_err, cov=True) axs[i].plot(r, np.poly1d(params)(r), '--k') # params, residuals, _, _, _ = numpy.polyfit(r, y, 1, w=1/y_err, # full=True) # chi2 = residuals / (len(r) - 2) figs[i].text(0.15, 0.84, r'grad: %.3f $\pm$ %.3f'%(params[0], np.sqrt(np.diag(cov))[0])) if gradient: out_plots = "%s/plots/population" % (output) index = np.zeros((40,40,2)) for i in range(40): for j in range(40): index[i,j,:] = np.array([i,j]) - center step_size = 4 annuli = np.arange(step_size, 26, step_size).astype(float) age_rad = np.zeros(len(annuli)) met_rad = np.zeros(len(annuli)) alp_rad = np.zeros(len(annuli)) age_err_rad = np.zeros(len(annuli)) met_err_rad = np.zeros(len(annuli)) alp_err_rad = np.zeros(len(annuli)) for i, a in enumerate(annuli): params = set_params(reps=0, opt='pop', gas=1, produce_plot=False) mask = (np.sqrt(index[:,:,0]**2 + index[:,:,1]**2) < a) * ( np.sqrt(index[:,:,0]**2 + index[:,:,1]**2) > a - step_size) spec = np.nansum(f[0].data[:,mask], axis=1) noise = np.sqrt(np.nansum(f[1].data[:,mask]**2, axis=1)) lam = np.arange(len(spec))*header['CDELT3'] + header['CRVAL3'] spec, lam, cut = apply_range(spec, lam=lam, set_range=params.set_range, return_cuts=True) lamRange = np.array([lam[0],lam[-1]]) noise = noise[cut] pp = run_ppxf(galaxy, spec, noise, lamRange, header['CDELT3'], params) pop = population(pp=pp, instrument='vimos', method=method) # pop.plot_probability_distribution() # plt.show() # axs['age'].errorbar(a, np.log10(pop.age), # yerr=np.abs(pop.unc_age/pop.age/np.log(10)), c='r', fmt='.') # axs['met'].errorbar(a, pop.metallicity, yerr=pop.unc_met, c='r', # fmt='.') # axs['alp'].errorbar(a, pop.alpha, yerr=pop.unc_alp, c='r', # fmt='.') for i in ['age', 'met', 'alp']: if i=='met': i2='metallicity' elif i=='alp': i2 = 'alpha' else: i2=i rad[i].append(getattr(pop, i2)) rad_err[i].append(getattr(pop, 'unc_'+i)) annuli *= header['CDELT1'] gradient_file = '%s/galaxies_pop_gradients.txt' % (out_dir) ageRe, ageG, e_ageG, metRe, metG, e_metG, alpRe, alpG, e_alpG = \ np.loadtxt(gradient_file, usecols=(1,2,3,4,5,6,7,8,9), unpack=True, skiprows=1) galaxy_gals = np.loadtxt(gradient_file, usecols=(0,), unpack=True, skiprows=1, dtype=str) i_gal = np.where(galaxy_gals == galaxy)[0][0] R_e = get_R_e(galaxy) for i in ['age', 'met', 'alp']: axs[i].set_xlabel('Radius (arcsec)') if i=='age': y = np.log10(rad[i]) y_err = np.abs(np.array(rad_err[i])/np.array(rad[i])/ np.log(10)) else: y = np.array(rad[i]) y_err = np.array(rad_err[i]) axs[i].errorbar(annuli, y, yerr=y_err, fmt='x', c='r') params, cov = np.polyfit(annuli, y, 1, w=1/y_err, cov=True) axs[i].plot(annuli, np.poly1d(params)(annuli), '-r') # params, residuals, _, _, _ = numpy.polyfit(annuli, y, 1, # w=1/y_err, full=True) # chi2 = residuals / (len(annuli) - 2) figs[i].text(0.15, 0.8, r'grad: %.3f $\pm$ %.3f'%(params[0], np.sqrt(np.diag(cov))[0]), color='r') if i =='age': axs[i].set_ylabel('log(Age (Gyr))') ageG[i_gal], e_ageG[i_gal] = params[0],np.sqrt(np.diag(cov))[0] ageRe[i_gal] = np.poly1d(params)(R_e) elif i == 'met': axs[i].set_ylabel('Metalicity [Z/H]') metG[i_gal], e_metG[i_gal] = params[0],np.sqrt(np.diag(cov))[0] metRe[i_gal] = np.poly1d(params)(R_e) elif i == 'alp': axs[i].set_ylabel('Alpha Enhancement [alpha/Fe]') alpG[i_gal], e_alpG[i_gal] = params[0],np.sqrt(np.diag(cov))[0] alpRe[i_gal] = np.poly1d(params)(R_e) figs[i].savefig('%s/%s_grad.png' % (out_plots, i)) plt.close(i) temp = "{0:12}{1:7}{2:7}{3:7}{4:7}{5:7}{6:7}{7:7}{8:7}{9:7}\n" with open(gradient_file, 'w') as f: f.write(temp.format('Galaxy', 'ageRe', 'ageG', 'e_ageG', 'metRe', 'metG', 'e_metG', 'alpRe', 'alpG', 'e_alpG')) for i in range(len(galaxy_gals)): f.write(temp.format(galaxy_gals[i], str(round(ageRe[i],1)), str(round(ageG[i],3)), str(round(e_ageG[i],3)), str(round(metRe[i],1)), str(round(metG[i],3)), str(round(e_metG[i],3)), str(round(alpRe[i],1)), str(round(alpG[i],3)), str(round(e_alpG[i],3)))) return D