def find_template(galaxy, set_range=None):
    params = set_params()
    params.gas = 0
    params.reps = 0
    params.set_range = set_range
    ## ----------========= Reading the spectrum  ===============---------

    dataCubeDirectory = get_dataCubeDirectory(galaxy)

    f = fits.open(dataCubeDirectory)

    ## write key parameters from header - can then be altered in future
    CRVAL_spec = f[1].header['CRVAL3']
    CDELT_spec = f[1].header['CD3_3']
    s = f[1].data.shape

    # Collapse to single spectrum
    gal_spec = np.zeros(s[0])
    gal_noise = np.zeros(s[0])

    for i in xrange(s[0]):
        gal_spec[i] = np.nansum(
            f[1].data[i,
                      int(s[1] / 2.0 - 50):int(s[1] / 2.0 + 50),
                      int(s[2] / 2.0 - 50):int(s[2] / 2.0 + 50)])
        gal_noise[i] = np.sqrt(
            np.nansum(f[2].data[i,
                                int(s[1] / 2.0 - 50):int(s[1] / 2.0 + 50),
                                int(s[2] / 2.0 - 50):int(s[2] / 2.0 + 50)]**2))

    del f

    ## ----------========= Calibrating the spectrum  ===========---------
    lam = np.arange(s[0]) * CDELT_spec + CRVAL_spec
    gal_spec, lam, cut = apply_range(gal_spec,
                                     window=201,
                                     repeats=0,
                                     lam=lam,
                                     return_cuts=True,
                                     set_range=params.set_range,
                                     n_sigma=2)
    lamRange = np.array([lam[0], lam[-1]])
    gal_noise = gal_noise[cut]

    pp = run_ppxf(galaxy,
                  gal_spec,
                  gal_noise,
                  lamRange,
                  CDELT_spec,
                  params,
                  use_all_temp=True)
    pp.fig.savefig('%s/Data/muse/analysis/%s/find_temp.png' %
                   (cc.base_dir, galaxy))

    with open('%s/Data/muse/analysis/%s/templates.txt' % (cc.base_dir, galaxy),
              'w') as f:
        for i in range(len(pp.component)):
            if pp.weights[i] != 0.0:
                f.write(str(i) + '   ' + str(pp.weights[i]) + '\n')
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)

    if cc.device == 'glamdring':
        dir = cc.base_dir
    else:
        dir = '%s/Data/muse' % (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=(1, 2))
    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[1].data
    header = f[1].header
    galaxy_noise = f[2].data

    ## write key parameters from header - can then be altered in future
    CRVAL_spec = header['CRVAL3']
    CDELT_spec = header['CD3_3']
    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='muse')
    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

## ----------============ Find dynamical mass ===============---------
    mg, mg_uncert = get_absorption(['Mg_b'], pp=pp, instrument='muse', res=8.4)

    return mg['Mg_b'], mg_uncert['Mg_b'], sigma_0, unc_sigma_0
