Exemple #1
0
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 __init__(self, galaxy='ngc3557', slit_h=4.5, slit_w=2, slit_pa=30, 
		method='Rampazzo_aperture', r1=0, r2=None, debug=False):
		print galaxy
		if 'Rampazzo' in method:
			from Rampazzo import rampazzo
			# Default is nuclear region: 0<r<R_e/16
			if r2 is None:
				r2 = get_R_e(galaxy)/16
			data = rampazzo(galaxy, method='aperture', slit_h=slit_h, r1=r1, r2=r2, 
				debug=debug)

			if 'gradient' in method:
				if '2' in method: data.method = 'gradient2'
				else: data.method = 'gradient'

		elif method == 'Ogando':
			from Ogando import ogando
			data = ogando(galaxy, debug=debug, slit_h=slit_h, slit_w=slit_w, 
				slit_pa=slit_pa)

		elif method == 'Miles':
			from Miles import miles
			data = miles(galaxy)

		gal_spec, gal_noise = data.get_spec()

		gal_spec, lam, cut = apply_range(gal_spec, window=201, repeats=3, 
			lam=data.lam, set_range=np.array([4200,10000]), return_cuts=True)
		gal_noise = gal_noise[cut]
		lamRange = np.array([lam[0],lam[-1]])/(1+data.z)
## ----------================= Templates ====================---------
		FWHM_gal = 2.5 # VIMOS documentation (and fits header)
		FWHM_gal = FWHM_gal/(1+data.z) # Adjust resolution in Angstrom

		stellar_templates = get_stellar_templates(galaxy, FWHM_gal)
		velscale = stellar_templates.velscale

		e_templates = get_emission_templates(gas, lamRange, 
			stellar_templates.logLam_template, FWHM_gal)

		if gas:
			templates = np.column_stack((stellar_templates.templates, e_templates.templates))
		else:
			templates = stellar_templates.templates
		component = [0]*len(stellar_templates.templatesToUse) + e_templates.component
		templatesToUse = np.append(stellar_templates.templatesToUse, 
			e_templates.templatesToUse)
		element = ['stellar'] + e_templates.element

		start = [[data.vel, data.sig]] * (max(component) + 1)
		moments = [stellar_moments] + [gas_moments] * max(component)
## ----------============== Final calibrations ==============---------
		## smooth spectrum to fit with templates resolution
		if FWHM_gal < stellar_templates.FWHM_tem:
			sigma = stellar_templates.FWHM_dif/2.355/data.f[0].header['CDELT3']
			gal_spec = ndimage.gaussian_filter1d(gal_spec, sigma)
			gal_noise = np.sqrt(ndimage.gaussian_filter1d(gal_noise**2, sigma))
		
		## rebin spectrum logarthmically
		gal_spec_log, logLam_bin, _ = util.log_rebin(lamRange, gal_spec, velscale=velscale)
		gal_noise_log, logLam_bin, _ = util.log_rebin(lamRange, gal_noise**2, 
			velscale=velscale)
		gal_noise_log = np.sqrt(gal_noise_log)

		gal_noise_log = gal_noise_log + 0.0000000000001



		dv = (stellar_templates.logLam_template[0]-logLam_bin[0])*c # km/s
		# Find the pixels to ignore to avoid being distracted by gas emission
		#; lines or atmospheric absorbsion line.  
		goodPixels = determine_goodpixels(logLam_bin,stellar_templates.lamRange_template,
			data.vel, data.z, gas=gas!=0) 
		lambdaq = np.exp(logLam_bin)
## ----------=================== pPXF =======================---------
		pp = ppxf(templates, gal_spec_log, gal_noise_log, velscale, start, 
			goodpixels=goodPixels, moments=moments, degree=-1, vsyst=dv, 
			component=component, lam=lambdaq, plot=not quiet, quiet=quiet, mdegree=10)
		self.pp = pp

		# Only use stellar templates (Remove emission lines)
		stellar_spec = gal_spec_log - \
			pp.matrix[:, -e_templates.ntemp:].dot(pp.weights[-e_templates.ntemp:])
		conv_spec = pp.matrix[:, :-e_templates.ntemp].dot(pp.weights[:-e_templates.ntemp])

		# Generate the unconvolved spectra ('0 km/s' resolution)
		unc_lam = stellar_templates.wav
		unc_spec = stellar_templates.lin_templates.dot(pp.weights[:stellar_templates.ntemp])
		unc_spec *= np.polynomial.legendre.legval(np.linspace(-1,1,
			len(unc_spec)), np.append(1, pp.mpolyweights))
