Example #1
0
def get_specFromAperture(galaxy, app_size=1.0, inside=True, res=0.2):
    f = fits.open(get_dataCubeDirectory(galaxy))
    s = f[1].data.shape

    x = np.arange(s[1]).repeat(s[2]).reshape(s[1], s[2])
    y = np.tile(np.arange(s[2]), s[1]).reshape(s[1], s[2])

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

    area = get_areaInAperture(s[1], s[2], x_cent, y_cent, app_size / res)

    if not inside:
        area = 1 - area

    # Deal with NaN
    d = f[1].data
    d[np.isnan(d)] = 0
    n = f[2].data
    n[np.isnan(n)] = 0
    return np.einsum('ijk,jk->i', d, area), np.einsum('ijk,jk->i', n, area), \
     np.arange(s[0])*f[1].header['CD3_3'] + f[1].header['CRVAL3']
def find_template(galaxy, set_range=None):
    params = set_params()
    params.gas = 0
    params.reps = 0
    params.set_range = set_range
    ## ----------========= Reading the spectrum  ===============---------

    dataCubeDirectory = get_dataCubeDirectory(galaxy)

    f = fits.open(dataCubeDirectory)

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

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

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

    del f

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

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

    with open('%s/Data/muse/analysis/%s/templates.txt' % (cc.base_dir, galaxy),
              'w') as f:
        for i in range(len(pp.component)):
            if pp.weights[i] != 0.0:
                f.write(str(i) + '   ' + str(pp.weights[i]) + '\n')
Example #3
0
	def galaxy_spectrum(self):
		if self.instrument == 'muse':
			ext = 1
			from errors2_muse import get_dataCubeDirectory
		elif self.instrument == 'vimos':
			ext = 0
			from errors2 import get_dataCubeDirectory
		cube_fits = fits.getdata(get_dataCubeDirectory(self.galaxy), ext)
		return np.nansum(cube_fits, axis=(1,2))
Example #4
0
	def galaxy_varience(self):
		warnings.warn('This returns uncertainty (sigma) NOT varience')
		if self.instrument == 'muse':
			ext = 1
			from errors2_muse import get_dataCubeDirectory
		elif self.instrument == 'vimos':
			ext = 0
			from errors2 import get_dataCubeDirectory
		return np.sqrt(np.sum(fits.getdata(get_dataCubeDirectory(self.galaxy), 
			ext+1)**2, axis=(1,2)))
Example #5
0
	def unbinned_flux(self):
		if self.instrument == 'muse':
			ext = 1
			from errors2_muse import get_dataCubeDirectory
			NAXIS3 = 3681
		elif self.instrument == 'vimos':
			ext = 0
			from errors2 import get_dataCubeDirectory
			NAXIS3 = 1916
		cube_fits, header = fits.getdata(get_dataCubeDirectory(self.galaxy), ext,
			header=True)
		return np.nansum(cube_fits, axis=0)# * NAXIS3 * header['CD3_3']
def save_muse(galaxy):
	if cc.device != 'uni':
		raise ValueError('This routine is to be run on your university computer.'
			+' Chump!')

	from errors2_muse import get_dataCubeDirectory
	f = fits.open(get_dataCubeDirectory(galaxy))

	ex0 = f[0]
	ex1 = fits.ImageHDU(np.array([np.nansum(f[1].data, axis=0)]), f[1].header, 
		name='DATA')
	ex2 = fits.ImageHDU(np.array([np.sqrt(np.nansum(f[2].data**2, axis=0))]), 
		f[2].header, name='ERROR')
	ex3 = fits.ImageHDU(np.nansum(f[3].data).astype(bool).astype(int), f[3].header, 
		name='BADPIX')
	f_new = fits.HDUList([ex0, ex1, ex2, ex3])

	corr_fits_file = '%s/Data/muse/%s/%s.clipped_home.fits' % (cc.base_dir, galaxy, 
		galaxy)

	f_new.writeto(corr_fits_file, overwrite=os.path.isfile(corr_fits_file))
Example #7
0
	def __init__(self, galaxy, opt):
		self.galaxy = galaxy
		self.opt = opt

		# Files
		self.tessellation_File = "%s/%s/voronoi_2d_binning_output_%s.txt" % (vin_dir, 
			galaxy, opt)
		self.tessellation_File2 = "%s/%s/voronoi_2d_binning_output2_%s.txt" %(vin_dir, 
			galaxy, opt)
		self.dataCubeDirectory = get_dataCubeDirectory(galaxy)
		if self.opt == 'kin':
			self.vin_dir_gasMC = '%s/%s/gas_MC' % (vin_dir, galaxy)
		else:
			self.vin_dir_gasMC = '%s/%s/pop_MC' % (vin_dir, galaxy)

		self.number_of_bins = int(max(self.bin_num) + 1) # zero-base
		self.norm_method = 'lwv'
		self.vel_norm = 0.0
		self.common_range = self.find_common_range()

		self.find_restFrame()


		# Check tessellation file is older than pPXF outputs (checks 
		# self.vin_dir_gasMC/0.dat only).
		if os.path.getmtime(self.tessellation_File) > os.path.getmtime('%s/0.dat' % (
			self.vin_dir_gasMC)): 
			if os.path.exists('%s/%i.dat' % (self.vin_dir_gasMC,max(self.bin_num))) and \
				not os.path.exists('%s/%i.dat' % (self.vin_dir_gasMC, 
				max(self.bin_num)+1)):
				# Issue warning, but do not stop.
				import warnings
				warnings.warn('WANING: The tesselation file '+\
					'voronoi_2d_binning_output_%s.txt may to have been changed.' % (opt))
			else:
				# Stop and raise exception
				raise UserWarning('WANING: The tesselation file '+\
					'voronoi_2d_binning_output_%s.txt has been overwritten.' % (opt))
Example #8
0
def add_(overplot,
         color,
         ax,
         galaxy,
         scale=None,
         close=False,
         radio_band=None,
         debug=False,
         FoV=None,
         nolegend=False):
    image_dir = getattr(get_dataCubeDirectory(galaxy, radio_band=radio_band),
                        overplot)
    if scale is None:
        if image_dir.default_scale is not None:
            scale = image_dir.default_scale
        else:
            scale = 'lin'
    if os.path.exists(image_dir):
        f = fits.open(image_dir)[0]
        # ****** NB: NOTE THE -VE SIGN ON CDELT1 ******
        x = (np.arange(f.header['NAXIS1']) - f.header['CRPIX1']) *\
         -abs(f.header['CDELT1']) + f.header['CRVAL1'] + (image_dir.RAoffset/(60.**2))
        y = (np.arange(f.header['NAXIS2']) - f.header['CRPIX2']) *\
         -f.header['CDELT2'] + f.header['CRVAL2'] + (image_dir.decoffset/(60.**2))

        x, y = np.meshgrid(x, y)
        #remove random extra dimenisons.
        s = np.array(f.data.shape)
        if any(s == 1):
            image = np.sum(f.data, axis=tuple(np.where(s == 1)[0]))
        else:
            image = f.data
        xlim = ax.get_xlim()
        ylim = ax.get_ylim()

        # Discard noise from outer parts of the galaxy -  for radio
        if overplot == 'radio' or scale == 'lin':
            lim = np.nanmean(image) + np.nanstd(image)
            image[image < lim] = lim

        if scale == 'log':
            image = np.log10(image)
        elif scale == 'lin':
            pass
            # m = np.nanmean(image)
            # s = np.nanstd(image)
            # image[image<m+s] = np.nan
        elif scale == 'sqrt':
            image = np.sqrt(image)
        else:
            raise ValueError("'scale' keyword has invaild value: %s" % (scale))

        # Plot
        cs = ax.contour(x,
                        y,
                        image,
                        colors=color,
                        linestyles='solid',
                        linewidth=1)
        # cs = ax.contour(image, colors=color, linestyles='solid', linewidth=1)
        if not nolegend:
            if overplot == 'radio':
                if scale != 'lin':
                    cs.collections[0].set_label(scale + ' ' + image_dir.band)
                else:
                    cs.collections[0].set_label(image_dir.band)
            else:
                if scale != 'lin':
                    cs.collections[0].set_label(scale + ' ' + overplot)
                else:
                    cs.collections[0].set_label(overplot)

        if not debug:
            ax.set_xlim(xlim)
            ax.set_ylim(ylim)
        elif FoV is not None:
            xdiff = xlim[1] - xlim[0]
            xcent = np.mean(xlim)
            ax.set_xlim(np.array([-1, 1]) * xdiff * FoV / 2. + xcent)
            ydiff = ylim[1] - ylim[0]
            ycent = np.mean(ylim)
            ax.set_ylim(np.array([-1, 1]) * ydiff * FoV / 2. + ycent)
        if not nolegend:
            leg = ax.legend(facecolor='w')

        # Save
        if hasattr(ax, 'saveTo'):
            saveTo = os.path.dirname(ax.saveTo)+"/Overplot/" + \
             os.path.basename(ax.saveTo)
            if not os.path.exists(os.path.dirname(saveTo)):
                os.makedirs(os.path.dirname(saveTo))
            plt.savefig(saveTo, bbox_inches="tight")

        if close:
            plt.close()
        elif not nolegend:
            leg.remove()
Example #9
0
    import matplotlib  # 20160202 JP to stop lack-of X-windows error
    matplotlib.use('Agg')  # 20160202 JP to stop lack-of X-windows error
    import matplotlib.pyplot as plt  # used for plotting
else:
    import matplotlib.pyplot as plt  # used for plotting
from errors2_muse import get_dataCubeDirectory
from classify import get_R_e
from prefig import Prefig
Prefig()
from Bin2 import Data
import disk_fit_functions_binned as dfn