def compare_absortion(galaxy, R_sig=False, corr_lines='all'):
	f = fits.open(get_dataCubeDirectory(galaxy))
	header = f[1].header

	lines = ['H_beta', 'Fe5015', 'Mg_b', 'Fe5270', 'Fe5335', 
		'Fe5406', 'Fe5709', 'Fe5782', 
		'NaD', 'TiO1', 'TiO2']
	color = ['purple',   'k',  'orange',   'g',       'b',      
		'c',  'lightblue',  'grey',
		 'r',  'gold', 'pink']



	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 = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=(1,), 
		dtype=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]

	data_file =  "%s/Data/muse/analysis/galaxies.txt" % (cc.base_dir)
	x_cent_gals, y_cent_gals = np.loadtxt(data_file, unpack=True, skiprows=1, 
		usecols=(1,2), dtype=int)
	galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0,),dtype=str)
	i_gal = np.where(galaxy_gals==galaxy)[0][0]
	center = np.array([x_cent_gals[i_gal], y_cent_gals[i_gal]])

	index = np.zeros((150,150,2))
	for i in range(150):
		for j in range(150):
			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([])
	t=[]
	e=[]
	g=[]
	h=[]
	j=[]
	r=[]
	w=[]
	for a in apertures:
		params = set_params(reps=0, opt='pop', gas=1, lines=corr_lines, 
			produce_plot=False)
		mask = np.sqrt(index[:,:,0]**2 + index[:,:,1]**2) * header['CD3_3'] < a

		spec = np.nansum(f[1].data[:,mask], axis=1)
		noise = np.sqrt(np.nansum(f[2].data[:,mask]**2, axis=1))

		lam = np.arange(len(spec))*header['CD3_3'] + 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['CD3_3'], 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)
			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')
			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)

		fig2.savefig('/Data/lit_absorption/Rampazzo/%s_rad_%.2f_muse.png'%(galaxy, a))
		plt.close(fig2)


		if R_sig:
			if isinstance(R_sig, bool):
				absorp, uncert = get_absorption(lines, pp=pp, instrument='muse', sigma=R_sigma(a))
				sigma = np.append(sigma, R_sigma(a))
			else:
				absorp, uncert = get_absorption(lines, pp=pp, instrument='muse', sigma=R_sigma(a)+R_sig*(pp.sol[0][1]-R_sigma(a)))
				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='muse')#, sigma=R_sigma(a))
			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')
	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/J_A+A_433_497_table9.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=5, 
			usecols=(col,col2))
		R_galaxies = np.loadtxt(Rampazzo_file, unpack=True, skiprows=5, usecols=(0,), 
			dtype=str)

		mask = R_galaxies==galaxy.upper()

		order = np.argsort(apertures)

		lit_value = Lick_to_LIS(l, R_obs[mask][order])
		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)


	ax.set_ylabel(r'Index strength, $\AA$')
	ax.set_xlabel('Radius, arcsec')
	fig.savefig('%s/Data/lit_absorption/Rampazzo_aperture_%s_%i_muse.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_muse.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_muse.png' % (
		cc.base_dir, galaxy))
	plt.close(fig4)


	return t, g, h, j, e, r, w
