def calib_impact(self, sigma_zp, sigma_dl):
     if self.impacted:
         self.J = NTuple.view(self.Jp)
         self.C = NTuple.view(self.Cp)
     else:
         self.Jp = NTuple.view(self.J)
         self.Cp = NTuple.view(self.C)
     ### delta-zp priors
     print 'Adding delta-zp priors'
     self.update_model(['zp' + band for band in 'grizy'], np.identity(5),
                       sigma_zp**2 * np.identity(5))
     self.update_model(['dl' + band for band in 'grizy'], np.identity(5),
                       sigma_dl**2 * np.identity(5))
     self.impacted = True
def create_log(survey_type, mjd_min=59884., _duration=None):
    bands = CARDS[survey_type]['bands']
    texp = CARDS[survey_type]['texp']
    sky = CARDS[survey_type]['sky']
    seeing = CARDS[survey_type]['seeing']
    if _duration is None:
        duration = CARDS[survey_type]['duration']
    else:
        duration = _duration
    cadences = CARDS[survey_type]['cadences']
    m5sig = CARDS[survey_type]['m5sig']
    mjd_max = mjd_min + duration
    log_example = NTuple.fromtxt('Observations_DD_290_LSSTPG.txt')
    dt = log_example.dtype
    dates, _bands, _seeing, _sky, _texp, _m5sig = [], [], [], [], [], []
    for i, band in enumerate(bands):
        date = np.arange(mjd_min, mjd_max, cadences[i])
        dates += [np.arange(mjd_min, mjd_max, cadences[i])]
        ld = len(date)
        _bands += [np.tile(np.array(bands[i]), ld)]
        _seeing += [np.tile(np.array(seeing[i]), ld)]
        _sky += [np.tile(np.array(sky[i]), ld)]
        _texp += [np.tile(np.array(texp[i]), ld)]
        _m5sig += [np.tile(np.array(m5sig[i]), ld)]
    dates = np.hstack(dates)
    log = np.zeros(len(dates), dtype=dt)
    log['mjd'] = dates
    log['band'] = np.hstack(_bands)
    log['seeing'] = np.hstack(_seeing)
    log['sky'] = np.hstack(_sky)
    log['kAtm'] = np.mean(log_example['kAtm'])
    log['airmass'] = 1
    log['exptime'] = np.hstack(_texp)
    log['m5sigmadepth'] = np.hstack(_m5sig)
    return log.view(NTuple)
def open_lc(fichier, tableau):
    idx_name = None
    for i, t_name in enumerate(tableau['name']):
        if t_name not in fichier:
            continue
        else:
            idx_name = i
    if idx_name is None:
        raise NotKeptError('No entry for %s found in the salt2 outpu' %
                           (fichier))
    lc = NTuple.fromtxt(fichier)
    bands = np.array(
        [band.replace('::', '_') for band in np.unique(lc['Filter'])])
    # if lc.keys['SURVEY'] == 'SDSS':
    #     try:
    #         sn_name = lc.keys['SURVEY'] + str(int(lc.keys['SN']))
    #     except ValueError:
    #         sn_name = str(lc.keys['SN'])
    # else:
    #     sn_name = str(lc.keys['SN'])
    _mags = from_salt_results(tableau[idx_name], bands)
    snr, mags, zps = np.zeros(len(bands)), np.zeros(len(bands)), np.zeros(
        len(bands))  #, dtype=np.dtype([(a, float) for a in bands]))
    for i, band in enumerate(bands):
        idx = lc['Filter'] == band.replace('_', '::')
        wi = 1. / lc[idx]['Fluxerr']**2
        fi2 = lc[idx]['Flux']**2
        snr[i] = np.sqrt(np.sum(wi * fi2))
        mags[i] = _mags[bands == band]
        zps[i] = np.mean(lc[idx]['ZP'])
    return bands, mags, snr, zps, tableau[idx_name]
