Beispiel #1
0
def ngc3100_NI_Hb():
	galaxy = 'ngc3100'
	opt='pop'
	instrument='vimos'
	from plot_results import add_
	from errors2 import get_dataCubeDirectory

	Prefig(size=(8,8))
	fig, ax = plt.subplots()

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

	D = Data(galaxy, instrument=instrument, opt=opt)

	ax = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, 
		D.components['[NI]d'].flux/D.components['Hbeta'].flux, header, 
		nodots=True, flux_unbinned=D.unbinned_flux, colorbar=True, ax=ax,
		label=r'$\mathrm{\frac{[NI]\lambda\lambda5197,5200}{H\beta}}$', 
		label_size=1.4)

	for o, color in {'radio':'g','CO':'w'}.iteritems():
		scale = 'log' if o == 'radio' else 'lin'
		add_(o, color, ax, galaxy, nolegend=True, scale=scale)
	ax.ax_dis.tick_params(top=True, bottom=True, left=True, right=True, 
		direction='in', which='major', length=20, width=3, labelsize='large')
	ax.ax_dis.tick_params(top=True, bottom=True, left=True, right=True, 
		direction='in', which='minor', length=10, width=3)

	fig.savefig('%s/Documents/paper/vimos/ngc3100_NI_Hb.png' % (
		cc.home_dir), dpi=300, bbox_inches='tight')
Beispiel #2
0
def H_profile(instrument='vimos'):
	from matplotlib import ticker


	if instrument=='vimos':
		galaxies = np.array(['ic1459', 'ngc0612', 'ngc3100'])
		str_galaxies = np.array(['IC 1459', 'NGC 612', 'NGC 3100'])
		cols = (4, 5)
		line = 'Hbeta'
		res = 0.67 # arcsec/pix

	elif instrument=='muse':
		galaxies = np.array(['ic1459', 'ngc1316'])
		str_galaxies = np.array(['IC 1459', 'NGC 1316'])
		cols = (1, 2)
		line = 'Halpha'
		res = 0.2 # arcsec/pix

	Prefig(size=np.array((len(galaxies), 0.43*len(galaxies)))*7)

	# if instrument=='vimos':
		# plt.rc('axes', labelsize='x-large') # facecolor='w'
		# plt.rc('xtick.major', size=10, width=2)
		# plt.rc('xtick.minor', size=10, width=2)
		# plt.rc('ytick.major', size=10, width=2)
		# plt.rc('ytick.minor', size=10, width=2)
	plt.rc('font', size=10*len(galaxies))


	fig, ax = plt.subplots(1, len(galaxies), sharey=True)

	analysis_dir = "%s/Data/%s/analysis" % (cc.base_dir, instrument)
	galaxiesFile = "%s/galaxies.txt" % (analysis_dir)
	x_cent_gals, y_cent_gals = np.loadtxt(galaxiesFile, unpack=True, 
		skiprows=1, usecols=cols, dtype=int)
	galaxy_gals = np.loadtxt(galaxiesFile, skiprows=1, usecols=(0,),
		dtype=str)


	for i, galaxy in enumerate(galaxies):
		print 'H profile:', galaxy
		if galaxy == 'ngc1316':
			D = Data(galaxy, instrument=instrument, opt='pop_test', overide=True)
		else:
			D = Data(galaxy, instrument=instrument, opt='pop')


		if instrument=='vimos':
			if galaxy=='ic1459':
				seeing_sigma = np.mean([0.82,0.84,1.20,1.26,1.10,1.27]) * 2.5
				norm_r = 2.4
				norm_y = 0.1
			elif galaxy=='ngc0612':
				seeing_sigma = np.mean([0.72,0.78,1.45,1.46,1.08,1.11]) * 2.5
				norm_r = 5
				norm_y = 0.2
			elif galaxy=='ngc3100':
				seeing_sigma = np.mean([0.76,0.82,0.75,0.82,1.16,1.20]) * 2.5
				norm_r = 2.9
				norm_y = 0.2
		elif instrument=='muse':
			from errors2_muse import get_dataCubeDirectory
			f=fits.open(get_dataCubeDirectory(galaxy))
			seeing_sigma = np.mean([f[0].header['ESO TEL AMBI FWHM START'],
				f[0].header['ESO TEL AMBI FWHM START']]) * 2.5
			if galaxy=='ic1459':
				norm_r = 1.7
				norm_y = 0.1
			elif galaxy=='ngc1316':
				norm_r = 3
				norm_y = 0.1

		i_gal = np.where(galaxy_gals==galaxy)[0][0]
		center = (x_cent_gals[i_gal], y_cent_gals[i_gal])

		r = np.sqrt((D.xBar - center[0])**2 + (D.yBar - center[1])**2) * res
		if line in D.e_components:

			H = D.e_line[line].flux

			ax[i].errorbar(r, H/np.nanmax(H), yerr=H.uncert/np.nanmax(H), 
				fmt='.', color='k')

			o = np.argsort(r)

			lim = ax[i].get_xlim()
			ax[i].set_xlim(0, min(lim[1], 22))
			lim = ax[i].get_xlim()

			x = np.arange(-seeing_sigma, lim[1], 0.01)

			y = 1/x**2
			y = ndimage.gaussian_filter1d(y, seeing_sigma) # convolve with seeing
			y = norm_y * norm_r**2 * y # normalised by eye

			ax[i].plot(x[x>=0], y[x>=0], zorder=10, color='r')
			ax[i].set_xlim(lim)

			ax[i].text(0.93*lim[1], 0.7, str_galaxies[i], ha='right')

			ax[i].set_ylim([0.01, 1.1])

			ax[i].set_yscale('log')
			ax[i].tick_params(which='major', direction='in', length=10, 
				width=2)
			ax[i].tick_params(axis='y', which='minor', direction='in', 
				length=6, width=2)
			for axis in [ax[i].xaxis, ax[i].yaxis]:
				axis.set_major_formatter(
					ticker.FuncFormatter(lambda y, _: '{:g}'.format(y)))



	if instrument == 'vimos':
		ax[0].set_ylabel(r'H$\,\beta$ normalised flux')
	if instrument == 'muse':
		ax[0].set_ylabel(r'H$\,\alpha$ normalised flux')
	for a in ax:
		a.set_xlabel('Radius (arcsec)')

	fig.subplots_adjust(wspace=0,hspace=0)
	fig.savefig('%s/Documents/paper/%s_profile.png' % (
		cc.home_dir, line), dpi=240, bbox_inches='tight')
	plt.close('all')