Exemplo n.º 4
0
def compare_absortion(galaxy, O_sig=False, corr_lines='all'):
    f = fits.open(get_dataCubeDirectory(galaxy))
    header = f[1].header

    # Load VIMOS values
    data_file = "%s/Data/vimos/analysis/galaxies.txt" % (cc.base_dir)
    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 == galaxy)[0][0]
    z = z_gals[i_gal]

    data_file = "%s/Data/muse/analysis/galaxies.txt" % (cc.base_dir)
    galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0, ), dtype=str)
    i_gal = np.where(galaxy_gals == galaxy)[0][0]
    x_cent_gals, y_cent_gals = np.loadtxt(data_file,
                                          unpack=True,
                                          skiprows=1,
                                          usecols=(1, 2),
                                          dtype=int)
    center = np.array([x_cent_gals[i_gal], y_cent_gals[i_gal]])

    data_file = "%s/Data/muse/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', 'Fe5270', 'Fe5335', 'Fe5406', 'Fe5709',
        'NaD'
    ]
    e_lines = [
        'e_H_beta', 'e_Fe5015', 'e_Mg_b', 'e_Fe5270', 'e_Fe5335', 'e_Fe5406',
        'e_Fe5709', 'e_NaD'
    ]

    # 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 / abs(header['CD1_1']) * 60**2,
                   2.5 / header['CD2_2'] * 60**2,
                   pa,
                   instrument='muse')

    ifu = np.array(f[1].data)
    ifu[np.isnan(ifu)] = 0
    spec = np.einsum('ijk,jk->i', ifu, mask)

    ifu = np.array(f[2].data)
    ifu[np.isnan(ifu)] = 0
    noise = np.sqrt(np.einsum('ijk,jk->i', ifu**2, mask))

    lam = np.arange(len(spec)) * header['CD3_3'] + 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['CD3_3'], params)

    if O_sig:
        if isinstance(O_sig, bool):
            absorp, uncert = get_absorption(lines,
                                            pp=pp,
                                            sigma=O_sigma(a),
                                            instrument='muse')
            sigma = O_sigma(a)
        else:
            absorp, uncert = get_absorption(lines,
                                            pp=pp,
                                            instrument='muse',
                                            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='muse')
        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 plot_stellar_pop(galaxy,
                     method='median',
                     opt='pop',
                     D=None,
                     overplot={},
                     gradient=True):
    print 'Plotting stellar population'

    if cc.device == 'glamdring':
        vin_dir = '%s/analysis_muse/%s/%s/pop' % (cc.base_dir, galaxy, opt)
        data_file = '%s/analysis_muse/galaxies.txt' % (cc.base_dir)
    else:
        vin_dir = '%s/Data/muse/analysis/%s/%s/pop' % (cc.base_dir, galaxy,
                                                       opt)
        data_file = "%s/Data/muse/analysis/galaxies.txt" % (cc.base_dir)

    file_headings = np.loadtxt(data_file, dtype=str)[0]
    col = np.where(file_headings == 'SN_%s' % (opt))[0][0]
    x_cent_gals, y_cent_gals, SN_target_gals = np.loadtxt(
        data_file,
        unpack=True,
        skiprows=1,
        usecols=(1, 2, col),
        dtype='int,int,float')
    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]
    center = (x_cent_gals[i_gal], y_cent_gals[i_gal])

    data_file = "%s/Data/vimos/analysis/galaxies.txt" % (cc.base_dir)
    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 == galaxy)[0][0]
    z = z_gals[i_gal]

    # Load pickle file from pickler.py
    out_dir = '%s/Data/muse/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[1].header
    if not gradient: f.close()

    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' % (galaxy.upper())
            u_title = '%s standard deviation' % (galaxy.upper())

        elif method == 'mostlikely':
            # from peakdetect import peakdetect

            age1 = np.zeros(D.number_of_bins)
            met1 = np.zeros(D.number_of_bins)
            alp1 = np.zeros(D.number_of_bins)

            age2 = np.zeros(D.number_of_bins)
            met2 = np.zeros(D.number_of_bins)
            alp2 = np.zeros(D.number_of_bins)
            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]
                    # peaks = np.array(peakdetect(hist, x_axis=x, lookahead=4)[0])
                    # plot[i] = peaks[np.argmax(peaks[:,1]), 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 = '%s mostlikely' % (galaxy.upper())
            u_title = '%s FWHM' % (galaxy.upper())

    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)

        # 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,
                               save='%s/Alpha_uncert.png' % (out_plots),
                               close=True)

        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((150, 150, 2))
        for i in range(index.shape[0]):
            for j in range(index.shape[1]):
                index[i, j, :] = np.array([i, j]) - center

        step_size = 12
        annuli = np.arange(step_size, 100, 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[1].data[:, mask], axis=1)
            noise = np.sqrt(np.nansum(f[2].data[:, mask]**2, axis=1))

            lam = np.arange(len(spec)) * header['CD3_3'] + 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['CD3_3'],
                          params)

            pop = population(pp=pp, instrument='muse', method=method)

            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 *= abs(header['CD1_1']) * (60**2)

        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