def main_opsim_log(filename='Observations_DD_290_LSSTPG.txt',
                   i_season=0,
                   X1=0.,
                   Color=0.,
                   label=None,
                   tofile=None,
                   zlim=None):

    d = NTuple.fromtxt(filename)
    cut = (d['band'] != 'LSSTPG::u')
    log = snsim.OpSimObsLog(d[cut])
    #    update_log_with_seeing_and_sky(log,
    #                                   seeing = {'LSSTPG::u':  0.92, 'LSSTPG::g': 0.87,  'LSSTPG::r':  0.83,  'LSSTPG::i':  0.80, 'LSSTPG::z':  0.78, 'LSSTPG::y': 0.76},
    #                                   mag_sky= {'LSSTPG::u': 22.95, 'LSSTPG::g': 22.24, 'LSSTPG::r': 21.20 , 'LSSTPG::i': 20.47, 'LSSTPG::z': 19.60, 'LSSTPG::y': 18.63})
    #    update_log_with_seeing_and_sky(log,
    #                                   mag_sky= {'LSSTPG::y': 18.63})

    seasons = log.split()
    log = seasons[i_season]
    lcmodel = init_lcmodel(log)

    instr = [get_instrument(nm) for nm in np.unique(log.instrument)]
    s = snsim.SnSurveyMC(obslog=log,
                         filename='lsst_survey.conf',
                         instruments=instr)

    sne = s.generate_sample()
    sne['X1'] = X1  # -3.
    sne['Color'] = Color  # 0.3

    lc = s.generate_lightcurves(sne, lcmodel, fit=True)
    res = reso(lc)

    fig = pl.figure()
    #    pl.plot(sne['z'], res['eColor'], marker='.', color='gray', ls='')
    p_first = (s.obslog.mjd.min() - sne['DayMax']) / (1. + sne['z'])
    p_last = (s.obslog.mjd.max() - sne['DayMax']) / (1. + sne['z'])
    idx = (p_first < -15.) & (p_last > 20.)
    print len(idx), idx.sum()
    pl.plot(sne['z'][idx], res['eColor'][idx], marker='.', color='b', ls='')

    pl.xlabel('$z$', fontsize=20)
    pl.ylabel('$\sigma_{\cal{C}}$', fontsize=20)
    pl.ylim((0., 0.15))
    pl.axhline(0.03, color='r', ls='--')
    if label:
        pl.annotate(label,
                    xy=(0.1, 0.8),
                    xycoords='axes fraction',
                    fontsize=18)
    pl.grid(1)
    if zlim:
        pl.axvline(zlim, ls='-.', color='gray', lw=2)

    if tofile:
        fig.savefig(tofile, bbox_inches='tight')

    pl.title('season=%d' % i_season)

    return s, sne, res, lc
Exemple #5
0
def check_m5sigma_depth():
    """
    Compare Philippe Gris' m5 with mine.
    """
    log = snsim.OpSimObsLog(NTuple.fromtxt('Observations_DD_290_LSSTPG.txt'))
    lsstpg = psf.find('LSSTPG')
    sky_flux = lsstpg.mag_to_flux(log.mag_sky, log.band)
    m5 = lsstpg.mag_lim(30., sky_flux, log.seeing, log.band)

    pl.figure()
    pl.plot(log.mjd, log.m5sigmadepth, marker='.', color='gray', ls='')
    pl.plot(log.mjd, m5, marker='.', color='r', ls='')
    pl.xlabel('MJD')

    for b in np.unique(log.band):
        idx = log.band == b
        pl.figure()
        pl.plot(log.mjd[idx],
                m5[idx] - log.m5sigmadepth[idx],
                marker='.',
                color='gray',
                ls='')
        pl.title(b)
    pl.xlabel('MJD')
    pl.xlabel('$\Delta m_{5\sigma} [%s]$' % b)
Exemple #6
0
def main_depth_wide(
    instr_name='LSSTPG',
    #                    bands=['g', 'r', 'i', 'z'],
    SNR=dict(zip(['LSSTPG::' + b for b in "griz"], [30., 40., 30., 20.])),
    target={
        'LSSTPG::g': (24.83, 3.),  # 23.86
        'LSSTPG::r': (24.35, 3.),  # 23.82
        'LSSTPG::i': (23.88, 3.),  # 23.51
        'LSSTPG::z': (23.30, 3.),  # 
    }):

    instr = psf.find(instr_name)
    bands = SNR.keys()

    # Wide survey
    logs = [
        snsim.OpSimObsLog(NTuple.fromtxt(fn))
        for fn in glob.glob('OpSimLogs/*_WFD_*.txt')
    ]
    m = np.hstack([log.median_values() for log in logs])
    lims = f5_cadence_lims(zs=[0.1, 0.2, 0.3, 0.4, 0.5], SNR=SNR)
    #                           bands=[instr_name + '::' + b for b in bands])
    for bn in bands:
        f5_cadence_plot(
            instr,
            bn,  # instr_name + '::' + bn, 
            lims,
            mag_range=(21., 24.8),
            dt_range=(0.5, 30.),
            median_log_summary=m,
            target=target)
        pl.gcf().savefig('m5_cadence_limits_wide_%s.png' % bn.split(':')[-1],
                         bbox_inches='tight')
        pl.gcf().savefig('m5_cadence_limits_wide_%s.pdf' % bn.split(':')[-1],
                         bbox_inches='tight')
def main(color=None):
    log = snsim.OpSimObsLog(NTuple.fromtxt('Observations_DD_290_LSSTPG.txt'))
    lcmodel = init_lcmodel(log.band)
    r = log.split()
    s = snsim.SnSurveyMC(obslog=r[2], filename='lsst_survey.conf')
    sne = s.generate_sample()
    sne.sort(order='z')
    sne['X1'] = 0
    if color is not None:
        sne['Color'] = color
    lc = s.generate_lightcurves(sne, lcmodel, fit=1)
    return lc, log, lcmodel