for galaxy in ['ic1459', 'ic4296', 'ngc1316', 'ngc1399']:
    print galaxy

    f = fits.open(get_dataCubeDirectory(galaxy))
    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 = (x_cent_gals[i_gal], y_cent_gals[i_gal])

    D = Data(galaxy, instrument='muse', opt='kin')
    opt = D.opt

    galaxy_gals, pa_gals = np.loadtxt('%s/Data/muse/analysis/galaxies2.txt' %
                                      (cc.base_dir),
Example #10
0
def fit_disk(galaxy, D=None, opt='kin'):
    Prefig(subplots=(3, 2))
    fig, ax = plt.subplots(2, 3)

    f = fits.open(get_dataCubeDirectory(galaxy))
    header = f[1].header
    f.close()

    if D is None:
        pickleFile = open('%s/Data/muse/analysis/%s/%s/pickled/dataObj.pkl' %
                          (cc.base_dir, galaxy, opt))
        D = pickle.load(pickleFile)
        pickleFile.close()

    # Use gas disk
    vel = D.components['Hbeta'].plot['vel'].unbinned
    vel_err = D.components['Hbeta'].plot['vel'].uncert.unbinned

    disk, pars = dfn.disk_fit_exp(vel.copy(),
                                  vel_err.copy(),
                                  sigclip=3.0,
                                  leeway=2.)

    ax[1, 0] = plot_velfield_nointerp(
        D.x,
        D.y,
        D.bin_num,
        D.xBar,
        D.yBar,
        D.components['Hbeta'].plot['vel'],
        header,  #vmin=vmin, vmax=vmax, 
        flux_unbinned=D.unbinned_flux,
        nodots=True,
        colorbar=True,
        ax=ax[1, 0],
        title=r'Gas observed velocity (v$_\mathrm{gas}$)')

    ax[1, 1].imshow(disk, cmap=sauron)
    ax[1, 1].set_title(r'Gas model velocity (v$_\mathrm{g,mod})$')

    plot = D.components['Hbeta'].plot['vel'] - D.rebin(disk,
                                                       flux_weighted=True)
    # vmin,vmax = set_lims(plot)

    ax[1, 2] = plot_velfield_nointerp(
        D.x,
        D.y,
        D.bin_num,
        D.xBar,
        D.yBar,
        plot,
        header,
        # vmin=vmin, vmax=vmax,
        flux_unbinned=D.unbinned_flux,
        nodots=True,
        colorbar=True,
        ax=ax[1, 2],
        title=r'Residuals: v$_\mathrm{gas}$ - v$_\mathrm{g,mod}$')

    # Use stellar disk
    vel = D.components['stellar'].plot['vel'].unbinned
    vel_err = D.components['stellar'].plot['vel'].uncert.unbinned

    disk, pars = dfn.disk_fit_exp(vel.copy(),
                                  vel_err.copy(),
                                  sigclip=3.0,
                                  leeway=2.)

    ax[0, 0] = plot_velfield_nointerp(
        D.x,
        D.y,
        D.bin_num,
        D.xBar,
        D.yBar,
        D.components['stellar'].plot['vel'],
        header,  #vmin=vmin, vmax=vmax, 
        flux_unbinned=D.unbinned_flux,
        nodots=True,
        colorbar=True,
        ax=ax[0, 0],
        title=r'Stellar observed velocity (v$_\mathrm{\ast}$)')

    ax[0, 1].imshow(disk, cmap=sauron)
    ax[0, 1].set_title(r'Gas model velocity (v$_\mathrm{\ast,mod}$)')

    plot = D.components['Hbeta'].plot['vel'] - D.rebin(disk,
                                                       flux_weighted=True)
    # vmin,vmax = set_lims(plot)

    ax[0, 2] = plot_velfield_nointerp(
        D.x,
        D.y,
        D.bin_num,
        D.xBar,
        D.yBar,
        plot,
        header,
        # vmin=vmin, vmax=vmax,
        flux_unbinned=D.unbinned_flux,
        nodots=True,
        colorbar=True,
        ax=ax[0, 2],
        title=r'Residuals: v$_\mathrm{gas}$ - v$_\mathrm{\ast,mod}$')

    fig.suptitle('Outflows in %s' % (galaxy))

    fig.savefig('%s/Data/muse/analysis/%s/%s/plots/outflows.png' %
                (cc.base_dir, galaxy, opt))

    return D
Example #11
0
def use_kinemetry(gal, opt='pop'):
	out_dir = '%s/Data/muse/analysis' % (cc.base_dir)
	# colors=['b','y','g']
	# fig, ax = plt.subplots()
	# pl_ob=[] # array for the plot objects
	# missing=0 # number of missing plots (out of 3)

	# Plot all avaliable types
	# for i, type in enumerate(['flux','vel','sigma']):
	# 	f = '%s/%s/%s/kinemetry/kinemetry_gas_%s.txt' % (out_dir, gal, opt,
	# 		type)
	# 	if os.path.exists(f):
	# 		rad, pa, er_pa, q, er_q, k1, erk1 = np.loadtxt(f, unpack=True, 
	#			skiprows=1)
	# 		pa = rollmed(pa, 5)
	# 		k1 = rollmed(k1, 5)
	# 		# rad*=0.2 # Change to arcsec

	# 		# Align pa[0] as closely as possible with flux pa[0] by +/- 360 deg
	# 		if type == 'flux': pa0 = pa[0]
	# 		else:
	# 			a = np.argmin(np.abs(pa[0]-pa0+[-360,0,360]))
	# 			if a == 0:
	# 				pa -= 360
	# 			elif a == 2:
	# 				pa += 360

	# 		# Optimizing PA
	# 		# cut = np.arange(360,0,-10)
	# 		# r = np.array([list(pa)]*len(cut))
	# 		# for j, c in enumerate(cut):
	# 		# 	r[j, np.where(r[j,:] > c)[0]] -=360
	# 		# l = np.argmin(np.ptp(r,axis=1))
	# 		# pa = r[l]

	# 		# Finding smoothest pa by add or subtracting 360 deg	
	# 		for j in range(1,len(pa)):
	# 		    test = np.array([pa[j]-360, pa[j], pa[j]+360])
	# 		    a = np.argmin(np.abs(test-pa[j-1]))
	# 		    if a==0: 
	# 		        pa[j:]-=360
	# 		    elif a==2: 
	# 		        pa[j:]+=360
			


	# 		pl = ax.plot(rad,pa,colors[i],label='%s PA' % (type))
	# 		pl_ob.append(pl)

	# 		# Plot k1 from velocity fit.
	# 		if type == 'vel':
	# 			ax2=ax.twinx()
	# 			b=ax2.plot(rad,k1,'r', label='k1')
	# 			ax2.spines['right'].set_color('red')
	# 			ax2.yaxis.label.set_color('red')
	# 			ax2.tick_params(axis='y', colors='red')
	# 			ax2.set_ylabel('k1',color='r', rotation=270, labelpad=10)

	# 			ax2.spines['left'].set_color('blue')

	# 	else:
	# 		print 'There is no %s KINEMETRY file for %s.' %(type, gal)
	# 		missing +=1

	# # If not all missing
	# if missing != 3:
	# 	# Get redshift of galaxy from data_file
	# 	data_file =  "%s/Data/vimos/analysis/galaxies.txt" % (cc.base_dir)
	# 	classify_file = "%s/Data/muse/analysis/galaxies_classify.txt" % (
	#		cc.base_dir)

	# 	# different data types need to be read separetly
	# 	z_gals = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=(1,))
	# 	galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0,),dtype=str)
	# 	i_gal = np.where(galaxy_gals==gal)[0][0]
	# 	z = z_gals[i_gal]

	# 	# Set secondary x axis in kpc.
	# 	ax3=ax.twiny()
	# 	c = 299792 #km/s
	# 	#H = 67.8 #(km/s)/Mpc # From Planck
	# 	H = 70.0 # value used by Bolonga group.
	# 	r_kpc = np.radians(rad/(60.0*60.0)) * z*c/H *1000
	# 	ax3.set_xlim(r_kpc[0],r_kpc[-1])
	# 	ax3.set_xlabel('Radius (kpc)')

	# 	#ax.yaxis.label.set_color('blue')
	# 	#ax.tick_params(axis='y', colors='blue')
	# 	ax.set_ylabel('PA')#,color='b')
	# 	ax.set_xlabel('radius (arcsec)')

	# 	# Mark extent of KDC
	# 	galaxy_gals2, KDC_size = np.loadtxt(classify_file, unpack=True, 
	# 		usecols=(0,5), dtype=str, skiprows=1)
	# 	has_KDC = KDC_size!='-'
	# 	galaxy_gals2 = galaxy_gals2[has_KDC]
	# 	KDC_size = KDC_size[has_KDC].astype(float)

	# 	if gal in galaxy_gals2:
	# 		ax.axvline(KDC_size[galaxy_gals2==gal][0])

	# 	# Legend
	# 	try:
	# 		lns = b
	# 		for l in pl_ob: lns+=l
	# 	except UnboundLocalError:
	# 		if missing==1:lns=pl_ob[0]+pl_ob[1]
	# 		else:lns=pl_ob[0]

	# 	labs = [l.get_label() for l in lns]
	# 	ax.legend(lns, labs, loc=0, facecolor='w')

	# 	# Moves title clear of upper x axis 
	# 	plt.subplots_adjust(top=0.85)
	# 	ax.set_title('KINEMETRY gas output (smoothed)', y=1.12)

	# 	fig.savefig('%s/%s/%s/kinemetry/kinemetry.png'%(out_dir, gal, opt))

	# plt.close()


	Prefig(size=(4*16,12), transparent=False)
	fig, ax = plt.subplots(1,5)
	fig.suptitle('Kinemetry fit to Ionised gas dynamics')

	f = fits.open(get_dataCubeDirectory(gal))
	header = f[1].header
	f.close()

	header['NAXIS1'] = 150
	header['NAXIS2'] = 150

	tessellation_File = "%s/%s/%s/setup/voronoi_2d_binning_output.txt" % (
		out_dir, gal, opt)
	x,y,bin_num = np.loadtxt(tessellation_File, usecols=(0,1,2), 
		unpack=True, skiprows=1, dtype=int)

	# f = '%s/%s/%s/kinemetry/kinemetry_stellar_vel_2Dmodel.txt' % (out_dir, gal, 
	# 	opt)
	f = '%s/%s/%s/kinemetry/kinemetry_stellar_vel_2Dmodel.txt' % (out_dir, gal, 
		'pop')
	xbin, ybin, velkin, velcirc  = np.loadtxt(f, unpack=True, skiprows=1)

	f = '%s/%s/%s/kinemetry/gas_vel.dat' % (out_dir, gal, opt)
	vel = np.loadtxt(f, usecols=(0,), unpack=True)
	m = np.where(vel!=9999)[0]
	# x = [i for j, i in enumerate(x) if bin_num[j] in m]
	# y = [i for j, i in enumerate(y) if bin_num[j] in m]
	# bin_num = [i for j, i in enumerate(bin_num) if bin_num[j] in m]
	# vel = vel[vel != 9999]

	vel[vel==9999] = np.nan
	velkin_new = vel*0
	velcirc_new = vel*0
	j = 0
	for i in range(len(vel)):
		if ~np.isnan(vel[i]):
			velkin_new[i] = velkin[j]
			velcirc_new[i] = velcirc[j]
			j += 1
	velkin = velkin_new
	velcirc = velcirc_new	


	velkin[velkin==max(velkin)] = np.nan
	velcirc[velcirc==max(velcirc)] = np.nan


	# f = '%s/%s/%s/kinemetry/stellar_vel.dat' % (out_dir, gal, opt)
	# velkin = np.loadtxt(f, usecols=(0,), unpack=True)
	# velkin[velkin==9999] = np.nan


	# norm = np.nanmean(vel/velkin)
	# norm = 3
	# velkin *= norm
	# velcirc *= norm


	# f = '%s/%s/%s/kinemetry/gas_flux.dat' % (out_dir, gal, opt)
	# flux = np.loadtxt(f)

	vmin, vmax = set_lims(vel, symmetric=True, positive=False)
	plot_velfield_nointerp(x, y, bin_num, xbin, ybin, 
		vel, header, vmin=vmin, vmax=vmax, nodots=True, 
		title='Observed Velocity', colorbar=False, ax=ax[0])

	plot_velfield_nointerp(x, y, bin_num, xbin, ybin, 
		velkin, header, vmin=vmin, vmax=vmax, nodots=True, 
		title='KINEMETRY velocity model', colorbar=False, ax=ax[1])

	plot_velfield_nointerp(x, y, bin_num, xbin, ybin, 
		velcirc, header, vmin=vmin, vmax=vmax, nodots=True, 
		title='KINEMETRY circluar velocity model', colorbar=False, ax=ax[3])

	# vmin, vmax = set_lims(vel-velkin, symmetric=True)
	plot_velfield_nointerp(x, y, bin_num, xbin, ybin, 
		vel-velkin, header, vmin=vmin, vmax=vmax, nodots=True, 
		title='KINEMETRY model residuals', colorbar=False, ax=ax[2])

	# vmin, vmax = set_lims(vel-velcirc, symmetric=True)
	plot_velfield_nointerp(x, y, bin_num, xbin, ybin, 
		vel-velcirc, header, vmin=vmin, vmax=vmax, nodots=True, 
		title='KINEMETRY circluar model residuals', colorbar=True, ax=ax[4])

	for a in ax:
		for o, c in {'radio':'g','CO':'c'}.iteritems():
			add_(o, c, a, gal, scale='log')#, radio_band='L')
	


	fig.savefig('%s/%s/%s/kinemetry/kinemetry_models.png'%(out_dir, gal, opt))
Example #12
0
def BPT(galaxy, D=None, opt='pop', norm="lwv"):
    print '   BPT'
    Prefig(size=np.array((3, 1)) * 7, transparent=False)

    analysis_dir = "%s/Data/muse/analysis" % (cc.base_dir)
    galaxiesFile = "%s/galaxies.txt" % (analysis_dir)
    x_cent_gals, y_cent_gals = np.loadtxt(galaxiesFile,
                                          unpack=True,
                                          skiprows=1,
                                          usecols=(1, 2),
                                          dtype=int)
    galaxy_gals = np.loadtxt(galaxiesFile,
                             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])

    # output = '%s/%s/%s' % (analysis_dir, galaxy, opt)
    if D is None:
        # pickleFile = open('%s/pickled/dataObj.pkl' % (output))
        # D = pickle.load(pickleFile)
        # pickleFile.close()
        D = Data(galaxy, instrument='muse', opt=opt)

    output = '%s/%s/%s' % (analysis_dir, galaxy, D.opt)

    if D.norm_method != norm:
        D.norm_method = norm
        D.find_restFrame()

    # D.__threshold__ = 3