Exemplo n.º 6
0
def KDC_pop(galaxy):
    params = set_params(opt='pop')
    params.reps = 10

    spec, noise, lam = get_specFromAperture(galaxy, app_size=1.0)
    CD = lam[1] - lam[0]
    spec, lam, cut = apply_range(spec,
                                 window=201,
                                 repeats=3,
                                 lam=lam,
                                 return_cuts=True,
                                 set_range=params.set_range,
                                 n_sigma=2)
    noise = noise[cut]
    lamRange = np.array([lam[0], lam[-1]])

    pp = run_ppxf(galaxy,
                  spec,
                  noise,
                  lamRange,
                  CD,
                  params,
                  produce_plot=False)

    pop = population(pp=pp, galaxy=galaxy)
    pop.plot_probability_distribution(label=' of core region')

    data_file = "%s/Data/muse/analysis/galaxies_core.txt" % (cc.base_dir)
    age_gals, age_unc_gals, met_gals, met_unc_gals, alp_gals, alp_unc_gals, \
     OIII_eqw_gals, OIII_eqw_uncer_gals, \
     age_gals_outer, age_unc_gals_outer, met_gals_outer, met_unc_gals_outer, \
     alp_gals_outer, alp_unc_gals_outer = np.loadtxt(data_file, unpack=True,
     skiprows=2, usecols=(1,2,3,4,5,6,7,8,9,10,11,12,13,14))
    galaxy_gals = np.loadtxt(data_file, skiprows=2, usecols=(0, ), dtype=str)
    i_gal = np.where(galaxy_gals == galaxy)[0][0]

    age_gals[i_gal] = pop.age
    age_unc_gals[i_gal] = pop.unc_age
    met_gals[i_gal] = pop.metallicity
    met_unc_gals[i_gal] = pop.unc_met
    alp_gals[i_gal] = pop.alpha
    alp_unc_gals[i_gal] = pop.unc_alp

    # Save plot from pop before clearing from memory
    f = pop.fig
    ax = pop.ax
    OIII_pos = np.argmin(np.abs(pp.lam - 5007))
    peak_width = 20
    OIII_pos += np.argmax(pop.e_line_spec[OIII_pos - peak_width:OIII_pos +
                                          peak_width]) - peak_width
    flux = np.trapz(pop.e_line_spec[OIII_pos - peak_width:OIII_pos +
                                    peak_width],
                    x=pp.lam[OIII_pos - peak_width:OIII_pos + peak_width])

    OIII_eqw_gals[i_gal] = flux / pop.continuum[OIII_pos]

    i_OIII = np.where(
        '[OIII]5007d' in [e for e in pp.templatesToUse
                          if not e.isdigit()])[0][0]
    flux_uncert = trapz_uncert(
        pp.MCgas_uncert_spec[i_OIII,
                             OIII_pos - peak_width:OIII_pos + peak_width],
        x=pp.lam[OIII_pos - peak_width:OIII_pos + peak_width])
    cont_uncert = np.sqrt(
        np.sum((pp.noise**2 + pp.MCgas_uncert_spec**2)[i_OIII, OIII_pos]))

    OIII_eqw_uncer_gals[i_gal] = np.sqrt(
        OIII_eqw_gals[i_gal]**2 * ((flux_uncert / flux)**2 +
                                   (cont_uncert / pop.continuum[OIII_pos])**2))
    del pop

    # Outside apperture
    spec, noise, lam = get_specFromAperture(galaxy, app_size=1.0, inside=False)
    CD = lam[1] - lam[0]
    spec, lam, cut = apply_range(spec,
                                 window=201,
                                 repeats=3,
                                 lam=lam,
                                 return_cuts=True,
                                 set_range=params.set_range,
                                 n_sigma=2)
    noise = noise[cut]
    lamRange = np.array([lam[0], lam[-1]])

    pp_outside = run_ppxf(galaxy,
                          spec,
                          noise,
                          lamRange,
                          CD,
                          params,
                          produce_plot=False)
    pop_outside = population(pp=pp_outside, galaxy=galaxy)
    pop_outside.plot_probability_distribution(f=f,
                                              ax_array=ax,
                                              label=' of outer region')

    pop_outside.fig.suptitle(
        '%s Probability Distribution within inner 1 arcsec' % (galaxy.upper()),
        y=0.985)
    h, l = pop_outside.ax[0, 0].get_legend_handles_labels()
    pop_outside.ax[1, 1].legend(h, l, loc=1)
    pop_outside.fig.savefig('%s/Data/muse/analysis/%s/pop_1arcsec.png' %
                            (cc.base_dir, galaxy))

    age_gals_outer[i_gal] = pop_outside.age
    age_unc_gals_outer[i_gal] = pop_outside.unc_age
    met_gals_outer[i_gal] = pop_outside.metallicity
    met_unc_gals_outer[i_gal] = pop_outside.unc_met
    alp_gals_outer[i_gal] = pop_outside.alpha
    alp_unc_gals_outer[i_gal] = pop_outside.unc_alp
    del pop_outside

    temp = "{0:10}{1:6}{2:6}{3:6}{4:6}{5:6}{6:6}{7:9}{8:10}{9:6}{10:6}{11:6}{12:6}{13:6}{14:6}\n"
    with open(data_file, 'w') as f:
        f.write(
            '          Core (inner 1arcsec)                                   Outer \n'
        )
        f.write(
            temp.format('Galaxy', 'Age', 'error', 'Metal', 'error', 'Alpha',
                        'error', 'OIII_eqw', 'error', 'Age', 'error', 'Metal',
                        'error', 'Alpha', 'error'))
        for i in range(len(galaxy_gals)):
            f.write(
                temp.format(galaxy_gals[i], str(round(age_gals[i], 2)),
                            str(round(age_unc_gals[i], 2)),
                            str(round(met_gals[i], 2)),
                            str(round(met_unc_gals[i], 2)),
                            str(round(alp_gals[i], 2)),
                            str(round(alp_unc_gals[i], 2)),
                            str(round(OIII_eqw_gals[i], 4)),
                            str(round(OIII_eqw_uncer_gals[i], 4)),
                            str(round(age_gals_outer[i], 2)),
                            str(round(age_unc_gals_outer[i], 2)),
                            str(round(met_gals_outer[i], 2)),
                            str(round(met_unc_gals_outer[i], 2)),
                            str(round(alp_gals_outer[i], 2)),
                            str(round(alp_unc_gals_outer[i], 2))))