Exemple #8
0
def texp_requirements():
    d = NTuple.fromtxt('Observations_DD_290_LSSTPG.txt')
    bands = ['LSSTPG::' + b for b in "rizy"]
    #    seeing = np.asarray([np.median(d[d['band'] == 'LSSTPG::' + bn]['seeing']) for bn in bands])
    #    sky = np.asarray([np.median(d[d['band'] == 'LSSTPG::' + bn]['sky']) for bn in bands])
    lsstpg = psf.ImagingInstrument('LSSTPG')
    for bn in bands:
        idx = lsstpg.data['band'] == bn
        lsstpg.data['iq'][idx] = np.median(d[d['band'] == bn]['seeing'])
        lsstpg.data['mag_sky'][idx] = np.median(d[d['band'] == bn]['sky'])
        print bn, np.median(d[d['band'] == bn]['seeing']), np.median(
            d[d['band'] == bn]['sky'])
    return lsstpg
def open_lc(fichier, fichier_results_salt):
    lc = NTuple.fromfile(fichier)
    tableau = NTuple.fromfile(fichier_results_salt)
    bands = np.unique(lc['Filter'])
    if lc.keys['SURVEY'] == 'SDSS':
        sn_name = lc.keys['SURVEY'] + str(int(lc.keys['SN']))
    else:
        sn_name = lc.keys['SN']
    idx_name = None
    for i, t_name in enumerate(tableau['name']):
        if sn_name not in t_name:
            continue
        else:
            idx_name = i
    if idx_name is None:
        raise ValueError('No entry in %s found for the SN in %s' %
                         (fichier_results_salt, fichier))
    snr = np.zeros(len(bands))  #, dtype=np.dtype([(a, float) for a in bands]))
    for i, band in enumerate(bands):
        idx = lc['Filter'] == band
        wi = 1. / self.lc[idx]['Fluxerr']**2
        fi2 = self.lc[idx]['Flux']**2
        snr[i] = np.sqrt(np.sum(wi * fi2))
    return bands, snr, tableau
Exemple #10
0
def get_sne_measurments(fichier, lcs=None, bands='grizy', taille_max=100000):
    dt = [('z', float), ('c', float), ('X0', float), 
          ('X1', float), ('dL', float),
          ('band', 'S1'), ('#SN', int),
          ('A', float), 
          ('l_eff', float),
          ('zp', float), 
          ('snr', float)]
    if os.path.exists(fichier):
        print 'Already have a data file --- '+time.ctime()
        data_ok = NTuple.fromfile(fichier).view(np.ndarray)
    elif lcs is not None:
        if len(lcs) > taille_max:
            lcs = np.random.choice(lcs, taille_max)
        data = np.zeros(6*len(lcs), dtype=dt)

        lambda_effs = np.zeros(1, dtype=[(band, object) for band in 'grizy'])
        zps = np.zeros(1, dtype=[(band, object) for band in 'grizy'])
        for band in 'grizy':
            lambda_effs[band] = get_lambda_f(band)
            zps[band] = get_zp(band)

        k = 0
        print 'Creating data ntuple (needs SALT2 redo) --- '+time.ctime()
        for i, lc in enumerate(lcs):
            bands = np.unique(lc.lc['band'])
            for j, band1 in enumerate(bands):
                band = band1[-1]
                data[k+j] = (lc.sn['z'], lc.sn['Color'], lc.lcmodel.X0(lc.sn), lc.sn['X1'], lc.sn['dL'], band, i,
                             find_amplitude(lc, band), lambda_effs[band][0], zps[band][0], find_snr(lc, band))
            k += len(bands)
            if (i+1)%100 == 0:
                print 'Data computed for %d supernovae' % (i+1)

        data['l_eff'] = 1./(1.+data['z'])*data['l_eff']
        data = data[data['band'] != '']

        data_ok = data[data['snr'] != 0]
        data_ok.view(NTuple).tofile(fichier)
    else:
        raise ValueError('Could not produce a data NTuple without an existing datafile or a list of light curves')
    return np.sort(data_ok, order='z')
def reso_vs_lc_amplitude():
    opsim = NTuple.fromtxt('Observations_DD_290_LSSTPG.txt')
    idx = opsim['band'] != 'LSSTPG::u'
    log = snsim.OpSimObsLog(opsim[idx])
    r = log.split()
    lcmodel = init_lcmodel(log)

    s = snsim.SnSurveyMC(obslog=r[2], filename='lsst_survey.conf')
    sne = s.generate_sample()
    lc = s.generate_lightcurves(sne, lcmodel, fit=1)
    bands = np.unique(log.band)
    r = []
    for l in lc:
        C = l.covmat()
        sa = []
        for b in bands:
            sa.append(l.amplitude_snr(b))
        r.append(np.sqrt(np.diag(C)).tolist() + sa)
    return sne, np.rec.fromrecords(r,
                                   names=['eX0', 'eX1', 'eColor', 'eDayMax'] +
                                   ['sig_' + b for b in bands])