# ------------=============== BPT diagram =================----------
    if all([
            l in D.e_components for l in [
                '[NII]6583d', '[SII]6716', '[OI]6300d', 'Hbeta', 'Halpha',
                '[OIII]5007d'
            ]
    ]):

        fig, ax = plt.subplots(1, 3, sharey=True)
        Prefig(size=(16, 12))
        fig2, ax2 = plt.subplots()
        r = np.sqrt((D.xBar - center[0])**2 + (D.yBar - center[1])**2)
        for i, l in enumerate(['[NII]6583d', '[SII]6716', '[OI]6300d']):

            y = np.log10(D.e_line['[OIII]5007d'].flux / 1.35 /
                         D.e_line['Hbeta'].flux)
            x = np.log10(D.e_line[l].flux / D.e_line['Halpha'].flux)

            y_err = np.sqrt((D.e_line['[OIII]5007d'].flux.uncert/
             D.e_line['[OIII]5007d'].flux)**2 +
             (D.e_line['Hbeta'].flux.uncert/D.e_line['Hbeta'].flux)**2)\
             / np.log(10)
            x_err = np.sqrt((D.e_line[l].flux.uncert/D.e_line[l].flux)**2 +
             (D.e_line['Halpha'].flux.uncert/D.e_line['Halpha'].flux)**2)\
             / np.log(10)

            large_err = (x_err > 0.5) + (y_err > 0.5)

            Seyfert2_combined = np.ones(len(x)).astype(bool)
            LINER_combined = np.ones(len(x)).astype(bool)
            SF_combined = np.ones(len(x)).astype(bool)
            x_line1 = np.arange(-2.2, 1, 0.001)
            if l == '[SII]6716':
                Seyfert2 = ((0.72/(x - 0.32) + 1.30 < y) + (x > 0.32)) \
                 * (1.89 * x + 0.76 < y) * ~large_err
                LINER = ((0.72/(x - 0.32) + 1.30 < y) + (x > 0.32)) \
                 * (1.89 * x + 0.76 > y) * ~large_err
                SF = (y < 0.72 / (x - 0.32) + 1.30) * (x < 0.32) * ~large_err

                y_line1 = 0.72 / (x_line1 - 0.32) + 1.30
                m = y_line1 < 1
                ax[i].plot(x_line1[m], y_line1[m], 'k')

                y_line2 = 1.89 * x_line1 + 0.76
                m = y_line2 > y_line1
                a = np.min(x_line1[m])
                x_line2 = np.arange(a, 0.60, 0.001)
                y_line2 = 1.89 * x_line2 + 0.76
                ax[i].plot(x_line2, y_line2, 'k')

                lab = r'[SII]$\lambda$$\lambda$6717,6731'

                ax[i].set_xlim([-1.2, 0.7])

            elif l == '[NII]6583d':
                x /= 1.34

                Seyfert2 = ((0.61/(x - 0.47) + 1.19 < y) + (x > 0.47)) \
                 * ~large_err
                LINER = ((0.61/(x - 0.47) + 1.19 < y) + (x > 0.47)) \
                 * ~large_err
                SF = (0.61 / (x - 0.47) + 1.19 > y) * (x < 0.47) * ~large_err

                y_line1 = 0.61 / (x_line1 - 0.47) + 1.19
                m = y_line1 < 1
                ax[i].plot(x_line1[m], y_line1[m], 'k')
                ax2.plot(x_line1[m], y_line1[m], 'k')

                y_line2 = 0.61 / (x_line1 - 0.05) + 1.3
                m1 = y_line2 < y_line1
                a = np.min(x_line1[m1])
                x_line2 = np.arange(a, 0.60, 0.001)
                y_line2 = 0.61 / (x_line2 - 0.05) + 1.3
                m2 = y_line2 < 1
                ax[i].plot(x_line2[m2], y_line2[m2], 'k--')
                ax2.plot(x_line2[m2], y_line2[m2], 'k--')

                lab = r'[NII]$\lambda$6584'

                ax[i].set_xlim([-2, 1])
                ax2.set_xlim([-2, 1])
                ax2.set_ylim([-1.2, 1.5])

                distance = np.zeros(len(x))
                for j in range(len(distance)):
                    distance[j] = np.sqrt(
                        np.min((x_line1[m] - x[j])**2 +
                               (y_line1[m] - y[j])**2))
                limit = 1  # if distance is greater than limit then consider
                #	it completely in it's region.
                distance[distance > limit] = limit
                distance[SF] *= -limit

                try:
                    ax2.scatter(x,
                                y,
                                c=distance,
                                cmap=sauron,
                                vmin=-limit,
                                vmax=limit)
                except:
                    print 'This did not work cotton. Galaxy: %s' % (galaxy)

                ax2.set_ylabel(r'log([OIII]/$H_\beta$)')
                ax2.set_xlabel(r'log(%s/$H_\alpha$)' % (lab))

                add_grids(ax[i], '[NII]', '[OIII]', x_Ha=True)

            elif l == '[OI]6300d':
                x /= 1.33

                Seyfert2 = ((y > 0.73/(x + 0.59) + 1.33) + (x > -0.59)) \
                 * (y > 1.18 * x + 1.30) * ~large_err
                LINER = ((y > 0.73/(x + 0.59) + 1.33) + (x > -0.59)) \
                * (y < 1.18 * x + 1.30) * ~large_err
                SF = (y < 0.73 / (x + 0.59) + 1.33) * (x < -0.59) * ~large_err

                y_line1 = 0.73 / (x_line1 + 0.59) + 1.33
                m = y_line1 < 1
                ax[i].plot(x_line1[m], y_line1[m], 'k')

                y_line2 = 1.18 * x_line1 + 1.30
                m = y_line2 > y_line1
                a = np.min(x_line1[m])
                x_line2 = np.arange(a, 0.60, 0.001)
                y_line2 = 1.18 * x_line2 + 1.30
                ax[i].plot(x_line2, y_line2, 'k')

                ax[i].axvline(-0.59, ls='--', c='k')

                lab = r'[OI]$\lambda$6300'

                ax[i].set_xlim([-2.2, 0])

                add_grids(ax[i], '[OI]', '[OIII]', x_Ha=True)

            ax[i].set_ylim([-1.2, 1.5])

            Seyfert2_combined *= Seyfert2
            LINER_combined *= LINER
            SF_combined *= SF

            myerrorbar(ax[i],
                       x,
                       y,
                       xerr=x_err,
                       yerr=y_err,
                       marker='.',
                       color=r)
            # ax[i].errorbar(x[LINER], y[LINER], yerr=y_err[LINER],
            # 	xerr=x_err[LINER], c='g', fmt='.')
            # ax[i].errorbar(x[Seyfert2], y[Seyfert2], yerr=y_err[Seyfert2],
            # 	xerr=x_err[Seyfert2], c='r', fmt='.')
            # ax[i].errorbar(x[SF], y[SF], yerr=y_err[SF], xerr=x_err[SF],
            # 	c='b', fmt='.')

            ax[0].set_ylabel(r'log [OIII]$\lambda$5007/H$\,\beta$')
            ax[i].set_xlabel(r'log(%s/$H_\alpha$)' % (lab))

        saveTo = '%s/plots/BPT.png' % (output)
        if not os.path.exists(os.path.dirname(saveTo)):
            os.makedirs(os.path.dirname(saveTo))
        fig.subplots_adjust(wspace=0)  #,hspace=0.01)
        fig.savefig(saveTo, dpi=100)
        fig2.savefig('%s/plots/BPT2.png' % (output), dpi=100)
        plt.close()
        Prefig(size=(16, 12), transparent=False)
        # ------------================= BPT map ===================----------
        m = np.ones(D.number_of_bins) * np.nan
        m[Seyfert2_combined] = +1
        m[LINER_combined] = 0
        m[SF_combined] = -1

        f = fits.open(get_dataCubeDirectory(galaxy))
        header = f[1].header
        f.close()
        saveTo = '%s/plots/AGN_map.png' % (output)
        ax = plot_velfield_nointerp(D.x,
                                    D.y,
                                    D.bin_num,
                                    D.xBar,
                                    D.yBar,
                                    m,
                                    header,
                                    vmin=-1.3,
                                    vmax=1.3,
                                    nodots=True,
                                    title='Map of AGN',
                                    save=saveTo,
                                    res=0.2,
                                    flux_unbinned=D.unbinned_flux,
                                    center=center)
        add_('radio', 'r', ax, galaxy)
        plt.close()

        # ------------================= BPT map2 ===================----------
        Prefig(size=(16, 12), transparent=False)
        f = fits.open(get_dataCubeDirectory(galaxy))
        header = f[1].header
        f.close()
        saveTo = '%s/plots/AGN_map2.png' % (output)
        ax = plot_velfield_nointerp(D.x,
                                    D.y,
                                    D.bin_num,
                                    D.xBar,
                                    D.yBar,
                                    distance,
                                    header,
                                    vmin=-1.3,
                                    vmax=1.3,
                                    nodots=True,
                                    title='Map of AGN',
                                    save=saveTo,
                                    res=0.2,
                                    flux_unbinned=D.unbinned_flux,
                                    center=center)
        ax.saveTo = saveTo
        add_('radio', 'r', ax, galaxy)
        plt.close()

# ------------============== WHaN2 diagram ================----------
    if all([l in D.e_components for l in ['[NII]6583d', 'Halpha']]):
        Prefig(size=(16, 12 * 3), transparent=False)
        fig, ax = plt.subplots(3)
        x = np.log10(D.e_line['[NII]6583d'].flux / D.e_line['Halpha'].flux)
        y = np.log10(D.e_line['Halpha'].equiv_width)

        Ha_Hapeak = D.e_line['Halpha'].flux / np.nanmax(
            D.e_line['Halpha'].flux)
        p1 = Ha_Hapeak <= 0.2
        p2 = Ha_Hapeak > 0.2
        c = np.array(np.sqrt((D.xBar - center[0])**2 +
                             (D.yBar - center[1])**2))

        passive = (D.e_line['Halpha'].equiv_width <
                   0.5) * (D.e_line['[NII]6583d'].equiv_width < 0.5)

        ax[0].scatter(x, y, c=c)
        ax[0].scatter(x[passive], y[passive], marker='x', c='r')

        xlim = ax[0].get_xlim()
        ylim = ax[0].get_ylim()
        xlim = [-2, 0.75]
        ylim = [-1, 1.2]

        ax[1].scatter(x[p1], y[p1], c=c[p1], vmin=np.min(c), vmax=np.max(c))
        ax[1].scatter(x[p1 * passive], y[p1 * passive], marker='x', c='r')
        ax[1].text(-1.9, -0.8,
                   r'0 $<$ H$_\alpha$/H$_\alpha^{\mathrm{peak}}$ $\leq$ 0.2')

        ax[2].scatter(x[p2], y[p2], c=c[p2], vmin=np.min(c), vmax=np.max(c))
        ax[2].scatter(x[p2 * passive], y[p2 * passive], marker='x', c='r')
        ax[2].text(-1.9, -0.8,
                   r'0.2 $<$ H$_\alpha$/H$_\alpha^{\mathrm{peak}}$ $\leq$ 1')

        # Dianotics lines from R Cid Fernandes et.al. 2011 MNRAS 413 1687
        for a in ax:
            a.axhline(np.log10(3), ls=':', c='k')  #
            a.plot([-0.4, -0.4], [np.log10(3), ylim[1]], ls=':', c='k')
            a.plot([-0.4, xlim[1]], [np.log10(6), np.log10(6)], ls=':', c='k')
            a.set_xlim(xlim)
            a.set_ylim(ylim)
            a.set_ylabel(r'log(EW(H$_\alpha$)/$\AA$)')
            a.set_xlabel(r'log([NII]/H$_\alpha$)')
            a.text(-1.9, 1, 'Star Forming')
            a.text(-0.35, 1, 'strong AGN')
            a.text(-0.35, 0.55, 'weak AGN')
            a.text(-1.9, 0.25, 'Retired Galaxies')
        fig.suptitle('WHaN2 plot')

        fig.savefig('%s/plots/WHaN2.png' % (output))
        plt.close()
