Skip to content

Commit

Permalink
lots o edits
Browse files Browse the repository at this point in the history
  • Loading branch information
autocorr committed May 12, 2015
1 parent 0d2cab4 commit 2e5e466
Show file tree
Hide file tree
Showing 6 changed files with 327 additions and 43 deletions.
60 changes: 32 additions & 28 deletions besl/bplot/dpdf_plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,15 @@
import matplotlib.pyplot as plt
from matplotlib import colors, cm
from matplotlib.ticker import MaxNLocator
from besl import catalog, units
from besl import catalog
from besl import util
from besl.dpdf_calc import (mc_sampler_1d, evo_stages,
gen_stage_mass_samples, gen_stage_area_samples)


plt.rc('font', **{'size':10})


def plot_dpdf_sampling(n=200):
"""
Plot a Monte Carlo sampling of a DPDF
Expand Down Expand Up @@ -46,7 +50,6 @@ def plot_dpdf_sum(outname='evo_dpdfs'):
fig : matplotlib.Figure
ax : matplotlib.Axes
"""
plt.rc('font', **{'size':14})
xdist = np.arange(1000) * 20. + 20.
# read data
pposts = catalog.read_pickle('ppv_dpdf_posteriors')
Expand All @@ -57,12 +60,14 @@ def plot_dpdf_sum(outname='evo_dpdfs'):
pstages, anno_labels = evo_stages(bgps=pevo)
dstages, anno_labels = evo_stages(bgps=devo)
# plot
fig, axes = plt.subplots(nrows=len(pstages), ncols=1, sharex=True)
fig, axes = plt.subplots(nrows=len(pstages), ncols=1, sharex=True,
figsize=(4, 3.5))
for ii, ax in enumerate(axes.flat):
if ii < 2:
[spine.set_linewidth(2.0) for spine in ax.spines.itervalues()]
for pdf, ddf, ax, alabel in zip(pstages, dstages, axes, anno_labels):
# take posterior sum and normalize
ax.tick_params(axis='y', which='major', labelsize=8)
pydist = np.sum([pposts[ii] for ii in pdf.index], axis=0)
pydist /= pydist.sum() * 20
dydist = np.sum([dposts[ii] for ii in ddf.index], axis=0)
Expand All @@ -80,19 +85,17 @@ def plot_dpdf_sum(outname='evo_dpdfs'):
ax.plot(pmed * np.ones(2), [0, 0.35], 'w-')
ax.plot(pmed * np.ones(2), [0, 0.35], 'k--')
# labels
ax.annotate(alabel['label'], xy=(0.775, 0.65), xycoords='axes fraction',
fontsize=13)
ax.annotate('$N = ' + str(pdf.shape[0]) + '$',
xy=(0.53, 0.65), xycoords='axes fraction',
fontsize=13)
ax.annotate('$(' + str(ddf.shape[0]) + ')$',
xy=(0.65, 0.65), xycoords='axes fraction',
fontsize=13, color='0.5')
ax.set_ylabel(r'${\rm Relative \ Probability}$')
ax.annotate(alabel['label'], xy=(0.73, 0.55), xycoords='axes fraction',
fontsize=9)
ax.annotate('$N = ' + str(pdf.shape[0]) + '$', xy=(0.45, 0.55),
xycoords='axes fraction', fontsize=9)
ax.annotate('$(' + str(ddf.shape[0]) + ')$', xy=(0.625, 0.55),
xycoords='axes fraction', fontsize=9, color='0.5')
axes[3].set_ylabel(r'${\rm Relative \ Probability}$')
ax.set_xlabel(r'${\rm Heliocentric \ Distance \ \ [kpc]}$')
plt.subplots_adjust(hspace=0.1)
plt.savefig(outname + '.pdf')
plt.savefig(outname + '.png', dpi=300)
plt.subplots_adjust(hspace=0.1, right=0.95, left=0.15, top=0.95,
bottom=0.125)
util.savefig(outname)
print '-- {0}.pdf written'.format(outname)
return fig, axes