Exemple #12
0
def load_instruments():
    # load instruments
    lsst = psf.ImagingInstrument('LSST')
    lsst.precompute(full=1)
    lsst_pg = psf.ImagingInstrument('LSSTPG')
    lsst_pg.precompute(full=1)

    lsst_pg_opsim = psf.ImagingInstrument('LSSTPG')
    log = snsim.OpSimObsLog(NTuple.fromtxt('Observations_DD_290_LSSTPG.txt'))
    d = update_instrument_summary_data_from_obslog(lsst_pg_opsim, log)
    lsst_pg_opsim.data[:] = d
    lsst_pg_opsim.precompute(full=1)

    # dump summary tables
    print "***** LSST [~LSE-40] ******"
    lsst.dump(exptime=30.)
    print "***** LSST [~SMTN-002 ] ******"
    lsst_pg.dump(exptime=30.)
    print "***** LSST [~SMTN-002 + OpSim default values ] ******"
    lsst_pg_opsim.dump(exptime=30.)

    return lsst, lsst_pg, lsst_pg_opsim
Exemple #13
0
def main_depth_ddf(
    instr_name='LSSTPG',
    #                   bands=['r', 'i', 'z', 'y'],
    SNR=dict(zip(['LSSTPG::' + b for b in "grizy"],
                 [25., 25., 60., 35., 20.])),
    target={  # 'LSSTPG::g': (26.91, 3.), # was 25.37
        'LSSTPG::r': (26.43, 3.),  # was 25.37
        'LSSTPG::i': (26.16, 3.),  # was 25.37      # could be 25.3 (400-s)
        'LSSTPG::z': (25.56, 3.),  # was 24.68      # could be 25.1 (1000-s)
        'LSSTPG::y': (24.68, 3.)
    }):  # was 24.72

    bands = SNR.keys()
    instr = psf.find(instr_name)

    # DDF survey
    #    logs = [snsim.OpSimObsLog(NTuple.fromtxt(fn)) for fn in glob.glob('OpSimLogs_LSST/*_DD_*.txt')]
    logs = [
        snsim.OpSimObsLog(NTuple.fromtxt(fn))
        for fn in glob.glob('OpSimLogs/*_DD_*.txt')
    ]
    m = np.hstack([log.median_values() for log in logs])
    lims = f5_cadence_lims(zs=[0.6, 0.7, 0.8, 0.9, 1.0, 1.1], SNR=SNR)
    #                           bands=[instr_name + '::' + b for b in bands])
    for bn in bands:
        f5_cadence_plot(
            instr,
            bn,  # instr_name + '::' + bn, 
            lims,
            target=target,
            mag_range=(23., 26.5),
            median_log_summary=m)
        pl.gcf().savefig('m5_cadence_limits_%s.png' % bn.split(':')[-1],
                         bbox_inches='tight')
        pl.gcf().savefig('m5_cadence_limits_%s.pdf' % bn.split(':')[-1],
                         bbox_inches='tight')
### m_{b} = P(\lambda_b / (1+z)) - 2.5log(X_0) + 30 + \mu
###         - 2.5log( \int T_b(\lambda) \lambda d\lambda) + 2.5log(1+z) - 2.5log(A_hc) + \Delta ZP_b + c*Cl(\lambda_b) + \beta*c
###############

### Préparation de la loi de couleur Cl(\lambda_b)
color_law_params = np.array(
    [0.01076587, -0.0856708, 0.38838263, -1.3387273, -0.02079356])
beta = 3.
###

lb = 4343.78
lv = 5462.1

### Color smeering
color_dispersion_source = NTuple.fromtxt(
    '/home/fhazenbe/software/snfit_data/snfit_data/salt2-4/salt2_color_dispersion.dat'
)
color_disp_func = scipy.interpolate.interp1d(color_dispersion_source['l'],
                                             color_dispersion_source['s'],
                                             bounds_error=False,
                                             fill_value=0.02)


def transfo(l):
    """
    Wavelength transformation as \lambda_B = 0 and \lambda_V = 1
    """
    ret = (l - lb) / (lv - lb)
    return ret

Exemple #15
0
from saunerie import saltpath, salt2
from saunerie.stellarlibs import FilterSet, ALIGN_WITH_INTEG_FLUX
import scipy.sparse as sparse
from scipy.interpolate import interp1d
from scikits.sparse.cholmod import cholesky
from pycosmo import cosmo
import scipy

###
# Extraction du spectre SALT2
###
m = InstrumentModel("LSSTPG")
cfg = saltpath.read_card_file(saltpath.fitmodel_filename)
salt2_model_path = saltpath.SALTPATH + os.sep + cfg['SALT2']
M0_filename = salt2_model_path + os.sep + 'salt2_template_0.dat'
nt = NTuple.fromtxt(M0_filename)
idx = nt['f0'] == 0
gx = np.linspace(nt['f1'][idx].min() - 1e-10, nt['f1'][idx].max() + 1e-10, 100)
base = bspline.BSpline(gx, order=4)
p = base.linear_fit(nt['f1'][idx], nt['f2'][idx])

