def test_write_griddata_ascii(): x0 = np.array([0., 1.]) x1 = np.array([0., 1., 2.]) y = np.zeros((2, 3)) f = StringIO() sncosmo.write_griddata_ascii(x0, x1, y, f) # Read it back f.seek(0) x0_in, x1_in, y_in = sncosmo.read_griddata_ascii(f) f.close() assert_allclose(x0_in, x0) assert_allclose(x1_in, x1) assert_allclose(y_in, y) # with a filename: dirname = mkdtemp() fname = os.path.join(dirname, 'griddata.dat') sncosmo.write_griddata_ascii(x0, x1, y, fname) x0_in, x1_in, y_in = sncosmo.read_griddata_ascii(fname) assert_allclose(x0_in, x0) assert_allclose(x1_in, x1) assert_allclose(y_in, y) os.remove(fname) os.rmdir(dirname)
def test_write_griddata_ascii(): x0 = np.array([0., 1.]) x1 = np.array([0., 1., 2.]) y = np.zeros((2, 3)) f = six.StringIO() sncosmo.write_griddata_ascii(x0, x1, y, f) # Read it back f.seek(0) x0_in, x1_in, y_in = sncosmo.read_griddata_ascii(f) f.close() assert_allclose(x0_in, x0) assert_allclose(x1_in, x1) assert_allclose(y_in, y) # with a filename: dirname = mkdtemp() fname = os.path.join(dirname, 'griddata.dat') sncosmo.write_griddata_ascii(x0, x1, y, fname) x0_in, x1_in, y_in = sncosmo.read_griddata_ascii(fname) assert_allclose(x0_in, x0) assert_allclose(x1_in, x1) assert_allclose(y_in, y) os.remove(fname) os.rmdir(dirname)
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 test_write_griddata_ascii(): x0 = np.array([0., 1.]) x1 = np.array([0., 1., 2.]) y = np.zeros((2, 3)) f = six.StringIO() sncosmo.write_griddata_ascii(x0, x1, y, f) # Read it back f.seek(0) x0_in, x1_in, y_in = sncosmo.read_griddata_ascii(f) assert_allclose(x0_in, x0) assert_allclose(x1_in, x1) assert_allclose(y_in, y)
#!/usr/bin/env python import os import numpy as np import sncosmo # generate arrays to input to interpolator x = np.array([-1., 0., 2., 4., 5., 6., 6.5, 7.]) y = np.array([1., 2., 3., 4., 5.]) z = np.sin(x)[:, None] * np.cos(0.25 * y) fname = '../sncosmo/tests/data/interpolation_test_input.dat' if os.path.exists(fname): print(fname, "already exists; skipping.") else: sncosmo.write_griddata_ascii(x, y, z, fname) print("wrote", fname) # generate test x and y arrays xs = np.array([-2., -1., 0.5, 2.4, 3.0, 4.0, 4.5, 6.5, 8.0]) ys = np.array([0., 0.5, 1.0, 1.5, 2.8, 3.5, 4.0, 4.5, 5.0, 6.0]) for arr, name in ((xs, 'x'), (ys, 'y')): fname = '../sncosmo/tests/data/interpolation_test_eval{}.dat'.format(name) if os.path.exists(fname): print(fname, "already exists; skipping.") else: np.savetxt(fname, arr)
def _addCCSpec(snType, sedFile, oldWave, specList=None, specName=None): phase, newWave, flux = sncosmo.read_griddata_ascii(sedFile) wave = np.append(newWave[newWave < oldWave[0]], newWave[newWave > oldWave[-1]]) if len(wave) == 0: return (flux) #flux=flux[:][newWave==wave] if specList: spec = createAveSpec(specList) elif specName: spec = os.path.join(__dir__, 'data', 'spectra', specName) allSpec = _readSpec(spec) else: tempInd, tempVal = _find_nearest(phase, 0) if snType == 'II': snType = 'IIP' allSpec, bestConst = _findBest(snType, newWave, flux[tempInd]) #spec=os.path.join(__dir__,'data','spectra',_defaultSpec[snType]) #allSpec=_readSpec(spec) x = [float(x[2:]) for x in allSpec.colnames if x != 'wave'] y = allSpec['wave'] allSpec.remove_column('wave') func = interp2d(x, y, np.array([list(r) for r in np.array(allSpec)])) tempFlux = np.transpose( func(phase[phase >= x[0]][phase[phase >= x[0]] <= x[-1]], newWave[newWave > 4000][newWave[newWave > 4000] < 7500])) finalFlux = np.transpose( func(phase[phase >= x[0]][phase[phase >= x[0]] <= x[-1]], wave[wave >= y[0]][wave[wave >= y[0]] <= y[-1]])) if np.max(np.max(finalFlux)) == 0: return #if os.path.basename(sedFile)=='SDSS-015339.SED': # print(finalFlux) # print(wave[wave>=y[0]][wave[wave>=y[0]]<=y[-1]]) # sys.exit() splines = [] for p in phase[phase >= x[0]][phase[phase >= x[0]] <= x[-1]]: ind = np.where(phase == p)[0][0] mySpline = spl( newWave[newWave > 4000][newWave[newWave > 4000] < 7500], flux[ind][newWave < 7500][newWave[newWave < 7500] > 4000], k=5, ext=1) tempSpline = mySpline( newWave[newWave < 7500][newWave[newWave < 7500] > 4000]) splines.append( np.log10( flux[ind][newWave < 7500][newWave[newWave < 7500] > 4000] / tempSpline)) splines = np.array(splines) waves = wave[wave >= y[0]][wave[wave >= y[0]] <= y[-1]] for i in range(len(phase[phase >= x[0]][phase[phase >= x[0]] <= x[-1]])): #const1=math.fabs(np.max(splines[i])/np.max(tempFlux[i])) #const2=math.fabs(np.min(splines[i])/np.max(tempFlux[i])) const = minimize(_specChi, np.array([bestConst]), args=(splines[i], tempFlux[i])).x #const=np.nanmedian([math.fabs(k) for k in splines[i]/tempFlux[i]]) finalFlux[i] *= const if i == 4: final = const #if tempFlux[i][0]>splines[i][0]: # constMinus=tempFlux[i][0]-splines[i][0] # finalFlux[i]-=constMinus #else: # constMinus=splines[i][0]-tempFlux[i][0] # tempFlux[i]+=constMinus #splines[i]+=finalFlux[i] ind = np.where(phase == phase[phase >= x[0]][ phase[phase >= x[0]] <= x[-1]][i])[0][0] for j in range(len(waves)): ind2 = np.where(newWave == waves[j])[0][0] flux[ind][ind2] = max(0, flux[ind][ind2] + finalFlux[i][j]) #fig=plt.figure() #ax=fig.gca() #ax.plot(newWave[newWave<7500][newWave[newWave<7500]>4000],tempFlux[4]*const) #ax.plot(newWave[newWave<7500][newWave[newWave<7500]>4000],splines[4]) #plt.savefig('test_'+os.path.basename(sedFile[:-3])+'pdf',format='pdf',overwrite=True) #plt.close() sncosmo.write_griddata_ascii(phase, newWave, flux, sedFile) return
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)
def _extrapolatesed(sedfile, newsedfile, color, table, time, modColor, bands, zpsys, bandsDone, UVoverwrite, IRoverwrite, niter=50): """ (Private) Intermediate sed extrapolation function. Interpolate the given transmission function to the wavestep of the SED, then get the area in the V band for color calculation and run the extrapolation algorithm. """ dlist, wlist, flist = _getsed( sedfile) #first time this is read in, should be in ergs/s/cm^2/AA i = 0 while dlist[i][0] < time[0]: i += 1 dlist = dlist[i:] wlist = wlist[i:] flist = flist[i:] i = -1 while dlist[i][0] > time[-1]: i -= 1 if i != -1: dlist = dlist[:i + 1] wlist = wlist[:i + 1] flist = flist[:i + 1] blue = color[0] red = color[-1] bWave = bands[blue].wave bTrans = bands[blue].trans rWave = bands[red].wave rTrans = bands[red].trans bInterpFunc = scint.interp1d(bWave, bTrans) rInterpFunc = scint.interp1d(rWave, rTrans) cInterpFunc = scint.interp1d(time, modColor) tempTime = [x[0] for x in dlist] colorData = cInterpFunc(tempTime) sed = createSNSED( sedfile, rescale=False) #now the original sed is in ergs/s/cm^2/AA model = sncosmo.Model(sed) #out = open( newsedfile, 'wb' ) log = open('./error.log', 'wb') def _extrap_helper(wave1, interpFunc1, wave2, interpFunc2, known, currentPhase): area = model.bandmag(bands[known], zpsys, currentPhase) val = int(math.ceil(wave2[0] / wavestep)) * wavestep val2 = int(math.floor(wave2[-1] / wavestep)) * wavestep wave = arange(val, val2 + 1, wavestep) trans = interpFunc2(wave) return (wave, trans, area) UV = False IR = False finalF = [] for i in range(len(dlist)): d, w, f = dlist[i], wlist[i], flist[i] wavestep = w[1] - w[0] if bands[blue].wave_eff <= _UVrightBound: bWave, bTrans, rArea = _extrap_helper(rWave, rInterpFunc, bWave, bInterpFunc, red, d[0]) wnew, fnew = _extrapolate_uv(blue, rArea, colorData[i], bTrans, bWave, f, w, niter, log, i, bands, zpsys, UVoverwrite) UV = True elif bands[red].wave_eff >= _IRleftBound: rWave, rTrans, bArea = _extrap_helper(bWave, bInterpFunc, rWave, rInterpFunc, blue, d[0]) wnew, fnew = _extrapolate_ir(red, bArea, colorData[i], rTrans, rWave, d, f, w, niter, log, i, IR, bands, zpsys, model, bandsDone, IRoverwrite) IR = True else: raise RuntimeError( "You supplied a color that does not support extrapolation to the IR or UV!" ) finalF.append(fnew) sncosmo.write_griddata_ascii(array([x[0] for x in dlist]), array(wnew), array(finalF), newsedfile) #for j in range( len( wnew ) ) : # fout.write("%5.1f %10i %12.7e \n"%( d[0], wnew[j], fnew[j] )) #fout.close() #log.close() return (UV, IR)
def setup_class(self): """Create a SALT2 model with a lot of components set to 1.""" phase = np.linspace(0.0, 100.0, 10) wave = np.linspace(1000.0, 10000.0, 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, 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.0, 20.0, 30.0, 40.0, 50.0] self.source.set(x1=0.0) result = self.source.bandflux_rcov(band, phase) expected = np.array( [ [0.05, 0.04, 0.0, 0.0, 0.0], [0.04, 0.05, 0.0, 0.0, 0.0], [0.0, 0.0, 0.05, 0.04, 0.0], [0.0, 0.0, 0.04, 0.05, 0.0], [0.0, 0.0, 0.0, 0.0, 0.05], ] ) assert_allclose(result, expected)
def sed_to_perturber(perturber_in, base_sed, perturber_var='Theta', scale_band='bessellb', rescale=True, outname='my_perturber.dat', phase_wave_source='perturber', diff_limit=np.inf, ave_spec=None): if isinstance(perturber_in, dict): perturber_dict = perturber_in out_perturber_dict = {e: {} for e in perturber_in.keys()} single = False else: perturber_dict = {'single': perturber_in} single = True base_phase = base_sed._phase base_wave = base_sed._wave overall_min_phase = -np.inf overall_max_phase = np.inf overall_max_wave = np.inf overall_min_wave = -np.inf for e in perturber_dict.keys(): perturber_sed = perturber_dict[e] perturber_phase = perturber_sed._phase perturber_wave = perturber_sed._wave if np.min(perturber_wave) > overall_min_wave: overall_min_wave = np.min(perturber_wave) if np.max(perturber_wave) < overall_max_wave: overall_max_wave = np.max(perturber_wave) if np.min(perturber_phase) > overall_min_phase: overall_min_phase = np.min(perturber_phase) if np.max(perturber_phase) < overall_max_phase: overall_max_phase = np.max(perturber_phase) fluxes = [] for phase in base_phase: base_flux = base_sed._flux(phase, base_wave).flatten() if phase >= np.min(perturber_phase) and phase <= np.max( perturber_phase ): # and ((e=='single' or float(e)<10.7001) or perturber_var!='hostmass'): scale_factor = perturber_sed.bandflux( scale_band, phase) / base_sed.bandflux(scale_band, phase) try: perturber_flux = perturber_sed._flux(phase, base_wave).flatten() except: perturber_flux = base_sed._flux( phase, base_wave ) #/np.max(base_sed._flux(phase,base_wave))#np.zeros(len(base_wave)) inds = base_wave[np.where( np.logical_and( base_wave >= np.min(perturber_wave), base_wave <= np.max(perturber_wave)))[0]] perturber_flux[inds] = perturber_sed._flux( phase, base_wave[inds]) if not rescale: scale_factor = 1. perturber_flux /= scale_factor if ave_spec is None: perturber_flux = (perturber_flux - base_flux) / base_flux else: perturber_flux = (perturber_flux - ave_spec._flux( phase, base_wave).flatten()) / base_flux perturber_flux[np.abs(perturber_flux) == np.inf] = np.nan perturber_flux[np.abs(perturber_flux) > diff_limit] = np.nan if np.isnan(perturber_flux[0]): perturber_flux[0] = 0 for i in range(1, len(perturber_flux)): if np.isnan(perturber_flux[i]): perturber_flux[i] = perturber_flux[i - 1] else: perturber_wave = base_wave perturber_flux = np.zeros(len(base_wave)) if not single: out_perturber_dict[e][phase] = { base_wave[i]: perturber_flux[i] for i in range(len(base_wave)) } else: fluxes.append(perturber_flux) accept_phase_inds = np.where( np.logical_and(base_phase >= overall_min_phase, base_phase <= overall_max_phase))[0] accept_wave_inds = np.where( np.logical_and(base_wave >= overall_min_wave, base_wave <= overall_max_wave))[0] if single: fluxes = np.array(fluxes).reshape((len(base_phase), len(base_wave))) base_phase = base_phase[accept_phase_inds].astype(int) base_wave = base_wave[accept_wave_inds].astype(int) fluxes = fluxes[np.ix_(accept_phase_inds, accept_wave_inds)] sncosmo.write_griddata_ascii(base_phase, base_wave, fluxes, outname) line_prepender(outname, '# phase wavelength flux') else: base_phase = base_phase[accept_phase_inds].astype(int) base_wave = base_wave[accept_wave_inds].astype(int) def func(velocity, phase, wavelength): flux = np.array([ out_perturber_dict[v][p][w] for v, p, w in zip(velocity, phase, wavelength) ]) return flux generate_ND_grids(func, outname, [perturber_var, 'phase', 'wavelength', 'flux'], np.sort(list(out_perturber_dict.keys())), base_phase, base_wave)