Beispiel #3
0
def ic4296_WHaN2():
	print 'WHaN2 for IC 4296'
	Prefig()
	fig, ax = plt.subplots()

	galaxy = 'ic4296'

	# galaxies = ['ic1459']
	# D = Ds()
	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])

	# pickleFile = open('%s/Data/muse/analysis/%s' % (cc.base_dir, galaxy) 
	# 	+ '/pop/pickled/dataObj.pkl')
	# D = pickle.load(pickleFile)
	# pickleFile.close()
	D = Data(galaxy, instrument='muse', opt='pop')

	D.sauron = True
	if all([l in D.e_components for l in ['[NII]6583d', 'Halpha']]):

		x = np.log10(D.e_line['[NII]6583d'].flux/1.34/D.e_line['Halpha'].flux)
		x_err = np.sqrt((D.e_line['[NII]6583d'].flux.uncert/
			D.e_line['[NII]6583d'].flux)**2 +
			(D.e_line['Halpha'].flux.uncert/D.e_line['Halpha'].flux)**2)/\
			np.log(10)

		y = np.log10(D.e_line['Halpha'].equiv_width)
		y_err = y.uncert

		r = np.sqrt((D.xBar-center[0])**2 + (D.yBar-center[1])**2)
		m = np.isfinite(x)*np.isfinite(y)*np.isfinite(x_err)*np.isfinite(y_err)*\
			np.isfinite(r)
		myerrorbar(ax, x[m], y[m], xerr=x_err[m], yerr=y_err[m], color=r[m], 
			marker='o')

		# myerrorbar(ax, x, y, xerr=x_err, yerr=y_err, color=r, marker='o')

	ax.set_ylim([-0.1, 1.2])
	ax.set_xlim([-1., 1.])
	xlim = ax.get_xlim()
	ylim = ax.get_ylim()
	ax.axhline(np.log10(3), ls=':', c='k')

	ax.plot([-0.4, -0.4], [np.log10(3), ylim[1]], ls=':', c='k')
	ax.plot([-0.4, xlim[1]], [np.log10(6), np.log10(6)], ls=':', c='k')

	ax.set_xlim(xlim)
	ax.set_ylim(ylim)
	ax.set_ylabel(r'log(EW(H$_\alpha$)/$\AA$)')
	ax.set_xlabel(r'log [NII]$\lambda$6548/H$\,\alpha$')
	ax.text(-0.95, 1., 'Star Forming')
	ax.text(-0.3, 1., 'Strong AGN')
	ax.text(-0.3, 0.65, 'Weak AGN')
	ax.text(-0.95, 0.3,'Retired Galaxies')

	fig.savefig('%s/Documents/paper/WHaN2.png' % (cc.home_dir), dpi=240)
Beispiel #4
0
def WHbN1():
	Prefig()
	fig, ax = plt.subplots()

	galaxies = np.array(['ic1459', 'ic1531', 'ic4296', 'ngc3100', 'ngc3557', 
		'ngc7075'])
	str_galaxies = np.array(['IC 1459', 'IC 1531', 'IC 4296', 'NGC 3100', 
		'NGC 3557', 'NGC 7075'])
	c = np.array(['b', 'orange', 'g', 'r', 'mediumorchid', 'saddlebrown'])

	# galaxies = ['ic1459']
	# D = Ds()

	for i, galaxy in enumerate(galaxies):
		print 'WHbN1:', galaxy
		D = Data(galaxy, instrument='vimos', opt='pop')

		if all([l in D.e_components for l in ['[NI]d', 'Hbeta']]):

			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)

			y = np.log10(D.e_line['Hbeta'].equiv_width)
			y_err = y.uncert

			m = (D.components['[NI]d'].equiv_width < 0.5) * (
				D.components['Hbeta'].equiv_width < EqW_Ha_to_EqW_Hb(0.5))

			ax.errorbar(x[~m], y[~m], xerr=x_err[~m], yerr=y_err[~m], 
				label=str_galaxies[i], fmt='o', ms=9, c=c[i])

			ax.errorbar(x[m], y[m], xerr=x_err[m], yerr=y_err[m], fmt='x', ms=9, 
				c=c[i])

	ax.legend(loc=3)

	ax.set_ylim([-1., 0.6])
	ax.set_xlim([-1.75, 0.75])
	xlim = ax.get_xlim()
	ylim = ax.get_ylim()
	ax.axhline(np.log10(EqW_Ha_to_EqW_Hb(3)), ls=':', c='k')

	ax.plot([log_NII_Ha_to_NI_Hb(-0.4), log_NII_Ha_to_NI_Hb(-0.4)],
		[np.log10(EqW_Ha_to_EqW_Hb(3)), ylim[1]], ls=':', c='k')
	ax.plot([log_NII_Ha_to_NI_Hb(-0.4), xlim[1]], 
		[np.log10(EqW_Ha_to_EqW_Hb(6)), np.log10(EqW_Ha_to_EqW_Hb(6))], ls=':', 
		c='k')

	ax.set_xlim(xlim)
	ax.set_ylim(ylim)
	ax.set_ylabel(r'log(EW(H$_\beta$)/$\AA$)')
	ax.set_xlabel(r'log [NI]$\lambda\lambda$5197,5200/H$\,\beta$')
	ax.text(-1.65, 0.45, 'Star Forming')
	ax.text(-0.95, 0.45, 'Strong AGN')
	ax.text(-0.95, 0.1, 'Weak AGN')
	ax.text(-1.65, -0.2,'Retired Galaxies')

	fig.savefig('%s/Documents/paper/WHbN1.png' % (cc.home_dir), dpi=240)