### Préparation de la loi de couleur
#color_law_params = np.array([  1.86053680e-13,  -3.60052385e-09,   2.60815642e-05, -8.46865354e-02,   1.04582345e+02])
#color_law_params = np.array([  4.40357739e-14,  -1.03606013e-09,   9.09426282e-06, -3.58966206e-02,   5.34152535e+01])
color_law_params = np.array([
    4.83000620e-14, -1.13062696e-09, 9.85181326e-06, -3.84767882e-02,
    5.65383601e+01
])

beta = 3.
###
Exemple #16
0
def plot_figure_3():
    log = snsim.OpSimObsLog(NTuple.fromtxt('Observations_DD_290_LSSTPG.txt'))
    r = log.split()
    log = r[2]

    # Wide
    lsstpg = psf.find('LSSTPG')
    r = plot_sigc_vs_z(lsstpg,
                       delta=4.,
                       exptimes={
                           'LSSTPG::g': 30,
                           'LSSTPG::r': 30,
                           'LSSTPG::i': 30.,
                           'LSSTPG::z': 30.
                       },
                       zmax=0.5,
                       sigc_filename='sigc_lsstpg_wide_30',
                       snr_filename='snr_lsstpg_wide_30')
    r = plot_sigc_vs_z(lsstpg,
                       delta=3.,
                       exptimes={
                           'LSSTPG::g': 30,
                           'LSSTPG::r': 30,
                           'LSSTPG::i': 30.,
                           'LSSTPG::z': 30.
                       },
                       zmax=0.5,
                       sigc_filename='sigc_lsstpg_wide_30_cad3',
                       snr_filename='snr_lsstpg_wide_30_cad3')
    r = plot_sigc_vs_z(lsstpg,
                       delta=4.,
                       exptimes={
                           'LSSTPG::g': 30,
                           'LSSTPG::r': 30,
                           'LSSTPG::i': 30.,
                           'LSSTPG::z': 30.
                       },
                       zmax=0.5,
                       sigc_filename='sigc_lsstpg_wide_30_minion',
                       snr_filename='snr_lsstpg_wide_30_minion',
                       reference_log=log)

    # DDF
    r = plot_sigc_vs_z(lsstpg,
                       delta=4.,
                       exptimes={
                           'LSSTPG::r': 600,
                           'LSSTPG::i': 600.,
                           'LSSTPG::z': 780.,
                           'LSSTPG::y': 600
                       },
                       zmax=1.1,
                       sigc_filename='sigc_lsstpg_ddf_600',
                       snr_filename='snr_lsstpg_ddf_600')
    r = plot_sigc_vs_z(lsstpg,
                       delta=3.,
                       exptimes={
                           'LSSTPG::r': 1200,
                           'LSSTPG::i': 1800.,
                           'LSSTPG::z': 1800.,
                           'LSSTPG::y': 1800
                       },
                       zmax=1.1,
                       sigc_filename='sigc_lsstpg_ddf_1800_cad3',
                       snr_filename='snr_lsstpg_ddf_1800_cad3')

    #    r = plot_sigc_vs_z(lsstpg,  delta=3., exptimes={'LSSTPG::r': 600, 'LSSTPG::i': 600., 'LSSTPG::z': 780., 'LSSTPG::y': 600},
    #                       zmax=1.1, sigc_filename='sigc_lsstpg_ddf_1200_minion', snr_filename='snr_lsstpg_ddf_1200_minion', reference_log=log)
    #    r = plot_sigc_vs_z(lsstpg,  delta=3., exptimes={'LSSTPG::r': 1200, 'LSSTPG::i': 1200., 'LSSTPG::z': 1200., 'LSSTPG::y': 1200},
    #                       zmax=1.1, sigc_filename='sigc_lsstpg_ddf_1200_cad2', snr_filename='snr_lsstpg_ddf_1200_cad2')

    lsst = psf.find('LSST')
    r = plot_sigc_vs_z(lsst,
                       delta=4.,
                       exptimes={
                           'LSST::r': 600.,
                           'LSST::i': 600.,
                           'LSST::z': 780.,
                           'LSST::y4': 600
                       },
                       zmax=1.1,
                       sigc_filename='sigc_lsst_ddf_600',
                       snr_filename='snr_lsst_ddf_600')
    r = plot_sigc_vs_z(lsst,
                       delta=3.,
                       exptimes={
                           'LSST::r': 1200,
                           'LSST::i': 1800.,
                           'LSST::z': 1800.,
                           'LSST::y4': 1800
                       },
                       zmax=1.1,
                       sigc_filename='sigc_lsst_ddf_1800_cad3',
                       snr_filename='snr_lsst_ddf_1800_cad3')