# ------------=============== MEx diagram =================----------
    if all([l in D.e_components for l in ['[OIII]5007d', 'Hbeta']]):
        Prefig()
        # from Atlas3D XXXI (Section 6.2.1)
        fig, ax = plt.subplots()
        y = np.log10(D.e_line['[OIII]5007d'].flux / 1.35 /
                     D.e_line['Hbeta'].flux)
        y_err = y * np.sqrt((D.e_line['[OIII]5007d'].flux.uncert /
                             D.e_line['[OIII]5007d'].flux)**2 +
                            (D.e_line['Hbeta'].flux.uncert /
                             D.e_line['Hbeta'].flux)**2) / np.log(10)

        large_err = y_err**2 > 1
        m = ~large_err * (D.e_line['[OIII]5007d'].equiv_width < 0.8)
        ax.errorbar(D.components['stellar'].plot['sigma'][m],
                    y[m],
                    c='b',
                    xerr=D.components['stellar'].plot['sigma'].uncert[m],
                    yerr=y_err[m],
                    fmt='.',
                    label='EW([OIII]) < 0.8')

        m = ~large_err * (D.e_line['[OIII]5007d'].equiv_width >= 0.8)
        ax.errorbar(D.components['stellar'].plot['sigma'][m],
                    y[m],
                    c='r',
                    xerr=D.components['stellar'].plot['sigma'].uncert[m],
                    yerr=y_err[m],
                    fmt='.',
                    label=r'EW([OIII]) $\ge 0.8$')

        ax.legend(facecolor='w')

        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, min(max(D.components['stellar'].plot['sigma'][m]), 500)])
        ax.set_ylim([-1.2, 1.5])

        ax.axvline(70, c='k')
        ax.axhline(np.log10(0.5),
                   xmin=70. /
                   min(max(D.components['stellar'].plot['sigma'][m]), 500),
                   c='k')
        ax.axhline(np.log10(1),
                   xmin=70. /
                   min(max(D.components['stellar'].plot['sigma'][m]), 500),
                   c='k')

        ylim = ax.get_ylim()
        yrange = ylim[1] - ylim[0]
        ax.text(60, 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.set_xlabel(r'$\sigma_\ast$')
        ax.set_ylabel(r'log [OIII]$\lambda$5007/H$\,\beta$')
        ax.set_title('Mass-excitation (MEx) diagnotics for %s' %
                     (galaxy.upper()))

        fig.savefig('%s/plots/MEx.png' % (output))
# ------------============== SAURON diagram ===============----------
    if all([l in D.e_components for l in ['[NI]d', 'Hbeta', '[OIII]5007d']]):

        # from SAURON XVI.
        fig, ax = plt.subplots()
        # y and y_err as MEx above

        x = np.log10(D.e_line['[NI]d'].flux / D.e_line['Hbeta'].flux)
        x_err = np.sqrt(
            (D.e_line['[NI]d'].flux.uncert / D.e_line['[NI]d'].flux)**2 +
            (D.e_line['Hbeta'].flux.uncert /
             D.e_line['Hbeta'].flux)**2) / np.log(10)

        ax.errorbar(x, y, xerr=x_err, yerr=y_err, fmt='.')

        # Add BPT line - transformed to NI
        xlim = np.array([-2.5, 0.5])
        x_line = np.linspace(xlim[0], xlim[1], 100)
        y_line = 0.61 / (x_line - 0.47) + 1.19

        m = y_line < 1
        plt.plot(x_line[m] - lnd + lbd, y_line[m], 'k')

        y_line2 = 0.61 / (x_line1 - 0.05) + 1.3
        m1 = y_line2 < y_line1
        a = np.min(x_line1[m1])
        x_line2 = np.arange(a, 0.60, 0.001)
        y_line2 = 0.61 / (x_line2 - 0.05) + 1.3
        m2 = y_line2 < 1
        ax.plot(x_line2[m2] - lnd + lbd, y_line2[m2], 'k--')

        ax.set_xlim([-2.5, 0.5])
        ax.set_ylim([-1.5, 1.5])
        ax.set_xlabel(r'log [NI]$\lambda\lambda$5197,5200/H$\,\beta$')
        ax.set_ylabel(r'log [OIII]$\lambda$5007/H$\,\beta$')
        ax.set_title('SAURON diagnotics for %s' % (galaxy.upper()))

        add_grids(ax, '[NI]', '[OIII]')

        fig.savefig('%s/plots/SAURON_diagnoistic.png' % (output))
        plt.close()


# ------------=========== Hbeta flux profile ===============----------
    if 'Hbeta' in D.components.keys():
        Prefig()
        fig, ax = plt.subplots()

        Hb = D.e_line['Hbeta'].flux

        myerrorbar(ax, r, Hb, yerr=Hb.uncert,
         color=np.log10(D.e_line['[OIII]5007d'].flux/1.35\
         / D.e_line['Hbeta'].flux).clip(-1,1))

        o = np.argsort(r)

        # ax.plot(r[o][1:], Hb[np.argmin(np.abs(r-1))] * r[o][1:]**-2, 'k')
        ax.plot(
            r[o],
            np.nanmedian(r[o][np.isfinite(Hb[o])])**2 *
            np.nanmedian(Hb[o][np.isfinite(Hb[o])]) * r[o]**-2, 'k')

        ax.set_yscale('log')
        ax.set_ylabel(r'H$_\beta$ Flux')
        ax.set_xlabel('Radius (pixels)')

        fig.savefig('%s/plots/Hbeta_profile.png' % (output))
        plt.close(fig)

    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
Example #14
0
def compare_absortion(galaxy, O_sig=False, corr_lines='all'):
    f = fits.open(get_dataCubeDirectory(galaxy))
    header = f[1].header

    # Load VIMOS values
    data_file = "%s/Data/vimos/analysis/galaxies.txt" % (cc.base_dir)
    z_gals = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=(1, ))
    galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0, ), dtype=str)
    i_gal = np.where(galaxy_gals == galaxy)[0][0]
    z = z_gals[i_gal]

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

    data_file = "%s/Data/muse/analysis/galaxies2.txt" % (cc.base_dir)
    pa_gals = np.loadtxt(data_file, unpack=True, skiprows=1, usecols=(3, ))
    galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0, ), dtype=str)
    i_gal = np.where(galaxy_gals == galaxy)[0][0]
    pa = pa_gals[i_gal]

    lines = [
        'H_beta', 'Fe5015', 'Mg_b', 'Fe5270', 'Fe5335', 'Fe5406', 'Fe5709',
        'NaD'
    ]
    e_lines = [
        'e_H_beta', 'e_Fe5015', 'e_Mg_b', 'e_Fe5270', 'e_Fe5335', 'e_Fe5406',
        'e_Fe5709', 'e_NaD'
    ]

    # load Ogando values
    cols = Ogando_data = np.loadtxt('%s/Data/lit_absorption/Ogando.txt' %
                                    (cc.base_dir),
                                    dtype=str)[0]
    cols = [i for i, co in enumerate(cols) if co in lines or co in e_lines]
    Ogando_data = np.loadtxt('%s/Data/lit_absorption/Ogando.txt' %
                             (cc.base_dir),
                             unpack=True,
                             skiprows=2,
                             usecols=np.append([1, 2], cols))
    galaxies = np.loadtxt('%s/Data/lit_absorption/Ogando.txt' % (cc.base_dir),
                          unpack=True,
                          skiprows=2,
                          usecols=(0, ),
                          dtype=str)
    i_gal = np.where(galaxies == galaxy)[0][0]
    O_sigma, O_sigma_err = 10**Ogando_data[0, i_gal], np.abs(
        10**Ogando_data[0, i_gal] * Ogando_data[0, i_gal] *
        Ogando_data[1, i_gal] / 10)

    O_val = {}
    O_err = {}
    for i in range(0, 2 * len(lines), 2):
        O_val[lines[i / 2]] = Ogando_data[i, i_gal]
        O_err[lines[i / 2]] = Ogando_data[i + 1, i_gal]

    params = set_params(reps=0,
                        opt='pop',
                        gas=1,
                        lines=corr_lines,
                        produce_plot=False)

    mask = slitFoV(center,
                   4.1 / abs(header['CD1_1']) * 60**2,
                   2.5 / header['CD2_2'] * 60**2,
                   pa,
                   instrument='muse')

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

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

    lam = np.arange(len(spec)) * header['CD3_3'] + header['CRVAL3']
    spec, lam, cut = apply_range(spec,
                                 lam=lam,
                                 set_range=params.set_range,
                                 return_cuts=True)
    lamRange = np.array([lam[0], lam[-1]])
    noise = noise[cut]

    pp = run_ppxf(galaxy, spec, noise, lamRange, header['CD3_3'], params)

    if O_sig:
        if isinstance(O_sig, bool):
            absorp, uncert = get_absorption(lines,
                                            pp=pp,
                                            sigma=O_sigma(a),
                                            instrument='muse')
            sigma = O_sigma(a)
        else:
            absorp, uncert = get_absorption(lines,
                                            pp=pp,
                                            instrument='muse',
                                            sigma=O_sigma(a) + O_sig *
                                            (pp.sol[0][1] - O_sigma(a)))
            sigma = O_sigma(a) + O_sig * (pp.sol[0][1] - O_sigma(a))
    else:
        absorp, uncert = get_absorption(lines, pp=pp, instrument='muse')
        sigma = pp.sol[0][1]

    my = []
    e_my = []
    og = []
    e_og = []
    sig = []
    lin = []

    for i, l in enumerate(lines):
        lin = np.append(lin, l)
        sig = np.append(sig, sigma)
        # Aperture correction:
        r_ab = 1.025 * np.sqrt(4.1 * 2.5 / np.pi)  # arcsec
        r_ab = np.radians(r_ab / 60**2) * z * c / H * 1000  # kpc
        if l == 'H_beta' or l == 'Hbeta':
            l2 = 'hb'
            beta = 0.002  # from table 5 in Ogando '08
            e_beta = 0.027
        elif l == 'Fe5015':
            l2 = l
            beta = -0.012
            e_beta = 0.027
        elif l == 'Mg_b':
            l2 = 'mgb'
            beta = -0.031
            e_beta = 0.034
        elif l == 'NaD':
            l2 = 'nad'
            beta = -0.034
            e_beta = 0.022
        # elif l=='TiO1':
        # 	l2='tio1'
        # elif l=='TiO2':
        # 	l2='tio2'
        elif l == 'Fe5270':
            l2 = 'fe52'
            beta = -0.016
            e_beta = 0.025
        elif l == 'Fe5335':
            l2 = 'fe53'
            beta = -0.012
            e_beta = 0.027
        elif l == 'Fe5406':
            l2 = l
            beta = -0.015
            e_beta = 0.029
        elif l == 'Fe5702':
            l2 = l
            beta = 0
            e_beta = 0.036

        # Change to mag units
        s = spectrum(lam=pp.lam, lamspec=pp.galaxy)
        I = -2.5 * np.log10(1 - absorp[l] / np.diff(getattr(s, l2))[0])
        e_I = np.abs(2.5 / np.log(10) * uncert[l] /
                     (np.diff(getattr(s, l2))[0] - absorp[l]))

        I = I - beta * np.log10(r_ab / 1.19)  # Choosen from Davies 1987
        e_I = np.sqrt(e_I**2 + (e_beta**2 * np.log10(r_ab / 1.19)))

        absorp[l] = (1 - 10**(-I / 2.5)) * np.diff(getattr(s,
                                                           l2))[0]  # Back to A
        uncert[l] = np.abs(2.5 * absorp[l] * np.log(10) * e_I)

        lit_value = Ogando_data[i * 2 + 2, i_gal]
        e_lit_value = Ogando_data[i * 2 + 3, i_gal]

        e_lit_value = np.mean([
            np.abs(
                Lick_to_LIS(l, lit_value + e_lit_value) -
                Lick_to_LIS(l, lit_value)),
            np.abs(
                Lick_to_LIS(l, lit_value - e_lit_value) -
                Lick_to_LIS(l, lit_value))
        ])
        lit_value = Lick_to_LIS(l, lit_value)

        my.append(absorp[l])
        e_my.append(uncert[l])

        og.append(lit_value)
        e_og.append(e_lit_value)

    return my, e_my, og, e_og, lin