Beispiel #5
0
def SAURON():
	Prefig(size=(13,10))
	fig, ax = plt.subplots()

	galaxies = np.array(['eso443-g024', 'ic1459', 'ic1531', 'ic4296', 
		'ngc0612', 'ngc1399', 'ngc3100', 'ngc3557', 'ngc7075', 
		'pks0718-34'])
	str_galaxies = np.array(['ESO 443-G24', 'IC 1459', 'IC 1531', 'IC 4296', 
		'NGC 612', 'NGC 1399', 'NGC 3100', 'NGC 3557', 'NGC 7075', 
		'PKS 718-34'])

	# galaxies = ['ic1459']
	# D = Ds()

	for i, galaxy in enumerate(galaxies):
		# pickleFile = open('%s/Data/vimos/analysis/%s' % (cc.base_dir, galaxy) 
		# 	+ '/pop/pickled/dataObj.pkl')
		# D = pickle.load(pickleFile)
		# pickleFile.close()
		D = Data(galaxy, instrument='vimos', opt='pop')

		if all([l in D.e_components for l in ['[NI]d', 'Hbeta', 
			'[OIII]5007d']]):

			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)

			y = np.log10(D.e_line['[OIII]5007d'].flux/1.35
				/ D.e_line['Hbeta'].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)

			ax.errorbar(x, y, xerr=x_err, yerr=y_err, label=str_galaxies[i],
				fmt='o', ms=9)

	ax.legend()
	ax.text(0, 1.2, 'Seyfert 2/LINER')
	ax.text(-1.9, -0.2, 'Star-forming')
	ax.text(-0.7, -0.75, 'Composite', rotation=280, va='center', ha='center')

	ax.set_xlabel(r'$\log\left(\frac{[NI]\lambda\lambda5197,5200}{H\beta}\right)$')
	ax.set_ylabel(r'$\log\left(\frac{[OIII]\lambda5007}{H\beta}\right)$')

	ax.set_xlim([-2., 1.])
	ax.set_ylim([-1.5, 1.5])
	xlim = ax.get_xlim()
	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(log_NII_Ha_to_NI_Hb(x_line[m]), y_line[m], 'k')

	y_line2 = 0.61/(x_line - 0.05) + 1.3
	m1 = y_line2 < y_line
	a = np.min(x_line[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(log_NII_Ha_to_NI_Hb(x_line2[m2]), y_line2[m2],'k--')

	## Add MAPPINGS-III grids
	add_grids(ax, '[NI]', '[OIII]')
	ax.set_xlim([-2., 1.])
	ax.set_ylim([-1.5, 1.5])


	fig.savefig('%s/Documents/paper/SAURON.png' % (cc.home_dir), dpi=240,
		bbox_inches='tight')
Beispiel #6
0
def BPT():
	from errors2_muse import get_dataCubeDirectory
	opt = 'pop'
	instrument = 'muse'
	Prefig(size=np.array((3, 2))*6, transparent=False)
	fig, ax = plt.subplots(2,3, sharey=True)
	
	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)

	for j, galaxy in enumerate(['ic1459','ngc1316']):
		i_gal = np.where(galaxy_gals==galaxy)[0][0]
		center = (x_cent_gals[i_gal], y_cent_gals[i_gal])

		D = Data(galaxy, instrument=instrument, opt=opt)
		opt = D.opt

		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':
				ax[j, i].text(-0.7, 1.2, 'Seyfert 2')
				ax[j, i].text(-1.1, -0.2, 'Star-forming')
				ax[j, i].text(0.2, -0.5, 'LINER')

				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[j, 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[j, i].plot(x_line2, y_line2, 'k')

				lab = r'$\log\left(\frac{[SII]\lambda\lambda6717,6731}{H\alpha}\right)$'
				ax[j, i].set_xlim([-1.2, 0.7])


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

				ax[j, i].text(-0.5, 1.2, 'Seyfert 2/LINER')
				ax[j, i].text(-1.9, -0.2, 'Star-forming')
				ax[j, i].text(-0.1, -0.75, 'Composite', rotation=280, va='center',
					ha='center')

				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[j, i].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[j, i].plot(x_line2[m2], y_line2[m2],'k--')

				lab = r'$\log\left(\frac{[NII]\lambda6584}{H\alpha}\right)$'

				ax[j, i].set_xlim([-2, 1])
				# add_grids(ax[j, i], '[NII]','[OIII]', x_Ha=True)

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

				ax[j, i].text(-1.5, 1.2, 'Seyfert 2')
				ax[j, i].text(-2.0, -0.2, 'Star-forming')
				ax[j, i].text(-0.6, -0.5, 'LINER')

				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[j, 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[j, i].plot(x_line2, y_line2, 'k')

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

				lab = r'$\log\left(\frac{[OI]\lambda6300}{H\alpha}\right)$'

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

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

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

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

			myerrorbar(ax[j, i], x, y, xerr=x_err, yerr=y_err, marker='.', 
				color=r)

			# ax[1, i].set_xlabel(r'%sH$\alpha$)' % (lab), size='x-large')
			ax[1, i].set_xlabel(lab, size='x-large')

	y_loc = np.mean([ax[0,0].get_position().y0, ax[1,0].get_position().y1])
	fig.text(ax[0,0].get_position().x0-0.03, y_loc, 
		r'$\log\left(\frac{[OIII]\lambda5007}{H\beta}\right)$', va='center', ha='right', 
		rotation='vertical', size='x-large')
	for i, g in enumerate(['IC 1459', 'NGC 1316']):
		loc = np.mean([ax[i,0].get_position().y0, 
			ax[i,0].get_position().y1])
		print g
		fig.text(0.06, loc, g, va='center', ha='right', 
			rotation='vertical', size='xx-large')
	for a in ax[0,:]:
		a.set_xticklabels([])


	saveTo = '%s/Documents/paper/BPT.png' % (cc.home_dir)		
	fig.subplots_adjust(wspace=0,hspace=0)
	fig.savefig(saveTo, dpi=240)
	plt.close()
Beispiel #7
0
def ngc1316_inflow():
	galaxy = 'ngc1316'
	opt = 'pop'
	instrument = 'muse'
	from plot_results_muse import add_
	from errors2_muse import get_dataCubeDirectory
	import disk_fit_functions_binned as dfn

	Prefig(size=np.array((3.6, 1))*5.5)
	fig, ax = plt.subplots(1,3)

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

	D = Data('ngc1316', instrument=instrument, opt=opt)

	vel = D.components['[OIII]5007d'].plot['vel']
	m = ~np.isnan(vel)

	d, params = dfn.disk_fit_exp(D.xBar[m], D.yBar[m], np.array(vel).copy()[m], 
		vel.uncert.copy()[m], sigclip=5.0, leeway=0., verbose=False, grid_length=150)
	d *= -1 # Seems to be slight quirk of the system.
	params[5:] *= -1
	disc = vel.copy() # reinsert nans
	disc[m] = d

	vmin, vmax = set_lims(D.components['[OIII]5007d'].plot['vel'], 
		symmetric=True, positive=False)
	ax[0] = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, 
		vel, header, vmin=vmin, max=vmax, nodots=True, flux_unbinned=D.unbinned_flux,
		colorbar=False, ax=ax[0])
	ax[1] = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, 
		disc, header, vmin=vmin, vmax=vmax, nodots=True, 
		flux_unbinned=D.unbinned_flux, colorbar=False, ax=ax[1])
	ax[2] = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, D.yBar, 
		vel - disc, header, vmin=vmin, vmax=vmax, nodots=True, 
		flux_unbinned=D.unbinned_flux, colorbar=False, ax=ax[2])

	for a in ax:
		for o, color in {'radio':'g','CO':'w'}.iteritems():
			scale = 'log' if o == 'radio' else 'lin'
			add_(o, color, a, galaxy, nolegend=True, scale=scale)
		if hasattr(a, 'ax_dis'):
			a.ax_dis.tick_params(top=True, bottom=True, left=True, 
				right=True, direction='in', which='major', length=20,
				width=3, labelsize='large')
			a.ax_dis.tick_params(top=True, bottom=True, left=True, 
				right=True, direction='in', which='minor', length=10,
				width=3)

	# Decrease gap between maps
	for i in range(len(ax)):
		for a in ax[i:]:
			ax_loc = a.get_position()
			ax_loc.x0 -= 0.03
			ax_loc.x1 -= 0.03

			a.set_position(ax_loc)
			if hasattr(a, 'ax_dis'):
				a.ax_dis.set_position(ax_loc)

	for i, t in enumerate([r'$V_\mathrm{gas}$', r'$V_\mathrm{model}$', 
		r'$V_\mathrm{residuals} = V_\mathrm{gas} - V_\mathrm{model}$']):
		fig.text(ax[i].ax_dis.get_position().x0+0.02, 
			ax[i].ax_dis.get_position().y1-0.04, t, va='top', color='w', zorder=15)

	for a in ax[1:]:
		if hasattr(a, 'ax_dis'): 
			a.ax_dis.set_yticklabels([])
			a.ax_dis.set_ylabel('')

	ax_loc = ax[2].ax_dis.get_position()
	cax = fig.add_axes([ax_loc.x1+0.03, ax_loc.y0, 0.02, ax_loc.height])
	cbar = plt.colorbar(ax[0].cs, cax=cax)
	# cbar.ax.set_yticklabels([])
	fig.text(ax_loc.x1+0.08, 0.5, r'Mean velocity (km s$^{-1}$)', 
		rotation=270, verticalalignment='center')
	
	fig.savefig('%s/Documents/paper/ngc1316_inflow.png' % (
		cc.home_dir), dpi=300, bbox_inches='tight')