Exemplo n.º 7
0
def whole_image(galaxy, verbose=False):
    print galaxy
    max_reps = 100

    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)
    galaxy_gals, z_gals = np.loadtxt(data_file,
                                     unpack=True,
                                     skiprows=1,
                                     usecols=(0, 1),
                                     dtype=str)
    galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0, ), dtype=str)
    i_gal = np.where(galaxy_gals == galaxy)[0][0]
    z = float(z_gals[i_gal])
    D = z * c / H0  # Mpc

    data_file = "%s/Data/muse/analysis/galaxies.txt" % (cc.base_dir)
    x_gals, y_gals = np.loadtxt(data_file,
                                unpack=True,
                                skiprows=1,
                                usecols=(1, 2),
                                dtype=int)
    galaxy_gals = np.loadtxt(data_file,
                             unpack=True,
                             skiprows=1,
                             usecols=(0, ),
                             dtype=str)
    i_gal = np.where(galaxy_gals == galaxy)[0][0]
    centre = (x_gals[i_gal], y_gals[i_gal])

    limits_file = '%s/Data/muse/analysis/galaxies_gasMass.txt' % (cc.base_dir)
    galaxy_gals, mass, e_mass, bulmer, e_bulmer = np.loadtxt(limits_file,
                                                             unpack=True,
                                                             dtype=str,
                                                             skiprows=1)
    i_gal = np.where(galaxy_gals == galaxy)[0][0]

    max_radius = 90
    Mass_sav = 0
    radius = float(max_radius)
    if 'ic' in galaxy:
        f = fits.open(get_dataCubeDirectory(galaxy))
    elif 'ngc' in galaxy:
        f = fits.open(get_dataCubeDirectory(galaxy)[:-5] + '2.fits')
    while radius > 2:
        mask = in_aperture(centre[0], centre[1], radius, instrument='muse')

        spec = f[1].data
        noise = f[2].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)

        if radius == max_radius:
            reps = max_reps
            params = set_params(opt='pop',
                                reps=reps,
                                temp_mismatch=True,
                                produce_plot=False)


        lam = (np.arange(len(spec)) - (f[1].header['CRPIX3'] - 1)) * \
         f[1].header['CD3_3'] + f[1].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[1].header['CD3_3'],
                      params)

        # pp.ax.ax2.plot(pp.lam, pp.matrix[:,
        # 	pp.templatesToUse=='Hbeta'].flatten(), 'k')
        # pp.fig.savefig('%s.png'%(galaxy))

        # pp.noise = np.min([pp.noise, np.abs(pp.galaxy-pp.bestfit)],axis=0)

        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

        # print 'From Hbeta'
        # Mass = get_mass(Ha_flux, D, instrument='muse') # Solar masses
        # if max(OIII_spec)/np.median(pp.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(pp.noise[
        # 		(pp.lam < 4861./(1 + (pp.sol[1][0] - 300)/c)) *
        # 		(pp.lam > 4861./(1 + (pp.sol[1][0] + 300)/c))]) > 2.5:

        # 		print '    %.2f log10(Solar Masses)' % (np.log10(Mass))
        # 	else:
        # 		print '    <%.2f log10(Solar Masses)' % (np.log10(Mass))
        # else:
        # 	print '    <%.2f log10(Solar Masses)' % (np.log10(Mass))

        Ha_spec = pp.matrix[:, pp.templatesToUse=='Halpha'].flatten() * \
         pp.weights[pp.templatesToUse=='Halpha']
        Ha_flux = np.trapz(Ha_spec, x=pp.lam)

        Ha_spec2 = pp.matrix[:, pp.templatesToUse=='Halpha'].flatten() \
         / np.max(pp.matrix[:, pp.templatesToUse=='Halpha']) \
         * np.median(noise[(pp.lam < 6563./(1 + (pp.sol[1][0] - 300)/c))
         * (pp.lam > 6563./(1 + (pp.sol[1][0] + 300)/c))])
        Ha_flux2 = np.trapz(Ha_spec2, x=pp.lam)
        Mass2 = get_Mass(Ha_flux2, D, instrument='muse')

        if reps == max_reps:
            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_spec_uncert = pp.MCgas_uncert_spec[pp.templatesToUse[
                pp.component != 0] == 'Halpha', :].flatten()
            Ha_flux_uncert = trapz_uncert(Ha_spec_uncert, x=pp.lam)
        Mass = get_Mass(Ha_flux, D, instrument='muse')
        e_Mass = get_Mass(Ha_flux_uncert, D, instrument='muse')

        if max(OIII_spec) / np.median(pp.noise[
            (pp.lam < 5007. / (1 + (pp.sol[1][0] - 300) / c)) *
            (pp.lam > 5007. / (1 + (pp.sol[1][0] + 300) / c))]) > 4:

            if max(Ha_spec) / np.median(pp.noise[
                (pp.lam < 6563. / (1 + (pp.sol[1][0] - 300) / c)) *
                (pp.lam > 6563. / (1 + (pp.sol[1][0] + 300) / c))]) > 2.5:

                if reps == max_reps:
                    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])
                        # fig, ax = plt.subplots(2)
                        # pp.ax = ax[0]
                        # from ppxf import create_plot
                        # fig, ax = create_plot(pp).produce
                        # ax.set_xlim([4800, 4900])
                        # ax.legend()

                        # pp.ax = ax[1]
                        # from ppxf import create_plot
                        # fig, ax = create_plot(pp).produce
                        # ax.set_xlim([6500, 6600])

                        # fig.savefig('%s.png'%(galaxy))
                    radius = -1
                else:  # Repeat but calculate uncert
                    reps = max_reps

                if max(Hb_spec) / np.median(pp.noise[
                    (pp.lam < 4861. / (1 + (pp.sol[1][0] - 300) / c)) *
                    (pp.lam > 4861. / (1 + (pp.sol[1][0] + 300) / c))]) > 2.5:
                    b = Ha_flux / Hb_flux
                    e_bulmer[i_gal] = str(
                        round(
                            b * np.sqrt((Ha_flux_uncert / Ha_flux)**2 +
                                        (Hb_flux_uncert / Hb_flux)**2), 2))
                    bulmer[i_gal] = str(round(b, 2))
                else:
                    b = Ha_flux / Hb_flux
                    e_bulmer[i_gal] = str(
                        round(
                            b * np.sqrt((Ha_flux_uncert / Ha_flux)**2 +
                                        (Hb_flux_uncert / Hb_flux)**2), 2))
                    bulmer[i_gal] = '<' + str(round(b, 2))
            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))
                b = Ha_flux / Hb_flux
                e_bulmer[i_gal] = str(
                    round(
                        b * np.sqrt((Ha_flux_uncert / Ha_flux)**2 +
                                    (Hb_flux_uncert / Hb_flux)**2), 2))
                bulmer[i_gal] = '<' + str(round(b, 2))
                if verbose:
                    print '%s +/- %s log10(Solar Masses)' % (mass[i_gal],
                                                             e_mass[i_gal])
                radius -= 5
                reps = 0

        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))
            b = Ha_flux / Hb_flux
            e_bulmer[i_gal] = str(
                round(
                    b * np.sqrt((Ha_flux_uncert / Ha_flux)**2 +
                                (Hb_flux_uncert / Hb_flux)**2), 2))
            bulmer[i_gal] = '<' + str(round(b, 2))
            if verbose:
                print '%s +/- %s log10(Solar Masses)' % (mass[i_gal],
                                                         e_mass[i_gal])
        radius -= 5
        reps = 0

        params = set_params(opt='pop',
                            reps=reps,
                            temp_mismatch=True,
                            produce_plot=False)

    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], bulmer[i],
                            e_bulmer[i]))