def plotBelos(files=None, leg=None): if files is None: files = ['./Picard.txt'] i = 0 for file_str in files: lin_iter = ex.extract(file_str, ex.BelosMaxItPattern) linatol = ex.extract(file_str, ex.BelosArTolPattern) print(linatol) pl.figure(4) if isinstance(lin_iter, float): # wtf lin_iter = [lin_iter] pl.plot(range(1, len(lin_iter) + 1), lin_iter, marker='.') pl.xlabel('Picard iteration') pl.ylabel(r'linear iterations') pl.ylabel(r'linear iterations', ha='left', va='bottom', rotation=0) pl.gca().yaxis.set_label_coords(-0.08, 1.02) if leg is not None: pl.legend(leg, loc=0) pl.gca().get_xaxis().set_major_locator(pl.MaxNLocator(integer=True)) pl.savefig('liniter.pdf', bbox_inches='tight') # pl.figure(5) pl.semilogy(range(1, len(linatol) + 1), linatol, marker='.') pl.xlabel('Picard iteration') pl.ylabel(r'archieved tolerance of the linear solver') pl.ylabel(r'archieved tolerance of the linear solver', ha='left', va='bottom', rotation=0) pl.gca().yaxis.set_label_coords(-0.08, 1.02) # legend(leg,bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) if leg is not None: pl.legend(leg, loc=0) pl.gca().get_xaxis().set_major_locator(pl.MaxNLocator(integer=True))
def plot_one_PSTH(arr, n_trial, ax, rng=DEF_PSTH_RANGE_MS, xrng=DEF_PSTH_RANGE_MS, \ aggregate=10, ymax=250, color='#999999', nticks=5, visible=False, txt=None, nondraw=False): arr = np.array(arr) # plot PSTH if n_trial > 0: arr = arr / 1000. # to ms interval = rng[1] - rng[0] bins = int(interval / aggregate) weight = 1000. / aggregate / n_trial # to convert into Spiks/s. weights = np.array([weight] * len(arr)) if nondraw: rtn = np.histogram(arr, range=rng, bins=bins, weights=weights) pl.axhline(y=0, color='#333333') else: rtn = pl.hist(arr, range=rng, bins=bins, weights=weights, fc=color, ec=color) # beutify axes pl.xlim(xrng) pl.ylim([0, ymax]) ax.xaxis.set_major_locator(pl.MaxNLocator(nticks)) ax.yaxis.set_major_locator(pl.MaxNLocator(nticks)) if not visible: ax.set_xticklabels([''] * nticks) ax.set_yticklabels([''] * nticks) pl.axvline(x=0, ymin=0, ymax=1, lw=0.5, color='r') if txt != None: if nondraw: pl.text(xrng[1] - 20, ymax - 70, txt, size=6, va='top', ha='right') else: pl.text(xrng[1] - 20, ymax - 20, txt, size=6, va='top', ha='right') return rtn
def plot_refinement(path='./', save=False, r_min=None, nf_max=None): """ plots residual refinement ... over iterations """ file_str = path + 'refinementTest.txt' res = pl.loadtxt(file_str) print(res) pl.figure(1) ax1 = pl.subplot(211) pl.subplots_adjust(hspace=0) iters = __my_cumsum(res[:, 0]) Markersize = 3 pl.semilogy(iters, res[:, 2] / (2. * res[:, 1] + 1), marker=MARKERS[0], markersize=Markersize, color=COLORS[0], linestyle=LINES[0], label=r'$\|\mathbf{r}\|$') pl.semilogy(iters, res[:, 3] / res[:, 4] / 2., marker=MARKERS[1], color=COLORS[1], linestyle=LINES[1], markersize=Markersize, label=r'$\Delta r$') # , nonposy='clip' # pl.ylabel(r'$\|\mathbf{r}\|$') pl.legend(loc=0, handletextpad=0.1) pl.setp(ax1.get_xticklabels(), visible=False) ax2 = pl.subplot(212, sharex=ax1) for i in range(len(res[:, 1])): if res[i, 3] == 0.: res[i, 4] = 0 pl.plot( iters, res[:, 1], marker=MARKERS[3], color=COLORS[0], markersize=Markersize, linestyle=LINES[3], label=r'$N_f$', ) pl.plot(iters, res[:, 4], marker=MARKERS[4], color=COLORS[1], markersize=Markersize, linestyle=LINES[4], label=r'$N_f^{\mathrm{inc}}$') pl.legend(loc=0, handletextpad=0.1) # pl.ylabel(r'$N_f$') pl.xlabel('Picard step') pl.gca().get_xaxis().set_major_locator(pl.MaxNLocator(integer=True)) pl.gca().get_yaxis().set_major_locator(pl.MaxNLocator(integer=True)) # setting limits if necessary if r_min is not None: ax1.set_ylim(ymin=r_min) if r_min is not None: ax2.set_ylim(ymax=nf_max) if save: pl.savefig(path + 'refF.pdf', bbox_inches='tight')
def plotNOX(paths=None, filename='output', run='', newton=False, save=False): """ plots residual ... over iterations (deprecated) """ if paths is None: paths = ['./'] for path in paths: iter_count = ex.extract(path + filename + str(run), ex.NOXIterPattern) res = ex.extract(path + filename + str(run), ex.NOXResPattern) # dof = ex.extract(path+filename+str(run), ex.PimpDofPattern)[0][0] # print('dof: ', dof) print(iter_count) print(res) pl.figure(1) # pl.semilogy(iter_count, res[:, 0]/pl.sqrt(dof)) # pl.semilogy(res[:, 0]/pl.sqrt(dof), marker='.') pl.semilogy(res[:, 0], marker='.') if newton: pl.xlabel('Newton step') else: pl.xlabel('Picard iteration') pl.ylabel(r'$||\mathbf{r}||_2/\sqrt{N}$') # pl.ylabel(r'$||\mathbf{r}||_2/\sqrt{N}$', ha='left', va='bottom', # rotation=0) # pl.gca().yaxis.set_label_coords(-0.08, 1.02) pl.gca().get_xaxis().set_major_locator(pl.MaxNLocator(integer=True)) if save: pl.savefig('F.pdf', bbox_inches='tight') pl.figure(2) pl.semilogy(iter_count[1:], res[1:, 1], basey=2, marker='.') if newton: pl.xlabel('Newton step') else: pl.xlabel('Picard iteration') pl.ylabel(r'step width') # pl.ylabel(r'step width', ha='left', va='bottom', rotation=0) # pl.gca().yaxis.set_label_coords(-0.08, 1.02) pl.gca().get_xaxis().set_major_locator(pl.MaxNLocator(integer=True)) if save: pl.savefig('lam.pdf', bbox_inches='tight') # pl.figure(3) # pl.semilogy(iter_count[1:], res[1:, 2]/pl.sqrt(dof), marker='.') pl.semilogy(iter_count[1:], res[1:, 2], marker='.') if newton: pl.xlabel('Newton step') else: pl.xlabel('Picard step') pl.ylabel(r'$||\delta\mathbf{q}||_2/\sqrt{N}$') pl.gca().yaxis.set_label_coords(-0.08, 1.02) pl.gca().get_xaxis().set_major_locator(pl.MaxNLocator(integer=True)) if save: pl.savefig('du.pdf', bbox_inches='tight')
def plot_engergy_spectrum(path='./', ref=0, iters=None, prefix='xv', linestyle='-', label=None, scale=1.): """ plots development of each norm over Picards iteration, corresponds to NOXPrePostSpecturm """ if iters is None: iters = [0] pl.ylabel(r'$\frac{1}{2}\|\hat{\mathbf{u}}_k\|^2_2$', ha='left', va='bottom', rotation=0) pl.gca().yaxis.set_label_coords(-0.08, 1.02) pl.xlabel(r'$k$') pl.gca().get_xaxis().set_major_locator(pl.MaxNLocator(integer=True)) for i in iters: spec = pl.loadtxt(path + prefix + '_' + str(ref) + '_' + str(i) + '.txt') print(spec) pl.semilogy(spec[:, 0], 0.5 * scale * spec[:, 1]**2, marker='.', linestyle=linestyle, label=label)
def plot_vs(path='./', refs=1, save=False): """ plots development of each norm over Picards iteration, corresponds to NOXPrePostSpecturm """ prefixes = ['x', 'res', 'cor'] fields = ['v', 'p'] for prefix in prefixes: pl.figure() if prefix == 'x': pl.ylabel(r'$\|\mathbf{q}\|$', ha='left', va='bottom', rotation=0) elif prefix == 'res': pl.ylabel(r'$\|\mathbf{r}\|$', ha='left', va='bottom', rotation=0) elif prefix == 'cor': pl.ylabel(r'$\|\delta \mathbf{q}\|$', ha='left', va='bottom', rotation=0) pl.gca().yaxis.set_label_coords(-0.08, 1.02) pl.xlabel(r'iteration step') pl.gca().get_xaxis().set_major_locator(pl.MaxNLocator(integer=True)) for i, field in enumerate(fields): digdeep(path=path, prefix=prefix + field, refs=refs, color=COLORS[i], linestyle=LINES[i]) if save: pl.savefig(prefix + '.pdf')
def plot_linear(file_str='./Picard.txt', label=None, save=False, fig=1, offset=0, linestyle='-'): """ plots the linear iteration and achieved tolerance """ lin_iter = ex.extract(file_str, ex.BelosMaxItPattern) linatol = ex.extract(file_str, ex.BelosArTolPattern) print(linatol) pl.figure(fig) if isinstance(lin_iter, float): # wtf lin_iter = [lin_iter] pl.plot(pl.arange(1, len(lin_iter) + 1) + offset, lin_iter, marker='.', label=label, linestyle=linestyle) pl.xlabel('Picard step') pl.ylabel(r'linear iteration steps', ha='left', va='bottom', rotation=0) pl.gca().yaxis.set_label_coords(-0.08, 1.02) pl.gca().get_yaxis().set_major_locator(pl.MaxNLocator(integer=True)) if save: pl.savefig('liniter.pdf', bbox_inches='tight') # pl.figure(fig + 1) pl.semilogy(pl.arange(1, len(linatol) + 1) + offset, linatol, marker='.', label=label, linestyle=linestyle) pl.xlabel('Picard step') # pl.ylabel(r'achieved tolerance of the linear solver', ha='left', # va='bottom', rotation=0) # pl.gca().yaxis.set_label_coords(-0.08, 1.02) pl.ylabel(r'achieved tolerance of the linear solver') pl.gca().get_xaxis().set_major_locator(pl.MaxNLocator(integer=True)) if save: pl.savefig('lintol.pdf', bbox_inches='tight') offset += len(linatol) return offset
def doaxes(edges, nx, ny, ix, iy, sharex=None, sharey=None, extra=0.05): '''Set up one of multiple plots with shared axes''' xoff, xoffr, yoff, yoffr = edges xwi = (1.0 - xoff - xoffr) / float(nx) ywi = (1.0 - yoff - yoffr) / float(ny) xll = xoff + ix * xwi yll = 1.0 - yoffr - (iy + 1) * ywi if nx > 1: xoffr -= extra * xwi xwi = (1 - extra) * (1.0 - xoff - xoffr) / float(nx) if ny > 1: yoffr -= extra * ywi ywi = (1 - extra) * (1.0 - yoff - yoffr) / float(ny) axc = plt.axes([xll, yll, xwi, ywi], sharex=sharex, sharey=sharey) if ix > 0: plt.setp(axc.get_yticklabels(), visible=False) if iy < (ny - 1): plt.setp(axc.get_xticklabels(), visible=False) axc.yaxis.set_major_locator(plt.MaxNLocator(5, prune='both')) axc.xaxis.set_major_locator(plt.MaxNLocator(5, prune='both')) return axc
def plotchains(samples, lnp, do_cut=False, cut=200): nwalkers, nsteps, ndim = samples.shape nper = (ndim - 1) / 4 cols = ['k', 'c', 'm', 'y'] labels = labels_QP(nper, merge=True) fig = pl.figure(figsize=(8, 1.5 * 6)) gs = gridspec.GridSpec(6, 1) gs.update(left=0.15, right=0.98, bottom=0.1, top=0.98, hspace=0.0) ax1 = pl.subplot(gs[0, 0]) ax1.yaxis.set_major_locator(pl.MaxNLocator(5, prune='both')) pl.setp(ax1.get_xticklabels(), visible=False) pl.ylabel(r"$\log \, \mathrm{posterior}$") for j in range(nwalkers): pl.plot(lnp[j, :], color='k', alpha=0.3) if do_cut: pl.axvline(cut, color='c') print 'Discarding first %d steps as burn-in' % cut for i in range(4): axc = pl.subplot(gs[i + 1, 0]) axc.yaxis.set_major_locator(pl.MaxNLocator(5, prune='both')) pl.setp(axc.get_xticklabels(), visible=False) pl.ylabel(labels[i]) for j in range(nwalkers): for k in range(nper): col = np.roll(cols, -k)[0] pl.plot(samples[j, :, k * 4 + i], color=col, alpha=0.3) if do_cut: pl.axvline(cut, color='c') axc = pl.subplot(gs[-1, 0]) axc.yaxis.set_major_locator(pl.MaxNLocator(5, prune='both')) pl.ylabel(labels[-1]) for j in range(nwalkers): pl.plot(samples[j, :, -1], color='k', alpha=0.3) if do_cut: pl.axvline(cut, color='c') pl.xlabel('iteration') if do_cut == True: return fig, samples[:, cut:, :], lnp[:, cut:] else: return fig, samples, lnp
def main(dirn, fname, solvers): (xs, ysPerSolver, ydevsPerSolver) = CommonViz.parseData(dirn, fname, solvers) CommonConf.setupMPPDefaults() colors = CommonConf.getLineColorsDict() fmts = CommonConf.getLineFormatsDict() linewidth = CommonConf.getLineMarkersLWDict() mrkrs = CommonConf.getLineMarkersDict() mrkrsize = CommonConf.getLineMarkersSizeDict() fig = pp.figure(figsize=(12, 6)) ax = fig.add_subplot(111) # ax.set_xscale("log", basex=2) index = 0 #xs.append(max(xs)+2) for (solver, ys), (solver, ydevs) in zip(ysPerSolver.iteritems(), ydevsPerSolver.iteritems()): xs_arr = np.asarray(xs) xs_arr = xs_arr + random.random() / 10 ax.errorbar(xs_arr, ys, yerr=ydevs, alpha=0.8, color=colors[solver], label=CommonConf.gen_label(solver), linewidth=linewidth[solver], linestyle=fmts[solver], marker=mrkrs[solver], markersize=mrkrsize[solver]) ax.set_xlabel(X_LABEL) ax.set_ylabel(Y_LABEL) ax.legend(loc=0, borderaxespad=1., fancybox=True) ymin, ymax = pp.ylim() pp.ylim(0.5, 1.05) xa = ax.get_xaxis() xa.set_major_locator(pylab.MaxNLocator(integer=True)) #ax.annotate('link (s2-s12) fails', xy=(1.8, 0.54), xytext=(0.95, 0.6), # arrowprops=dict(facecolor='black', shrink=0.05), fontsize=14 # ) #pp.axvline(1.8, linestyle='dashed' ) pp.subplots_adjust(left=0.1, right=0.8, top=0.9, bottom=0.1) #pp.savefig(dirn+"/"+fname+"-".join(solvers)+".pdf") pp.savefig(dirn + "/" + fname + "-".join(solvers) + ".svg")
def plot_score_history(self, output_path: Optional[str] = None) -> None: """ Plot the history of the scores, for every agent, by transaction. :param output_path: an optional output path where to save the figure generated. :return: None """ keys, history = self.score_history() plt.clf() plt.plot(history) plt.legend([self.game.configuration.agent_pbk_to_name[agent_pbk] for agent_pbk in keys], loc="best") plt.xlabel("Transactions") plt.ylabel("Score") plt.gca().xaxis.set_major_locator(plt.MaxNLocator(integer=True)) if output_path is None: plt.show() else: plt.savefig(output_path)
def _graph(ax, dates, legend=True): ax.xaxis.set_ticks(ticks) pylab.setp(ax.xaxis.get_ticklabels(), rotation=90, fontsize=8) ax.xaxis.set_major_formatter(pylab.FixedFormatter(tick_labels)) ylocator = pylab.MaxNLocator(10, steps=[1,2,5,10],integer=1) ax.yaxis.set_major_locator(ylocator) ax.yaxis.grid(1) if self.stack: bottom = pylab.zeros(self.n_bins) legend_handles = [] legend_labels = [] strata_bins = self.strata_date_bin(dates, self.stack) if self.stack_ratios: strata_bins = self.strata_ratios(strata_bins) for n, (v, l) in enumerate(self.stack.order_labels): if self.stack_suppress and v in self.stack_suppress: continue bins = strata_bins[(v,)] handles = pylab.bar(x, bins, bottom=bottom, width=1.0, align='center', color=colors[n]) legend_handles.append(handles[0]) legend_labels.append(wrap(l)) bottom += bins if legend: l = pylab.legend(legend_handles, legend_labels, loc=0, prop=dict(size=8), title=wrap(self.stack_label)) pylab.setp(l.get_title(), fontsize=9) # pylab.setp(l.get_texts(), fontsize=8) if self.stack_ratios: ax.set_ylim(0, 100) else: bins = self.date_bin(dates) pylab.bar(x, bins, width=1.0, color='#bbbbff', align='center') pad_axis(ax, 'x') pad_axis(ax, 'y')
def plot_amp_res(ran, w_ran, n, ds, h, k_est, k, v, h_pw, h_mean_pw, k_pw, k_mean_pw, v_pw, v_mean_pw, teo_h_pw, teo_k_pw, teo_v_pw, ran_ticks=[], ran_ticks_labels=[], delta_label='', split_h=None, split_k=None, split_v=None, ymax_h=None, ymax_k=None, ymax_v=None, ytick_top_h=None, ytick_bottom_h=None, ytick_top_k=None, ytick_bottom_k=None, yticks_k=None, ytick_top_v=None, ytick_bottom_v=None, lw=2, fig=None, tuning_curve=None, ms=5): if fig is None: pl.figure(figsize=(10, 6)) pl.subplots_adjust(left=0.1, right=0.99, wspace=0.4, hspace=.8, bottom=0.1, top=0.95) # --------------------------------- Input ------------------------------------ half_ran = (ran[-1] + ds) / 2 pl.subplot(231) pp.custom_axes() if tuning_curve is not None: pl.plot(ran - half_ran, np.roll(tuning_curve, n / 2), '-k', color=[.7, .7, .7], lw=lw) pl.plot(ran - half_ran, np.roll(h, n / 2), '-k', lw=lw) pl.xlim([-half_ran, half_ran]) pl.xticks(ran_ticks, ran_ticks_labels) pl.ylim([-2, 2]) pl.gca().yaxis.set_major_locator(pl.MaxNLocator(3)) # --------------------------------- Filter ------------------------------------ ax = pl.subplot(232, frameon=False) xlim = [-half_ran, half_ran] ylim_top = [20, np.ceil(1 / ds) + 10] ylim_bottom = [-1.5, 1.5] xlabel = '' ax_top, ax_bottom = pp.broken_axis(ax, xlim, ylim_top, ylim_bottom, xlabel, ratio=0.5) ax_top.set_yticks([ 1 / ds, ]) ax_top.set_yticklabels([delta_label], fontsize=12) ax_bottom.set_yticks([-1, 1]) pl.sca(ax_bottom) pl.xticks(ran_ticks, ran_ticks_labels) #ax_top.plot(ran-half_ran,np.roll(k_est,n/2),color=[0.6,0.6,0.6],lw=lw,ls='-') #ax_bottom.plot(ran-half_ran,np.roll(k_est,n/2),color=[0.6,0.6,0.6],lw=lw,ls='-') ax_top.plot(ran - half_ran, np.roll(k, n / 2), '-k', lw=lw) ax_bottom.plot(ran - half_ran, np.roll(k, n / 2), '-k', lw=lw) # --------------------------- Output ----------------------------------------- pl.subplot(233) pp.custom_axes() #if tuning_curve is not None: # pl.plot(ran-half_ran,np.roll(tuning_curve,n/2),'-k',color=[0.7,0.7,0.7],lw=lw*3) pl.plot(ran - half_ran, np.roll(v, n / 2), '-k', lw=lw) pl.xlim([-half_ran, half_ran]) pl.ylim([-2, 2]) pl.xticks(ran_ticks, ran_ticks_labels) pl.gca().yaxis.set_major_locator(pl.MaxNLocator(3)) #---------------------------------------------------------------------------- # =========== FREQUENCY DOMAIN ============================================== #---------------------------------------------------------------------------- #--------------------------- Input ------------------------------------------- ax = pl.subplot(234, frameon=split_h is None) plot_spectrum(w_ran, h_pw, h_mean_pw, teo_h_pw, split_lims=split_h, ymax_top=ymax_h, ytick_top=ytick_top_h, ytick_bottom=ytick_bottom_h, ms=ms) #---------------- Equivalent Feed-farward filter ----------------------------- ax = pl.subplot(235, frameon=split_k is None) plot_spectrum(w_ran, k_pw, k_mean_pw, teo_k_pw, split_lims=split_k, ymax_top=ymax_k, ytick_top=ytick_top_k, ytick_bottom=ytick_bottom_k, yticks=yticks_k, ms=ms) #--------------------------- Output------------------------------------------- ax = pl.subplot(236, frame_on=split_v is None) plot_spectrum(w_ran, v_pw, v_mean_pw, teo_v_pw, split_lims=split_v, ymax_top=ymax_v, ytick_top=ytick_top_v, ytick_bottom=ytick_bottom_v, ms=ms)
def locator(self): # {{{ import pylab as pyl return pyl.MaxNLocator(nbins=9, steps=[1, 3, 6, 10])
I2 = branch['data'][idx, mask_unstable] ax.plot(branch['data'][0, mask_unstable] / tscale, I1, color=caudad_color, linestyle='--') ax.plot(branch['data'][0, mask_unstable] / tscale, I2, color=rostrad_color, linestyle='--') ax.set_ylabel("NICD") ax.set_xlabel(r"k$_t$ (s$^{-1}$)") ax.set_ylim([-1100 * 0.05, 1100 * 1.05]) ax.set_xlim([0, 2.]) ax.xaxis.set_major_locator(pl.MaxNLocator(5)) ax.yaxis.set_major_locator(pl.MaxNLocator(5)) ax1 = fig.add_subplot(132) se = 20. #100. E0 = 200. for branch in branch_list: mask_stable = branch['stability'] < 0 idx = branch['varnames'].index('I1') I1 = branch['data'][idx, mask_stable] E1 = E0 * (1. / (1. + (I1 / se)**4.)) idx = branch['varnames'].index('I2') I2 = branch['data'][idx, mask_stable] E2 = E0 * (1. / (1. + (I2 / se)**4.)) ax1.plot(branch['data'][0, mask_stable] / tscale, E1, color=caudad_color) ax1.plot(branch['data'][0, mask_stable] / tscale, E2, color=rostrad_color)
def xticknum(ax, n): import matplotlib.pylab as plt ax.xaxis.set_major_locator(plt.MaxNLocator(n)) return
def FastSpy(nrow, ncol, irow, jcol, **kwargs): """ To plot the sparsity pattern of a sparse matrix in coordinate format. :parameters: :nrow: Number of rows of the matrix. :ncol: Number of columns of the matrix. :irow: Integer Numpy array of length nnz giving the row indices of the nonzero elements. :jcol: Integer Numpy array of length nnz giving the column indices of the nonzero elements. :keywords: :ax: A Pylab Axes instance used to plot the sparsity pattern. If none is given, this function returns an Axes instance. :sym: Should be set to True if the matrix is symmetric and only one triangle is passed in (irow,jcol). :title: String to be used as title for the plot. If none is given, the title defaults to giving the order of the matrix and the number of nonzero elements. :comment: Comment to be appended to the default plot title in case no title is supplied. :showtitle: Show or hide plot title. :val: Float Numpy array of length nnz giving the values of the nonzero elements of the matrix. If supplied, a scatter plot is produced with patches of size proportional to the magnitude of the element. This option can slow down the plot for large values of the number of nonzero elements. """ ax = kwargs.get('ax', None) if ax is None: fig = pylab.figure() ax = fig.gca() sym = kwargs.get('sym', False) t = kwargs.get('title', None) comment = kwargs.get('comment', '') showtitle = kwargs.get('showtitle', True) val = kwargs.get('val', None) nnz = len(irow) if val is not None: # Produce a scatter plot absval = numpy.abs(numpy.asarray(val)) mag = 100.0 / numpy.max(absval) s = 100.0 * absval / numpy.linalg.norm(val, ord=numpy.infty) ax.scatter(jcol, irow, s, s, marker='o', alpha=0.75) if sym: ax.scatter(irow, jcol, s, s, marker='o', alpha=0.75) else: ms = 1 if nrow + ncol <= 100: ms = 5 ax.plot(jcol, irow, 'ks', markersize=ms, linestyle='None') if sym: ax.plot(irow, jcol, 'ks', markersize=ms, linestyle='None') ax.xaxis.set_major_locator( pylab.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True)) ax.yaxis.set_major_locator( pylab.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True)) ax.xaxis.set_ticks_position('both') ax.yaxis.set_ticks_position('both') ticklabels = ax.get_xticklabels() ticklabels.extend(ax.get_yticklabels()) if max(nrow, ncol) < 1000: labelfontsize = 'small' elif max(nrow, ncol) < 100000: labelfontsize = 'x-small' else: labelfontsize = 'xx-small' for label in ticklabels: label.set_fontsize(labelfontsize) ax.set_xlim(xmin=-1, xmax=ncol) ax.set_ylim(ymin=nrow, ymax=-1) ax.set_aspect('equal') if nrow == ncol: #ax.set_aspect('equal') if t is None: t = 'Order %-d with %-d nonzeros' % (nrow, nnz) else: #ratio = (1.0*nrow)/ncol #ax.set_aspect(ratio) if t is None: t = 'Size (%-d,%-d) with %-d nonzeros' % (nrow, ncol, nnz) if t is not None: t = comment + t if showtitle: ax.set_title(t, fontsize='x-small') return ax
for i in range(8): y = X[i][ilo:] x = pl.linspace(dx, dx +(i+len(y))* 2e-5, len(y)) h = exppfit(x, y, 2) hp = h[0] hp0 = hp[i0] hp1 = hp[i1] hp1[0] = y[0] infx = exppinf(hp) hy = exppval(hp, x) hy0 = exppval(hp0, x) hy1 = exppval(hp1, x) #ss = spikeShape(2.0000000000000002e-05) #ss.analyse(X) ax = pl.subplot(2, 4, i+1) pl.plot(x, y, 'c') pl.hold(True) pl.plot(x, hy, 'k') pl.plot(x, hy0, 'g') pl.plot(x, hy1, 'r') tau = [1.0 / pl.exp(hp1[3]), 1.0 / pl.exp(hp0[3])] ax.xaxis.set_major_locator(pl.MaxNLocator(4)) miny = y.min() pl.ylim([miny, miny+7.0]) #pl.title(''.join([r'$\Lambda_0=', str(hp1[3]), '$, ', r'$\Lambda_1=', str(hp0[3]), '$'])) pl.title(''.join([r'$\alpha_0=', str(hp1[1]), '$, ', r'$\alpha_1=', str(hp0[1]), '$'])) pl.show() print(hp)
def do_plot(plotfile, component, component2, outFile, log, minval, maxval, minval2, maxval2, eps, dpi, origin, annotation, xmin_pass, ymin_pass, zmin_pass, xmax_pass, ymax_pass, zmax_pass): pylab.rc("font", size=9) #-------------------------------------------------------------------------- # construct the output file name #-------------------------------------------------------------------------- if (outFile == ""): outFile = os.path.normpath(plotfile) + "_" + component if (not component2 == ""): outFile += "_" + component2 if (not eps): outFile += ".png" else: outFile += ".eps" else: # make sure the proper extension is used if (not eps): if (not string.rfind(outFile, ".png") > 0): outFile = outFile + ".png" else: if (not string.rfind(outFile, ".eps") > 0): outFile = outFile + ".eps" #-------------------------------------------------------------------------- # read in the meta-data from the plotfile #-------------------------------------------------------------------------- (nx, ny, nz) = fsnapshot.fplotfile_get_size(plotfile) time = fsnapshot.fplotfile_get_time(plotfile) (xmin, xmax, ymin, ymax, zmin, zmax) = \ fsnapshot.fplotfile_get_limits(plotfile) dx = (xmax - xmin) / nx x = xmin + numpy.arange((nx), dtype=numpy.float64) * dx dy = (ymax - ymin) / ny y = ymin + numpy.arange((ny), dtype=numpy.float64) * dy if (nz > 0): dz = (zmax - zmin) / nz z = zmin + numpy.arange((nz), dtype=numpy.float64) * dz if (nz == -1): #---------------------------------------------------------------------- # 2-d plots #---------------------------------------------------------------------- extent = [xmin, xmax, ymin, ymax] ix0 = 0 ix = nx iy0 = 0 iy = ny if (not xmin_pass == None): extent[0] = xmin_pass ix0 = int((xmin_pass - xmin) / dx) if (not ymin_pass == None): extent[2] = ymin_pass iy0 = int((ymin_pass - ymin) / dy) if (not xmax_pass == None): extent[1] = xmax_pass ix = int((xmax_pass - xmin) / dx) if (not ymax_pass == None): extent[3] = ymax_pass iy = int((ymax_pass - ymin) / dy) sparseX = 0 if (ny >= 3 * nx): sparseX = 1 # read in the main component data = numpy.zeros((nx, ny), dtype=numpy.float64) (data, err) = fsnapshot.fplotfile_get_data_2d(plotfile, component, data) if (not err == 0): sys.exit(2) data = numpy.transpose(data) # read in the component #2, if present if (not component2 == ""): data2 = numpy.zeros((nx, ny), dtype=numpy.float64) (data2, err) = fsnapshot.fplotfile_get_data_2d(plotfile, component2, data2) if (not err == 0): sys.exit(2) data2 = numpy.transpose(data2) # log? if log: if (numpy.min(data) < 0): data = numpy.log10(numpy.abs(data)) else: data = numpy.log10(data) if (not component2 == ""): if (numpy.min(data2) < 0.0): data2 = numpy.log10(numpy.abs(data2)) else: data2 = numpy.log10(data2) if (not minval == None): minval = math.log10(minval) if (not maxval == None): maxval = math.log10(maxval) if (not minval2 == None): minval2 = math.log10(minval2) if (not maxval2 == None): maxval2 = math.log10(maxval2) #---------------------------------------------------------------------- # plot main component #---------------------------------------------------------------------- if (not component2 == ""): ax = pylab.subplot(1, 2, 1) pylab.subplots_adjust(wspace=0.5) else: ax = pylab.subplot(1, 1, 1) divider = mpl_toolkits.axes_grid1.make_axes_locatable(ax) im = pylab.imshow(data[iy0:iy, ix0:ix], origin='lower', extent=extent, vmin=minval, vmax=maxval) pylab.title(component) pylab.xlabel("x") pylab.ylabel("y") # axis labels in scientific notation with LaTeX ax = pylab.gca() ax.xaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) ax.yaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) if (sparseX): ax.xaxis.set_major_locator(pylab.MaxNLocator(3)) # make space for a colorbar -- getting it the same size as the # vertical extent of the plot is surprisingly tricky. See # http://matplotlib.sourceforge.net/mpl_toolkits/axes_grid/users/overview.html#colorbar-whose-height-or-width-in-sync-with-the-master-axes ax_cb = divider.new_horizontal(size="10%", pad=0.1) fig1 = ax.get_figure() fig1.add_axes(ax_cb) formatter = matplotlib.ticker.ScalarFormatter(useMathText=True) cb = pylab.colorbar(im, format=formatter, cax=ax_cb) # make the font size for the colorbar axis labels small. Note # the offsetText is the 10^N that appears at the top of the # y-axis. cl = pylab.getp(cb.ax, 'ymajorticklabels') pylab.setp(cl, fontsize=10) cb.ax.yaxis.offsetText.set_fontsize("small") # do a fixed offset in pixels from the (xmin,ymin) data point trans = matplotlib.transforms.offset_copy(ax.transData, x=0, y=-0.5, fig=fig1, units='inches') pylab.text(xmin, ymin, "time = %7.3g s" % (time), verticalalignment="bottom", transform=trans, clip_on=False, fontsize=10) if (not annotation == ""): trans = matplotlib.transforms.offset_copy(ax.transData, x=0, y=-0.65, fig=fig1, units='inches') pylab.text(xmin, ymin, "%s" % (annotation), verticalalignment="bottom", transform=trans, clip_on=False, fontsize=10) #---------------------------------------------------------------------- # plot component #2 #---------------------------------------------------------------------- if (not component2 == ""): ax = pylab.subplot(1, 2, 2) divider = mpl_toolkits.axes_grid1.make_axes_locatable(ax) im = pylab.imshow(data2[iy0:iy, ix0:ix], origin='lower', extent=extent, vmin=minval2, vmax=maxval2) pylab.title(component2) pylab.xlabel("x") pylab.ylabel("y") # axis labels in scientific notation with LaTeX ax.xaxis.set_major_formatter( pylab.ScalarFormatter(useMathText=True)) ax.yaxis.set_major_formatter( pylab.ScalarFormatter(useMathText=True)) if (sparseX): ax.xaxis.set_major_locator(pylab.MaxNLocator(3)) # make space for a colorbar -- getting it the same size as # the vertical extent of the plot is surprisingly tricky. # See # http://matplotlib.sourceforge.net/mpl_toolkits/axes_grid/users/overview.html#colorbar-whose-height-or-width-in-sync-with-the-master-axes ax_cb = divider.new_horizontal(size="10%", pad=0.1) fig1 = ax.get_figure() fig1.add_axes(ax_cb) formatter = matplotlib.ticker.ScalarFormatter(useMathText=True) cb = pylab.colorbar(im, format=formatter, cax=ax_cb) # make the font size for the colorbar axis labels small. Note the # offsetText is the 10^N that appears at the top of the y-axis. cl = pylab.getp(cb.ax, 'ymajorticklabels') pylab.setp(cl, fontsize=10) cb.ax.yaxis.offsetText.set_fontsize("small") #ax_cb.yaxis.tick_right() else: #---------------------------------------------------------------------- # 3-d plot #---------------------------------------------------------------------- # starting points for the figure positions # assume that the width of the plotting area is 0.05 to 0.95, # leaving 0.9 to be split amongst the 3 plots. So each has a # width of 0.3 # for the height, we will assume that the colorbar at the # bottom gets 0.15, and that we go until 0.95, leaving 0.8 of # height for the plots. pos1 = [0.05, 0.15, 0.3, 0.8] pos2 = [0.35, 0.15, 0.3, 0.8] pos3 = [0.65, 0.15, 0.3, 0.8] fig = pylab.figure() # read in the slices # x-y data_xy = numpy.zeros((nx, ny), dtype=numpy.float64) indir = 3 (data_xy, err) = \ fsnapshot.fplotfile_get_data_3d(plotfile, component, indir, origin, data_xy) if (not err == 0): sys.exit(2) data_xy = numpy.transpose(data_xy) if log: if (numpy.min(data_xy) < 0): data_xy = numpy.log10(numpy.abs(data_xy)) else: data_xy = numpy.log10(data_xy) # x-z data_xz = numpy.zeros((nx, nz), dtype=numpy.float64) (data_xz, err) = \ fsnapshot.fplotfile_get_data_3d(plotfile, component, 2, origin, data_xz) if (not err == 0): sys.exit(2) data_xz = numpy.transpose(data_xz) if log: if (numpy.min(data_xz) < 0): data_xz = numpy.log10(numpy.abs(data_xz)) else: data_xz = numpy.log10(data_xz) # y-z data_yz = numpy.zeros((ny, nz), dtype=numpy.float64) (data_yz, err) = \ fsnapshot.fplotfile_get_data_3d(plotfile, component, 1, origin, data_yz) if (not err == 0): sys.exit(2) data_yz = numpy.transpose(data_yz) if log: if (numpy.min(data_yz) < 0): data_yz = numpy.log10(numpy.abs(data_yz)) else: data_yz = numpy.log10(data_yz) if (not minval == None): if (log): minval = math.log10(minval) else: minval = numpy.min(data_xy) minval = min(minval, numpy.min(data_xz)) minval = min(minval, numpy.min(data_yz)) if (not maxval == None): if (log): maxval = math.log10(maxval) else: maxval = numpy.max(data_xy) maxval = max(maxval, numpy.max(data_xz)) maxval = max(maxval, numpy.max(data_yz)) # x-y extent = [xmin, xmax, ymin, ymax] ix0 = 0 ix = nx iy0 = 0 iy = ny if (not xmin_pass == None): extent[0] = xmin_pass ix0 = int((xmin_pass - xmin) / dx) if (not ymin_pass == None): extent[2] = ymin_pass iy0 = int((ymin_pass - ymin) / dy) if (not xmax_pass == None): extent[1] = xmax_pass ix = int((xmax_pass - xmin) / dx) if (not ymax_pass == None): extent[3] = ymax_pass iy = int((ymax_pass - ymin) / dy) ax = pylab.subplot(1, 3, 1) pylab.subplots_adjust(wspace=0.4) #fig.add_axes(pos1) im = pylab.imshow(data_xy[iy0:iy, ix0:ix], origin='lower', extent=extent, vmin=minval, vmax=maxval, axes=pos1) pylab.xlabel("x") pylab.ylabel("y") # axis labels in scientific notation with LaTeX ax = pylab.gca() ax.xaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) ax.yaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) ax.xaxis.offsetText.set_fontsize("small") ax.yaxis.offsetText.set_fontsize("small") cl = pylab.getp(ax, 'ymajorticklabels') pylab.setp(cl, fontsize=10) cl = pylab.getp(ax, 'xmajorticklabels') pylab.setp(cl, fontsize=10) # do a fixed offset in pixels from the (xmin,ymin) data point fig1 = ax.get_figure() trans = matplotlib.transforms.offset_copy(ax.transData, x=0, y=-0.5, fig=fig1, units='inches') # pylab.text(xmin_pass, ymin_pass, "time = %7.3g s" % (time), # verticalalignment="bottom", transform = trans, # clip_on=False, fontsize=10) # x-z extent = [xmin, xmax, zmin, zmax] ix0 = 0 ix = nx iz0 = 0 iz = nz if (not xmin_pass == None): extent[0] = xmin_pass ix0 = int((xmin_pass - xmin) / dx) if (not zmin_pass == None): extent[2] = zmin_pass iz0 = int((zmin_pass - zmin) / dz) if (not xmax_pass == None): extent[1] = xmax_pass ix = int((xmax_pass - xmin) / dx) if (not zmax_pass == None): extent[3] = zmax_pass iz = int((zmax_pass - zmin) / dz) ax = pylab.subplot(1, 3, 2) #fig.add_axes(pos2) im = pylab.imshow(data_xz[iz0:iz, ix0:ix], origin='lower', extent=extent, vmin=minval, vmax=maxval, axes=pos2) pylab.xlabel("x") pylab.ylabel("z") # axis labels in scientific notation with LaTeX ax = pylab.gca() ax.xaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) ax.yaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) ax.xaxis.offsetText.set_fontsize("small") ax.yaxis.offsetText.set_fontsize("small") cl = pylab.getp(ax, 'ymajorticklabels') pylab.setp(cl, fontsize=10) cl = pylab.getp(ax, 'xmajorticklabels') pylab.setp(cl, fontsize=10) # y-z extent = [ymin, ymax, zmin, zmax] iy0 = 0 iy = ny iz0 = 0 iz = nz if (not ymin_pass == None): extent[0] = ymin_pass iy0 = int((ymin_pass - ymin) / dy) if (not zmin_pass == None): extent[2] = zmin_pass iz0 = int((zmin_pass - zmin) / dz) if (not ymax_pass == None): extent[1] = ymax_pass iy = int((ymax_pass - ymin) / dy) if (not zmax_pass == None): extent[3] = zmax_pass iz = int((zmax_pass - zmin) / dz) ax = pylab.subplot(1, 3, 3) #fig.add_axes(pos3) im = pylab.imshow(data_yz[iz0:iz, iy0:iy], origin='lower', extent=extent, vmin=minval, vmax=maxval, axes=pos3) pylab.xlabel("y") pylab.ylabel("z") # axis labels in scientific notation with LaTeX ax = pylab.gca() ax.xaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) ax.yaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) ax.xaxis.offsetText.set_fontsize("small") ax.yaxis.offsetText.set_fontsize("small") cl = pylab.getp(ax, 'ymajorticklabels') pylab.setp(cl, fontsize=10) cl = pylab.getp(ax, 'xmajorticklabels') pylab.setp(cl, fontsize=10) # colorbar pylab.subplots_adjust(bottom=0.1, left=0.05, right=0.95) formatter = matplotlib.ticker.ScalarFormatter(useMathText=True) cax = pylab.axes([0.05, 0.06, 0.9, 0.04]) pylab.colorbar(orientation="horizontal", cax=cax, format=formatter) pylab.title(component) #-------------------------------------------------------------------------- # save the figure #-------------------------------------------------------------------------- # try: pylab.tight_layout() # requires matplotlib >= 1.1 # except: # pass if (not eps): pylab.savefig(outFile, bbox_inches='tight', dpi=dpi, pad_inches=0.33) else: pylab.savefig(outFile) #, bbox_inches='tight', pad_inches=0.33)
"b--", label='DFT $n$') #n_plt.plot(r/2,n0*4*numpy.pi/3,"c-.",label="$n_0$") #n_plt.plot(r/2,nA*4*numpy.pi/3,"m--",label="$n_A$") #n_plt.plot(r_2[r_2>=radius],n_2[r_2>=radius]*4*numpy.pi/3,"b--",label='DFT $n$ (mark II)') #n_plt.plot(r,n0*4*numpy.pi/3,"c--",label="$n_0$") #n_plt.plot(r,nA*4*numpy.pi/3,"m-.",label="$n_A$") if (n[dft_len - 3] * 4 * numpy.pi / 3 < 0.15 and n[dft_len - 3] * 4 * numpy.pi / 3 > 0.05): n_plt.legend(loc='lower right', ncol=1).draw_frame(False) #get_frame().set_alpha(0.5) else: n_plt.legend(loc='upper right', ncol=1).draw_frame(False) #get_frame().set_alpha(0.5) n_plt.yaxis.set_major_locator( pylab.MaxNLocator(3, steps=[1, 5, 10], prune='upper')) pylab.xlim(showrmin / 2, showrmax / 2) pylab.ylim(0, n.max() * 4 * numpy.pi / 3 * 1.1) pylab.xlabel(r"$r$/$\sigma$") pylab.ylabel("filling fraction") #pylab.legend(loc='lower left', ncol=2).get_frame().set_alpha(0.5) #pylab.twinx() off = 2 me = 4 A_plt = pylab.subplot(3, 1, 1) #A_plt.set_title("Spherical solute with radius %s and filling fraction 0.%s" % (radiusname, ffdigit)) A_plt.axvline(x=radius / 2, color='k', linestyle=':') A_plt.plot(r_mc / 2, gA_mc, "r-", label="$r_\sigma^A$ MC")
def plotit(dftdata, mcdata): dft_len = len(dftdata[:, 0]) dft_dr = dftdata[2, 0] - dftdata[1, 0] mcdata = numpy.insert(mcdata, 0, 0, 0) mcdata[0, 0] = -10 mcoffset = 10 / 2 offset = -3 / 2 n0 = dftdata[:, 6] nA = dftdata[:, 8] nAmc = mcdata[:, 11] n0mc = mcdata[:, 10] pylab.figure(figsize=(4, 4)) pylab.subplots_adjust(hspace=0.001) n_plt = pylab.subplot(3, 1, 3) n_plt.plot(mcdata[:, 0] / 2 + mcoffset, mcdata[:, 1] * 4 * numpy.pi / 3, "b-", label='$n$ Monte Carlo') n_plt.yaxis.set_major_locator( pylab.MaxNLocator(6, steps=[1, 5, 10], prune='upper')) pylab.ylim(ymin=0) pylab.xlim(xmin, xmax) pylab.xlabel("$z/\sigma$") pylab.ylabel("$n(\mathbf{r})$") n_plt.axvline(x=0, color='k', linestyle=':') n = len(mcdata[:, 0]) #pylab.twinx() stop_here = int(dft_len - 1 / dft_dr) print stop_here start_here = int(2.5 / dft_dr) off = 1 me = 55 A_plt = pylab.subplot(3, 1, 1) A_plt.axvline(x=0, color='k', linestyle=':') A_plt.plot(mcdata[:, 0] / 2 + mcoffset, mcdata[:, 2 + 2 * off] / nAmc, "r-", label="$g_\sigma^A$ Monte Carlo") A_plt.yaxis.set_major_locator( pylab.MaxNLocator(integer=True, prune='upper')) pylab.ylim(ymin=0) pylab.ylabel("$g_\sigma^A$") pylab.xlim(xmin, xmax) n0mc[0] = 1 mcdata[0, 10] = 1 S_plt = pylab.subplot(3, 1, 2) S_plt.axvline(x=0, color='k', linestyle=':') S_plt.plot(mcdata[:, 0] / 2 + mcoffset, mcdata[:, 3 + 2 * off] / n0mc, "g-", label="$g_\sigma^S$ Monte Carlo") S_plt.yaxis.set_major_locator( pylab.MaxNLocator(5, integer=True, prune='upper')) pylab.xlim(xmin, xmax) pylab.ylim(ymin=0) pylab.ylabel("$g_\sigma^S$") xticklabels = A_plt.get_xticklabels() + S_plt.get_xticklabels() pylab.setp(xticklabels, visible=False)
def jm_set_Yvar_ticks(myScale=4): xa=pl.gca() xa.yaxis.set_major_locator(pl.MaxNLocator(myScale)) jm_clip_Yticks()
def contourTri(chain,**kwargs): """ #Given a chain, labels and a list of which parameters to plot, plots the contours # Arguments: # chain=an array of the chain (not using weights, i.e. each row counts only once) # p= a list of integers: the two parameters you want to plot (refers to two columns in the chain) #kwargs: labels= the labels of the parameters (list of strings) # col=a tuple of the two colours for the contour plot # line=boolean whether or not to just do a line contour plot # outfile='triangle.png' # binsize=50 # reconstruct=boolean whether or not to plot reconstruction # autoscale=boolean whether or not to autoscale axes # ranges=dictionary of plot range lists, labelled by # parameter name, e.g. {'A':[0.0,1.0],etc.} # title=outdir p is now ignored """ # Collate the contour-region info bundle=chain TRUNCATE_C=False FONTSIZE=6.5 #For 2 models FONTSIZE=13# ROTATION=60.0 ROTATION_r_xticks=240 ROTATION_r_ylabels= 270 ROTATION_r_yticks=210 Rotate_axis=False FIGSIZE=(5.,5.); DPI=300 #FIGSIZE=(8.27,11.69); DPI=400 AXIS_LABEL_OFFSET=-0.5 #-0.7 if 'FONTSIZE' in kwargs: FONTSIZE=kwargs['FONTSIZE'] if 'Y_LABEL_OFFSET' in kwargs: X_LABEL_OFFSET=kwargs['X_LABEL_OFFSET'] if 'Y_LABEL_OFFSET' in kwargs: Y_LABEL_OFFSET=kwargs['Y_LABEL_OFFSET'] #X_LABEL_OFFSET= x_LABEL_OFFSET#-0.6 #-0.8 #Y_LABEL_OFFSET= y_LABEL_OFFSET #-0.6 # !!!! BEWARE THE BINSIZE --- PLOT IS A STRONG FUNCTION OF THIS if 'binsize' in kwargs: binsize=kwargs['binsize'] else: binsize=50 print 'Using binsize = %i' % binsize if 'labels' in kwargs: labels=kwargs['labels'] parameters=labels # How did this ever work without?? else: labels = ['x', 'y'] if 'ranges' in kwargs: ranges=kwargs['ranges'] else: ranges=None if 'title' in kwargs: title=kwargs['title'] else: title='' if 'autoscale' in kwargs: autoscale=kwargs['autoscale'] else: autoscale=True p = range(len(labels)) pairs = trianglePairs(p) nparams = len(p) # Start setting up the plot ipanel=0; ax={} pylab.clf() for panel in pairs: ipanel+=1 H,xedges,yedges=numpy.histogram2d(chain[:,panel[0]],chain[:,panel[1]],bins=(binsize,binsize)) x=[] y=[] z=[] for i in range(len(xedges[:-1])): for j in range(len(yedges[:-1])): x.append(xedges[:-1][i]) y.append(yedges[:-1][j]) z.append(H[i, j]) SMOOTH=False if SMOOTH: sz=50 smth=80e6 spl = interpolate.bisplrep(x, y, z, s=smth) X = numpy.linspace(min(xedges[:-1]), max(xedges[:-1]), sz) Y = numpy.linspace(min(yedges[:-1]), max(yedges[:-1]), sz) Z = interpolate.bisplev(X, Y, spl) else: X=xedges[:-1] Y=yedges[:-1] Z=H #I think this is the weird thing I have to do to make the contours work properly X1=numpy.zeros([len(X), len(X)]) Y1=numpy.zeros([len(X), len(X)]) for i in range(len(X)): X1[ :, i]=X Y1[i, :]=Y X=X1 Y=Y1 N100,N95,N68 = findconfidence(Z) if 'col' in kwargs: col=kwargs['col'] else: col =('#a3c0f6','#0057f6') #A pretty blue #col =('#a8a495','#929591') #grey and dark gray #d8dcd6 light gray # Now construct the subplot ax[ipanel]=pylab.subplot2grid((nparams,nparams),panel[::-1]) # Reverse quadrant if 'line' in kwargs and kwargs['line']==True: CS=pylab.contour(X, Y,Z,levels=[N95,N68,N100],colors=col, linewidth=100) else: CS=pylab.contourf(X, Y,Z,levels=[N95,N68,N100],colors=col) # Identify points lying within 68 percent contour region #print ipanel,bundle.shape,chain.shape #v=CS.collections[0].get_paths()[0].vertices #w=CS.collections[1].get_paths()[0].vertices #print v[:,0] #print v[:,1] #b=bundle[:,[panel[0],panel[1]]] #mask=Path(v).contains_points(b) #mask2=Path(w).contains_points(b) #print panel[0],panel[1],b[:,0].size,b[:,0][mask].size,b[:,0][mask2].size,labels[panel[0]],labels[panel[1]] if 'truth' in kwargs and kwargs['truth'] is not None: truth=kwargs['truth'] #pylab.plot(truth[labels[panel[0]]],truth[labels[panel[1]]],'r+',\ #markersize=20) #Truth vales using MAP mx,my = numpy.where(Z==Z.max()) #print mx,my, X[panel[0]][mx],Y[panel[1],my] #s pylab.plot(X[mx[0],panel[0]],Y[panel[1],my[0]],'r+',\ markersize=5) if 'labelDict' in kwargs and kwargs['labelDict'] is not None: labelDict=kwargs['labelDict'] else: labelDict=dict((name,name) for name in parameters) # Set the axis labels only for left and bottom: #print ax[ipanel].get_xlabel(),ax[ipanel].get_ylabel() if panel[1] == (nparams-1): ax[ipanel].set_xlabel(labelDict[labels[panel[0]]],fontsize=FONTSIZE+2.5)#+5 skads pl ax[ipanel].xaxis.set_label_coords(0.5,X_LABEL_OFFSET) # align axis labels ax[ipanel].xaxis.set_major_formatter(FormatStrFormatter('%.1f')) ax[ipanel].yaxis.set_major_formatter(FormatStrFormatter('%.1f')) #ax[ipanel].xaxis.set_major_locator(pylab.MaxNLocator(4)) ax[ipanel].xaxis.set_minor_locator(pylab.MaxNLocator(4)) else: ax[ipanel].set_xlabel('') ax[ipanel].get_xaxis().set_ticklabels([]) ax[ipanel].yaxis.set_major_locator(pylab.MaxNLocator(4)) if panel[0] == 0: if Rotate_axis: ax[ipanel].set_ylabel(labelDict[labels[panel[1]]],fontsize=FONTSIZE+0.,rotation=ROTATION_r_ylabels)#+1 skads pl else: ax[ipanel].set_ylabel(labelDict[labels[panel[1]]],fontsize=FONTSIZE+0.)#+1 skads pl ax[ipanel].yaxis.set_label_coords(Y_LABEL_OFFSET,0.5) # align axis labels #ax[ipanel].xaxis.set_major_formatter(FormatStrFormatter('%.2f')) ax[ipanel].yaxis.set_major_locator(pylab.MaxNLocator(4)) #ax[ipanel].xaxis.set_minor_locator(pylab.MaxNLocator(2)) ax[ipanel].yaxis.set_major_formatter(FormatStrFormatter('%.1f')) else: ax[ipanel].set_ylabel('') ax[ipanel].get_yaxis().set_ticklabels([]) if panel[0]==6 or panel[0]==4 or panel[0]==7 or panel[0]==10 or panel[0]==3: ax[ipanel].xaxis.set_major_locator(pylab.MaxNLocator(4)) # Set plot limits if autoscale: # HACK FOR C ONLY: if TRUNCATE_C:# and panel[0]==0: xxlo,xxhi=ax[ipanel].xaxis.get_data_interval() print 'nani','\n \n \n \n' if xxhi>1.0e4: pylab.xlim(xxlo,1.0e4) #ax[ipanel].set_xscale('log') autoscale=True #locs,labels = plt.xticks() #plt.xticks(locs, map(lambda x: "%g" % x, locs*1.0e5)) else: xlo=ranges[labels[panel[0]]][0] xhi=ranges[labels[panel[0]]][1] ylo=ranges[labels[panel[1]]][0] yhi=ranges[labels[panel[1]]][1] pylab.xlim(xlo,xhi) pylab.ylim(ylo,yhi) # Some housekeeping if Rotate_axis: pylab.yticks(fontsize=FONTSIZE,rotation=ROTATION_r_yticks) pylab.xticks(fontsize=FONTSIZE,rotation=ROTATION_r_xticks) else: pylab.xticks(fontsize=FONTSIZE,rotation=ROTATION) pylab.yticks(fontsize=FONTSIZE,rotation=0) pylab.locator_params(nbins=4) # Set up the 1-D plots on the diagonal if nparams==5: ipanel=[4,7,9,10] #for a single model pl bottom,top,left, right=bottom=0.12, 0.99, 0.11 ,0.95 elif nparams==6: ipanel=[5,9,12,14,15] bottom,top,left, right=0.14, 0.99, 0.11 ,0.95 elif nparams==12: ipanel=[11,21,30,38,45,51,56,60,63,65,66] #this for two models bottom,top,left, right=0.074, 0.99, 0.06, 0.99 for iparam in range(nparams): # b=numpy.histogram(R,bins=bins) J,edges=numpy.histogram(chain[:,iparam],density=True,bins=binsize) ax1d=pylab.subplot2grid((nparams,nparams),(iparam,iparam)) pylab.plot(edges[:-1],J,color='#0057f6',linewidth=1) #print iparam,nparplotplotams,labels[iparam] #if 'truth' in kwargs and kwargs['truth'] is not None: # truth=kwargs['truth'] #pylab.axvline(truth[parameters[iparam]],color='r') if iparam == 99: # 0we don't really need the label for the top hist ax1d.set_ylabel(labelDict[labels[iparam]],fontsize=FONTSIZE+0.) #+1 skads pl ax1d.yaxis.set_label_coords(Y_LABEL_OFFSET,0.5) # align axis labels if iparam == (nparams-1): ax1d.set_xlabel(labelDict[labels[iparam]],fontsize=FONTSIZE+3.5) #+5 skads pl +4 skads ax1d.xaxis.set_label_coords(0.5,X_LABEL_OFFSET) # align axis labels # Set plot limits #parameters=['x', 'y', 'S', 'sig', 'Q', 'el', 'em', 'R'] if autoscale: # HACK FOR C ONLY: if TRUNCATE_C and iparam==0: xxlo,xxhi=ax1d.xaxis.get_data_interval() if xxhi>1.0e4: pylab.xlim(xxlo,1.0e4) #ax1d.set_xscale('log') autoscale=True #if iparam <5: #1 model #if iparam <4: # pl if iparam <(nparams-1): #The 1d hist is sometimes mis-aligned with the 2dhist xlo,xhi=ax[ipanel[iparam]].get_xlim() pylab.xlim(xlo,xhi) if not autoscale: xlo,xhi=ranges[parameters[iparam]] pylab.xlim(xlo,xhi) if TRUNCATE_C:# and iparam==0: xxlo,xxhi=ax1d.xaxis.get_data_interval() if xxhi>1.0e4: pylab.xlim(xxlo,1.0e4) if iparam < (nparams-1): ax1d.get_xaxis().set_ticklabels([]) ax1d.get_yaxis().set_ticklabels([]) if Rotate_axis: pylab.xticks(fontsize=FONTSIZE,rotation=ROTATION_r_xticks) else: pylab.xticks(fontsize=FONTSIZE,rotation=ROTATION) pylab.yticks(fontsize=FONTSIZE) pylab.locator_params(nbins=3) #if iparam == 12: ax[iparam].xaxis.set_major_locator(pylab.MaxNLocator(3)) #ax1d.set_xscale('linear') #axinfo=pylab.subplot2grid((nparams,nparams),(0,nparams-3)) axinfo=pylab.subplot2grid((nparams,nparams),(0,nparams-nparams%2-1)) axinfo.get_xaxis().set_visible(False) axinfo.get_yaxis().set_visible(False) pylab.axis('off') pylab.title(title) # Plot the truth - this needs to be generalized for non-lumfunc if 'truth' in kwargs and kwargs['truth'] is not None: truth=kwargs['truth'] note=['nparams %i\n truth:' % nparams] for k,v in truth.items(): notelet='%s = %4.2e' % (k,v) note.append(notelet) #pylab.text(-1,-1,'\n'.join(note)) if 'reconstruct' in kwargs: reconstruct=kwargs['reconstruct'] axrecon=pylab.subplot2grid((nparams,nparams),(0,nparams-2),\ rowspan=2,colspan=2) axrecon.set_xscale('log') axrecon.set_yscale('log') pylab.xticks(fontsize=FONTSIZE,rotation=60) pylab.yticks(fontsize=FONTSIZE) pylab.locator_params(nbins=5) median_bins=medianArray(reconstruct[0]) dnds=calculateDnByDs(median_bins,reconstruct[1]) dndsN=calculateDnByDs(median_bins,ksNoisy) print median_bins print dnds print 'truth items \n' print truth.items() recon=numpy.zeros(numpy.shape(median_bins)) post=numpy.zeros(numpy.shape(median_bins)) print '# i Smedian ks dnds dndsS2.5 NRecon dndsRecon dndsS2.5Recon log10dnds log10dndsR diffR dndsN' if nparams == 4: (C,alpha,Smin,Smax)\ =(truth['C'],truth['alpha'],truth['Smin'],truth['Smax']) area=10.0 # Hack # Reconstruct powerLaw points given truth for i in range(len(median_bins)): recon[i]=powerLawFuncS(median_bins[i],\ C,alpha,Smin,Smax,area) post[i]=powerLawFuncS(median_bins[i],\ 9.8,-0.63,0.04,14.1,area) #recon *= lumfunc.ksRaw #dndsR=lumfunc.calculateDnByDs(median_bins,recon) # **** XXXX Where does the 1000 come from!? :(( XXXX dndsR=recon*1000.0 dndsP=post*1000.0 # cols: i Smedian ks dnds dndsS2.5 NRecon dndsRecon # dndsS2.5Recon log10dnds log10dndsR diffR dndsN for i in range(len(median_bins)): print '%i %f %i %i %i %i %i %i %f %f %i %i' % (i,median_bins[i],\ reconstruct[-1][i],dnds[i],\ dnds[i]*median_bins[i]**2.5,recon[i],dndsR[i],\ dndsR[i]*median_bins[i]**2.5,numpy.log10(dnds[i]),\ numpy.log10(dndsR[i]),int(dndsR[i]-dnds[i]),dndsN[i]) #print recon pylab.xlim(reconstruct[0][0],reconstruct[0][-1]) #pylab.ylim(1.0e2,1.0e8) #pylab.plot(median_bins,dnds*numpy.power(median_bins,2.5)*lumfunc.sqDeg2sr,'+') power=2.5 pylab.plot(median_bins,dnds*sqDeg2sr*numpy.power(median_bins,power),'+') pylab.plot(median_bins,dndsR*sqDeg2sr*numpy.power(median_bins,power),'-') pylab.plot(median_bins,dndsN*sqDeg2sr*numpy.power(median_bins,power),'+') pylab.plot(median_bins,dndsP*sqDeg2sr*numpy.power(median_bins,power),'-') #pylab.plot(dnds,dndsR*numpy.power(median_bins,1.0)) #b=lumfunc.simtable(lumfunc.bins,a=-1.5,seed=1234,noise=10.0,dump=False) if 'outfile' in kwargs: outfile=kwargs['outfile'] pylab.subplots_adjust(wspace=0.05, hspace=0.05, bottom=0.16, top=0.99,left=0.11,right=0.95) #pl #pylab.subplots_adjust(wspace=0.05, hspace=0.05, bottom=bottom, top=top,left=left,right=right) #two models #pylab.subplots_adjust(wspace=0.05, hspace=0.05, bottom=0.2, top=0.99,left=0.21,right=0.95) #skads pylab.show() pylab.savefig(outfile,figsize=FIGSIZE,dpi=DPI) print 'Run: open %s' % outfile pylab.close() else: pylab.show() return bundle
def sane_axes(): fig.gca().xaxis.set_major_locator(pl.MaxNLocator(4)) fig.gca().yaxis.set_major_locator(pl.MaxNLocator(5)) fig.gca().set_aspect('equal', 'datalim')
def plotit(dftdata, mcdata): dft_len = len(dftdata[:, 0]) dft_dr = dftdata[2, 0] - dftdata[1, 0] mcdata = numpy.insert(mcdata, 0, 0, 0) mcdata[0, 0] = -10 mcoffset = 10 / 2 offset = -3 / 2 n0 = dftdata[:, 6] nA = dftdata[:, 8] nAmc = mcdata[:, 11] n0mc = mcdata[:, 10] pylab.figure(figsize=(6, 6)) pylab.subplots_adjust(hspace=0.001) n_plt = pylab.subplot(3, 1, 3) n_plt.plot(mcdata[:, 0] / 2 + mcoffset, mcdata[:, 1] * 4 * numpy.pi / 3, "b-", label='$n$ Monte Carlo') n_plt.plot(dftdata[:, 0] / 2 + offset, dftdata[:, 1] * 4 * numpy.pi / 3, "b--", label='$n$ DFT') n_plt.legend(loc='best', ncol=1).draw_frame(False) #.get_frame().set_alpha(0.5) n_plt.yaxis.set_major_locator( pylab.MaxNLocator(6, steps=[1, 5, 10], prune='upper')) pylab.ylim(ymin=0) pylab.xlim(xmin, xmax) pylab.xlabel("$z/\sigma$") pylab.ylabel("$n(\mathbf{r})$") n_plt.axvline(x=0, color='k', linestyle=':') n = len(mcdata[:, 0]) #pylab.twinx() dftr = dftdata[:, 0] / 2 + offset thiswork = dftdata[:, 5] gross = dftdata[:, 7] stop_here = int(dft_len - 1 / dft_dr) print stop_here start_here = int(2.5 / dft_dr) off = 1 me = 40 A_plt = pylab.subplot(3, 1, 1) A_plt.axvline(x=0, color='k', linestyle=':') A_plt.plot(mcdata[:, 0] / 2 + mcoffset, mcdata[:, 2 + 2 * off] / nAmc, "r-", label="$g_\sigma^A$ Monte Carlo") A_plt.plot(dftr[dftr >= 0], thiswork[dftr >= 0], "ro", markevery=me * .8, label="$g_\sigma^A$ this work") A_plt.plot(dftr[dftr >= 0], gross[dftr >= 0], "rx", markevery=me, label="Gross", markerfacecolor='none', markeredgecolor='red', markeredgewidth=1) A_plt.legend(loc='best', ncol=1).draw_frame(False) #.get_frame().set_alpha(0.5) A_plt.yaxis.set_major_locator( pylab.MaxNLocator(integer=True, prune='upper')) pylab.ylim(ymin=0) pylab.ylabel("$g_\sigma^A$") pylab.xlim(xmin, xmax) n0mc[0] = 1 mcdata[0, 10] = 1 S_plt = pylab.subplot(3, 1, 2) S_plt.axvline(x=0, color='k', linestyle=':') S_plt.plot(mcdata[:, 0] / 2 + mcoffset, mcdata[:, 3 + 2 * off] / n0mc, "g-", label="$g_\sigma^S$ Monte Carlo") S_plt.plot(dftdata[:, 0] / 2 + offset, dftdata[:, 4], "gx", markevery=me / 2, label="Yu and Wu") S_plt.legend(loc='best', ncol=1).draw_frame(False) #.get_frame().set_alpha(0.5) #pylab.ylim(ymax=12) S_plt.yaxis.set_major_locator( pylab.MaxNLocator(5, integer=True, prune='upper')) pylab.xlim(xmin, xmax) pylab.ylim(ymin=0) pylab.ylabel("$g_\sigma^S$") xticklabels = A_plt.get_xticklabels() + S_plt.get_xticklabels() pylab.setp(xticklabels, visible=False)
edgecolor='k') H, L, P = ax.hist(cores_merge['peak'], bins=bins, facecolor='none', histtype='step') ax.set_xscale('log') ax.set_ylim(0, H.max() + 1) ax.set_xlim(0.001, 15) ax.set_ylabel("Peak") ax.xaxis.set_ticklabels([]) ax.set_xlabel("Peak $T_B$ [K]") ax.set_xlabel("") max_yticks = 3 yloc = pl.MaxNLocator(max_yticks) ax.yaxis.set_major_locator(yloc) class_colors = { 'DustyHII': 'w', 'ExtendedColdCore': 'b', 'ExtendedHotCore': 'k', #'HII': 'w', 'HotCore': 'g', 'StarlessCore': 'r', 'UncertainCompact': 'c', 'UncertainExtended': 'y', } print() print("Fit each aperture excluding free-free fluxes")
gain_sums = np.sum(np.abs(gains[:, 0, :, 0, 0]), 1) gain_std = np.std(np.sum(np.abs(gains[:, 0, :, 0, 0]), 1)) print sq_ants fig, ax = pl.subplots(gparrsz[0], gparrsz[1], sharex='all', sharey='all') #fig.set_size_inches(10,10) for i in range(gparrsz[0]): for j in range(gparrsz[1]): if np.sum(np.angle(gains[sq_ants[i, j], 0, :, 0, 0])) > .0: #ax[i,j].set_title(str(sq_ants[i,j]+1)) ax[i, j].plot(frqs, np.abs(gains[sq_ants[i, j], 0, :, 0, 0]), '.', markersize=1) ax[i, j].xaxis.set_major_locator(pl.MaxNLocator(3)) ax[i, j].yaxis.set_major_locator(pl.MaxNLocator(3)) pl.xlim(120, 180) good_ant = np.abs(gain_sums[sq_ants[i, j]] - np.mean(gain_sums)) < gain_std if good_ant: ax[i, j].annotate(str(sq_ants[i, j]), xy=(.65, .1), xycoords='axes fraction') else: ax[i, j].annotate(str(sq_ants[i, j]), xy=(.65, .1), xycoords='axes fraction', color='r') else: ax[i, j].annotate(str(sq_ants[i, j]),
def dovis(myData, n): pylab.clf() pylab.rc("font", size=10) dens = myData.getVarPtr("density") xmom = myData.getVarPtr("x-momentum") ymom = myData.getVarPtr("y-momentum") ener = myData.getVarPtr("energy") # get the velocities u = xmom/dens v = ymom/dens # get the pressure magvel = u**2 + v**2 # temporarily |U|^2 rhoe = (ener - 0.5*dens*magvel) magvel = numpy.sqrt(magvel) # access gamma from the object instead of using the EOS so we can # use dovis outside of a running simulation. gamma = myData.getAux("gamma") p = rhoe*(gamma - 1.0) e = rhoe/dens myg = myData.grid # figure out the geometry L_x = myData.grid.xmax - myData.grid.xmin L_y = myData.grid.ymax - myData.grid.ymin orientation = "vertical" shrink = 1.0 sparseX = 0 allYlabel = 1 if (L_x > 2*L_y): # we want 4 rows: # rho # |U| # p # e fig, axes = pylab.subplots(nrows=4, ncols=1, num=1) orientation = "horizontal" if (L_x > 4*L_y): shrink = 0.75 elif (L_y > 2*L_x): # we want 4 columns: # # rho |U| p e fig, axes = pylab.subplots(nrows=1, ncols=4, num=1) if (L_y >= 3*L_x): shrink = 0.5 sparseX = 1 allYlabel = 0 else: # 2x2 grid of plots with # # rho |u| # p e fig, axes = pylab.subplots(nrows=2, ncols=2, num=1) pylab.subplots_adjust(hspace=0.25) ax = axes.flat[0] img = ax.imshow(numpy.transpose(dens[myg.ilo:myg.ihi+1,myg.jlo:myg.jhi+1]), interpolation="nearest", origin="lower", extent=[myg.xmin, myg.xmax, myg.ymin, myg.ymax]) ax.set_xlabel("x") ax.set_ylabel("y") ax.set_title(r"$\rho$") if sparseX: ax.xaxis.set_major_locator(pylab.MaxNLocator(3)) pylab.colorbar(img, ax=ax, orientation=orientation, shrink=shrink) ax = axes.flat[1] img = ax.imshow(numpy.transpose(magvel[myg.ilo:myg.ihi+1,myg.jlo:myg.jhi+1]), interpolation="nearest", origin="lower", extent=[myg.xmin, myg.xmax, myg.ymin, myg.ymax]) ax.set_xlabel("x") if (allYlabel): ax.set_ylabel("y") ax.set_title("U") if sparseX: ax.xaxis.set_major_locator(pylab.MaxNLocator(3)) pylab.colorbar(img, ax=ax, orientation=orientation, shrink=shrink) ax = axes.flat[2] img = ax.imshow(numpy.transpose(p[myg.ilo:myg.ihi+1,myg.jlo:myg.jhi+1]), interpolation="nearest", origin="lower", extent=[myg.xmin, myg.xmax, myg.ymin, myg.ymax]) ax.set_xlabel("x") if (allYlabel): ax.set_ylabel("y") ax.set_title("p") if sparseX: ax.xaxis.set_major_locator(pylab.MaxNLocator(3)) pylab.colorbar(img, ax=ax, orientation=orientation, shrink=shrink) ax = axes.flat[3] img = ax.imshow(numpy.transpose(e[myg.ilo:myg.ihi+1,myg.jlo:myg.jhi+1]), interpolation="nearest", origin="lower", extent=[myg.xmin, myg.xmax, myg.ymin, myg.ymax]) ax.set_xlabel("x") if (allYlabel): ax.set_ylabel("y") ax.set_title("e") if sparseX: ax.xaxis.set_major_locator(pylab.MaxNLocator(3)) pylab.colorbar(img, ax=ax, orientation=orientation, shrink=shrink) pylab.figtext(0.05,0.0125, "t = %10.5f" % myData.t) #fig.tight_layout() pylab.draw()
def plot_4panel(data, mod, tab, outfile, r_min_k=None, mass_max_lim=2, log=False): # Calculate the model on a similar timescale to the data. tmax = np.max(np.append(data['t_phot1'], data['t_phot2'])) + 90.0 t_mod_ast = np.arange(data['t_ast'].min() - 180.0, tmax, 2) t_mod_pho = np.arange(data['t_phot1'].min(), tmax, 2) # Get the linear motion curves for the source (includes parallax) p_unlens_mod = mod.get_astrometry_unlensed(t_mod_ast) p_unlens_mod_at_ast = mod.get_astrometry_unlensed(data['t_ast']) # Get the lensed motion curves for the source p_lens_mod = mod.get_astrometry(t_mod_ast) p_lens_mod_at_ast = mod.get_astrometry(data['t_ast']) # Geth the photometry m_lens_mod = mod.get_photometry(t_mod_pho, filt_idx=0) m_lens_mod_at_phot1 = mod.get_photometry(data['t_phot1'], filt_idx=0) m_lens_mod_at_phot2 = mod.get_photometry(data['t_phot2'], filt_idx=1) # Calculate the delta-mag between R-band and K-band from the # flat part at the end. tidx = np.argmin(np.abs(data['t_phot1'] - data['t_ast'][-1])) if r_min_k == None: r_min_k = data['mag1'][tidx] - data['mag2'][-1] print('r_min_k = ', r_min_k) # Plotting plt.close(2) plt.figure(2, figsize=(18, 4)) pan_wid = 0.15 pan_pad = 0.09 fig_pos = np.arange(0, 4) * (pan_wid + pan_pad) + pan_pad # Brightness vs. time fm1 = plt.gcf().add_axes([fig_pos[0], 0.36, pan_wid, 0.6]) fm2 = plt.gcf().add_axes([fig_pos[0], 0.18, pan_wid, 0.2]) fm1.errorbar(data['t_phot1'], data['mag1'], yerr=data['mag_err1'], color = mpl_b, fmt='.', alpha=0.05) # fm1.errorbar(data['t_phot2'], data['mag2'] + r_min_k, yerr=data['mag_err2'], # fmt='k.', alpha=0.9) fm1.plot(t_mod_pho, m_lens_mod, 'r-') fm2.errorbar(data['t_phot1'], data['mag1'] - m_lens_mod_at_phot1, yerr=data['mag_err1'], color = mpl_b, fmt='.', alpha=0.05) # fm2.errorbar(data['t_phot2'], data['mag2'] + r_min_k - m_lens_mod_at_phot2, yerr=data['mag_err2'], # fmt='k.', alpha=0.9) # fm2.set_yticks(np.array([0.0, 0.2])) fm1.yaxis.set_major_locator(plt.MaxNLocator(4)) fm2.xaxis.set_major_locator(plt.MaxNLocator(2)) fm2.axhline(0, linestyle='--', color='r') fm2.set_xlabel('Time (HJD)') fm1.set_ylabel('Magnitude') fm1.invert_yaxis() fm2.set_ylabel('Res.') # RA vs. time f1 = plt.gcf().add_axes([fig_pos[1], 0.36, pan_wid, 0.6]) f2 = plt.gcf().add_axes([fig_pos[1], 0.18, pan_wid, 0.2]) f1.errorbar(data['t_ast'], data['xpos']*1e3, yerr=data['xpos_err']*1e3, fmt='k.', zorder = 1000) f1.plot(t_mod_ast, p_lens_mod[:, 0]*1e3, 'r-') f1.plot(t_mod_ast, p_unlens_mod[:, 0]*1e3, 'r--') f1.get_xaxis().set_visible(False) f1.set_ylabel(r'$\Delta \alpha^*$ (mas)') f1.get_shared_x_axes().join(f1, f2) f2.errorbar(data['t_ast'], (data['xpos'] - p_unlens_mod_at_ast[:,0]) * 1e3, yerr=data['xpos_err'] * 1e3, fmt='k.', alpha=1, zorder = 1000) f2.plot(t_mod_ast, (p_lens_mod[:, 0] - p_unlens_mod[:, 0])*1e3, 'r-') f2.axhline(0, linestyle='--', color='r') f2.xaxis.set_major_locator(plt.MaxNLocator(3)) f2.set_xlabel('Time (HJD)') f2.set_ylabel('Res.') # Dec vs. time f3 = plt.gcf().add_axes([fig_pos[2], 0.36, pan_wid, 0.6]) f4 = plt.gcf().add_axes([fig_pos[2], 0.18, pan_wid, 0.2]) f3.errorbar(data['t_ast'], data['ypos']*1e3, yerr=data['ypos_err']*1e3, fmt='k.', zorder = 1000) f3.plot(t_mod_ast, p_lens_mod[:, 1]*1e3, 'r-') f3.plot(t_mod_ast, p_unlens_mod[:, 1]*1e3, 'r--') f3.set_ylabel(r'$\Delta \delta$ (mas)') f3.yaxis.set_major_locator(plt.MaxNLocator(4)) f3.get_xaxis().set_visible(False) f3.get_shared_x_axes().join(f3, f4) f4.errorbar(data['t_ast'], (data['ypos'] - p_unlens_mod_at_ast[:,1]) * 1e3, yerr=data['ypos_err'] * 1e3, fmt='k.', alpha=1, zorder = 1000) f4.plot(t_mod_ast, (p_lens_mod[:, 1] - p_unlens_mod[:, 1])*1e3, 'r-') f4.axhline(0, linestyle='--', color='r') f4.xaxis.set_major_locator(plt.MaxNLocator(3)) # f4.set_yticks(np.array([0.0, -0.2])) # For OB140613 f4.set_xlabel('Time (HJD)') f4.set_ylabel('Res.') # Mass posterior masses = 10**tab['log_thetaE'] / (8.14 * 10**tab['log_piE']) weights = tab['weights'] f5 = plt.gcf().add_axes([fig_pos[3], 0.18, pan_wid, 0.8]) bins = np.arange(0., 10, 0.1) f5.hist(masses, weights=weights, bins=bins, alpha = 0.9, log=log) f5.set_xlabel('Mass (M$_\odot$)') f5.set_ylabel('Probability') f5.set_xlim(0, mass_max_lim) plt.savefig(outfile) return
def plot_spectrum(w_ran, pw, mean_pw, teo_pw, ymax_top=None, ytick_top=None, ytick_bottom=None, yticks=None, split_lims=None, bar_color=[0.7, 0.7, 0.7], line_color='black', lw=1, ms=5): if split_lims is not None: y_max_bottom, y_min_top = split_lims[0], split_lims[1] xlim = [-.5, 9.5] if ymax_top is None: ymax_top = teo_pw.max() if ytick_bottom is None: ytick_bottom = split_lims[0] if ytick_top is None: ytick_top = ymax_top / 2 ylim_top = [y_min_top, ymax_top] ylim_bottom = [0, y_max_bottom] ax_top, ax_bottom = pp.broken_axis(pl.gca(), xlim, ylim_top, ylim_bottom, '', ratio=0.5) pp.bar(pw, N=10, ax=ax_top, color=bar_color, edgecolor=bar_color) pp.bar(pw, N=10, ax=ax_bottom, color=bar_color, edgecolor=bar_color) ax_top.set_xticks([]) ax_top.yaxis.set_major_locator(pl.MaxNLocator(nbins=3)) ax_bottom.plot(mean_pw, marker='s', markersize=ms, linewidth=0, color=line_color, markeredgecolor=line_color) ax_top.plot(mean_pw, marker='s', markersize=ms, linewidth=0, color=line_color, markeredgecolor=line_color) ax_bottom.yaxis.set_major_locator(pl.MaxNLocator(nbins=3)) ax_bottom2 = ax_bottom.twiny() ax_bottom2.set_ylim(ylim_bottom) ax_bottom2.plot(w_ran, teo_pw, color=line_color, linestyle='-', linewidth=lw) ax_bottom2.set_xlim(-0.5, 9.5) ax_bottom2.set_xticks([]) ax_bottom2.set_yticks([0, ytick_bottom]) pp.custom_axes(ax_bottom2) ax_top2 = ax_top.twiny() ax_top2.set_ylim(ylim_top) ax_top2.plot(w_ran, teo_pw, color=line_color, linestyle='-', linewidth=lw) ax_top2.set_xticks([]) ax_top2.set_yticks([ytick_top, ymax_top]) ax_top2.spines['bottom'].set_color('none') ax_top2.set_xlim(-0.5, 9.5) pp.custom_axes(ax_top2) else: pp.custom_axes() pp.bar(pw, N=10, color=bar_color, edgecolor=bar_color) pl.plot(mean_pw, marker='s', markersize=ms, linewidth=0, color=line_color, markeredgecolor=line_color) pl.plot(w_ran, teo_pw, color=line_color, linestyle='-', linewidth=lw) if ymax_top is not None: pl.ylim(0, ymax_top) if yticks is not None: pl.yticks(yticks)