## ----------============== Absorption Line =================---------

		lines = ['G4300', 'Fe4383', 'Ca4455', 'Fe4531', 'H_beta', 'Fe5015', 'Mg_b']
		self.result = {}
		self.uncert = {}
		for line in lines:		
			ab, ab_uncert = absorption(line, lambdaq, stellar_spec, noise=gal_noise_log, 
				unc_lam=unc_lam, unc_spec=unc_spec,	conv_spec=conv_spec)#, 
				#lick=True)

			if method == 'Ogando':
				# Aperture correction
				ab_file = '%s/Documents/useful_files/ab_linelist.dat' % (cc.home_dir)
				i1, i2, b1, b2, r1, r2, units = np.genfromtxt(ab_file, unpack=True, 
					usecols=(1,2,3,4,5,6,7), skip_header=2, skip_footer=2)
				ls = np.genfromtxt(ab_file, unpack=True, dtype=str, usecols=(8), 
					skip_header=2, skip_footer=2)
				l = np.where(ls == line)[0][0]
				index = [i1[l], i2[l]]

				# Convert to mag
				ab = -2.5 * np.log(1 - ab/(index[1]-index[0]))

				# Aperture Correction: beta values taken from paper
				beta = {'H_beta':0.002, 'Fe5015':-0.012, 'Mg_b':-0.031} 
				# If line is not observed by Ogando
				if line not in beta.keys():
					self.result[line] = np.nan
					self.uncert[line] = np.nan
					continue
				H = 70.0 # value used by Bolonga group.
				r_ab = np.degrees(1.19/1000 * H/(c * data.z)) * 60 * 60 # 1.19 kpc -> arcsec
				# Correction is def in eq (9) with r_ab and r_norm def in eq (1) - not 
				#	100% sure if I've got them correct.
				ab = ab - beta[line] * np.log(1.025 * np.sqrt(slit_w*r_ab/np.pi)/slit_h)

				# Back to Angstroms
				ab = (index[1]-index[0]) * (1 - np.exp(ab/-2.5))

			elif 'Rampazzo' in method:
				self.r = data.r
			self.result[line] = ab
			self.uncert[line] = ab_uncert

		if debug:
			for line in lines:
				print '%s:	%.3f +/- %.3f' % (line, self.result[line], self.uncert[line])
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
Exemple #4
0
def sigma_e(i_gal=None):
	if i_gal is None: i_gal=int(sys.argv[1])
## ----------===============================================---------
## ----------============= Input parameters  ===============---------
## ----------===============================================---------
	params = set_params()
	params.reps = 3
	
	galaxies = ['ngc3557', 'ic1459', 'ic1531', 'ic4296', 'ngc0612', 'ngc1399', 
		'ngc3100', 'ngc7075', 'pks0718-34', 'eso443-g024']
	galaxy = galaxies[i_gal]

	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]

	R_e = get_R_e(galaxy)

## ----------===============================================---------
## ----------=============== Run analysis  =================---------
## ----------===============================================---------
## ----------========= Reading the spectrum  ===============---------

	dataCubeDirectory = "%s/cubes/%s.cube.combined.corr.fits" % (dir,galaxy)
		
	galaxy_data, header = fits.getdata(dataCubeDirectory, 0, header=True)
	# Normalise each spaxel for population pipeline
	galaxy_noise = fits.getdata(dataCubeDirectory, 1)
	galaxy_badpix = fits.getdata(dataCubeDirectory, 3)

	## write key parameters from header - can then be altered in future	
	CRVAL_spec = header['CRVAL3']
	CDELT_spec = header['CDELT3']
	R_e_pix = R_e/header['CDELT1']
	s = galaxy_data.shape

	rows_to_remove = range(params.discard)
	rows_to_remove.extend([s[1]-1-i for i in range(params.discard)])
	cols_to_remove = range(params.discard)
	cols_to_remove.extend([s[2]-1-i for i in range(params.discard)])

	galaxy_data = np.delete(galaxy_data, rows_to_remove, axis=1)
	galaxy_data = np.delete(galaxy_data, cols_to_remove, axis=2)
	galaxy_noise = np.delete(galaxy_noise, rows_to_remove, axis=1)
	galaxy_noise = np.delete(galaxy_noise, cols_to_remove, axis=2)
	galaxy_badpix = np.delete(galaxy_badpix, rows_to_remove, axis=1)
	galaxy_badpix = np.delete(galaxy_badpix, cols_to_remove, axis=2)

	s = galaxy_data.shape