def plot_absorption(galaxy, opt='pop', D=None, uncert=True, overplot={}):
    # Find lines:
    lines = [  #'G4300', 'Fe4383', 'Ca4455', 'Fe4531', 
        'H_beta',
        'Fe5015',
        # 'Mg_1', 'Mg_2',
        'Mg_b',
        'Fe5270',
        'Fe5335',
        'Fe5406',
        'Fe5709',
        'Fe5782',
        'NaD',
        'TiO1',
        'TiO2'
    ]
    # limits = {#'G4300', 'Fe4383', 'Ca4455', 'Fe4531',
    # 	'H_beta':[1.0,2.9], 'Fe5015':[3.5,5.9], 'Mg_b':[3.1,4.7]}
    titles = {
        'H_beta': r'H$_\beta$',
        'Fe5015': 'Fe5015',
        'Mg_b': r'Mg$_b$',
        'Fe5270': 'Fe5270',
        'Fe5335': 'Fe5335',
        'Fe5406': 'Fe5406',
        'Fe5709': 'Fe5709',
        'Fe5782': 'Fe5782',
        'NaD': 'NaD',
        'TiO1': 'TiO1',
        'TiO2': 'TiO2'
    }

    print 'Absorption lines'

    # 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/absorption" % (output)
    if not os.path.exists(out_plots): os.makedirs(out_plots)

    if D is None:
        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[1].header
    f.close()

    data_file = "%s/galaxies.txt" % (out_dir)
    # different data types need to be read separetly
    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] - 10
    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]

    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=titles[line],
                                    cmap='gnuplot2',
                                    redshift=z,
                                    center=center,
                                    flux_unbinned=D.unbinned_flux,
                                    signal_noise=D.SNRatio,
                                    signal_noise_target=SN_target,
                                    save=saveTo)
        ax.saveTo = saveTo
        if overplot:
            for o, color in overplot.iteritems():
                add_(o, color, ax, galaxy, close=True)

        if uncert:
            abmin, abmax = set_lims(ab_uncert)

            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=titles[line],
                                   cmap='gnuplot2',
                                   flux_unbinned=D.unbinned_flux,
                                   signal_noise=D.SNRatio,
                                   signal_noise_target=SN_target,
                                   close=True,
                                   save='%s/%s_uncert.png' % (out_plots, line))
    return D
Example #16
0
def plot_results(galaxy,
                 discard=0,
                 norm="lwv",
                 plots=False,
                 residual=False,
                 overplot={},
                 show_bin_num=False,
                 D=None,
                 mapping=mapping(),
                 opt='kin'):

    pa = {'ic1459': 0, 'ic4296': 0, 'ngc1316': 0, 'ngc1399': 0}

    pa = pa[galaxy]  # PA from reduction

    data_file = "%s/galaxies.txt" % (vin_dir)
    # different data types need to be read separetly
    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] - 10
    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]

    # Remove option if overplot file does not exist.
    if overplot:
        for o in overplot.keys():
            if not getattr(get_dataCubeDirectory(galaxy), o):
                del overplot[o]

    dataCubeDirectory = get_dataCubeDirectory(galaxy)
    output = "%s/%s/%s" % (out_dir, galaxy, opt)
    out_plots = "%s/plots" % (output)
    out_nointerp = "%s/notinterpolated" % (out_plots)
    vin_dir_gasMC = "%s/%s/%s/MC" % (vin_dir, galaxy, opt)  # for chi2
    out_pickle = '%s/pickled' % (output)

    cubeFile = fits.open(dataCubeDirectory)
    header = cubeFile[1].header
    cubeFile.close()
    # ------------== Reading pickle file and create plot  ===----------

    # Load pickle file from pickler.py
    if D is None:
        pickleFile = open("%s/dataObj.pkl" % (out_pickle), 'rb')
        D = pickle.load(pickleFile)
        pickleFile.close()

    # D.__threshold__ = 3.0

    if D.norm_method != norm:
        D.norm_method = norm
        D.find_restFrame()

    # Adjust by hand
    # if galaxy == 'ic1459' and norm == 'lws':
    # 	D.vel_norm -= 15
    # if galaxy == 'ic4296' and norm == 'lws':
    # 	D.vel_norm += 20
    # if galaxy == 'ngc1399' and norm =='lws':
    # 	D.vel_norm += 35

    # Create figure and array for axes
    n_rows = 2 + 2 * len(D.e_components) + int(
        np.ceil(len(D.e_components) * (len(D.e_components) - 1) / 6.0))
    f = plt.figure(frameon=False)
    ax_array = []

    # ------------================ Plot SNR =================----------
    if mapping.SNR:
        print '    SNR'
        saveTo = "%s/SNR.png" % (out_nointerp)
        ax1 = plot_velfield_nointerp(D.x,
                                     D.y,
                                     D.bin_num,
                                     D.xBar,
                                     D.yBar,
                                     D.SNRatio,
                                     header,
                                     colorbar=True,
                                     nodots=True,
                                     title='SNR',
                                     save=saveTo,
                                     close=True,
                                     flux_unbinned=D.unbinned_flux,
                                     center=center,
                                     show_bin_num=show_bin_num,
                                     galaxy=galaxy.upper(),
                                     redshift=z)
# ------------=============== Plot image ================----------
    if mapping.image:
        print "    Image"

        title = "Total Flux"
        CBLabel = r"Flux (erg $10^{-20}$ s$^{-1}$ cm$^{-2}$)"

        ax = f.add_subplot(111, aspect='equal')
        saveTo = "%s/total_image.png" % (out_nointerp)
        ax.saveTo = saveTo
        ax.figx, ax.figy = 0, 0

        fmin, fmax = set_lims(D.flux, positive=True)

        ax = plot_velfield_nointerp(D.x,
                                    D.y,
                                    D.bin_num,
                                    D.xBar,
                                    D.yBar,
                                    D.flux,
                                    header,
                                    vmin=fmin,
                                    vmax=fmax,
                                    nodots=True,
                                    colorbar=True,
                                    label=CBLabel,
                                    title=title,
                                    ax=ax,
                                    cmap='gist_yarg',
                                    flux_unbinned=D.unbinned_flux,
                                    center=center)
        if plots:
            plt.show()

        ax_array.append(ax)
        f.delaxes(ax)
        f.delaxes(ax.cax)
        if hasattr(ax, 'ax2'): f.delaxes(ax.ax2)
        if hasattr(ax, 'ax3'): f.delaxes(ax.ax3)
# ------------========= Plot intensity (& EW) ===========----------
    if mapping.equivalent_width:
        print "    gas map(s) and equivalent widths"
        for c in D.e_components:
            print "        " + c

            if 'OIII' in c:
                c_title = '[OIII]'
            elif 'Hbeta' in c:
                c_title = r'H$_\beta$'
            elif 'Hgamma' in c:
                c_title = r'H$_\gamma$'
            else:
                c_title = c
            if 'n_' in c_title or 'n_' in c:
                c_title = 'Narrow line ' + c_title.strip('n_')

            f_title = "%s Flux" % (c_title)
            fh_title = "%s Flux Histogram" % (c_title)
            # from header
            fCBtitle = r"Flux ($10^{-20}$ erg s$^{-1}$ cm$^{-2}$)"
            f_min, f_max = set_lims(D.e_line[c].flux, positive=True)

            saveTo = "%s/%s_flux_hist.png" % (out_plots, c)
            plot_histogram(D.e_line[c].flux,
                           galaxy=galaxy.upper(),
                           redshift=z,
                           vmin=f_min,
                           vmax=f_max,
                           weights=D.n_spaxels_in_bin,
                           title=fh_title,
                           xaxis=fCBtitle,
                           save=saveTo)

            ax = f.add_subplot(111, aspect='equal')
            saveTo = "%s/%s_img.png" % (out_nointerp, c)
            ax.saveTo = saveTo

            ax = plot_velfield_nointerp(
                D.x,
                D.y,
                D.bin_num,
                D.xBar,
                D.yBar,
                D.e_line[c].flux,
                header,
                vmin=f_min,
                vmax=f_max,
                colorbar=True,
                nodots=True,
                label=fCBtitle,
                title=f_title,
                ax=ax,
                redshift=z,
                flux_unbinned=D.unbinned_flux,
                center=center,
                galaxy=galaxy.upper())  #, signal_noise=D.e_line[c].amp_noise,
            # signal_noise_target=5)
            #cmap = 'gist_yarg')
            ax_array.append(ax)
            f.delaxes(ax)
            f.delaxes(ax.cax)
            if hasattr(ax, 'ax2'): f.delaxes(ax.ax2)
            if hasattr(ax, 'ax3'): f.delaxes(ax.ax3)

            if plots: plt.show()

            # Uncertainy in flux
            fu_title = "%s Flux Uncertainty" % (c_title)
            f_uncert_min, f_uncert_max = set_lims(D.e_line[c].flux.uncert,
                                                  positive=True)

            saveTo = "%s/%s_img_uncert.png" % (out_nointerp, c)
            ax1 = plot_velfield_nointerp(D.x,
                                         D.y,
                                         D.bin_num,
                                         D.xBar,
                                         D.yBar,
                                         D.e_line[c].flux.uncert,
                                         header,
                                         vmin=f_uncert_min,
                                         vmax=f_uncert_max,
                                         flux_unbinned=D.unbinned_flux,
                                         nodots=True,
                                         colorbar=True,
                                         label=fCBtitle,
                                         galaxy=galaxy.upper(),
                                         title=fu_title,
                                         save=saveTo,
                                         close=True,
                                         center=center)

            # Equivalent Width
            eq_title = "%s Equivalent Width" % (c_title)
            eqh_title = "%s Equivalent Width Histogram" % (c_title)
            eqCBtitle = r"Equivalent Width ($\AA$)"

            eq_min, eq_max = set_lims(D.e_line[c].equiv_width)

            saveTo = "%s/%s_eqWidth_hist.png" % (out_plots, c)
            plot_histogram(D.e_line[c].equiv_width,
                           galaxy=galaxy.upper(),
                           redshift=z,
                           vmin=eq_min,
                           vmax=eq_max,
                           weights=D.n_spaxels_in_bin,
                           title=eqh_title,
                           xaxis=eqCBtitle,
                           save=saveTo)

            ax = f.add_subplot(111, aspect='equal')
            saveTo = "%s/%s_equiv_width.png" % (out_nointerp, c)
            ax.saveTo = saveTo

            ax = plot_velfield_nointerp(
                D.x,
                D.y,
                D.bin_num,
                D.xBar,
                D.yBar,
                D.e_line[c].equiv_width,
                header,
                vmin=eq_min,
                vmax=eq_max,
                colorbar=True,
                nodots=True,
                label=eqCBtitle,
                title=eq_title,
                ax=ax,
                flux_unbinned=D.unbinned_flux,
                # signal_noise=D.e_line[c].amp_noise, signal_noise_target=5,
                center=center,
                galaxy=galaxy.upper(),
                redshift=z)
            ax_array.append(ax)
            f.delaxes(ax)
            f.delaxes(ax.cax)
            if hasattr(ax, 'ax2'): f.delaxes(ax.ax2)
            if hasattr(ax, 'ax3'): f.delaxes(ax.ax3)

            # Uncertainy in EW
            equ_title = "%s Equivalent Width Uncertainty" % (c_title)
            eq_uncert_min, eq_uncert_max = set_lims(
                D.e_line[c].equiv_width.uncert, positive=True)

            saveTo = "%s/%s_equiv_width_uncert.png" % (out_nointerp, c)
            ax1 = plot_velfield_nointerp(D.x,
                                         D.y,
                                         D.bin_num,
                                         D.xBar,
                                         D.yBar,
                                         D.e_line[c].equiv_width.uncert,
                                         header,
                                         vmin=eq_uncert_min,
                                         vmax=eq_uncert_max,
                                         flux_unbinned=D.unbinned_flux,
                                         nodots=True,
                                         colorbar=True,
                                         label=eqCBtitle,
                                         galaxy=galaxy.upper(),
                                         title=equ_title,
                                         save=saveTo,
                                         close=True,
                                         center=center)