Beispiel #8
0
def plot(galaxies, str_galaxies, file_name, instrument, debug=False):
	if instrument == 'vimos':
		from plot_results import add_
		from errors2 import get_dataCubeDirectory
	elif instrument == 'muse':
		from plot_results_muse import add_
		from errors2_muse import get_dataCubeDirectory

	opt = 'pop'
	overplot={'CO':'w', 'radio':'g'}
	Prefig(size=np.array((4, len(galaxies)))*7)
	fig, axs = plt.subplots(len(galaxies), 4)#, sharex=True, sharey=True)
	out_dir = '%s/Documents/paper/%s' % (cc.home_dir, instrument)

	for i, galaxy in enumerate(galaxies):
		if debug:
			from produce_plots import Ds
			D = Ds()
		else:
			D = Data(galaxy, instrument=instrument, opt=opt)
			opt = D.opt

		print galaxy

		vin_dir = '%s/Data/%s/analysis' % (cc.base_dir, instrument)
		data_file =  "%s/galaxies.txt" % (vin_dir)
		file_headings = np.loadtxt(data_file, dtype=str)[0]
		col = np.where(file_headings=='SN_%s' % (opt))[0][0]
		SN_target_gals = np.loadtxt(data_file, 
			unpack=True, skiprows=1, usecols=(col,))
		galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0,),
			dtype=str)
		i_gal = np.where(galaxy_gals==galaxy)[0][0]
		SN_target=SN_target_gals[i_gal]

		attr, vmin, vmax = np.loadtxt('%s/lims.txt' % (vin_dir), dtype=str, 
			usecols=(0,1,2), skiprows=1, unpack=True)
		vmin, vmax = vmin.astype(float), vmax.astype(float)

		f = fits.open(get_dataCubeDirectory(galaxy))
		if instrument == 'vimos':
			header = f[0].header
		elif instrument == 'muse':
			header = f[1].header
		f.close()

		plots = [
			"components['[OIII]5007d'].plot['vel']",
			"components['[OIII]5007d'].plot['sigma']",
			"components['[OIII]5007d'].plot['vel'].uncert",
			"components['[OIII]5007d'].plot['sigma'].uncert"
			]

		# Velocity
		if galaxy == 'ngc3100':
			vmin_vel, vmax_vel = -100, 100 #set_lims(
				# D.components['[OIII]5007d'].plot['vel'], symmetric=True, 
				# n_std=5)
			print 'NGC 3100 velocity scale:', vmin_vel,'km/s to ', \
				vmax_vel, 'km/s'
		else:
			vmin_vel=vmin[attr==plots[0]][0]
			vmax_vel=vmax[attr==plots[0]][0]

		axs[i,0] = plot_velfield_nointerp(D.x, D.y, D.bin_num, 
			D.xBar, D.yBar, D.components['[OIII]5007d'].plot['vel'], header, 
			vmin=vmin_vel, vmax=vmax_vel, cmap=sauron, 
			flux_unbinned=D.unbinned_flux, signal_noise=D.SNRatio, 
			signal_noise_target=SN_target, ax=axs[i,0])
		if overplot:
			for o, color in overplot.iteritems():
				scale = 'log' if o == 'radio' else 'lin'
				add_(o, color, axs[i, 0], galaxy, nolegend=True, 
					scale=scale)


		axs[i,1] = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, 
			D.yBar, D.components['[OIII]5007d'].plot['vel'].uncert, header, 
			vmin=vmin[attr==plots[2]][0], vmax=vmax[attr==plots[2]][0], 
			cmap=sauron, flux_unbinned=D.unbinned_flux, 
			signal_noise=D.SNRatio, signal_noise_target=SN_target, 
			ax=axs[i,1])

		# Velocty dispersion
		axs[i,2] = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar, 
			D.yBar, D.components['[OIII]5007d'].plot['sigma'], header, 
			vmin=vmin[attr==plots[1]][0], vmax=vmax[attr==plots[1]][0], 
			cmap=sauron, flux_unbinned=D.unbinned_flux, 
			signal_noise=D.SNRatio, signal_noise_target=SN_target, 
			ax=axs[i,2])
		if overplot:
			for o, color in overplot.iteritems():
				scale = 'log' if o == 'radio' else 'lin'
				add_(o, color, axs[i, 2], galaxy, nolegend=True, 
					scale=scale)

		axs[i,3] = plot_velfield_nointerp(D.x, D.y, D.bin_num, D.xBar,
			D.yBar, D.components['[OIII]5007d'].plot['sigma'].uncert, header, 
			vmin=vmin[attr==plots[3]][0], vmax=vmax[attr==plots[3]][0], 
			cmap=sauron, flux_unbinned=D.unbinned_flux, 
			signal_noise=D.SNRatio, signal_noise_target=SN_target, 
			ax=axs[i,3])


	for a in axs.flatten():
		if hasattr(a, 'ax_dis'):
			a.ax_dis.tick_params(top=True, bottom=True, left=True, 
				right=True, direction='in', which='major', length=20,
				width=3, labelsize='large')
			a.ax_dis.tick_params(top=True, bottom=True, left=True, 
				right=True, direction='in', which='minor', length=10,
				width=3)
			a.ax_dis.xaxis.label.set_size(22)
			a.ax_dis.yaxis.label.set_size(22)


	for a in axs[:,1:].flatten():
		if hasattr(a, 'ax_dis'): 
			a.ax_dis.set_yticklabels([])
			a.ax_dis.set_ylabel('')

	# for a in axs[range(0, len(galaxies), 2), 1:].flatten():
	# 	if hasattr(a, 'ax_dis'): 
	# 		a.ax_dis.set_yticklabels([])
	# 		a.ax_dis.set_ylabel('')
	for a in axs[:-1,:].flatten():
		if hasattr(a, 'ax_dis'): 
			a.ax_dis.set_xticklabels([])
			a.ax_dis.set_xlabel('')

	# Create gap between galaxies
	for i in range(1, len(galaxies)):
		for a in axs[i, :].flatten():
			ax_loc = a.get_position()
			ax_loc.y0 -= i*0.01
			ax_loc.y1 -= i*0.01

			a.set_position(ax_loc)
			if hasattr(a, 'ax_dis'):
				a.ax_dis.set_position(ax_loc)

	loc = np.mean([axs[0,0].get_position().x0, axs[0,1].get_position().x1])
	fig.text(loc, 0.92, r'Mean Velocity', va='top', ha='center', size='xx-large')
	loc = np.mean([axs[0,2].get_position().x0, axs[0,3].get_position().x1])
	fig.text(loc, 0.92, r'Velocity Dispersion', va='top', ha='center', 
		size='xx-large')

	for i, g in enumerate(str_galaxies):
		loc = np.mean([axs[i,0].get_position().y0, 
			axs[i,0].get_position().y1])
		fig.text(0.07, loc, g, va='center', ha='right', 
			rotation='vertical', size='xx-large')
	
	# Add colorbar
	ticks_sym = ticker.MaxNLocator(nbins=4, symmetric=True, 
		min_n_ticks=6)
	ticks_pos = ticker.MaxNLocator(nbins=4, min_n_ticks=3)
	ax_loc = axs[0,3].get_position()

	# Left
	cax = fig.add_axes([ax_loc.x1+0.06, ax_loc.y0, 0.02, ax_loc.height])
	cbar = plt.colorbar(axs[0,0].cs, cax=cax, ticks=ticks_pos)
	fig.text(ax_loc.x1+0.02, (ax_loc.y0+ax_loc.y1)/2, 
		r'Velocity (km s$^{-1}$)', rotation=90, va='center', ha='center')

	# Right
	fig.text(ax_loc.x1+0.13, (ax_loc.y0+ax_loc.y1)/2, 
		r'Velocity Dispersion (km s$^{-1}$)', rotation=270, va='center', 
		ha='center')
	cax2 = cax.twinx()
	cax2.set_ylim(axs[0,2].cs.get_clim())
	cax2.yaxis.set_major_locator(ticks_sym)
	

	# Colorbar for Uncertainy
	ax_loc = axs[1,3].get_position()
	ticks_pos = ticker.MaxNLocator(nbins=4)

	# Left
	cax = fig.add_axes([ax_loc.x1+0.06, ax_loc.y0, 0.02, ax_loc.height])
	cbar = plt.colorbar(axs[1,1].cs, cax=cax, ticks=ticks_pos)
	fig.text(ax_loc.x1+0.02, (ax_loc.y0+ax_loc.y1)/2, 
		r'Velocity Uncertainy (km s$^{-1}$)', rotation=90, va='center', 
		ha='center')

	# Right
	fig.text(ax_loc.x1+0.13, (ax_loc.y0+ax_loc.y1)/2, 
		r'Velocity Dispersion Uncertainy(km s$^{-1}$)', rotation=270, 
		va='center', ha='center')
	cax2 = cax.twinx()
	cax2.set_ylim(axs[1,3].cs.get_clim())
	cax2.yaxis.set_major_locator(ticks_pos)


	# Add extra colorbar for NGC 3100
	if 'ngc3100' in galaxies:
		loc = np.where(np.array(galaxies)=='ngc3100')[0][0]
		ax_loc = axs[loc, 3].get_position()
		ticks_sym = ticker.MaxNLocator(nbins=4, min_n_ticks=3)

		cax = fig.add_axes([ax_loc.x1+0.06, ax_loc.y0, 0.02, ax_loc.height])
		cbar = plt.colorbar(axs[loc,1].cs, cax=cax, ticks=ticks_sym)
		fig.text(ax_loc.x1+0.13, (ax_loc.y0+ax_loc.y1)/2, 
			r'Velocity for NGC 3100 (km s$^{-1}$)', rotation=270, 
			va='center', ha='center')


	if debug:
		fig.savefig('%s/%s.png' % (out_dir, 'test'), bbox_inches='tight',
			dpi=240)
	else:
		fig.savefig('%s/%s.png' % (out_dir, file_name), bbox_inches='tight',
			dpi=240)

	plt.close('all')