Exemple #17
0
def plot_lc_snr(filename='Observations_DD_290_LSSTPG.txt',
                z=1.1,
                X1=0.,
                Color=0.,
                DayMax=0.,
                bands=['LSSTPG::' + b for b in "rizy"],
                rest_frame_margins=(-15., 30.),
                snr_min=20.,
                fig=None):
    """Return a metric from a log and a fiducial supernova. 

    Args:
      z, X1, Color, DayMax: fiducial supernova 
      
    """
    lsstpg = psf.find('LSSTPG')
    colors = band_colors(lsstpg)
    mjd, shapes = get_pulse_shapes(bands, z=z, X1=X1, Color=Color)
    mjd_margins = rest_frame_margins[0] * (1. +
                                           z), rest_frame_margins[1] * (1. + z)

    log = snsim.OpSimObsLog(NTuple.fromtxt(filename))
    r = log.split(delta=100.)

    #    f5 = lsstpg.mag_to_flux(log.m5sigmadepth, log.band)
    flux_sky = lsstpg.mag_to_flux(log.mag_sky, log.band)
    f5 = lsstpg.flux_lim(log.exptime, flux_sky, log.seeing, log.band)
    #    print lsstpg.mag_lim(log.exptime, flux_sky, log.seeing, log.band)
    #    print lsstpg.mag_to_flux(lsstpg.mag_lim(log.exptime, flux_sky, log.seeing, log.band), log.band)

    if fig is None:
        fig = pl.figure(figsize=(12, 12))
    ax = None

    mjd = np.arange(log.mjd.min(), log.mjd.max(), 1.)

    for i, bn in enumerate(bands):
        if ax is None:
            ax = pl.subplot(len(bands), 1, i + 1)
            pl.title('$SN[X1=%5.1f,C=%5.1f]\ at\ z=%4.2f$ [%s]' %
                     (X1, Color, z, filename))
        else:
            ax = pl.subplot(len(bands), 1, i + 1)

        # runs
        for rr in r:
            pl.axvspan(rr.mjd.min(), rr.mjd.max(), color='gray', alpha=0.25)
            pl.axvspan(rr.mjd.min() - rest_frame_margins[0],
                       rr.mjd.max() - rest_frame_margins[1],
                       color='gray',
                       alpha=0.35)

        # plot the cadence metric
        idx = log.band == bn
        c = CadenceMetric(log.mjd[idx], f5[idx], log.band[idx], shapes[bn])
        y = c(mjd)
        pl.plot(mjd, y, color=colors[bn], marker='.', ls=':')
        pl.ylabel('$SNR [%s]$' % bn.split(':')[-1],
                  fontsize=16)  #  color=colors[bn])
        pl.axhline(snr_min, ls='--', color='r')
        pl.ylim((0., max((y.max(), snr_min + 1))))

        # plot the average number of observations averaged over a
        # window of ~ 21 days.
        c_sched = SimpleCadenceMetric(log.mjd[idx], 21.)
        print c_sched.sumw.min(), c_sched.sumw.max()
        y_sched = c_sched(mjd)
        ax = pl.gca().twinx()
        ax.plot(mjd, y_sched, color='gray', ls='-')
        pl.ylim((0., 0.28))
        pl.ylabel("Cadence [day$^{-1}$]", color='black')
        cad = 1. / (4. * (1. + z))
        pl.axhline(cad, ls=':', color='gray')

        if i < len(bands) - 1:
            ax.get_xaxis().set_ticklabels([])
    pl.subplots_adjust(hspace=0.06)
    pl.xlabel('$MJD$ [days]', fontsize=16)

    return c
