def setup_class(self): """Create a SALT2 model with a lot of components set to 1.""" phase = np.linspace(0., 100., 10) wave = np.linspace(1000., 10000., 100) vals1d = np.zeros(len(phase), dtype=np.float64) vals = np.ones([len(phase), len(wave)], dtype=np.float64) # Create some 2-d grid files files = [] for i in [0, 1]: f = StringIO() sncosmo.write_griddata_ascii(phase, wave, vals, f) f.seek(0) # return to start of file. files.append(f) # CL file. The CL in magnitudes will be # CL(wave) = -(wave - B) / (V - B) [B = 4302.57, V = 5428.55] # and transmission will be 10^(-0.4 * CL(wave))^c clfile = StringIO() clfile.write("1\n" "0.0\n" "Salt2ExtinctionLaw.version 1\n" "Salt2ExtinctionLaw.min_lambda 3000\n" "Salt2ExtinctionLaw.max_lambda 7000\n") clfile.seek(0) # Create some more 2-d grid files for factor in [1., 0.01, 0.01, 0.01]: f = StringIO() sncosmo.write_griddata_ascii(phase, wave, factor * vals, f) f.seek(0) # return to start of file. files.append(f) # Create a 1-d grid file (color dispersion) cdfile = StringIO() for w in wave: cdfile.write("{0:f} {1:f}\n".format(w, 0.2)) cdfile.seek(0) # return to start of file. # Create a SALT2Source self.source = sncosmo.SALT2Source(m0file=files[0], m1file=files[1], clfile=clfile, errscalefile=files[2], lcrv00file=files[3], lcrv11file=files[4], lcrv01file=files[5], cdfile=cdfile) for f in files: f.close() cdfile.close() clfile.close()
def setup_class(self): """Create a SALT2 model with a lot of components set to 1.""" phase = np.linspace(0., 100., 10) wave = np.linspace(1000., 10000., 100) vals1d = np.zeros(len(phase), dtype=np.float64) # Create some 2-d grid files files = [] for i in [0, 1]: f = six.StringIO() sncosmo.write_griddata_ascii(phase, wave, vals, f) f.seek(0) # return to start of file. files.append(f) # CL file. The CL in magnitudes will be # CL(wave) = -(wave - B) / (V - B) [B = 4302.57, V = 5428.55] # and transmission will be 10^(-0.4 * CL(wave))^c clfile = six.StringIO() clfile.write("1\n" "0.0\n" "Salt2ExtinctionLaw.version 1\n" "Salt2ExtinctionLaw.min_lambda 3000\n" "Salt2ExtinctionLaw.max_lambda 7000\n") clfile.seek(0) # Create some more 2-d grid files for factor in [1., 0.01, 0.01, 0.01]: f = six.StringIO() sncosmo.write_griddata_ascii(phase, wave, factor * vals, f) f.seek(0) # return to start of file. files.append(f) # Create a 1-d grid file (color dispersion) cdfile = six.StringIO() for w in wave: cdfile.write("{0:f} {1:f}\n".format(w, 0.2)) cdfile.seek(0) # return to start of file. # Create a SALT2Source self.source = sncosmo.SALT2Source(m0file=files[0], m1file=files[1], clfile=clfile, errscalefile=files[2], lcrv00file=files[3], lcrv11file=files[4], lcrv01file=files[5], cdfile=cdfile) def test_bandflux_rcov(self): # component 1: # ans = (F0/F1)^2 S^2 (V00 + 2 x1 V01 + x1^2 V11) # when x1=0, this reduces to S^2 V00 = 1^2 * 0.01 = 0.01 # # component 2: # cd^2 = 0.04 band = ['bessellb', 'bessellb', 'bessellr', 'bessellr', 'besselli'] phase = [10., 20., 30., 40., 50.] self.source.set(x1=0.0) result = self.source.bandflux_rcov(band, phase) expected = np.array([[0.05, 0.04, 0., 0., 0.], [0.04, 0.05, 0., 0., 0.], [0., 0., 0.05, 0.04, 0.], [0., 0., 0.04, 0.05, 0.], [0., 0., 0., 0., 0.05]]) assert_allclose(result, expected)
if args.emcee: if not os.path.exists('./plots/emcee/jla'): os.makedirs('./plots/emcee/jla') if not os.path.exists('./plots/emcee/jla/triangle'): os.makedirs('./plots/emcee/jla/triangle') if not os.path.exists('./plots/emcee/jla/salt'): os.makedirs('./plots/emcee/jla/salt') # make the 2stretch source, apply dust, set it to the right z source = Salt2XSource(version='2.4', modeldir=modeldir) model = sncosmo.Model(source=source, effects=[dust], effect_names=['mw'], effect_frames=['obs']) SaltSource = sncosmo.SALT2Source(version='2.4', modeldir=modeldir) SaltModel = sncosmo.Model(source=SaltSource, effects=[dust], effect_names=['mw'], effect_frames=['obs']) model.set(z=z, mwebv=float(mwebv), mwr_v=3.1) SaltModel.set(z=z, mwebv=float(mwebv), mwr_v=3.1) if args.noskew: emfit = fitters.emcee_salt_fit_noskew(data, model, SaltModel) else: emfit = fitters.emcee_salt_fit(data, model, SaltModel) try: try:
"dark_current": 0.015, "IPC": 0.02, "TTel": TTel, "zodi_fl": file_to_fn(wfirst_data_path + "/pixel-level/input/aldering.txt"), "bad_pixel_rate": 0.01, "waves": arange(6000., 23000.1, 25.) } redshifts = [0.4, 0.8, 1.7, 2.0] phases = [-10, 0] nsne = 40 filt = sys.argv[1] exp_times = 10**arange(1.0, 4.01, 0.05) source = sncosmo.SALT2Source(modeldir=wfirst_data_path + "/salt2_extended/") effective_meters2_fl = file_to_fn(wfirst_data_path + "/pixel-level/input/" + filt + ".txt") for sqrtt in [0, 1]: plt.figure(figsize=(6 * len(redshifts), 4 * len(phases))) pltname = "StoN_vs_exptime_%s_TTel_%.1f_%s%s" % (filt, TTel, psfnm, "_sqrtt" * sqrtt) if not sqrtt: fres = open(pltname + ".txt", 'w') for i in range(len(phases)): for j in range(len(redshifts)): plt.subplot(len(phases), len(redshifts), i * len(redshifts) + j + 1)
def __init__(self, param, simu_param, reference_lc=None, gamma=None, mag_to_flux=None, dustcorr=None, snr_fluxsec='interp', error_model=True): super().__init__(param.name, param.sn_parameters, param.gen_parameters, param.cosmology, param.telescope, param.SNID, param.area, param.x0_grid, mjdCol=param.mjdCol, RACol=param.RACol, DecCol=param.DecCol, filterCol=param.filterCol, exptimeCol=param.exptimeCol, nexpCol=param.nexpCol, m5Col=param.m5Col, seasonCol=param.seasonCol, seeingEffCol=param.seeingEffCol, seeingGeomCol=param.seeingGeomCol, airmassCol=param.airmassCol, skyCol=param.skyCol, moonCol=param.moonCol, salt2Dir=param.salt2Dir) """ SN class - inherits from SN_Object Parameters -------------- param: dict parameters requested for the simulation (SN_Object) simu_param : dict parameters for the simulation: name: simulator name (str) model: model name for SN (exempla: salt2-extended) (str) version: version of the model (str) reference_lc : griddata,opt reference_light curves (default: None) gamma: griddata, opt reference gamma values (default: None) mag_to_flux: griddata, opt reference mag->flux values (default: None) snr_fluxsec: str, opt type of method to estimate snr and flux in pe.s-1: lsstsim: estimated from lsstsims tools interp: estimated from interpolation (default) all : estimated from the two above-mentioned methods """ model = simu_param['model'] version = str(simu_param['version']) self.model = model self.version = version self.gamma = gamma self.mag_to_flux = mag_to_flux self.snr_fluxsec = snr_fluxsec self.error_model = error_model if model == 'salt2-extended': model_min = 300. model_max = 180000. wave_min = 3000. wave_max = 11501. if model == 'salt2': model_min = 3400. model_max = 11501. wave_min = model_min wave_max = model_max self.wave = np.arange(wave_min, wave_max, 1.) if not self.error_model: source = sncosmo.get_source(model, version=version) else: SALT2Dir = 'SALT2.Guy10_UV2IR' self.SALT2Templates(SALT2Dir=SALT2Dir, blue_cutoff=10. * self.sn_parameters['blue_cutoff']) source = sncosmo.SALT2Source(modeldir=SALT2Dir) self.dustmap = sncosmo.OD94Dust() self.lsstmwebv = EBV.EBVbase() self.SN = sncosmo.Model(source=source, effects=[self.dustmap, self.dustmap], effect_names=['host', 'mw'], effect_frames=['rest', 'obs']) self.SN.set(z=self.sn_parameters['z']) self.SN.set(t0=self.sn_parameters['daymax'] + self.gen_parameters['epsilon_daymax']) self.SN.set(c=self.sn_parameters['color'] + self.gen_parameters['epsilon_color']) self.SN.set(x1=self.sn_parameters['x1'] + self.gen_parameters['epsilon_x1']) # need to correct X0 for alpha and beta lumidist = self.cosmology.luminosity_distance( self.sn_parameters['z']).value * 1.e3 self.X0 = self.x0(lumidist) self.dL = lumidist self.SN.set(x0=self.X0) """ self.SN.set_source_peakabsmag(self.sn_parameters['absmag'], self.sn_parameters['band'], self.sn_parameters['magsys']) self.X0 = self.SN.get('x0') """ self.defname = dict( zip(['healpixID', 'pixRA', 'pixDec'], ['observationId', param.RACol, param.DecCol])) # names for metadata self.names_meta = [ 'RA', 'Dec', 'x0', 'epsilon_x0', 'x1', 'epsilon_x1', 'color', 'epsilon_color', 'daymax', 'epsilon_daymax', 'z', 'survey_area', 'healpixID', 'pixRA', 'pixDec', 'season', 'dL', 'ptime', 'snr_fluxsec_meth', 'status', 'ebvofMW' ] self.mag_inf = 100. # mag values to replace infs # band registery in sncosmo for band in 'grizy': throughput = self.telescope.atmosphere[band] bandcosmo = sncosmo.Bandpass(throughput.wavelen, throughput.sb, name='LSST::' + band, wave_unit=u.nm) sncosmo.registry.register(bandcosmo, force=True)
import numpy as np import sncosmo import pylab as plt import cPickle import copy source_salt24 = sncosmo.SALT2Source(modeldir='../../2-4-0/data/salt2-4/') model = sncosmo.Model(source=source_salt24) for_pf_bis = cPickle.load(open('../sugar/data_input/spectra_snia.pkl')) #for_pf_bis = cPickle.load(open('../sugar/data_input/File_for_PF.pkl')) meta = cPickle.load(open('../sugar/data_input/SNF-0203-CABALLOv2/META.pkl')) for sn in for_pf_bis.keys(): #sn = 'SN2006cj' #phase='0' print sn model.set(z=meta[sn]['host.zhelio'], t0=0., x0=meta[sn]['salt2.X0'], x1=meta[sn]['salt2.X1'], c=meta[sn]['salt2.Color']) wave = copy.deepcopy( for_pf_bis[sn]['0']['X']) * (1 + meta[sn]['host.zhelio']) for phase in for_pf_bis[sn].keys(): #for_pf_bis[sn][phase].update({'PF_flux':model.flux(for_pf_bis[sn][phase]['phase_salt2'],wave)*(1+meta[sn]['host.zhelio'])**3}) for_pf_bis[sn][phase].update({ 'PF_flux': model.flux(for_pf_bis[sn][phase]['phase_salt2'], wave) * (1 + meta[sn]['host.zhelio'])**2 })
def __init__(self, x1=-2.0, color=0.2, daymax=0.0, blue_cutoff=380., redcutoff=800., mjdCol='observationStartMJD', filterCol='filter', SALT2Dir=''): model = 'salt2-extended' version = '1.0' source = sncosmo.get_source(model, version=version) if SALT2Dir != '': source = sncosmo.SALT2Source(modeldir=SALT2Dir) dustmap = sncosmo.OD94Dust() lsstmwebv = EBV.EBVbase() self.mjdCol = mjdCol self.filterCol = filterCol self.x1 = x1 self.color = color self.daymax = daymax # SN model self.SN = sncosmo.Model(source=source, effects=[dustmap, dustmap], effect_names=['host', 'mw'], effect_frames=['rest', 'obs']) # SN parameters self.SN.set(t0=daymax) self.SN.set(c=color) self.SN.set(x1=x1) # SN normalisation # cosmology H0 = 72.0 Omega_m = 0.3 Omega_l = 0.70 w0 = -1.0 wa = 0.0 self.cosmo = self.cosmology(H0, Omega_m, Omega_l, w0, wa) # x0 normalisation self.x0_grid = self.x0(-19.0906) self.x0_from_grid = griddata( (self.x0_grid['x1'], self.x0_grid['color']), self.x0_grid['x0_norm'], (x1, color), method='nearest') # wavelength for the model wave_min = 3000. wave_max = 11501. self.wave = np.arange(wave_min, wave_max, 1.) # telescope self.telescope = Telescope(airmass=1.2) lambda_min = dict(zip('grizy', [300., 670., 300., 300., 300.])) # band registery in sncosmo for band in 'grizy': throughput = self.telescope.atmosphere[band] print(band, lambda_min[band]) idx = throughput.wavelen <= lambda_min[band] # throughput.sb[idx] = 0. bandcosmo = sncosmo.Bandpass(throughput.wavelen, throughput.sb, name='LSST::' + band, wave_unit=u.nm) sncosmo.registry.register(bandcosmo, force=True)
def Gen_SN(peak_date, Ra, Dec, redshift, colour, x_1, int_dis, cur=cur): #Use below if on Iridis source = sncosmo.SALT2Source( modeldir="/scratch/cf5g09/Monte_Carlos/salt2-4") ##Use below if not on iridis #source=sncosmo.get_source('salt2',version='2.4') alpha = 0.141 beta = 3.101 m = Get_Obs_Conditions(Ra, Dec, peak_date, cur=cur) mabs = -19.05 - alpha * x_1 + beta * colour + int_dis #Setting the absolute Magnitude of the Supernova if m.size == 0: return mabs, 9999.99, False, 9999.99 #print 'MW Extinction E(B-V): ', m[:,7][0] dust = sncosmo.CCM89Dust() model = sncosmo.Model(source=source, effects=[dust], effect_names=['mw'], effect_frames=['obs']) model.set(z=redshift, t0=peak_date, x1=x_1, c=colour, mwebv=m[:, 7][0]) #Setting redshift model.set_source_peakabsmag( mabs, 'bessellb', 'ab', cosmo=FlatLambdaCDM(H0=70, Om0=0.3)) #Fixing my peak absolute magnitude #model.set(x1=x_1, c=colour) band = sncosmo.get_bandpass('ptf48r') #Retrieving the ptf48r bandpass maglc = model.bandmag('ptf48r', 'ab', m[:, 0]) #Creating a magnitude array of the lightcurve fluxlc = model.bandflux('ptf48r', m[:, 0]) #Creating a flux array of the lightcurve absmagb = model.source_peakabsmag('bessellb', 'ab', cosmo=FlatLambdaCDM(H0=70, Om0=0.3)) absmag_r = model.source_peakabsmag('ptf48r', 'ab', cosmo=FlatLambdaCDM(H0=70, Om0=0.3)) ''' m[:,2] | ccdid m[:,3] | lmt_mg_new m[:,4] | Seeing_ratio m[:,5] | medsky_new m[:,6] | good_pix_area ''' ##Getting Rid of NANs in the Mag arrays time_array = m[:, 0][~np.isnan(maglc)] mag_lc = maglc[~np.isnan(maglc)] flux_lc = fluxlc[~np.isnan(maglc)] ccd_lc = m[:, 2][~np.isnan(maglc)] lmt_lc = m[:, 3][~np.isnan(maglc)] see_rat = m[:, 4][~np.isnan(maglc)] med_lc = m[:, 5][~np.isnan(maglc)] pix_lc = m[:, 6][~np.isnan(maglc)] #print maglc #print mag_lc sn_par = np.array((time_array, mag_lc, flux_lc, ccd_lc, lmt_lc, see_rat, med_lc, pix_lc)).T '''snapr snpar[:,0] | time snpar[:,1] | mag_lc snpar[:,2] | flux_lc snpar[:,3] | ccd_lc snpar[:,4] | lmt_lc snpar[:,5] | see_rat snpar[:,6] | med_lc snpar[:,7] | pix_lc ''' #print sn_par return mabs, absmag_r, sn_par, m[:, 7][0] #m[:,7][0] is color_excess