Exemplo n.º 1
0
def plot_nondetection_limits(ax, sn, band, x_col, yerr_col, ymax=1e42):
    """Plot UV luminosity limits for GALEX non-detections."""

    lc = LightCurve(sn, band)

    # Effective filter wavelength
    wl_eff = effective_wavelength(band).value

    # Remove detections, inc. spurious
    detections = lc.detect_csm(DET_SIGMA, count=DET_COUNT)
    nondetections = lc(tmin=XLIM[0], tmax=XLIM[1]).drop(detections.index)

    # Plot nondetections below SN 2015cp luminosity
    below_max = nondetections[PLOT_SIGMA * nondetections[yerr_col] <= ymax]
    ax.scatter(below_max[x_col],
               wl_eff * PLOT_SIGMA * below_max[yerr_col],
               marker='v',
               s=MS_GALEX**2,
               color=COLORS[band],
               edgecolors='none',
               alpha=ALPHA_NON,
               zorder=3,
               rasterized=True)

    return ax
Exemplo n.º 2
0
    def from_name(self,
                  sn_name,
                  band,
                  tstart,
                  scale,
                  sn_info=[],
                  model='Chev94',
                  **kwargs):
        """Generate Injection instance from a supernova name and GALEX band,
        also creating a Supernova and LightCurve object in the process."""

        sn = Supernova(sn_name, sn_info=sn_info)
        lc = LightCurve(sn, band, sed=model)
        return Injection(sn, lc, tstart, scale, **kwargs)
Exemplo n.º 3
0
def run_all(supernovae,
            iterations,
            tstart_lims,
            scale_lims,
            sn_info=[],
            overwrite=False,
            model='Chev94',
            save_dir=SAVE_DIR,
            **kwargs):
    """Run injection recovery trials on all supernovae in given list.
    Inputs:
        supernovae: list of supernova names
        iterations: iterations of injection & recovery for each SN
        tstart_lims: tuple or list of bounds on start time
        scale_lims: tuple or list of bounds on scale factor
        sn_info: supernova info reference DataFrame
        overwrite: bool, whether to overwrite previous save files
        kwargs: keyword arguments for run_trials
    """

    # Remove SNe with previous save files from list
    if not overwrite:
        supernovae = [
            s for s in supernovae
            if not check_save(s, iterations, save_dir=save_dir)
        ]

    for i, sn_name in enumerate(supernovae):
        print('\n%s [%s/%s]' % (sn_name, i + 1, len(supernovae)))
        # Initialize SN object
        sn = Supernova(sn_name, sn_info=sn_info)
        # Import light curves
        lcs = []
        for band in ['FUV', 'NUV']:
            try:
                lc = LightCurve(sn, band, data_dir=DATA_DIR, sed=model)
            except:
                # No data for this channel
                continue

            # Skip if no data after minimum recovery time
            if np.max(lc.data['t_delta_rest']) < RECOV_MIN:
                print(
                    '\tno %s data after minimum %s days past discovery, skipping'
                    % (band, RECOV_MIN))
                continue

            lcs.append(lc)

        # If light curve import was unsuccessful
        if len(lcs) == 0:
            print('\tno data available!')
            continue

        run_trials(sn,
                   lcs,
                   iterations,
                   tstart_lims,
                   scale_lims,
                   model=model,
                   save_dir=save_dir,
                   **kwargs)
Exemplo n.º 4
0
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from light_curve import LightCurve

# sn_name = 'SNLS-04D3df'
# sn_name = 'SDSS-II SN 18647'
sn_name = 'PS1-10k'

lc = LightCurve.from_name(sn_name, 'NUV')

fig, axs = plt.subplots(2, 2, figsize=(8, 5))

fig.suptitle(sn_name)

axs[0, 0].scatter(lc('detxs') / 600, lc('detys') / 600, s=10)
axs[0, 0].set_xlabel('detxs [deg]')
axs[0, 0].set_ylabel('detys [deg]')

axs[0, 1].scatter(lc('detrad') / 600, lc('detxs') / 600, s=10)
axs[0, 1].axvline(0.55, c='r')
axs[0, 1].set_xlabel('detrad [deg]')
axs[0, 1].set_ylabel('detxs [deg]')