# ------------============ Amplitude/Noise ==============----------
    if mapping.amp_noise:
        for c in D.e_components:
            if 'OIII' in c:
                c_title = '[OIII]'
            elif 'Hbeta' in c:
                c_title = r'H$_\beta$'
            elif 'Hgamma' in c:
                c_title = r'H$_\gamma$'
            else:
                c_title = c
            if 'n_' in c_title or 'n_' in c:
                c_title = 'Narrow line ' + c_title.strip('n_')

            amp_title = '%s Amplitude to Noise ratio' % (c_title)
            amp_min, amp_max = set_lims(D.e_line[c].amp_noise, positive=True)
            saveTo = "%s/%s_amp_noise.png" % (out_nointerp, c)

            ax1 = plot_velfield_nointerp(D.x,
                                         D.y,
                                         D.bin_num,
                                         D.xBar,
                                         D.yBar,
                                         D.e_line[c].amp_noise,
                                         header,
                                         vmin=amp_min,
                                         vmax=amp_max,
                                         colorbar=True,
                                         nodots=True,
                                         title=amp_title,
                                         save=saveTo,
                                         close=True,
                                         flux_unbinned=D.unbinned_flux,
                                         center=center)
# ------------=========== Setting titles etc ============----------
    if mapping.kinematics:
        print '    Kinematics'
        # for c in ['stellar']: # For debugging
        for c in D.independent_components:
            print '        %s' % (c)

            im_type = c
            pl = c
            if "gas" in im_type:
                im_type = ""
                pl = '[OIII]5007d'
            elif "SF" in im_type:
                im_type = " (Star Forming)"
                pl = '[OIII]5007d'
            elif "Shocks" in im_type:
                im_type = " (Shocking)"
                pl = 'Hbeta'
            elif 'Hbeta' in im_type:
                im_type = " (" + r'H$_\beta$' + ")"
            elif 'Hgamma' in im_type:
                im_type = " (" + r'H$_\gamma$' + ")"
            elif 'OIII' in im_type:
                im_type = " (OIII)"
            else:
                im_type = " (" + im_type + ")"

            if 'n_' in im_type or 'n_' in c:
                im_type = 'Narrow line ' + im_type.strip('n_')
                pl = 'n_' + pl.strip('n_')

            SNR = D.SNRatio
            SN_target_kine = SN_target
            if pl != 'stellar':
                SNR = D.gas_dynamics_SN
                SN_target_kine = 5

            for k in D.components[pl].plot.keys():

                symmetric = False
                positive = False

                CBLabel = None
                if k == "vel":
                    title = 'Velocity'
                    CBLabel = r"V (km s$^{-1}$)"
                    symmetric = True

                if k == "sigma":
                    title = 'Velocity Dispersion'
                    CBLabel = r'$\mathrm{\sigma}$ (km s$^{-1}$)'
                    positive = True

                if k == "h3":
                    title = 'h3'
                    symmetric = True
                    CBLabel = r"h$_3$ (km s$^{-1}$)"

                if k == "h4":
                    title = 'h4'
                    CBLabel = r"h$_4$ (km s$^{-1}$)"

                if c == "stellar":
                    utitle = "Stellar Uncertainty " + title + " Map"
                    htitle = "Stellar " + title + " Histogram"
                    uhtitle = "Stellar Uncertainty " + title + " Histogram"
                    title = "Stellar " + title + " Map"
                else:
                    utitle = "Ionised" + im_type + " Gas Uncertainty " + title + \
                     " Map"
                    htitle = "Ionised" + im_type + " Gas " + title + " Histogram"
                    uhtitle = "Ionised" + im_type + " Gas Uncertainty " + title + \
                     " Histogram"
                    title = "Ionised" + im_type + " Gas\n" + title + " Map"
# ------------============ Setting v range ==============----------
                vmin, vmax = set_lims(D.components[pl].plot[k],
                                      positive=positive,
                                      symmetric=symmetric)
                v_uncert_min, v_uncert_max = set_lims(
                    D.components[pl].plot[k].uncert, positive=True)
                # # ------------============== Plot Histogram =============----------
                # Field histogram
                # saveTo = "%s/%s_hist_%s.png" % (out_plots, plot_title)
                # plot_histogram(D.components[c].plot[k], galaxy=galaxy.upper(),
                # 	redshift=z, vmin=vmin,vmax=vmax, weights=D.n_spaxels_in_bin,
                # 	title=htitle, xaxis=CBLabel, save=saveTo)
                # # Uncertainty histogram
                # saveTo = "%s/%s_hist_%s.png" % (out_plots, plot_title+'_uncert',
                # 	wav_range)
                # plot_histogram(D.components[c].plot[k].uncert,
                # 	galaxy=galaxy.upper(), redshift=z, vmin=v_uncert_min,
                # 	vmax=v_uncert_max, weights=D.n_spaxels_in_bin, title=uhtitle,
                # 	xaxis=CBLabel, save=saveTo)

                # if plots:
                # 	plt.show()
                # ------------==== Plot velfield - no interperlation ====----------
                # Field plot
                ax = f.add_subplot(111, aspect='equal')
                saveTo = ("%s/%s_%s_field.png" % (out_nointerp, c, k))
                ax.saveTo = saveTo
                ax = plot_velfield_nointerp(D.x,
                                            D.y,
                                            D.bin_num,
                                            D.xBar,
                                            D.yBar,
                                            D.components[pl].plot[k],
                                            header,
                                            vmin=vmin,
                                            vmax=vmax,
                                            flux_unbinned=D.unbinned_flux,
                                            nodots=True,
                                            colorbar=True,
                                            label=CBLabel,
                                            galaxy=galaxy.upper(),
                                            redshift=z,
                                            title=title,
                                            ax=ax,
                                            signal_noise=SNR,
                                            signal_noise_target=SN_target_kine,
                                            center=center)
                # add_R_e(ax, galaxy, pa=pa)
                if plots:
                    plt.show()
                ax_array.append(ax)
                f.delaxes(ax)
                f.delaxes(ax.cax)
                if hasattr(ax, 'ax2'): f.delaxes(ax.ax2)
                if hasattr(ax, 'ax3'): f.delaxes(ax.ax3)

                # Uncertainty plot
                saveTo = "%s/%s_%s_uncert_field.png" % (out_nointerp, c, k)
                ax1 = plot_velfield_nointerp(D.x,
                                             D.y,
                                             D.bin_num,
                                             D.xBar,
                                             D.yBar,
                                             D.components[pl].plot[k].uncert,
                                             header,
                                             vmin=v_uncert_min,
                                             vmax=v_uncert_max,
                                             flux_unbinned=D.unbinned_flux,
                                             nodots=True,
                                             colorbar=True,
                                             label=CBLabel,
                                             galaxy=galaxy.upper(),
                                             title=utitle,
                                             save=saveTo,
                                             close=True,
                                             center=center)
                if plots:
                    plt.show()
# ------------============= Plot residuals ==============----------
    if residual and (mapping.plot_resid):
        print "    " + residual + " residuals"

        average_residuals = np.zeros(D.number_of_bins)
        for i, bin in enumerate(D.bin):
            residuals = np.abs(bin.spectrum - bin.bestfit) / bin.spectrum
            # remove edge pixels
            residuals = np.delete(
                residuals,
                [np.arange(5), len(residuals) + np.arange(-5, 0)],
                axis=0)

            if residual == "mean":
                average_residuals[i] = np.mean(residuals)
            elif residual == "median":
                average_residuals[i] = np.median(residuals)
            elif residual == "max":
                average_residuals[i] = np.max(np.abs(residuals))

        minres, maxres = set_lims(average_residuals, positive=True)

        CBLabel = "Residuals"
        title = "Fractional " + str.capitalize(residual) + " Residuals"
        saveTo = "%s/%s_residual.png" % (out_nointerp, residual)

        ax1 = plot_velfield_nointerp(D.x,
                                     D.y,
                                     D.bin_num,
                                     D.xBar,
                                     D.yBar,
                                     average_residuals,
                                     header,
                                     vmin=minres,
                                     vmax=maxres,
                                     flux_type='notmag',
                                     nodots=True,
                                     colorbar=True,
                                     label=CBLabel,
                                     galaxy=galaxy.upper(),
                                     title=title,
                                     save=saveTo,
                                     close=True,
                                     center=center,
                                     flux_unbinned=D.unbinned_flux)
        if plots:
            plt.show()
# # ------------=============== Plot Chi2/DOF =============----------
# print "    chi2"

# chi2 = np.zeros(D.number_of_bins)
# for i in range(D.number_of_bins):
# 	chi2[i] = np.loadtxt("%s/chi2/%d.dat" % (vin_dir_gasMC, i))

# minchi2, maxchi2 = set_lims(chi2, positive = True)

# CBLabel = "Chi2/DOF"
# title = "Chi2/DOF of the bestfit"
# saveTo = "%s/chi2_%s.png" % (out_nointerp)