Expand Down Expand Up @@ -207,7 +210,6 @@ def stages_hist(label, xlabel, bgps=None, color=True, left_label=False):
bgps = catalog.read_cat('bgps_v210_evo').set_index('v210cnum')
else:
assert bgps.index.name == 'v210cnum'
plt.rc('font', **{'size':14})
# evo stages
post = catalog.read_pickle('ppv_dpdf_posteriors')
dix = post.keys()
Expand All @@ -228,11 +230,13 @@ def stages_hist(label, xlabel, bgps=None, color=True, left_label=False):
'stepfilled', 'linestyle': 'solid', 'linewidth': 1}
stages_labels = [i.values()[0] for i in anno_labels]
# create plot
fig, axes = plt.subplots(nrows=len(stages), ncols=1, sharex=True)
fig, axes = plt.subplots(nrows=len(stages), ncols=1, sharex=True,
figsize=(4, 3.5))
for i, ax in enumerate(axes):
if i < 2:
[spine.set_linewidth(2.0) for spine in ax.spines.itervalues()]
# draw plots
ax.tick_params(axis='y', which='major', labelsize=8)
kwargs_hist = dict(kwargs_gen.items() + anno_labels[i].items())
hist_heights, hist_edges = np.histogram(stages[i][label], bins=lbins)
ymax = np.nanmax([np.max(hist_heights), 1])
Expand Down Expand Up @@ -260,21 +264,21 @@ def stages_hist(label, xlabel, bgps=None, color=True, left_label=False):
ax.locator_params(axis='y', tight=True, nbins=4)
ax.set_xscale('log')
if not left_label:
slabel_xoffset = 0.775
slabel_xoffset = 0.73
else:
slabel_xoffset = 0.15
ax.annotate(stages_labels[i], xy=(slabel_xoffset, 0.65), xycoords='axes fraction',
fontsize=13)
ax.annotate(df.shape[0], xy=(0.05, 0.65), xycoords='axes fraction',
fontsize=13)
ax.annotate(stages_labels[i], xy=(slabel_xoffset, 0.55),
xycoords='axes fraction', fontsize=9)
ax.annotate(df.shape[0], xy=(0.05, 0.55), xycoords='axes fraction',
fontsize=9)
axes[-1].set_xlabel(xlabel)
axes[3].set_ylabel(r'$N$')
# save
plt.subplots_adjust(hspace=0.1)
plt.savefig('stages_hist_{}.pdf'.format(label))
plt.savefig('stages_hist_{}.eps'.format(label))
plt.savefig('stages_hist_{}.png'.format(label), dpi=300)
plt.subplots_adjust(hspace=0.1, right=0.95, left=0.15, top=0.95,
bottom=0.125)
util.savefig('stages_hist_{0}'.format(label))
print '-- stages_hist_{}.pdf written'.format(label)
return [fig, axes]
return fig, axes