axs[1, 0].scatter(lc('detrad') / 600, lc('exptime'), s=10)
axs[1, 0].axvline(0.55, c='r')
axs[1, 0].set_xlabel('detrad [deg]')
axs[1, 0].set_ylabel('exptime')

axs[1, 1].scatter(lc('detrad') / 600, lc('responses'), s=10)
axs[1, 1].axvline(0.55, c='r')
Exemplo n.º 5
0
def main():

    sn_info = pd.read_csv(Path('ref/sn_info.csv'), index_col='name')
    det_sne = ['SN2007on', 'SN2008hv', 'SN2009gf', 'SN2010ai']

    x_col = 't_delta_rest'
    y_col = 'luminosity_hostsub'
    yerr_col = 'luminosity_hostsub_err'

    fig, ax = plt.subplots(figsize=(6.5, 5), tight_layout=True)

    # Plot Swift SN2011fe from Brown+ 2012
    band = 'UVM2'
    disc_date = Time('2011-08-24', format='iso').mjd
    dist = 6.4 * u.Mpc  #from Shappee & Stanek 2011
    dist_err = 0. * u.Mpc
    z = 0  # too close to need correction
    z_err = 0
    a_v = 0  # won't worry about it right now
    a_band = 'NUV'  # close enough
    wl_eff = effective_wavelength(band).value  # UVM2 effective wavelength
    lc = import_swift('SN2011fe', disc_date, z)
    lc = lc[lc['Filter'] == band]
    lc['luminosity'], lc['luminosity_err'] = flux2luminosity(
        lc['flux'], lc['flux_err'], dist, dist_err, z, z_err, a_v, a_band)
    ax.plot(lc['t_delta_rest'],
            wl_eff * lc['luminosity'],
            color='brown',
            label='SN2011fe (%s)' % band,
            zorder=1,
            lw=2,
            rasterized=True)

    # Import and plot HST non-detections
    print('Importing HST non-detections...')
    hst_data = pd.read_csv(Path('ref/Graham_observations.csv'), index_col=0)
    wl_eff = effective_wavelength('F275W').value
    nondetections = hst_data[hst_data['Detection'] == False]
    for i, sn_name in enumerate(nondetections.index):
        obs = GrahamObservation(sn_name, hst_data)
        ax.scatter(obs.rest_phase,
                   wl_eff * obs.luminosity_limit,
                   marker='v',
                   s=MS_HST**2,
                   color='w',
                   edgecolors=COLORS['F275W'],
                   alpha=ALPHA_NON,
                   zorder=3,
                   rasterized=True)

    # Plot near-peak SNe Ia
    for sn_name in det_sne:
        sn = Supernova(sn_name, sn_info)
        band = 'NUV'
        lc = LightCurve(sn, band)
        lc.to_hz()  # Convert to erg/s/Hz units
        # Effective filter frequency
        # nu_eff = (const.c / effective_wavelength(band)).to('Hz').value
        wl_eff = effective_wavelength(band).value
        # Plot near-peak detections
        detections = lc.detect_csm(DET_SIGMA, count=DET_COUNT)
        # ax.errorbar(detections[x_col], nu_eff * detections[y_col],
        #         yerr=nu_eff * detections[yerr_col], label='%s (%s)' % (sn.name, band),
        #         linestyle='none', ms=MS_DET, marker=MARKERS[sn.name],
        #         color=COLORS[sn.name], mec='k', ecolor='k', elinewidth=1,
        #         zorder=9, rasterized=True)
        ax.errorbar(detections[x_col],
                    wl_eff * detections[y_col],
                    yerr=wl_eff * detections[yerr_col],
                    label='%s (%s)' % (sn.name, band),
                    linestyle='none',
                    ms=MS_DET,
                    marker=MARKERS[sn.name],
                    color=COLORS[sn.name],
                    mec='k',
                    ecolor='k',
                    elinewidth=1,
                    zorder=9,
                    rasterized=True)

    # Plot non-detection limits
    print('Importing GALEX detections and limits...')
    for sn_name in tqdm(sn_info.index):
        sn = Supernova(sn_name, sn_info)

        for band in ['FUV', 'NUV']:
            try:
                plot_nondetection_limits(ax,
                                         sn,
                                         band,
                                         x_col,
                                         yerr_col,
                                         ymax=YLIM[1])
            except (FileNotFoundError, pd.errors.EmptyDataError):
                continue

    # Import and plot HST detections
    print('Importing HST detections...')
    wl_eff = effective_wavelength('F275W').value
    detections = hst_data[hst_data['Detection']]
    markers = ['X', '*']
    colors = ['y', 'r']
    sizes = [64, 81]
    for i, sn_name in enumerate(detections.index):
        obs = GrahamObservation(sn_name, hst_data)
        ax.scatter(obs.rest_phase,
                   wl_eff * obs.luminosity,
                   marker=markers[i],
                   color=colors[i],
                   edgecolors='k',
                   label='%s (F275W)' % sn_name,
                   zorder=10,
                   s=sizes[i])

    print('Plotting...')

    # Format axes
    ax.set_xlabel('Time since discovery [rest-frame days]', size=12)
    ax.set_ylabel('$\\lambda L_\\lambda$ [erg s$^{-1}$]', size=12)
    ax.set_xlim(XLIM)
    ax.set_yscale('log')
    ax.set_ylim(YLIM)

    # Legend
    handles, labels = ax.get_legend_handles_labels()
    legend_elements = [
        Line2D([0], [0],
               marker='v',
               markerfacecolor='w',
               markeredgecolor=COLORS['F275W'],
               markersize=MS_HST,
               alpha=ALPHA_NON,
               label='detection limit (F275W)',
               lw=0),
        Line2D([0], [0],
               marker='v',
               markerfacecolor=COLORS['FUV'],
               markeredgecolor='none',
               markersize=MS_GALEX,
               alpha=ALPHA_NON,
               label='detection limit (FUV)',
               lw=0),
        Line2D([0], [0],
               marker='v',
               markerfacecolor=COLORS['NUV'],
               markeredgecolor='none',
               markersize=MS_GALEX,
               alpha=ALPHA_NON,
               label='detection limit (NUV)',
               lw=0)
    ]
    plt.legend(handles=handles + legend_elements,
               loc='lower center',
               ncol=3,
               handletextpad=0.5,
               handlelength=1.0,
               bbox_to_anchor=(0.5, 1.01))

    plt.savefig(Path('out/limits.pdf'), dpi=300)
    plt.savefig(Path('out/limits.png'), dpi=300)

    plt.show()