"""

### Préparation de la loi de couleur
color_law_params  = np.array([ 0.01076587, -0.0856708 ,  0.38838263, -1.3387273 , -0.02079356])
beta = 3.
###

dt = [('z', float), ('c', float), ('X0', float), 
      ('X1', float), ('dL', float),
      ('band', 'S1'), ('#SN', int),
      ('A', float), 
      ('l_eff', float),
      ('zp', float), 
      ('snr', float)]

color_dispersion_source = NTuple.fromtxt('/home/fhazenbe/software/snfit_data/snfit_data/salt2-4/salt2_color_dispersion.dat')
color_disp_func = scipy.interpolate.interp1d(color_dispersion_source['l'], color_dispersion_source['s'])

def find_amplitude(snova, band, k='LSSTPG::'):
    band = k + band
    amplitude = snova.lcmodel(snova.sn, [snova.sn.DayMax], [band])[0]
    return amplitude

def find_snr(snova, band, k='LSSTPG::'):
    band = k + band
    snr = snova.amplitude_snr(band)
    return snr

def rescale_mag(fi, dL, zp, z):
    A_hc = 50341170
    M = -2.5*np.log10(fi) - 5*( np.log10(dL) ) - 30 + 2.5 * np.log10(ALIGN_WITH_INTEG_FLUX) - zp + 2.5*np.log10(A_hc) - 2.5*np.log10(1+z)
import saunerie.constants as constants
from saunerie import saltpath, salt2
from saunerie.stellarlibs import FilterSet, ALIGN_WITH_INTEG_FLUX
import scipy.sparse as sparse
from scipy.interpolate import interp1d
from scikits.sparse.cholmod import cholesky
from pycosmo import cosmo

###
# Extraction du spectre SALT2
###
m = InstrumentModel("LSSTPG")
cfg = saltpath.read_card_file(saltpath.fitmodel_filename)
salt2_model_path = saltpath.SALTPATH + os.sep + cfg['SALT2']
M0_filename = salt2_model_path + os.sep + 'salt2_template_0.dat'
nt = NTuple.fromtxt(M0_filename)
idx = nt['f0'] == 0
gx = np.linspace(nt['f1'][idx].min() - 1e-10, nt['f1'][idx].max() + 1e-10, 100)
base = bspline.BSpline(gx, order=4)
p = base.linear_fit(nt['f1'][idx], nt['f2'][idx])

lcs0, log0, model = example.main(0)
lcs1, log1, model = example.main(1)

color_law_params = np.array([
    1.86053680e-13, -3.60052385e-09, 2.60815642e-05, -8.46865354e-02,
    1.04582345e+02
])

dt = [('z', float), ('c', float), ('X1', float), ('dL', float), ('band', 'S1'),
      ('#SN', int), ('A', float), ('l_eff', float), ('zp', float),
###
# Extraction du spectre SALT2
###


class NotKeptError(Exception):
    pass


print 'Starting --- ' + time.ctime()
m = InstrumentModel("LSSTPG")
cfg = saltpath.read_card_file(saltpath.fitmodel_filename)
salt2_model_path = saltpath.SALTPATH + os.sep + cfg['SALT2']
M0_filename = salt2_model_path + os.sep + 'salt2_template_0.dat'
nt = NTuple.fromtxt(M0_filename)
idx = nt['f0'] == 0
gx = np.linspace(nt['f1'][idx].min() - 1e-10, nt['f1'][idx].max() + 1e-10, 100)
base = bspline.BSpline(gx, order=4)
p = base.linear_fit(nt['f1'][idx], nt['f2'][idx])

color_disp_fit = np.array([
    -1.33846154e-18, 3.98286713e-14, -4.66894522e-10, 2.69988432e-06,
    -7.71355752e-03, 8.74507867e+00
])

# def color_disp_func(l):
#     """ SALT2 colour dispersion as a function of wavelength (from Guy et al. 2010, Fig 8)
#     """
#     disps = np.zeros(len(l))
#     disps[l<3000] = 2e-1
Exemple #21
0
except ImportError:
    from astropy.io import fits as pyfits
from saunerie.spectrum import Spectrum

###
# Extraction du spectre SALT2
###
print 'Starting --- '+time.ctime()
m = InstrumentModel("LSSTPG")

### Préparation de la loi de couleur
color_law_params  = np.array([ 0.01076587, -0.0856708 ,  0.38838263, -1.3387273 , -0.02079356])
beta = 3.
lb = 4343.78 # Central wavelength of B-band
lv = 5462.1  # Central wavelength of V-band
color_dispersion_source = NTuple.fromtxt('/home/fhazenbe/software/snfit_data/snfit_data/salt2-4/salt2_color_dispersion.dat') # Color Dispersion law from Guy et al.
color_disp_func = interp1d(color_dispersion_source['l'], color_dispersion_source['s'])


### Constantes
A_hc = 50341170.
X0 = 76516964.662612781
###

def find_amplitude(snova, band, k='LSSTPG::'):
    band = k + band
    amplitude = snova.lcmodel(snova.sn, [snova.sn.DayMax], [band])[0]
    return amplitude

def find_snr(snova, band, k='LSSTPG::'):
    band = k + band
    Files   = []
    k = 1
    while( k<narg ):
        if( sys.argv[k][0] != "-" ):
            Files.append( sys.argv[k] )
            k += 1
        elif( sys.argv[k] == "-v" ):
            k += 1
            values=sys.argv[k:] 
            break
 
    nb = len(values)
    out = []
    for file in Files:
        found = 0
        data =  NTuple.fromtxt(file)
        for k in values:
            for key, val in data.keys.iteritems():                
                if ((str(val).lower()).find(k.lower())>=0):
                    found +=1
                    break
            if (found == 0):
                break
            
        if (found == nb):
            print file
            out.append(file)

    print 'files_list : ', out
   
import time
from saunerie.linearmodels import SparseSystem
import pyfits
from saunerie.spectrum import Spectrum
from saunerie.instruments import FilterWheel
from glob import glob