# ax1 = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, chi2,
# 	vmin=minchi2, vmax=maxchi2, flux_type='notmag',
# 	nodots=True, show_bin_num=show_bin_num, colorbar=True,
# 	label=CBLabel, flux_unbinned=D.unbinned_flux,
# 	galaxy = galaxy.upper(), redshift = z, title=title,
# 	save=saveTo, close=not overplot=={}, center=center)#, cmap=cm.blue)
# if plots:
# 	plt.show()
# if overplot:
# 	ax1.saveTo = saveTo
# 	for o, c in overplot.iteritems():
# 		add_(o, c, ax1, galaxy, header, close=True)
# ------------============ Line ratio maps ==============----------
# if any('OIII' in o for o in D.list_components) and line_ratios:
    if len(D.list_components) > 2 and mapping.line_ratios and \
     not D.broad_narrow:

        print "    line ratios"
        if 'Halpha' in D.list_components and 'Hbeta' in D.list_components:
            CBtitle = r'$H_\alpha/H_\beta/2.8$'
            saveTo = "%s/lineratio/Dust.png" % (out_nointerp)
            dust = D.e_line['Halpha'].flux / D.e_line['Hbeta'].flux / 2.8

            d_min, d_max = set_lims(dust)

            ax1 = plot_velfield_nointerp(D.x,
                                         D.y,
                                         D.bin_num,
                                         D.xBar,
                                         D.yBar,
                                         dust,
                                         header,
                                         vmin=d_min,
                                         vmax=d_max,
                                         colorbar=True,
                                         nodots=True,
                                         title='Balmer Decrement',
                                         label=CBtitle,
                                         galaxy=galaxy.upper(),
                                         redshift=z,
                                         center=center,
                                         save=saveTo,
                                         close=not overplot,
                                         flux_unbinned=D.unbinned_flux)
            for o, c in overplot.iteritems():
                add_(o, c, ax1, galaxy)
            else:
                plt.close()

        t_num = (len(D.e_components) - 1) * len(D.e_components) / 2
        for n in range(t_num):
            i = 0
            m = t_num
            while m > n:
                i += 1
                m -= i

            cA = D.e_components[len(D.e_components) - i - 1]
            cB = D.e_components[len(D.e_components) - i + n - m]

            # Always put Balmer lines on the denominator
            if ('[' in cA) and ('H' in cB):
                cA, cB = cB, cA

            line_ratio = np.log10(D.e_line[cB].flux / D.e_line[cA].flux)
            if 'OIII' in cA:
                cA_title = '[OIII]'
            elif 'Hbeta' in cA:
                cA_title = r'H$_\beta$'
            elif 'Hdelta' in cA:
                cA_title = r'H$_\delta$'
            elif 'Hgamma' in cA:
                cA_title = r'H$_\gamma$'
            else:
                cA_title = cA

            if 'OIII' in cB:
                cB_title = '[OIII]'
            elif 'Hbeta' in cB:
                cB_title = r'H$_\beta$'
            elif 'Hdelta' in cB:
                cB_title = r'H$_\delta$'
            elif 'Hgamma' in cB:
                cB_title = r'H$_\gamma$'
            else:
                cB_title = cB

            lr_title = "%s/%s Line Ratio" % (cB_title, cA_title)
            lrCBtitle = r"log$_{10}$ (%s/%s)" % (cB_title, cA_title)

            lr_min, lr_max = set_lims(line_ratio)

            ax = f.add_subplot(111, aspect='equal')
            saveTo = "%s/lineratio/%s_%s_line_ratio.png" % (out_nointerp, cB,
                                                            cA)
            ax.saveTo = saveTo
            ax.figx, ax.figy = n % 3, n_rows - int(np.ceil(t_num / 3)) + int(
                np.ceil(n / 3))

            ANRatio = np.min([D.e_line[cA].amp_noise, D.e_line[cB].amp_noise],
                             axis=0)

            ax = plot_velfield_nointerp(D.x,
                                        D.y,
                                        D.bin_num,
                                        D.xBar,
                                        D.yBar,
                                        line_ratio,
                                        header,
                                        vmin=lr_min,
                                        vmax=lr_max,
                                        colorbar=True,
                                        nodots=True,
                                        title=lr_title,
                                        label=lrCBtitle,
                                        ax=ax,
                                        galaxy=galaxy.upper(),
                                        redshift=z,
                                        center=center,
                                        flux_unbinned=D.unbinned_flux,
                                        signal_noise=ANRatio,
                                        signal_noise_target=5)

            ax_array.append(ax)
            f.delaxes(ax)
            f.delaxes(ax.cax)
            if hasattr(ax, 'ax2'): f.delaxes(ax.ax2)
            if hasattr(ax, 'ax3'): f.delaxes(ax.ax3)

# ------------============= Plot and save ===============----------
    print "    Plotting and saving"

    for i, a in enumerate(ax_array):
        f.add_axes(a)
        a.axis('tight')
        f.add_axes(a.cax)
        if hasattr(a, 'ax2'): f.add_axes(a.ax2)
        if hasattr(a, 'ax3'): f.add_axes(a.ax3)

        if not os.path.exists(os.path.dirname(a.saveTo)):
            os.makedirs(os.path.dirname(a.saveTo))
        plt.savefig(a.saveTo, bbox_inches="tight")

        if overplot:
            for o, c in overplot.iteritems():
                add_(o, c, a, galaxy)

        f.delaxes(a)
        f.delaxes(a.cax)
        if hasattr(a, 'ax2'): f.delaxes(a.ax2)
        if hasattr(a, 'ax3'): f.delaxes(a.ax3)

    return D
Example #17
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]))
Example #18
0
def pickler(galaxy,
            discard=0,
            norm='',
            opt="kin",
            override=False,
            save_fits=True):
    print "    Loading D"

    tessellation_File = "%s/%s/%s/setup/voronoi_2d_binning_output.txt" % (
        vin_dir, galaxy, opt)
    tessellation_File2 = "%s/%s/%s/setup/voronoi_2d_binning_output2.txt" % (
        vin_dir, galaxy, opt)
    dataCubeDirectory = get_dataCubeDirectory(galaxy)
    output = "%s/%s/%s" % (out_dir, galaxy, opt)
    vin_dir_gasMC = "%s/%s/%s/MC" % (vin_dir, galaxy, opt)
    # out_pickle = '%s/pickled' % (output)

    # Check tessellation file is older than pPXF outputs (checks
    # vin_dir_gasMC/0.dat only).
    if not override:
        if os.path.getmtime(tessellation_File) > os.path.getmtime(
                '%s/0.dat' % (vin_dir_gasMC)):
            bin_num = np.loadtxt(tessellation_File,
                                 unpack=True,
                                 skiprows=1,
                                 usecols=(2, ),
                                 dtype=int)
            if os.path.exists('%s/%i.dat' % (vin_dir_gasMC,max(bin_num))) and not \
             os.path.exists('%s/%i.dat' % (vin_dir_gasMC, max(bin_num)+1)):
                # Issue warning, but do not stop.
                warnings.warn('WANING: The tesselation file '+\
                 'voronoi_2d_binning_output.txt may to have been changed.')
            else:
                # Stop and raise exception
                raise UserWarning('WANING: The tesselation file '+\
                 'voronoi_2d_binning_output.txt has been overwritten. ' + \
                 "Use the 'override' keyword to run this routine anyway.")
# ------------======== Reading the spectrum  ============----------
    D = Data(np.loadtxt(tessellation_File,
                        unpack=True,
                        skiprows=1,
                        usecols=(0, 1, 2)),
             sauron=True)

    galaxy_data = fits.getdata(dataCubeDirectory, 0)

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

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

    D.unbinned_flux = np.nansum(galaxy_data, axis=0)

    for i in range(D.number_of_bins):
        D.bin[i].spectrum = np.loadtxt("%s/input/%d.dat" % (vin_dir_gasMC, i),
                                       unpack=True)
        D.bin[i].noise = np.loadtxt("%s/noise_input/%d.dat" %
                                    (vin_dir_gasMC, i),
                                    unpack=True)
        D.bin[i].lam = np.loadtxt("%s/lambda/%d.dat" % (vin_dir_gasMC, i))

        # Getting emission templates used
        lines = {
            'Hdelta': 4101.76,
            'Hgamma': 4340.47,
            'Hbeta': 4861.33,
            '[OIII]5007d': 5004.0,
            '[NI]d': 5200.0,
            'Halpha': 6562.8,
            '[SII]6716': 6716.0,
            '[SII]6731': 6731.0,
            '[OI]6300d': 6300.0,
            '[NII]6583d': 6583.0
        }
        matrix = np.loadtxt("%s/bestfit/matrix/%d.dat" % (vin_dir_gasMC, i),
                            dtype=str)
        ms = matrix.shape
        for j in range(ms[0]):
            if not matrix[j, 0].isdigit():
                line = matrix[j, 0]
                D.bin[i].components[matrix[j, 0]] = emission_line(
                    D.bin[i], line, lines[line.strip('n_')],
                    matrix[j, 1:].astype(float))
                # Skip step if file is empty.
                with warnings.catch_warnings():
                    warnings.simplefilter('error')
                    try:
                        D.bin[i].components[line].uncert_spectrum = np.loadtxt(
                            '%s/gas_uncert_spectrum/%s/%i.dat' %
                            (vin_dir_gasMC, line, i))
                    except Warning:
                        pass
                D.add_e_line(matrix[j, 0], lines[line.strip('n_')])

        D.bin[i].bestfit = np.loadtxt("%s/bestfit/%d.dat" % (vin_dir_gasMC, i),
                                      unpack=True)
        if 'kin' in opt:
            D.bin[i].apweight = np.loadtxt("%s/apweights/%d.dat" %
                                           (vin_dir_gasMC, i),
                                           unpack=True)
        elif 'pop' in opt:
            D.bin[i].mpweight = np.loadtxt("%s/mpweights/%d.dat" %
                                           (vin_dir_gasMC, i),
                                           unpack=True)

        #Setting the weighting given to the gas templates
        temp_name, temp_weight = np.loadtxt("%s/temp_weights/%d.dat" %
                                            (vin_dir_gasMC, i),
                                            unpack=True,
                                            dtype='str')
        D.bin[i].set_templates(temp_name, temp_weight.astype(float))

    D.xBar, D.yBar = np.loadtxt(tessellation_File2,
                                unpack=True,
                                skiprows=1,
                                ndmin=2)
    # ------------=========== Read kinematics results ==============----------
    componants = [d for d in os.listdir(vin_dir_gasMC + "/gas") if \
     os.path.isdir(os.path.join(vin_dir_gasMC + "/gas", d))] if \
     os.path.exists(vin_dir_gasMC + "/gas") else []

    if len(componants) == 0: gas = 0
    elif 'gas' in componants: D.gas = 1
    elif 'Shocks' in componants and 'SF' in componants: D.gas = 2
    else: D.gas = 3

    if any(['n_' in c for c in componants]): D.broad_narrow = True
    else: D.broad_narrow = False

    for c in D.list_components:
        dynamics = {
            'vel': np.zeros(D.number_of_bins) * np.nan,
            'sigma': np.zeros(D.number_of_bins) * np.nan,
            'h3': np.zeros(D.number_of_bins) * np.nan,
            'h4': np.zeros(D.number_of_bins) * np.nan
        }
        dynamics_uncert = {
            'vel': np.zeros(D.number_of_bins) * np.nan,
            'sigma': np.zeros(D.number_of_bins) * np.nan,
            'h3': np.zeros(D.number_of_bins) * np.nan,
            'h4': np.zeros(D.number_of_bins) * np.nan
        }

        for bin in range(D.number_of_bins):
            # Bestfit values
            glamdring_file = "%s/%i.dat" % (vin_dir_gasMC, bin)
            c_in_bin = np.loadtxt(glamdring_file,
                                  unpack=True,
                                  usecols=(0, ),
                                  dtype=str)

            if D.gas == 1 and c != 'stellar':
                if 'n_' not in c:
                    c_type = 'gas'
                else:
                    c_type = 'n_gas'
            elif D.gas == 2 and c != 'stellar':
                if 'n_' not in c:
                    if 'H' in c:
                        c_type = 'SF'
                    else:
                        c_type = 'Shocks'
                else:
                    if 'H' in c:
                        c_type = 'n_SF'
                    else:
                        c_type = 'n_Shocks'
            else:
                c_type = c

            # check componant is in bin
            if c_type in c_in_bin:
                i = np.where(c_in_bin == c_type)[0][0]
                with open(glamdring_file, 'r') as g:
                    rows = g.read().splitlines()
                    row = np.array(rows[i].split('   '))
                for j, d in enumerate(['vel', 'sigma', 'h3', 'h4']):
                    try:
                        dynamics[d][bin] = float(row[j + 1])
                    except IndexError:
                        pass

                # Calculating uncertainties
                if c_type != "stellar": MC_dir = "%s/gas" % (vin_dir_gasMC)
                else: MC_dir = vin_dir_gasMC

                glamdring_file = '%s/%s/%i.dat' % (MC_dir, c_type, bin)
                # Ignore empty file warnings
                with warnings.catch_warnings():
                    warnings.simplefilter("ignore")
                    f = np.loadtxt(glamdring_file, unpack=True)
                # Check if MC has been run.
                if len(f) != 0:
                    for j, d in enumerate(['vel', 'sigma', 'h3', 'h4']):
                        try:
                            dynamics_uncert[d][bin] = np.std(f[j, :])
                        except IndexError:
                            pass
                else:
                    pass  # uncert array is already nan

        for kine in dynamics.keys():
            if np.isnan(dynamics[kine]).all():
                D.components_no_mask[c].unset(kine)
            else:
                D.components_no_mask[c].setkin(kine, dynamics[kine])
                D.components_no_mask[c].setkin_uncert(kine,
                                                      dynamics_uncert[kine])

    if norm != '':
        D.norm_method = norm
    D.find_restFrame()
    # ------------================ Pickling =================----------
    print "    Pickling D"
    # if not os.path.exists(out_pickle):
    # 	os.makedirs(out_pickle)
    # pickleFile = open("%s/dataObj.pkl" % (out_pickle), 'wb')
    # pickle.dump(D,pickleFile)
    # pickleFile.close()
    # if 'kin' in opt:
    # 	save(galaxy, instrument='muse', stellar=True, emission=False,
    # 		absorption=False, absorption_nomask=False, population=False,
    # 		kin_opt=opt, pop_opt='pop', D=D, D2=D)
    # if 'pop' in opt:
    # 	save(galaxy, instrument='muse', stellar=False, emission=True,
    # 		absorption=True, absorption_nomask=True, population=True,
    # 		kin_opt='kin', pop_opt=opt, D=D, D2=D)
    if save_fits:
        save(galaxy,
             instrument='muse',
             stellar=True,
             emission=True,
             absorption=True,
             absorption_nomask=True,
             population=True,
             kin_opt=opt,
             pop_opt=opt,
             D=D,
             D2=D)

    return D
