def generate_plots(p_list, fobj, mu_vals, fmt_vals, ax=None): """Makes plots. Yeah. Logical follow-on to generate_tabs""" if ax is None: plt.figure() ax = plt.gca() ax.errorbar(fobj.kevs, fobj.data, yerr=fobj.eps, fmt='ok', label='Data') for p, mu, fmt in zip(p_list, mu_vals, fmt_vals): fit_type = p.metadata['fit-type'] fit_kws = p.metadata['fit-kws'] if fit_type == 'simp': kevs_m = np.linspace(fobj.kevs[0]-0.2, fobj.kevs[-1]+0.2, 100) fwhms_m = models.width_dump(p, kevs_m, fobj.snr) elif fit_type == 'full': fill_kevs = np.linspace(fobj.kevs[0]-0.2, fobj.kevs[-1]+0.2, 5) kevs_m = np.sort(np.hstack((fobj.kevs, fill_kevs))) if fit_kws is not None and 'model_kws' in fit_kws: model_kws = fit_kws['model_kws'] else: model_kws = {} fwhms_m = models.width_cont(p, kevs_m, fobj.snr, verbose=False, **model_kws) ax.plot(kevs_m, fwhms_m, fmt, label=r'$\mu = {:0.2f}$'.format(mu)) # Prepare composite plot fplot('Energy (keV)', 'FWHM (arcsec)', axargs='tight') ax.legend(loc='best') ax.set_title(fobj.title) return ax
def generate_plots(p_list, fobj, mu_vals, fmt_vals, ax=None): """Makes plots. Yeah. Logical follow-on to generate_tabs""" if ax is None: plt.figure() ax = plt.gca() ax.errorbar(fobj.kevs, fobj.data, yerr=fobj.eps, fmt='ok', label='Data') for p, mu, fmt in zip(p_list, mu_vals, fmt_vals): fit_type = p.metadata['fit-type'] fit_kws = p.metadata['fit-kws'] if fit_type == 'simp': kevs_m = np.linspace(fobj.kevs[0] - 0.2, fobj.kevs[-1] + 0.2, 100) fwhms_m = models.width_dump(p, kevs_m, fobj.snr) elif fit_type == 'full': fill_kevs = np.linspace(fobj.kevs[0] - 0.2, fobj.kevs[-1] + 0.2, 5) kevs_m = np.sort(np.hstack((fobj.kevs, fill_kevs))) if fit_kws is not None and 'model_kws' in fit_kws: model_kws = fit_kws['model_kws'] else: model_kws = {} fwhms_m = models.width_cont(p, kevs_m, fobj.snr, verbose=False, **model_kws) ax.plot(kevs_m, fwhms_m, fmt, label=r'$\mu = {:0.2f}$'.format(mu)) # Prepare composite plot fplot('Energy (keV)', 'FWHM (arcsec)', axargs='tight') ax.legend(loc='best') ax.set_title(fobj.title) return ax
def check_eta2_simp(self, eta2_vals, mus, fmts): """Plot chi-squared space for eta2, based on simple model""" ax = plt.gca() for mu, fmt in zip(mus, fmts): b0_vals = [] chisqr_vals = [] for eta2 in eta2_vals: res = self.fitter_simp(mu, eta2=eta2, eta2_free=False) b0_vals.append(res.params['B0']) chisqr_vals.append(res.chisqr) ax.plot(eta2_vals, chisqr_vals, fmt, lw=2) fplot(r'$\eta_2$ (-)', r'Best fit $\chi^2$', scales=('log', 'log')) ax.legend(tuple(r'$\mu = {:0.2f}$'.format(mu) for mu in mus), loc='best') return ax
def check_eta2_simp(self, eta2_vals, mus, fmts): """Plot chi-squared space for eta2, based on simple model""" ax = plt.gca() for mu, fmt in zip(mus, fmts): b0_vals = [] chisqr_vals = [] for eta2 in eta2_vals: res = self.fitter_simp(mu, eta2=eta2, eta2_free=False) b0_vals.append(res.params['B0']) chisqr_vals.append(res.chisqr) ax.plot(eta2_vals, chisqr_vals, fmt, lw=2) fplot(r'$\eta_2$ (-)', r'Best fit $\chi^2$', scales=('log','log')) ax.legend( tuple(r'$\mu = {:0.2f}$'.format(mu) for mu in mus), loc='best') return ax
def check_B0_grid(self, eta2, mus, fmts): """Plot chisqr(B0) from grid for fixed eta2, multiple mu values Verify that we can resolve chisq minimum in B0 grid Input: eta2: where in grid shall we slice? mus: list of mu values to check/plot fmts: list of linespec strings for plots Output: matplotlib.Axis object """ ax = plt.gca() for mu, fmt in zip(mus, fmts): B0_vals, fwhms = self.tab[mu][eta2] chisqr_vals = self.fwhm_scan(fwhms) ax.plot(B0_vals * 1e6, chisqr_vals, fmt) fplot(r'$B_0$ ($\mu$G)', r'$\chi^2$', axargs='tight') return ax
def check_eta2_grid(self, mus, fmts): """Plot chisqr-eta2 space from (eta2,B0) grids for multiple mu values JACKSON POLLOCK DOES ASTROPHYSICS Input: mus: list of mu values to check/plot fmts: list of linespec strings for plots Output: matplotlib.Axis object """ ax = plt.gca() for mu, fmt in zip(mus, fmts): eta2s, B0s, fwhms, chisqrs = self.grid_scan(mu) ax.plot(eta2s, chisqrs, fmt) ax.set_xscale('log') ax.set_yscale('log') ax.legend(tuple(r'$\mu={:0.2f}$'.format(mu) for mu in mus), loc='best') fplot(r'$\eta_2$', r'$\chi^2$', axargs='tight') return ax
def check_B0_grid(self, eta2, mus, fmts): """Plot chisqr(B0) from grid for fixed eta2, multiple mu values Verify that we can resolve chisq minimum in B0 grid Input: eta2: where in grid shall we slice? mus: list of mu values to check/plot fmts: list of linespec strings for plots Output: matplotlib.Axis object """ ax = plt.gca() for mu, fmt in zip(mus, fmts): B0_vals, fwhms = self.tab[mu][eta2] chisqr_vals = self.fwhm_scan(fwhms) ax.plot(B0_vals*1e6, chisqr_vals, fmt) fplot(r'$B_0$ ($\mu$G)', r'$\chi^2$', axargs='tight') return ax
def get_fwhm_fits(rdict, n_reg, labels, fitter, blist_reg=None, **kwargs): """Compute and store FWHM fits for all rdict bands Intended for interactive IPython notebook usage Input: rdict, n_reg: initialized region dict, region number fitter: function passed to bdict_fwhm_fit for profile fitting blist_reg: list of blacklisted (bad) energy bands, else None Other **kwargs (cap, sub_bkg, dx, xconst) sent to bdict_fwhm_fit Output: region dict w/data populated for each energy band """ fig, axes = plt.subplots(1, len(rdict), figsize=(5 * len(rdict), 4)) print '\nRegion: {:02d}\n'.format(n_reg), 10 * '=' for lab, ax in zip(labels, axes): print '\nEnergy band: {}\n'.format(lab) want_err = not (blist_reg and lab in blist_reg) if not want_err: print 'Blacklisted profile' bdict = bdict_fwhm_fit(rdict[lab], fitter, want_err=want_err, **kwargs) print 'FWHM = {}, errors {}'.format(bdict['fwhm'], bdict['errs']) rdu.plot_fwhm_fit(bdict, ax) rdict[lab] = bdict plt.show() plt.figure(figsize=(8, 6)) for lab in labels: bdict = rdict[lab] fwhm = bdict['fwhm'] if np.isfinite(fwhm): nerr, perr = bdict['errs'] en = float(re.split('-', lab)[0]) plt.errorbar([en], [fwhm], yerr=[[nerr], [perr]], fmt='bs') fplot('Energy (keV)', 'FWHM (arcsec)', ax=plt.gca(), axargs=[0., 7., plt.ylim()[0], plt.ylim()[1]]) plt.show() return rdict
def plot_smoothing_cut(bdict, ax, show_smth=True): """Plot cut/uncut data, smoothing used to determine cut (optional) Adds axis labels and sets limits """ x, y, y_err, c = bdict['data'] wlen, wtype = bdict['wlen'], bdict['wtype'] # Plot data outside, inside fit domain ax.errorbar(x[:c], y[:c], yerr=y_err[:c], fmt='r.', capsize=0, alpha=0.5, markersize=3) ax.errorbar(x[c:], y[c:], yerr=y_err[c:], fmt='k.', capsize=0, alpha=1, markersize=3) if show_smth: # Smoothing used to determine fit domain ax.plot(x, fsmooth.std_smooth(y, wlen, wtype), '-k', alpha = 0.3) # IF necessary, use axargs='tight' and ax.set_ylim(0., ax.get_ylim()[1]) fplot('Radial position (arcsec.)', 'Intensity (a.u.)', ax=ax, axargs='tight') ax.set_ylim(0., ax.get_ylim()[1]) return ax
def get_fwhm_fits(rdict, n_reg, labels, fitter, blist_reg=None, **kwargs): """Compute and store FWHM fits for all rdict bands Intended for interactive IPython notebook usage Input: rdict, n_reg: initialized region dict, region number fitter: function passed to bdict_fwhm_fit for profile fitting blist_reg: list of blacklisted (bad) energy bands, else None Other **kwargs (cap, sub_bkg, dx, xconst) sent to bdict_fwhm_fit Output: region dict w/data populated for each energy band """ fig, axes = plt.subplots(1, len(rdict), figsize=(5*len(rdict),4)) print '\nRegion: {:02d}\n'.format(n_reg), 10*'=' for lab, ax in zip(labels, axes): print '\nEnergy band: {}\n'.format(lab) want_err = not(blist_reg and lab in blist_reg) if not want_err: print 'Blacklisted profile' bdict = bdict_fwhm_fit(rdict[lab], fitter, want_err=want_err, **kwargs) print 'FWHM = {}, errors {}'.format(bdict['fwhm'], bdict['errs']) rdu.plot_fwhm_fit(bdict, ax) rdict[lab] = bdict plt.show() plt.figure(figsize=(8,6)) for lab in labels: bdict = rdict[lab] fwhm = bdict['fwhm'] if np.isfinite(fwhm): nerr, perr = bdict['errs'] en = float(re.split('-', lab)[0]) plt.errorbar([en], [fwhm], yerr=[[nerr], [perr]], fmt='bs') fplot('Energy (keV)', 'FWHM (arcsec)', ax=plt.gca(), axargs=[0., 7., plt.ylim()[0], plt.ylim()[1]]) plt.show() return rdict
def generate_plots(rspecs, datroot, pltroot, labels, verbose=False, subplot=False): """Iterate through generated dat files and make multi-band plots""" if subplot: n = len(labels) plt.figure(figsize=(4*n,4)) else: plt.figure(figsize=(6,4)) if verbose: print 'Generating {} plots...'.format(len(rspecs)) print 'First plot will hang a little longer' # Make a plot for each region for i in xrange(len(rspecs)): # Plot line/points for each label for flab, j in zip(labels, xrange(n)): dat_fname = '{0}_{1:02d}_band_{2}.dat'.format(datroot, i+1, flab) a = np.loadtxt(dat_fname) if subplot: plt.subplot(1, n, j+1) # j indexes labels plt.plot(a[:,0], a[:,1], '-o') # Use default color cycle plt.title('Region {:g}, band {}'.format(i+1, flab)) fplot('Radial dist. (?)', 'Intensity? (?)') else: plt.plot(a[:,0], a[:,1], '-o') # Use default color cycle # Format overall plot if not subplot: fplot('Radial dist. (?)', 'Intensity? (?)') plt.title('Region %g' % (i+1)) plt.legend(labels, loc='best') plt.tight_layout() plt.savefig('{0}_{1:02d}.png'.format(pltroot, i+1), dpi=150) plt.clf() if verbose: print 'Saved: {0}_{1:02d}.png'.format(pltroot, i+1)
import numpy as np import matplotlib.pyplot as plt from fplot import fplot a = np.loadtxt('tycho_velocs.txt') msk = a[:, 1] > 2500 nmsk = np.array(map(lambda x: not (x), msk)) plt.errorbar(a[:, 0][msk], a[:, 1][msk], yerr=a[:, 2][msk], fmt='ob') plt.errorbar(a[:, 0][nmsk], a[:, 1][nmsk], yerr=a[:, 2][nmsk], fmt='or') fplot('Azimuthal angle east of north (deg.)', r'Shock velocity (km s${}^{-1}$), with $D = 2.3$ kpc') plt.show() print 'Statistics of data with vs > 2500 km/s' print 'Mean: {}, median: {}'.format(np.mean(a[:, 1][msk]), np.median(a[:, 1][msk])) print 'Min: {}, max: {}'.format(min(a[:, 1][msk]), max(a[:, 1][msk]))
import numpy as np import matplotlib.pyplot as plt from fplot import fplot a = np.loadtxt('tycho_velocs.txt') msk = a[:,1]>2500 nmsk = np.array(map(lambda x: not(x), msk)) plt.errorbar(a[:,0][msk], a[:,1][msk], yerr=a[:,2][msk], fmt='ob') plt.errorbar(a[:,0][nmsk], a[:,1][nmsk], yerr=a[:,2][nmsk], fmt='or') fplot('Azimuthal angle east of north (deg.)', r'Shock velocity (km s${}^{-1}$), with $D = 2.3$ kpc') plt.show() print 'Statistics of data with vs > 2500 km/s' print 'Mean: {}, median: {}'.format(np.mean(a[:,1][msk]), np.median(a[:,1][msk])) print 'Min: {}, max: {}'.format(min(a[:,1][msk]), max(a[:,1][msk]))