## ----------========== Spatially Integrating =============---------
	frac_in_ap = in_aperture(x_cent_pix, y_cent_pix, R_e, np.arange(s[1]).repeat(s[2]), 
		np.tile(np.arange(s[2]),s[1])).fraction.reshape(s[1],s[2])
	galaxy_data = np.einsum('ijk,jk->ijk', galaxy_data, frac_in_ap)
	galaxy_noise = np.einsum('ijk,jk->ijk', galaxy_noise, frac_in_ap)
	bin_lin = np.nansum(galaxy_data,axis=(1,2))
	bin_lin_noise = np.nansum(galaxy_noise**2, axis=(1,2))
	bin_lin_noise = np.sqrt(bin_lin_noise)
## ----------========= 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_e  =================---------
	sigma_e = pp.sol[0][1]
	unc_sigma_r = np.std(pp.stellar_output[:,1])

	area = np.sum(frac_in_ap)*0.67**2 
	if area < 0.97 * np.pi * R_e**2:
		R = np.sqrt(area/np.pi)

		sigma_e = sigma_e * (R_e/R)**-0.066
		unc_sigma_e = np.sqrt(unc_sigma_r**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_e**2/G

## ----------============ Write ouputs to file =============---------
	data_file = "%s/analysis/galaxies_sigma_e.txt" % (dir)
	try:
		galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0,),dtype=str)
		sigma_e_gals, unc_sigma_e_gals, mass_gals = np.loadtxt(data_file, skiprows=1, 
			usecols=(1,2,3), unpack=True, dtype=float)

		if sigma_e_gals.shape == ():
			sigma_e_gals = np.array([sigma_e_gals])
			unc_sigma_e_gals = np.array([unc_sigma_e_gals])
			mass_gals = np.array([mass_gals])
			galaxy_gals = np.array([galaxy_gals])
	except IOError:
		galaxy_gals = np.array([galaxy])
		sigma_e_gals = np.array([sigma_e])
		mass_gals = np.array([M])
		unc_sigma_e_gals = np.array([unc_sigma_e])

	i_gal = np.where(galaxy_gals==galaxy)[0]

	if len(i_gal) == 0:
		galaxy_gals = np.append(galaxy_gals, galaxy)
		sigma_e_gals = np.append(sigma_e_gals, sigma_e)
		unc_sigma_e_gals = np.append(unc_sigma_e_gals, unc_sigma_e)
		mass_gals = np.append(mass_gals, M)
	else:
		sigma_e_gals[i_gal] = sigma_e
		unc_sigma_e_gals[i_gal] = unc_sigma_e
		mass_gals[i_gal] = M


	temp = "{0:12}{1:9}{2:15}{3:9}\n"
	with open(data_file, 'w') as f:
		f.write(temp.format("Galaxy", "sigma_e", "uncert sigma_e", "Dyn mass"))
		for i in range(len(galaxy_gals)):
			f.write(temp.format(galaxy_gals[i], str(round(sigma_e_gals[i],4)),
				str(round(unc_sigma_e_gals[i],4)), '{:0.2e}'.format(mass_gals[i])))
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
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
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 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]))
Exemple #9
0
def KDC_pop(galaxy):
	params = set_params(opt='pop', produce_plot=False, reps=10)


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

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

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

	data_file = "%s/Data/vimos/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

	del pop

	# Calculate OIII equivalent width
	e_lines = pp.component != 0
	e_line_spec =  pp.matrix[:,e_lines].T.astype(float)
	e_line_spec = np.einsum('ij,i->j',e_line_spec, pp.weights[e_lines])
	OIII_pos = np.argmin(np.abs(pp.lam - 5007)) # pix in spectrum at 5007A
	peak_width = 20 # Integrate over 2 * peak_width of pixels
	OIII_pos += np.argmax(e_line_spec[OIII_pos - peak_width:OIII_pos + peak_width]
		) - peak_width # find redshifted peak
	flux = np.trapz(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/((pp.galaxy - e_line_spec)[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/
		(pp.galaxy - e_line_spec)[OIII_pos])**2))
	

	# Outside apperture
	params = set_params(opt='pop', produce_plot=False, reps=10)

	spec, noise, lam = get_specFromAperture(galaxy, app_size=1.0, inside=False)
	CD = lam[1] - lam[0]
	spec, lam, cut = apply_range(spec, lam=lam, return_cuts=True, 
		set_range=params.set_range)
	noise = noise[cut]
	lamRange = np.array([lam[0],lam[-1]])

	

	pp_outside = run_ppxf(galaxy, spec, noise, lamRange, CD, params)
	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/vimos/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:13}{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))))
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 __init__(self,
                 galaxy_name,
                 bin_lin_in,
                 bin_lin_noise_in,
                 CDELT,
                 CRVAL,
                 params,
                 z=0.):

        if hasattr(CDELT, '__iter__'):
            raise ValueError(
                "The routine that has called run_ppxf has not been " +
                "updated since lamRange was removed as keyword. CRVAL is now "
                + "provided instead.")

        self.galaxy_name = galaxy_name
        self.CDELT = CDELT
        self.params = params

        ## ----------========= Calibrating the spectrum  ===========---------
        lam = np.arange(len(bin_lin_in)) * CDELT + CRVAL
        bin_lin, lam, cut = apply_range(bin_lin_in,
                                        lam=lam,
                                        return_cuts=True,
                                        set_range=params.set_range)
        lamRange = np.array([lam[0], lam[-1]])
        bin_lin_noise = bin_lin_noise_in[cut]

        self.bin_lin = bin_lin
        self.bin_lin_noise = bin_lin_noise
        self.lamRange = lamRange

        # if set_range_star is set
        if self.params.set_range[0] != self.params.set_range_star[0] or \
         self.params.set_range[1] != self.params.set_range_star[1]:

            bin_lin_untruncated = np.copy(bin_lin)
            bin_lin_noise_untruncated = np.copy(bin_lin_noise)
            lamRange_untruncated = np.copy(lamRange)

            lam = np.arange(len(bin_lin_in)) * CDELT + CRVAL
            bin_lin, lam, cut = apply_range(bin_lin_in,
                                            lam=lam,
                                            return_cuts=True,
                                            set_range=params.set_range_star)
            lamRange = np.array([lam[0], lam[-1]])
            bin_lin_noise = bin_lin_noise_in[cut]

            self.bin_lin = bin_lin
            self.bin_lin_noise = bin_lin_noise
            self.lamRange = lamRange

        if galaxy_name is not None:
            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)
            # different data types need to be read separetly
            z_gals, vel_gals, sig_gals = np.loadtxt(data_file,
                                                    unpack=True,
                                                    skiprows=1,
                                                    usecols=(1, 2, 3))
            galaxy_gals = np.loadtxt(data_file,
                                     skiprows=1,
                                     usecols=(0, ),
                                     dtype=str)
            i_gal = np.where(galaxy_gals == galaxy_name)[0][0]
            self.vel = vel_gals[i_gal]
            self.sig = sig_gals[i_gal]
            self.z = z_gals[i_gal]
        else:
            self.vel = 150.
            self.sig = 100.
            self.z = z

        self.lamRange = self.lamRange / (1 + self.z)
        self.FWHM_gal = self.params.FWHM_gal / (
            1 + self.z)  # Adjust resolution in Angstrom
        if self.params.res is not None:
            res = self.params.res / (1 + self.z)
            FWHM_dif = res - self.FWHM_gal
            sigma = FWHM_dif / 2.355 / self.CDELT  # Change in px
            self.bin_lin = ndimage.gaussian_filter1d(self.bin_lin, sigma)
            self.bin_lin_noise = np.sqrt(
                ndimage.gaussian_filter1d(self.bin_lin_noise**2, sigma))
            self.FWHM_gal = res

        self.rebin()
        self.load_stellar_templates()

        if not self.params.temp_mismatch or self.params.gas == 0:
            self.load_emission_templates()
            self.run()
        elif self.params.temp_mismatch and self.params.gas == 1:
            from copy import copy
            # Fit stellar component only.
            params_sav = copy(params)
            self.params.gas = 0
            self.params.produce_plot = False
            self.load_emission_templates()

            save_bin_log = np.array(self.bin_log)
            save_bin_log_noise = np.array(self.bin_log_noise)
            save_lamRange = np.array(self.lamRange)

            self.run()

            MCstellar_kin = np.array(self.MCstellar_kin)
            MCstellar_kin_err = np.array(self.MCstellar_kin_err)

            # if set_range_star is NOT set
            if self.params.set_range[0] == self.params.set_range_star[0] and \
             self.params.set_range[1] == self.params.set_range_star[1]:
                self.bin_log = np.copy(save_bin_log)
                self.bin_log_noise = np.copy(save_bin_log_noise)
                self.lamRange = np.copy(save_lamRange)
            else:  # set_range_star IS set
                self.bin_lin = np.copy(bin_lin_untruncated)
                self.bin_lin_noise = np.copy(bin_lin_noise_untruncated)
                self.lamRange = np.copy(lamRange_untruncated) / (1 + self.z)

                if self.params.res is not None:
                    res = self.params.res / (1 + self.z)
                    FWHM_dif = res - self.FWHM_gal
                    sigma = FWHM_dif / 2.355 / self.CDELT  # Change in px
                    self.bin_lin = ndimage.gaussian_filter1d(
                        self.bin_lin, sigma)
                    self.bin_lin_noise = np.sqrt(
                        ndimage.gaussian_filter1d(self.bin_lin_noise**2,
                                                  sigma))
                    self.FWHM_gal = res

                self.rebin()
                self.load_stellar_templates()

                save_bin_log = np.array(self.bin_log)
                save_bin_log_noise = np.array(self.bin_log_noise)
                save_lamRange = np.array(self.lamRange)

            # Find [OIII] kinematics and amplitude, enforce stellar kinematics
            self.params.stellar_moments *= -1
            self.params.start = [
                self.sol[0].tolist(), [None] * self.params.gas_moments
            ]
            self.params.gas = params_sav.gas
            self.params.lines = ['[OIII]5007d']
            self.load_emission_templates()

            self.run()

            MCgas_kin = np.array(self.MCgas_kin)
            MCgas_kin_err = np.array(self.MCgas_kin_err)
            OIII_uncert_spec = np.array(self.MCgas_uncert_spec)

            # Find all other gas amplitudes enforcing [OIII] and stellar
            # kinematics
            self.params.gas_moments *= -1
            self.params.start = [i.tolist() for i in self.sol]
            self.params.lines = params_sav.lines
            self.load_emission_templates()

            self.bin_log = np.copy(save_bin_log)
            self.bin_lin_noise = np.copy(save_bin_log_noise)
            self.lamRange = np.copy(save_lamRange)

            self.run()

            self.MCstellar_kin = MCstellar_kin
            self.MCstellar_kin_err = MCstellar_kin_err
            self.MCgas_kin = MCgas_kin
            self.MCgas_kin_err = MCgas_kin_err
            self.MCgas_uncert_spec[
             self.templatesToUse[self.component!=0]=='[OIII]5007d', :] = \
             OIII_uncert_spec.flatten()

            if params_sav.produce_plot:
                self.fig, self.ax = create_plot(self).produce

        else:  # gas == 2 or gas == 3
            from copy import copy
            # Fit stellar component only.
            params_sav = copy(params)
            self.params.gas = 0
            self.params.produce_plot = False
            self.load_emission_templates()

            save_bin_log = np.array(self.bin_log)
            save_bin_log_noise = np.array(self.bin_log_noise)
            save_lamRange = np.array(self.lamRange)

            self.run()

            MCstellar_kin = np.array(self.MCstellar_kin)
            MCstellar_kin_err = np.array(self.MCstellar_kin_err)

            # set_range_star is NOT set
            if self.params.set_range[0] == self.params.set_range_star[0] and \
             self.params.set_range[1] == self.params.set_range_star[1]:
                self.bin_log = np.copy(save_bin_log)
                self.bin_log_noise = np.copy(save_bin_log_noise)
                self.lamRange = np.copy(save_lamRange)
            else:  # set_range_star IS set
                self.bin_lin = np.copy(bin_lin_untruncated)
                self.bin_lin_noise = np.copy(bin_lin_noise_untruncated)
                self.lamRange = np.copy(lamRange_untruncated) / (1 + self.z)

                if self.params.res is not None:
                    res = self.params.res / (1 + self.z)
                    FWHM_dif = res - self.FWHM_gal
                    sigma = FWHM_dif / 2.355 / self.CDELT  # Change in px
                    self.bin_lin = ndimage.gaussian_filter1d(
                        self.bin_lin, sigma)
                    self.bin_lin_noise = np.sqrt(
                        ndimage.gaussian_filter1d(self.bin_lin_noise**2,
                                                  sigma))
                    self.FWHM_gal = res

                self.rebin()
                self.load_stellar_templates()

            # Find gas kinematics and amplitude, enforce stellar kinematics
            self.params.stellar_moments *= -1
            self.params.gas = params_sav.gas
            self.params.lines = params_sav.lines
            self.load_emission_templates()
            self.params.start = [self.sol[0].tolist()]
            self.params.start.extend([[None]*self.params.gas_moments]\
             * (len(self.element) - 1))

            self.run()

            self.MCstellar_kin = MCstellar_kin
            self.MCstellar_kin_err = MCstellar_kin_err

            if params_sav.produce_plot:
                self.fig, self.ax = create_plot(self).produce
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
Exemple #13
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]))
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 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 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 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