Exemplo n.º 6
0
sn_info = pd.read_csv(Path('ref/sn_info.csv'), index_col='name')

detections = []
total_epochs = 0
bg_epochs = 0
post_epochs = 0
below_15cp = 0

for sn_name in tqdm(sn_info.index):
    sn = Supernova(sn_name, sn_info)
    below_15cp_val = 0

    for band in ['FUV', 'NUV']:
        try:
            lc = LightCurve(sn, band)
        except (FileNotFoundError, pd.errors.EmptyDataError):
            continue

        # Count observation epochs
        total_epochs += lc.data.shape[0]
        bg_epochs += lc.bg_data.shape[0]
        post_epochs += lc.data[lc.data['t_delta_rest'] > 0].shape[0]

        det = lc.detect_csm(SIGMA, SIGCOUNT)

        if len(det.index) > 0:
            det_info = {
                'name':
                sn_name,
                'band':
    if sn_name in ['SN2007on', 'SN2008hv', 'SN2009gf']:
        lc = import_swift(sn.name, sn.disc_date.mjd, sn.z)
        plot_external(ax, sn, lc, ['UVW1', 'UVM2', 'UVW2'])

    # Plot CfA data
    if sn_name == 'SN2010ai':
        lc = import_cfa(sn)
        plot_external(ax, sn, lc, ['B', 'V', "r'", "i'"], marker='s')

    # Import and plot GALEX data
    ymin = []
    bg_max = 0
    pre_obs = 0
    for band in ['FUV', 'NUV']:
        try:
            lc = LightCurve(sn, band)
            # Pre-SN obs.
            before = lc.data[lc('t_delta_rest') <= DT_MIN]
            pre_obs += len(before.index)
            ymin.append(effective_wavelength(band).value * lc.bg / 1.5)
            bg_max = max(bg_max, lc.bg)

            plot_lc(ax, lc, TMAX)
        except FileNotFoundError:
            # No data for this channel
            continue

    # In-plot labels
    ax.set_title(sn_name.replace('SN', 'SN '), ha='right', va='top', x=0.9, y=0.85, size=14)
    xlim = np.array(ax.get_xlim())