###
# Extraction du spectre SALT2
###
print 'Starting --- ' + time.ctime()
m = InstrumentModel("LSSTPG")
cfg = saltpath.read_card_file(saltpath.fitmodel_filename)
salt2_model_path = saltpath.SALTPATH + os.sep + cfg['SALT2']
M0_filename = salt2_model_path + os.sep + 'salt2_template_0.dat'
nt = NTuple.fromtxt(M0_filename)
idx = nt['f0'] == 0
gx = np.linspace(nt['f1'][idx].min() - 1e-10, nt['f1'][idx].max() + 1e-10, 100)
base = bspline.BSpline(gx, order=4)
p = base.linear_fit(nt['f1'][idx], nt['f2'][idx])

color_disp_fit = np.array([
    -1.33846154e-18, 3.98286713e-14, -4.66894522e-10, 2.69988432e-06,
    -7.71355752e-03, 8.74507867e+00
])


def color_disp_func(l):
    """ SALT2 colour dispersion as a function of wavelength (from Guy et al. 2010, Fig 8)
    """
    disps = np.zeros(len(l))
Exemple #24
0
def figure1():

    d = NTuple.fromtxt('selected_sn.list')

    # nearby sample
    idx = d['SURVEY'] == 'CSP'
    idx |= d['SURVEY'] == 'CalanTololo'
    idx |= d['SURVEY'] == 'CfAI'
    idx |= d['SURVEY'] == 'CfAII'
    idx |= d['SURVEY'] == 'CfAIII'
    idx |= d['SURVEY'] == 'lowz'
    d_nearby = d[idx]

    # SDSS
    idx = d['SURVEY'] == 'SDSS'
    d_sdss = d[idx]

    # SNLS
    idx = d['SURVEY'] == 'SNLS'
    d_snls = d[idx]

    # plot samples
    fig = pl.figure()
    pl.errorbar(d_nearby['x1'],
                d_nearby['c'],
                xerr=d_nearby['x1e'],
                yerr=d_nearby['ce'],
                ls='',
                color='b',
                marker='o',
                alpha=0.25)
    pl.errorbar(d_sdss['x1'],
                d_sdss['c'],
                xerr=d_sdss['x1e'],
                yerr=d_sdss['ce'],
                ls='',
                color='g',
                marker='^',
                alpha=0.25)
    pl.errorbar(
        d_snls['x1'],
        d_snls['c'],
        xerr=d_snls['x1e'],
        yerr=d_snls['ce'],
        ls='',
        marker='s',
        color='orange',
        markerfacecolor=None,
        markeredgecolor='orange',
        alpha=0.25,
    )

    pl.xlabel('$X1$ [SALT2]')
    pl.ylabel('$Color$ [SALT2]')

    pl.axvline(-3, ls='--')
    pl.axvline(+3, ls='--')
    pl.axhline(0.3, ls='--')
    pl.axhline(-0.3, ls='--')

    pl.plot(-2., 0.2, marker='o', color='red', markersize=16)
    pl.annotate('faintest SN', (-2., 0.27),
                xytext=(-2, 0.35),
                arrowprops={
                    'facecolor': 'r',
                    'shrink': 0.05
                })
    pl.plot(+2., -0.2, marker='o', color='blue', markersize=16)
    pl.annotate('brightest SN', (+2., -0.27),
                xytext=(2, -0.35),
                arrowprops={
                    'facecolor': 'b',
                    'shrink': 0.05
                })

    e = Ellipse(xy=(0., 0.),
                width=5.6,
                height=0.56,
                fill=False,
                color='red',
                linestyle='dashdot')
    ax = pl.gca()
    ax.add_artist(e)

    fig.savefig('sn_parameter_space.pdf', bbox_inches='tight')
    fig.savefig('sn_parameter_space.png', bbox_inches='tight')
import scipy.sparse as sparse
from scipy.interpolate import interp1d
from scikits.sparse.cholmod import cholesky
from pycosmo import cosmo
import scipy
import time

###
# Extraction du spectre SALT2
###
print 'Starting --- ' + time.ctime()
m = InstrumentModel("LSSTPG")
cfg = saltpath.read_card_file(saltpath.fitmodel_filename)
salt2_model_path = saltpath.SALTPATH + os.sep + cfg['SALT2']
M0_filename = salt2_model_path + os.sep + 'salt2_template_0.dat'
nt = NTuple.fromtxt(M0_filename)
idx = nt['f0'] == 0
gx = np.linspace(nt['f1'][idx].min() - 1e-10, nt['f1'][idx].max() + 1e-10, 100)
base = bspline.BSpline(gx, order=4)
p = base.linear_fit(nt['f1'][idx], nt['f2'][idx])

### Préparation de la loi de couleur
color_law_params = np.array(
    [0.01076587, -0.0856708, 0.38838263, -1.3387273, -0.02079356])
beta = 3.
###

dt = [('z', float), ('c', float), ('X0', float), ('X1', float), ('dL', float),
      ('band', 'S1'), ('#SN', int), ('A', float), ('l_eff', float),
      ('zp', float), ('snr', float)]