Beispiel #9
0
def plot(galaxy, instrument='vimos', debug=True):
	print galaxy, instrument

	# opt = 'kin'
	overplot={'CO':'c', 'radio':'g'}
	if instrument=='vimos':
		from plot_results import add_, set_lims
		from errors2 import get_dataCubeDirectory
		ext = 0
		rows = 5

		plots = [[
			'D.flux',
			"D2.components['[OIII]5007d'].flux",
			"D.components['stellar'].plot['vel']",
			"D.components['stellar'].plot['vel'].uncert",
			"D.components['stellar'].plot['sigma']",
			"D.components['stellar'].plot['sigma'].uncert"
			],[
			"D2.absorption_line('G4300')",
			"D2.absorption_line('G4300',uncert=True)[1]",
			"D2.absorption_line('Fe4383')",
			"D2.absorption_line('Fe4383',uncert=True)[1]",
			"D2.absorption_line('Ca4455')",
			"D2.absorption_line('Ca4455',uncert=True)[1]"
			],[
			"D2.absorption_line('Fe4531')",
			"D2.absorption_line('Fe4531',uncert=True)[1]",
			"D2.absorption_line('H_beta')",
			"D2.absorption_line('H_beta',uncert=True)[1]",
			"D2.absorption_line('Fe5015')",
			"D2.absorption_line('Fe5015',uncert=True)[1]"
			],[
			"D2.absorption_line('Mg_b')",
			"D2.absorption_line('Mg_b',uncert=True)[1]",
			'',
			'',
			'',
			''
			]]

		str_plots = [[
			'Flux',
			r'[OIII]$\lambda\lambda$4959,5007 Flux',
			"Stellar mean velocity",
			"Stellar mean velocity\nuncertainty",
			"Stellar velocity dispersion",
			"Stellar velocity dispersion\nuncertainty"
			],[
			"G4300",
			"G4300 uncertainty",
			"Fe4383",
			"Fe4383 uncertainty",
			"Ca4455",
			"Ca4455 uncertainty"
			],[
			"Fe4531",
			"Fe4531 uncertainty",
			r'H$\,\beta$',
			r'H$\,\beta$ uncertainty',
			"Fe5015",
			"Fe5015 uncertainty"
			],[
			r'Mg$\,$b',
			r'Mg$\,$b uncertainty',
			'',
			'',
			'',
			''
			]]
		units = [[
			'',
			'',
			r'km s$^{-1}$',
			r'km s$^{-1}$',
			r'km s$^{-1}$',
			r'km s$^{-1}$'
			],[
			r'$\AA$',
			r'$\AA$',
			r'$\AA$',
			r'$\AA$',
			r'$\AA$',
			r'$\AA$'
			],[
			r'$\AA$',
			r'$\AA$',
			r'$\AA$',
			r'$\AA$',
			r'$\AA$',
			r'$\AA$'
			],[
			r'$\AA$',
			r'$\AA$',
			'',
			'',
			'',
			''
			]]

	elif instrument == 'muse':
		from plot_results_muse import add_, set_lims
		from errors2_muse import get_dataCubeDirectory
		ext = 1
		rows = 6
		
		plots = [[
			'D.flux',
			"D2.components['[OIII]5007d'].flux",
			"D.components['stellar'].plot['vel']",
			"D.components['stellar'].plot['vel'].uncert",
			"D.components['stellar'].plot['sigma']",
			"D.components['stellar'].plot['sigma'].uncert"
			],[
			"D2.absorption_line('H_beta')",
			"D2.absorption_line('H_beta',uncert=True)[1]",
			"D2.absorption_line('Fe5015')",
			"D2.absorption_line('Fe5015',uncert=True)[1]",
			"D2.absorption_line('Mg_b')",
			"D2.absorption_line('Mg_b',uncert=True)[1]"
			],[
			"D2.absorption_line('Fe5270')",
			"D2.absorption_line('Fe5270',uncert=True)[1]",
			"D2.absorption_line('Fe5335')",
			"D2.absorption_line('Fe5335',uncert=True)[1]",
			"D2.absorption_line('Fe5406')",
			"D2.absorption_line('Fe5406',uncert=True)[1]"
			],[
			"D2.absorption_line('Fe5709')",
			"D2.absorption_line('Fe5709',uncert=True)[1]",
			"D2.absorption_line('Fe5782')",
			"D2.absorption_line('Fe5782',uncert=True)[1]",
			"D2.absorption_line('NaD')",
			"D2.absorption_line('NaD',uncert=True)[1]"
			],[
			"D2.absorption_line('TiO1',remove_badpix=True)",
			"D2.absorption_line('TiO1',uncert=True,remove_badpix=True)[1]",
			"D2.absorption_line('TiO2',remove_badpix=True)",
			"D2.absorption_line('TiO2',uncert=True,remove_badpix=True)[1]",
			'',
			''
			]]

		str_plots = [[
			'Flux',
			r'[OIII]$\lambda\lambda$4959,5007 Flux',
			"Stellar mean velocity",
			"Stellar mean velocity\nuncertainty",
			"Stellar velocity dispersion",
			"Stellar velocity dispersion\nuncertainty"
			],[
			r'H$\,\beta$',
			r'H$\,\beta$ uncertainty',
			"Fe5015",
			"Fe5015 uncertainty",
			r'Mg$\,$b',
			r'Mg$\,$b uncertainty'
			],[
			'Fe5270',
			'Fe5270 uncertainty',
			'Fe5335',
			'Fe5335 uncertainty',
			'Fe5406',
			'Fe5406 uncertainty'
			],[
			'Fe5709',
			'Fe5709 uncertainty',
			'Fe5782',
			'Fe5782 uncertainty',
			'NaD',
			'NaD uncertainty'
			],[
			'TiO1',
			'TiO1 uncertainty',
			'TiO2',
			'TiO2 uncertainty',
			'',
			''
			]]
		units = [[
			'',
			'',
			r'km s$^{-1}$',
			r'km s$^{-1}$',
			r'km s$^{-1}$',
			r'km s$^{-1}$'
			],[
			r'$\AA$',
			r'$\AA$',
			r'$\AA$',
			r'$\AA$',
			r'$\AA$',
			r'$\AA$'
			],[
			r'$\AA$',
			r'$\AA$',
			r'$\AA$',
			r'$\AA$',
			r'$\AA$',
			r'$\AA$'
			],[
			r'$\AA$',
			r'$\AA$',
			r'$\AA$',
			r'$\AA$',
			r'$\AA$',
			r'$\AA$'
			],[
			'mag',
			'mag',
			'mag',
			'mag',
			'',
			''
			]]
	if galaxy in ['ngc0612', 'pks0718-34']:
		rows -= 1 # No Mgb
	if galaxy in ['ic1459', 'ngc0612', 'ngc1316', 'ngc3100']:
		rows += 1
		plots.insert(1, [
			"D2.components['[OIII]5007d'].plot['vel']",
			"D2.components['[OIII]5007d'].plot['vel'].uncert",
			"D2.components['[OIII]5007d'].plot['sigma']",
			"D2.components['[OIII]5007d'].plot['sigma'].uncert",
			'',
			''
			])
		str_plots.insert(1, [
			r"[OIII]$\lambda\lambda$4959,5007"+"\nmean velocity",
			r"[OIII]$\lambda\lambda$4959,5007"+"\nmean velocity uncertainty",
			r"[OIII]$\lambda\lambda$4959,5007"+"\nvelocity dispersion",
			r"[OIII]$\lambda\lambda$4959,5007"+"\nvelocity dispersion\nuncertainty",
			'',
			''
			])
		units.insert(1,[
			r'km s$^{-1}$',
			r'km s$^{-1}$',
			r'km s$^{-1}$',
			r'km s$^{-1}$',
			'',
			''
			])

	Prefig(size=np.array((6, rows))*6)
	fig, axs = plt.subplots(rows, 6)
	
	out_dir = '%s/Documents/paper/' % (cc.home_dir)

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


	if debug: 
		D = Ds()
		D2 = Ds()

	vin_dir = '%s/Data/%s/analysis' % (cc.base_dir, instrument)
	data_file =  "%s/galaxies.txt" % (vin_dir)
	file_headings = np.loadtxt(data_file, dtype=str)[0]
	col = np.where(file_headings=='SN_kin')[0][0]
	col2 = np.where(file_headings=='SN_pop')[0][0]
	SN_target_kin_gals, SN_target_pop_gals = np.loadtxt(data_file, 
		unpack=True, skiprows=1, usecols=(col,col2))
	galaxy_gals = np.loadtxt(data_file, skiprows=1, usecols=(0,),dtype=str)
	i_gal = np.where(galaxy_gals==galaxy)[0][0]
	SN_target_kin=SN_target_kin_gals[i_gal]
	SN_target_pop=SN_target_pop_gals[i_gal]

	# attr, vmin, vmax = np.loadtxt('%s/lims.txt' % (vin_dir), dtype=str, 
	# 	usecols=(0,1,2), skiprows=1, unpack=True)
	# vmin, vmax = vmin.astype(float), vmax.astype(float)

	vin_dir2 = str(vin_dir + '/%s/pop' % (galaxy)) 
	vin_dir += '/%s/kin' % (galaxy) 

	if not debug:
		# pickle_file = '%s/pickled' % (vin_dir)
		# pickleFile = open("%s/dataObj.pkl" % (pickle_file), 'rb')
		# D = pickle.load(pickleFile)
		# pickleFile.close()
		# pickle_file2 = '%s/pickled' % (vin_dir2)
		# pickleFile2 = open("%s/dataObj.pkl" % (pickle_file2), 'rb')
		# D2 = pickle.load(pickleFile2)
		# pickleFile2.close()
		D = Data(galaxy, instrument=instrument, opt='kin')
		D2 = Data(galaxy, instrument=instrument, opt='pop')

	for i, row in enumerate(plots):
		for j, p in enumerate(row):
			# print i, j, p
			if galaxy in ['ngc0612', 'pks0718-34'] and 'Mg_b' in p:
				break # break out of for-loop
			elif galaxy in ['ngc1399', 'pks0718-34'] and 'OIII' in p:
				axs[i,j].remove()
			elif 'flux' in p:
				if p == 'D.flux':
					axs[i,j] = plot_velfield_nointerp(D.x, D.y, D.bin_num, 
						D.xBar, D.yBar, eval(p), header, cmap='gist_yarg', 
						flux_unbinned=D.unbinned_flux, galaxy=str_plots[i][j],
						ax=axs[i,j])
				elif p == "D2.components['[OIII]5007d'].flux":
					axs[i,j] = plot_velfield_nointerp(D2.x, D2.y, D2.bin_num, 
						D2.xBar, D2.yBar, eval(p), header, cmap='gist_yarg', 
						flux_unbinned=D2.unbinned_flux, galaxy=str_plots[i][j],
						ax=axs[i,j])

				if overplot and p != '' and 'uncert' not in p:
					for o, color in overplot.iteritems():
						scale = 'log' if o == 'radio' else 'lin'
						add_(o, color, axs[i,j], galaxy, nolegend=True, scale=scale)
				if i > 0:
					if plots[i-1][j] != '' and hasattr(axs[i-1,j], 'ax_dis'):
						axs[i-1,j].ax_dis.set_xticklabels([])
						axs[i-1,j].ax_dis.set_xlabel('')
				if j > 0:
					if plots[i][j-1] != '' and hasattr(axs[i,j-1], 'ax_dis'):
						axs[i,j].ax_dis.set_yticklabels([])
						axs[i,j].ax_dis.set_ylabel('')

			elif p != '':
				vmin, vmax = set_lims(eval(p), 
					symmetric = 'vel' in p and 'uncert' not in p,
					positive = not ('vel' in p and 'uncert' not in p))
				if 'D2' in p:
					axs[i,j] = plot_velfield_nointerp(D2.x, D2.y, D2.bin_num, 
						D2.xBar, D2.yBar, eval(p), header, vmin=vmin, vmax=vmax, 
						flux_unbinned=D2.unbinned_flux, galaxy=str_plots[i][j],
						signal_noise=D2.SNRatio, signal_noise_target=SN_target_pop, 
						ax=axs[i,j], lim_labels=True, 
						lim_labels_units=units[i][j])
				else:
					axs[i,j] = plot_velfield_nointerp(D.x, D.y, D.bin_num, 
						D.xBar, D.yBar, eval(p), header, vmin=vmin, vmax=vmax, 
						flux_unbinned=D.unbinned_flux, galaxy=str_plots[i][j],
						signal_noise=D.SNRatio, signal_noise_target=SN_target_kin, 
						ax=axs[i,j], lim_labels=True,
						lim_labels_units=units[i][j])

				if overplot and p != '' and 'uncert' not in p:
					for o, color in overplot.iteritems():
						scale = 'log' if o == 'radio' else 'lin'
						add_(o, color, axs[i,j], galaxy, nolegend=True, scale=scale)
				if i > 0:
					if plots[i-1][j] != '' and hasattr(axs[i-1,j], 'ax_dis'):
						axs[i-1,j].ax_dis.set_xticklabels([])
						axs[i-1,j].ax_dis.set_xlabel('')
				if j > 0:
					if plots[i][j-1] != '' and hasattr(axs[i,j-1], 'ax_dis'):
						axs[i,j].ax_dis.set_yticklabels([])
						axs[i,j].ax_dis.set_ylabel('')
			
				
			else:
				axs[i,j].remove()


	# age = np.zeros(D2.number_of_bins)
	# met = np.zeros(D2.number_of_bins)
	# alp = np.zeros(D2.number_of_bins)
	# unc_age = np.zeros(D2.number_of_bins)
	# unc_met = np.zeros(D2.number_of_bins)
	# unc_alp = np.zeros(D2.number_of_bins)

	# if not debug:
	# 	for j in xrange(D2.number_of_bins):
	# 		ag, me, al = np.loadtxt('%s/pop/distribution/%i.dat' % (
	# 			vin_dir2, j), unpack=True)

	# 		for plot, unc_plot, pop in zip([age,met,alp],
	# 			[unc_age,unc_met,unc_alp], [ag,me,al]):

	# 			hist = np.histogram(pop, bins=40)
	# 			x = (hist[1][0:-1]+hist[1][1:])/2
	# 			hist = hist[0]
	# 			plot[j] = x[np.argmax(hist)]

	# 			gt_fwhm = hist >= np.max(hist)/2
	# 			unc_plot[j] = np.max(x[gt_fwhm]) - np.min(x[gt_fwhm])

	str_plots = ['Age', 'Age uncertainty', 'Metallicity', 'Metallicity uncertainty', 
		'Alpha enhancement', 'Alpha enhancement\nuncertainty']
	units = ['Gyr', 'Gyr', None, None, None, None]
	vmin = [0, 0, -2.25, 0, -0.3, 0]
	vmax = [15, 2, 0.67, 0.4, 0.5, 0.25]
	for j, p in enumerate(['age', 'age.uncert', 'metalicity', 'metalicity.uncert', 
		'alpha', 'alpha.uncert']):
		axs[-1, j] = plot_velfield_nointerp(D2.x, D2.y, D2.bin_num, 
			D2.xBar, D2.yBar, eval("D2.components['stellar']."+p), header,  
			vmin=vmin[j], vmax=vmax[j], 
			# cmap='inferno', 
			flux_unbinned=D2.unbinned_flux, galaxy=str_plots[j],
			signal_noise=D2.SNRatio, signal_noise_target=SN_target_pop, 
			ax=axs[-1,j], lim_labels=True, lim_labels_units=units[j])
		if j > 0:
			axs[-1,j].ax_dis.set_yticklabels([])
			axs[-1,j].ax_dis.set_ylabel('')

		if plots[-1][j] != '' or galaxy in ['ngc0612', 'pks0718-34']:
			axs[-2, j].ax_dis.set_xticklabels([])
			axs[-2, j].ax_dis.set_xlabel('')
		if overplot and 'unc' not in p:
			for o, color in overplot.iteritems():
				scale = 'log' if o == 'radio' else 'lin'
				add_(o, color, axs[-1,j], galaxy, nolegend=True, scale=scale)

	for i, a in enumerate(axs.flatten()):
		# if galaxy in ['ngc1399', 'pks0718-34'] and i==1:
		# 	break
		if hasattr(a, 'ax_dis'):
			a.ax_dis.tick_params(top=True, bottom=True, left=True, 
				right=True, direction='in', which='major', length=20,
				width=3, labelsize='large', zorder=10)
			a.ax_dis.tick_params(top=True, bottom=True, left=True, 
				right=True, direction='in', which='minor', length=10,
				width=3, zorder=10)
			a.ax_dis.xaxis.label.set_size(22)
			a.ax_dis.yaxis.label.set_size(22)

	# Create gap between pairs of columns
	for j in range(1, 6, 2):
		for a in axs[:, j].flatten():
			ax_loc = a.get_position()
			ax_loc.x0 -= 0.007
			ax_loc.x1 -= 0.007

			a.set_position(ax_loc)
			if hasattr(a, 'ax_dis'):
				a.ax_dis.set_position(ax_loc)
	# for j in range(0, 6, 2):
	# 	for a in axs[:, j+1].flatten():
	# 		ax_loc = a.get_position()
	# 		ax_loc.x0 += 0.01
	# 		ax_loc.x1 += 0.01

	# 		a.set_position(ax_loc)
	# 		if hasattr(a, 'ax_dis'):
	# 			a.ax_dis.set_position(ax_loc)


	# fig.text(0.24, 0.9, r'Flux', va='top', ha='center', size='xx-large')
	# fig.text(0.51, 0.9, r'Velocty', va='top', ha='center', size='xx-large')
	# fig.text(0.8, 0.9, r'Velocty Dispersion', va='top', ha='center', 
	# 	size='xx-large')

	
	# Add colorbar
	ax_loc = axs[0,-1].get_position()
	cax = fig.add_axes([ax_loc.x1+0.03, ax_loc.y0, 0.02, ax_loc.height])
	cbar = plt.colorbar(axs[1,1].cs, cax=cax)
	cbar.ax.set_yticklabels([])

	# plt.show()
	fig.savefig('%s/%s.png' % (out_dir, galaxy), bbox_inches='tight',
		dpi=200)