def binning_spaxels(galaxy,
                    targetSN=None,
                    opt='kin',
                    auto_override=False,
                    debug=False,
                    set_range=None):
    print '     Voronoi Binning'
    # ----------===============================================---------
    # ----------============ Default parameters ===============---------
    # ----------===============================================---------
    dir = "%s/Data/muse" % (cc.base_dir)
    data_file = "%s/analysis/galaxies.txt" % (dir)
    # Check if file has anything in it - it does need to exsist.
    try:
        d = np.loadtxt(data_file, unpack=True, dtype=str)
        galaxy_gals = d[0][1:]
        x_gals, y_gals = d[1][1:].astype(int), d[2][1:].astype(int)
        SN_gals = {d[i][0]: d[i][1:].astype(float) for i in range(3, len(d))}
    except StopIteration:
        galaxy_gals = np.array([])
        x_gals = np.array([])
        y_gals = np.array([])
        SN_gals = {}

    try:
        SN_used_gals = SN_gals['SN_%s' % (opt)]
    except KeyError:
        SN_used_gals = np.zeros([len(galaxy_gals)])

    i_gal = np.where(galaxy_gals == galaxy)[0]
    if len(i_gal) == 0:
        i_gal = -1
        galaxy_gals = np.append(galaxy_gals, galaxy)

    if targetSN is None and i_gal != -1:
        targetSN = SN_used_gals[i_gal]
    elif targetSN is not None and i_gal != -1:
        targetSN = check_overwrite(float(targetSN), SN_used_gals[i_gal],
                                   auto_override)
        SN_used_gals[i_gal] = targetSN
    elif targetSN is not None and i_gal == -1:
        SN_used_gals = np.append(SN_used_gals, targetSN)
    else:
        targetSN = 30.0
        SN_used_gals = np.append(SN_used_gals, targetSN)

    if i_gal == -1:
        x_gals = np.append(x_gals, 0)
        y_gals = np.append(y_gals, 0)

        SN_gals = {t: np.append(v, 0) for t, v in SN_gals.iteritems()}

# ----------================= Save SN_used ===============---------
    SN_gals['SN_%s' % (opt)] = SN_used_gals

    temp = "{0:12}{1:4}{2:4}" + ''.join([
        '{%i:%i}' % (i + 3, len(t) + 1) for i, t in enumerate(SN_gals.keys())
    ]) + '\n'

    SN_titles = list(SN_gals.keys())
    with open(data_file, 'w') as f:
        f.write(temp.format("Galaxy", "x", "y", *(s for s in SN_titles)))
        for i in range(len(galaxy_gals)):
            f.write(
                temp.format(galaxy_gals[i], str(int(x_gals[i])),
                            str(int(y_gals[i])),
                            *(str(round(SN_gals[s][i], 2))
                              for s in SN_titles)))

# ----------================ Find S/N ================------------
# Final wildcard notes that depending on the method used the quadrants
#may or may not have been flux calibrated.
    dataCubeDirectory = get_dataCubeDirectory(galaxy)

    f = fits.open(dataCubeDirectory)
    galaxy_data, header = f[1].data, 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

    x = np.zeros(s[1] * s[2])
    y = np.zeros(s[1] * s[2])

    if set_range is not None:
        set_range[0] = max(set_range[0], CRVAL_spec)
        set_range_pix = (set_range - CRVAL_spec) / CDELT_spec
    else:
        set_range_pix = np.array([0, s[0]])
    set_range_pix = set_range_pix.astype(int)

    # collapsing the spectrum for each spaxel.
    if debug:
        signal = np.array(
            galaxy_data[int(np.mean(set_range_pix)), :, :].flatten())
        # noise = np.sqrt(galaxy_noise[s[0]/2,:,:])#.flatten())
        noise = np.sqrt(np.abs(
            galaxy_data[int(np.mean(set_range_pix)), :, :])).flatten()
    else:
        signal = np.zeros((s[1], s[2]))
        # flux = np.zeros((s[1],s[2]))
        noise = np.zeros((s[1], s[2]))
        blocks = 10
        bl_delt1 = int(np.ceil(s[1] / float(blocks)))
        bl_delt2 = int(np.ceil(s[2] / float(blocks)))
        for i in xrange(blocks):
            for j in xrange(blocks):
                # flux[bl_delt1*i:bl_delt1*(i+1),bl_delt2*j:bl_delt2*(j+1)] = np.trapz(
                # 	galaxy_data[set_range_pix[0]:set_range_pix[1],
                # 	bl_delt1*i:bl_delt1*(i+1), bl_delt2*j:bl_delt2*(j+1)], axis=0,
                # 	dx=CDELT_spec)
                signal[bl_delt1*i:bl_delt1*(i+1),bl_delt2*j:bl_delt2*(j+1)] = \
                 np.nanmedian(galaxy_data[set_range_pix[0]:set_range_pix[1],
                 bl_delt1*i:bl_delt1*(i+1), bl_delt2*j:bl_delt2*(j+1)], axis=0)
                noise[bl_delt1*i:bl_delt1*(i+1),bl_delt2*j:bl_delt2*(j+1)] = \
                 np.nanmedian(galaxy_noise[set_range_pix[0]:set_range_pix[1],
                 bl_delt1*i:bl_delt1*(i+1), bl_delt2*j:bl_delt2*(j+1)], axis=0)
        # signal_sav = np.array(signal)
        # noise_sav = np.array(noise)
        signal = signal.flatten()
        noise = noise.flatten()

        bad_pix = (signal <= 0) + (noise <= 0)
        signal[bad_pix] = np.nan
        noise[bad_pix] = np.nan
        # noise +=0.000001

    galaxy_data = []
    del galaxy_data
    galaxy_noise = []
    del galaxy_noise

    for i in range(s[1]):
        for j in range(s[2]):
            # Assign x and y
            x[i * s[2] + j] = i
            y[i * s[2] + j] = j
    # x = max(x)-x

    mask = (np.isfinite(signal)) * (np.isfinite(noise))

    # nobin = signal/noise > targetSN*2

    # signal = signal[mask + ~nobin]
    # noise = noise[mask + ~nobin]
    # x = x[mask + ~nobin]
    # y = y[mask + ~nobin]
    # n_spaxels = np.sum(mask) # include the not-for-binning-bins

    signal = signal[mask]
    noise = noise[mask]
    x = x[mask]
    y = y[mask]
    n_spaxels = np.sum(mask)

    # fig,ax=plt.subplots()
    # s1=signal_sav/(flux/s[0])
    # s_order = np.sort(s1).flatten()
    # s1[s1>s_order[-15]] = s_order[-16]
    # a= ax.imshow(s1)
    # ax.set_title("'signal'/flux")
    # fig.colorbar(a)

    # fig2,ax2=plt.subplots()
    # a = ax2.imshow(noise_sav/(flux/s[0]))
    # fig2.colorbar(a)
    # ax2.set_title("'noise'/flux")

    # fig3,ax3=plt.subplots()
    # a = ax3.imshow(noise_sav/np.sqrt(flux/s[0]))
    # fig3.colorbar(a)
    # ax3.set_title("'noise'/sqrt(flux)")
    # plt.show()

    if not os.path.exists("%s/analysis/%s/%s/setup" % (dir, galaxy, opt)):
        os.makedirs("%s/analysis/%s/%s/setup" % (dir, galaxy, opt))

    # if not debug:
    binNum, xNode, yNode, xBar, yBar, sn, nPixels, scale = voronoi_2d_binning(
        x,
        y,
        signal,
        noise,
        targetSN,
        quiet=True,
        plot=False,
        saveTo='%s/analysis/%s/%s/setup/binning.png' % (dir, galaxy, opt))
    plt.close('all')
    # else:
    # 	binNum = np.arange(len(x))
    # 	xBar = x
    # 	yBar = y

    # xBar = np.append(xBar, x[nobin])
    # yBar = np.append(yBar, y[nobin])
    # binNum = np.append(binNum, np.arange(np.sum(nobin))+max(binNum)+1)

    order = np.argsort(binNum)
    xBin = np.zeros(n_spaxels)
    yBin = np.zeros(n_spaxels)

    # spaxel number
    i = 0
    for bin in range(max(binNum) + 1):
        while i < n_spaxels and bin == binNum[order[i]]:
            xBin[order[i]] = xBar[bin]
            yBin[order[i]] = yBar[bin]
            # move onto next spaxel
            i = i + 1

# ------------================ Saving Results ===============---------------

    temp = "{0:5}{1:5}{2:8}{3:10}{4:10}\n"
    temp2 = "{0:12}{1:12}\n"

    with open(
            "%s/analysis/%s/%s/setup/voronoi_2d_binning_output.txt" %
        (dir, galaxy, opt), 'w') as f:
        f.write(temp.format('X"', 'Y"', 'BIN_NUM', 'XBIN', 'YBIN'))
        for i in range(len(xBin)):
            f.write(
                temp.format(str(int(x[i])), str(int(y[i])),
                            str(int(binNum[i])), str(round(xBin[i], 5)),
                            str(round(yBin[i], 5))))

    with open(
            "%s/analysis/%s/%s/setup/voronoi_2d_binning_output2.txt" %
        (dir, galaxy, opt), 'w') as f:
        f.write(temp2.format('XBAR', 'YBAR'))
        for i in range(len(xBar)):
            f.write(
                temp2.format(str(round(xBar[i], 5)), str(round(yBar[i], 5))))

    print 'Number of bins: ', max(binNum) + 1
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',
                     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