def marginal_stages_hist(bgps=[], label='dust_mass', realiz=50, nsample=1e2):
Expand Down Expand Up @@ -427,7 +431,7 @@ def write_all_hists():
PlotData('nh3_tkin', r'$T_{\rm K} \ \ [{\rm K}]$', amm),
PlotData('nh3_gbt_pk11', r'$T_{\rm pk}({\rm NH_3 \ (1,1)}) \ \ [{\rm K}]$', amm),
PlotData('nh3_gbt_tau11', r'$\tau({\rm NH_3 \ (1,1)})$', amm),
PlotData('nh3_gbt_fwhm', r'$\Delta v({\rm NH_3 \ (1,1)}) \ \ [{\rm km \ s^{-1}}]$', amm),
PlotData('nh3_gbt_fwhm', r'$\Delta v({\rm NH_3}) \ \ [{\rm km \ s^{-1}}]$', amm),
# HCO+
PlotData('mol_hco_tpk', r'$T_{\rm pk}({\rm HCO^+}) \ \ [{\rm K}]$', hco),
PlotData('mol_hco_int', r'$I({\rm HCO^+}) \ \ [{\rm K \ km \ s^{-1}}]$', hco),
Expand Down
3 changes: 1 addition & 2 deletions besl/bplot/ppv_group_plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,7 @@ def plot_all_params(filen='obj_props', out_filen='ppv_grid', log_Z=False):
log_Z : bool
Create plots with logarithmic Z axis
"""
#cmap = cm.RdBu_r
cmap = cm.RdYlBu
cmap = cm.RdYlBu_r
obj_dict = pickle.load(open(filen + '.pickle', 'rb'))
X = obj_dict['velo']
Y = obj_dict['angle']
Expand Down
82 changes: 72 additions & 10 deletions besl/bplot/sf_frac.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from besl import util


plt.rc('font', **{'size':14})
plt.rc('font', **{'size':10})


def get_data(clip_lon=True):
Expand Down Expand Up @@ -210,17 +210,40 @@ def calc(self):
return hist


class LifeTimeData(MassData):
maser_col = 'ch3oh_f'

def calc(self):
masses = self.ms.draw()
scc_hist = np.zeros(len(self.bins)-1, dtype=float)
mas_hist = np.zeros(len(self.bins)-1, dtype=float)
print ':: Compute histogram'
for ii, dd in self.ms.dix.items():
mm = masses[ii-1]
if self.df.loc[ii, self.maser_col] == 1:
hh, _ = np.histogram(mm, bins=self.bins)
mas_hist += hh / self.nsamples
elif self.df.loc[ii, self.proto_col] <= 0.4:
hh, _ = np.histogram(mm, bins=self.bins)
scc_hist += hh / self.nsamples
else:
pass
return scc_hist / mas_hist


class Plot(object):
fontsize = 9

def __init__(self, od):
self.od = od

def make_fig(self):
fig, ax = plt.subplots(figsize=(8, 2.5))
fig, ax = plt.subplots(figsize=(4, 2))
ax.set_xscale('log')
ax.set_xlabel(self.od.xlabel)
ax.set_xlim(self.od.xmin, self.od.xmax)
ax.set_ylim(0, 1.1)
plt.subplots_adjust(bottom=0.22)
plt.subplots_adjust(left=0.15, right=0.95, bottom=0.25)
return fig, ax


Expand All @@ -245,12 +268,14 @@ def plot_win(self, dod=None, window_label=False):
fig, ax = self.make_fig()
if window_label:
ax.annotate(r'${\rm Window} = ' + str(2 * self.od.winr) + '$',
xy=(0.725, 0.1), xycoords='axes fraction', fontsize=13)
xy=(0.725, 0.1), xycoords='axes fraction',
fontsize=self.fontsize)
ax.set_ylabel(r'$R_{\rm proto}$')
# if over-plot with the distance sample
if dod is not None:
ax.annotate('$({0})$'.format(dod.nbins), xy=(0.850, 0.1),
xycoords='axes fraction', fontsize=13, color='0.5')
ax.annotate('$({0})$'.format(dod.nbins), xy=(0.860, 0.1),
xycoords='axes fraction', fontsize=self.fontsize,
color='0.5')
ax.hlines(dod.mean_frac, self.od.xmin, self.od.xmax,
linestyles='dotted', colors='0.5')
ax.plot(dod.bins, dod.wvals, color='0.5', linestyle='solid',
Expand All @@ -262,7 +287,7 @@ def plot_win(self, dod=None, window_label=False):
ax.vlines(dod.bins, 1.01, 1.040, colors='0.35',
linestyles='solid', linewidth=0.1)
ax.annotate('$N={0}$'.format(self.od.nbins), xy=(0.675, 0.1),
xycoords='axes fraction', fontsize=13)
xycoords='axes fraction', fontsize=self.fontsize)
ax.hlines(1, self.od.xmin, self.od.xmax, linestyles='dashed',
colors='0.5')
ax.hlines(self.od.mean_frac, self.od.xmin, self.od.xmax,
Expand All @@ -283,10 +308,11 @@ def plot_frac(self, up_label=False):
fig, ax = self.make_fig()
if up_label:
ax.annotate(self.od.up_label, xy=(0.47, 0.1),
xycoords='axes fraction', fontsize=13)
xycoords='axes fraction', fontsize=self.fontsize)
ax.hlines(0.165, 7.5, 9, colors='red')
ax.annotate(r'$N={0}$'.format(len(self.od.dix)),
xy=(0.675, 0.1), xycoords='axes fraction', fontsize=13)
xy=(0.675, 0.1), xycoords='axes fraction',
fontsize=self.fontsize)
ax.hlines(1, self.od.xmin / 1e3, self.od.xmax / 1e3,
linestyles='dashed', colors='0.5')
ax.hlines(self.od.mean_frac, self.od.xmin / 1e3, self.od.xmax / 1e3,
Expand All @@ -305,7 +331,8 @@ class MassPlot(Plot):
def plot_frac(self):
fig, ax = self.make_fig()
ax.annotate(r'$N={0}$'.format(len(self.od.ms.dix)),
xy=(0.675, 0.1), xycoords='axes fraction', fontsize=13)
xy=(0.675, 0.1), xycoords='axes fraction',
fontsize=self.fontsize)
ax.hlines(1, self.od.xmin, self.od.xmax,
linestyles='dashed', colors='0.5')
ax.hlines(self.od.mean_frac, self.od.xmin, self.od.xmax,
Expand All @@ -316,6 +343,35 @@ def plot_frac(self):
util.savefig('sf_frac_' + self.od.col, close=True)


class LifeTimePlot(Plot):
hi_life = 4.0e4
lo_life = 2.5e4
max_ix = 225

def plot_frac(self):
fig, ax = self.make_fig()
ax.annotate(r'$N={0}$'.format(len(self.od.ms.dix)),
xy=(0.675, 0.85), xycoords='axes fraction',
fontsize=self.fontsize)
bins = self.od.bins[:self.max_ix]
samples = self.od.sf_frac[:self.max_ix]
ax.fill_between([1e2, 4e2], 1e3, 1e7, facecolor='0.9',
edgecolor='none',)
ax.fill_between(bins, self.lo_life * samples, self.hi_life * samples,
facecolor='0.5', edgecolor='none')
ax.plot(bins, self.lo_life * samples, 'k-', drawstyle='steps')
ax.plot(bins, self.hi_life * samples, 'k-', drawstyle='steps')
ax.plot([bins[-1], bins[-1]],
[self.lo_life * samples[-1], self.hi_life * samples[-1]], 'k-')
ax.plot([1.2e4, 8e4], [9e3, 9e3], 'k-')
ax.plot([3.2e4], [7.3e3], 'kv', ms=5)
ax.set_yscale('log')
ax.set_ylim([1e3, 1e7])
ax.set_ylabel(r'$\tau_{\rm SCC} \ \ [{\rm yr}]$')
ax.set_xlim(1e2, self.od.xmax)
util.savefig('lifetime_' + self.od.col, close=True)


def plot_flux_window():
od = ObsData('flux', r'$S^{\rm Total}_{1.1} \ \ [{\rm Jy}]$')
dod = ObsData('flux', r'$S^{\rm Total}_{1.1} \ \ [{\rm Jy}]$',
Expand Down Expand Up @@ -384,6 +440,12 @@ def plot_mass(use_fwhm=False):
op.plot_frac()


def plot_lifetime(use_fwhm=False):
LifeTimeData.use_fwhm = use_fwhm
od = LifeTimeData()
op = LifeTimePlot(od)
op.plot_frac()


#####
# Old code to calculate fractions based on molecular detection.
Expand Down

0 comments on commit 2e5e466

Please sign in to comment.