Beispiel #10
0
import numpy as np
from astropy.io import fits
from checkcomp import checkcomp
cc = checkcomp()
if cc.remote:
    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])
Beispiel #11
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
Beispiel #12
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))
Beispiel #13
0
## Routine to plot the output from use_kinemetry_muse.pro
# Uses a rolling median to smooth the data

from checkcomp import checkcomp
cc=checkcomp()
if 'home' not in cc.device:
	import matplotlib # 20160202 JP to stop lack-of X-windows error
	matplotlib.use('Agg')
from prefig import Prefig
Prefig(transparent=False)
import numpy as np
import matplotlib.pyplot as plt
import os
from rolling_stats import rollmed
from plot_velfield_nointerp import plot_velfield_nointerp
from astropy.io import fits
from errors2_muse import get_dataCubeDirectory
from plot_results_muse import set_lims, add_

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):
Beispiel #14
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
    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
import cPickle as pickle
from plot_velfield_nointerp import plot_velfield_nointerp
import numpy as np
import os
from plot_results_muse import set_lims, add_
from errors2_muse import get_dataCubeDirectory, set_params, run_ppxf
from pop import get_absorption, population
from classify import get_R_e
from errors2 import apply_range
from astropy.io import fits
from prefig import Prefig
Prefig(size=(16 * 2, 12 * 3), transparent=False)


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,