Skip to content

Commit

Permalink
Merge pull request #104 from nikhil-sarin/some_changes_and_release
Browse files Browse the repository at this point in the history
Some changes and release
  • Loading branch information
nikhil-sarin committed Mar 11, 2022
2 parents bc65352 + a7477cc commit f8cde80
Show file tree
Hide file tree
Showing 56 changed files with 1,262 additions and 718 deletions.
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# All notable changes will be documented in this file

## [0.2.0] 2022-03-11
Version 1.1.5 release of redback

### Added
- Basic functionality
- Several examples
- Docs
21 changes: 9 additions & 12 deletions examples/SN2011kl_sample_in_t0_example.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import matplotlib.pyplot as plt

import redback
from bilby.core.prior import Uniform, Gaussian

Expand All @@ -9,45 +7,44 @@
# we want to sample in t0 and with extinction so we use
model = 't0_supernova_extinction'
# we want to specify a base model for the actual physics
base_model = "exponential_powerlaw"
base_model = "arnett"

data = redback.get_data.get_supernova_data_from_open_transient_catalog_data(sne)

# load the data into a supernova transient object which does all the processing and can be used to make plots etc
# we set the data_mode to flux density to use/fit flux density. We could use 'magnitude' or 'luminosity' or flux as well.
# However, for optical transients we recommend fitting in flux_density.
supernova = redback.supernova.Supernova.from_open_access_catalogue(name=sne, data_mode='flux_density')
supernova = redback.supernova.Supernova.from_open_access_catalogue(name=sne, data_mode='flux_density', use_phase_model=True)

# lets make a plot of the data
fig, axes = plt.subplots(2, 2, sharex=True, sharey=True, figsize=(12, 8))
supernova.plot_multiband(figure=fig, axes=axes, filters=["J", "H", "g", "i"])
supernova.plot_multiband(filters=["J", "H", "g", "i"])

# we are now only going to fit g and i bands. We set this using the transient object and the active bands attribute
bands = ["g", "i"]
supernova.active_bands = bands

# use default priors
priors = redback.priors.get_priors(model=model)
priors.update(redback.priors.get_priors(model=base_model))
# we know the redshift for SN2011kl so we just fix the prior for the redshift to the known value
priors['redshift'] = 0.677

# we also want to sample in t0 so we need a prior for that and extinction parameters
# we use bilby prior objects for this
# let's set t0 as a Gaussian around the first observation with sigma = 0.5 - There are many other priors to choose from.
# This also demonstates how one can change the latex labels etc
priors['t0'] = Gaussian(data['time [mjd]'], sigma=0.5, name='t0', latex_label=r'$T_{\rm{0}}$')
priors['t0'] = Gaussian(data['time'][0], sigma=0.5, name='t0', latex_label=r'$T_{\rm{0}}$')

# We also need a prior on A_v i.e., the total mag extinction.
# Just use uniform prior for now.
priors['av'] = Uniform(0.1, 1, name='av', latex_label=r'$a_{v}$')


model_kwargs = dict(frequencies=redback.utils.bands_to_frequencies(bands), output_format='flux_density')
model_kwargs = dict(frequency=supernova.filtered_frequencies, output_format='flux_density', base_model=base_model)

# returns a supernova result object
result = redback.fit_model(name=sne, transient=supernova, model=model, sampler=sampler, model_kwargs=model_kwargs,
prior=priors, data_mode='flux_density', sample='rslice', nlive=200, resume=False)
result = redback.fit_model(transient=supernova, model=model, sampler=sampler, model_kwargs=model_kwargs,
prior=priors, sample='rslice', nlive=200, resume=True)

result.plot_corner()

result.plot_lightcurve(random_models=1000)
result.plot_lightcurve(random_models=100)
42 changes: 24 additions & 18 deletions examples/broadband_afterglow_private_data_example.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,44 @@
# What if your data is not public, or if you simulated it yourself.
# You can fit it with redback but now by loading the transient object yourself.
# This example also shows how to fit afterglow models to broadband data.
# In particular, the afterglow of GRB170817A, the GRB that accompanied the first Binary neutron star merger
# In particular, the afterglow of GRB170817A, the GRB that accompanied the first binary neutron star merger

import redback
import pandas as pd

# load the data file
data = pd.read_csv('example_data/grb_afterglow.csv')
time_d = data['time']
flux_density = data['flux']
frequency = data['frequency']
flux_density_err = data['flux_err']
time_d = data['time'].values
flux_density = data['flux'].values
frequency = data['frequency'].values
flux_density_err = data['flux_err'].values

# we now load the afterglow transient object. We are using flux_density data here so we need to use that data mode
# we now load the afterglow transient object. We are using flux_density data here, so we need to use that data mode
data_mode = 'flux_density'

# set some other useful things as variables
name = '170817A'
redshift = 1e-2

afterglow = redback.transient.Afterglow(name=name, data_mode=data_mode, time=time_d,
flux_density=flux_density, flux_err=flux_density_err, frequency=frequency)
afterglow = redback.transient.Afterglow(
name=name, data_mode=data_mode, time=time_d,
flux_density=flux_density, flux_density_err=flux_density_err, frequency=frequency)

# Now we have loaded the data up, we can plot it.
# We can pass keyword arguments here to not show, save the plot or change the aesthetics.
afterglow.plot_data()
afterglow.plot_multiband()

# now let's actually fit it with data. We will use all the data and a gaussiancore structured jet from afterglowpy.
# Note this is not a fast example so we will make some sampling sacrifices for speed.
# Note to make the example run quick, we will make some sampling sacrifices for speed and fix several parameters.

model = 'gaussiancore'

# use default priors and 'nestle' sampler
sampler = 'nestle'
# use default priors and 'dynesty' sampler
sampler = 'dynesty'
priors = redback.priors.get_priors(model=model)

#fix the redshift
priors['redshift'] = redshift

# We are gonna fix some of the microphysical parameters for speed
Expand All @@ -43,15 +48,16 @@
priors['logepsb'] = -3.8
priors['ksin'] = 1.

model_kwargs = dict(frequencies=frequency, output_format='flux_density')
model_kwargs = dict(frequency=frequency, output_format='flux_density')

# returns a supernova result object
result = redback.fit_model(name=name, transient=afterglow, model=model, sampler=sampler, model_kwargs=model_kwargs,
prior=priors, data_mode='flux_density', sample='rslice', nlive=200, resume=False)
# Fitting returns a afterglow result object, which can be used for plotting or doing further analysis.
result = redback.fit_model(transient=afterglow, model=model, sampler=sampler, model_kwargs=model_kwargs,
prior=priors, sample='rslice', nlive=500, resume=True)
# plot corner
result.plot_corner()

# plot multiband lightcurve. This will plot a panel for every unique frequency
# plot multiband lightcurve.
# This will plot a panel for every unique frequency,
# along with the fitted lightcurve from a 100 random realisations randomly drawn from the prior.
# We can change other settings by passing in different keyword arguments here.
result.plot_multiband_lightcurve(random_models=100)


22 changes: 14 additions & 8 deletions examples/fit_your_own_model_example.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import bilby.core.prior

import redback
from bilby.core.prior import LogUniform, Uniform


# If your favourite model is not implemented in redback. You can still fit it using redback!
# Now instead of passing a string as the model. You need to pass a python function.

# let's make a simple power law. A power law model is already in redback but this is just an example.
# You can make up any model you like.

# time must be the first element.
def my_favourite_model(time, l0, alpha):
return l0*time**alpha
def my_favourite_model(time, l0, alpha, **kwargs):
return l0 * time ** alpha


model = my_favourite_model

Expand All @@ -24,18 +28,20 @@ def my_favourite_model(time, l0, alpha):
afterglow = redback.afterglow.SGRB.from_swift_grb(name=GRB, data_mode='flux',
truncate=True, truncate_method="prompt_time_error")


# uses an analytical k-correction expression to create luminosity data if not already there.
# Can also use a numerical k-correction through CIAO
afterglow.analytical_flux_to_luminosity()
afterglow.plot_data()

# You need to create your own priors for this new model.
# The model has two parameters l0 and alpha. We use bilby priors for this
priors = {}
priors['l0'] = LogUniform(1e40, 1e55, 'l0', latex_label = r'$l_{0}$')
priors['alpha_1'] = Uniform(-7, -1, 'alpha_1', latex_label = r'$\alpha_{1}$')
priors = bilby.core.prior.PriorDict()
priors['l0'] = LogUniform(1e-10, 1e5, 'l0', latex_label=r'$l_{0}$')
priors['alpha'] = Uniform(-7, 0, 'alpha', latex_label=r'$\alpha$')

# Call redback.fit_model to run the sampler and obtain GRB result object
result = redback.fit_model(name=GRB, model=model, sampler='dynesty', nlive=200, transient=afterglow,
prior=priors, data_mode='luminosity', sample='rslice')
result = redback.fit_model(model=model, sampler='dynesty', nlive=200, transient=afterglow,
prior=priors, sample='rslice', resume=False)

result.plot_lightcurve(random_models=1000)
result.plot_lightcurve(random_models=100, model=my_favourite_model)
13 changes: 7 additions & 6 deletions examples/kilonova_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,19 @@
# creates a GRBDir with GRB
kilonova = redback.kilonova.Kilonova.from_open_access_catalogue(
name=kne, data_mode="flux_density", active_bands=np.array(["g", "i"]))
# kilonova.flux_density_data = True
kilonova.plot_data(plot_show=False)
fig, axes = plt.subplots(3, 2, sharex=True, sharey=True, figsize=(12, 8))
kilonova.plot_multiband(figure=fig, axes=axes, filters=["g", "r", "i", "z", "y", "J"])
kilonova.plot_multiband(figure=fig, axes=axes, filters=["g", "r", "i", "z", "y", "J"], plot_show=False)

# use default priors
priors = redback.priors.get_priors(model=model)
priors['redshift'] = 1e-2

model_kwargs = dict(frequency=kilonova.filtered_frequencies, output_format='flux_density')

result = redback.fit_model(name=kne, transient=kilonova, model=model, sampler=sampler, model_kwargs=model_kwargs,
prior=priors, data_mode='flux_density', sample='rslice', nlive=200, resume=False)
result = redback.fit_model(transient=kilonova, model=model, sampler=sampler, model_kwargs=model_kwargs,
prior=priors, sample='rslice', nlive=200, resume=True)
result.plot_corner()
# returns a Kilonova result object
result.plot_lightcurve(random_models=1000)
result.plot_lightcurve(plot_show=False)
# Even though we only fit the 'g' band, we can still plot the fit for different bands.
result.plot_multiband_lightcurve(filters=["g", "r", "i", "z", "y", "J"], plot_show=False)
15 changes: 8 additions & 7 deletions examples/magnetar_boosted_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,10 @@
model = 'mergernova'

kne = 'at2017gfo'
path = 'KNDir'
# gets the magnitude data for AT2017gfo, the KN associated with GW170817
data = redback.get_data.get_kilonova_data_from_open_transient_catalog_data(transient=kne)
# creates a GRBDir with GRB
kilonova = redback.kilonova.Kilonova.from_open_access_catalogue(name=kne, data_mode="flux_density")
kilonova = redback.kilonova.Kilonova.from_open_access_catalogue(name=kne, data_mode="flux_density", active_bands=['g'])
# kilonova.flux_density_data = True
fig, axes = plt.subplots(3, 2, sharex=True, sharey=True, figsize=(12, 8))
bands = ["g"]
Expand All @@ -27,10 +26,12 @@
priors['tau_sd'] = 1e3
priors['thermalisation_efficiency'] = 0.3

model_kwargs = dict(frequencies=redback.utils.bands_to_frequencies(bands), output_format='flux_density')
model_kwargs = dict(frequency=redback.utils.bands_to_frequency(bands), output_format='flux_density')

result = redback.fit_model(name=kne, transient=kilonova, model=model, sampler=sampler, model_kwargs=model_kwargs,
path=path, prior=priors, data_mode='flux_density', sample='rslice', nlive=200)
result.plot_corner()
result = redback.fit_model(transient=kilonova, model=model, sampler=sampler, model_kwargs=model_kwargs,
prior=priors, sample='rslice', nlive=200, resume=True)
# result.plot_corner()
# returns a Kilonova result object
result.plot_lightcurve(random_models=1000)
# result.plot_lightcurve(random_models=50)
# Even though we only fit the 'g' band, we can still plot the fit for different bands.
result.plot_multiband_lightcurve(filters=["g", "r", "i", "z", "y", "J"])
12 changes: 7 additions & 5 deletions examples/magnetar_example.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import redback
import bilby

# We implemented many models implemented, including
# afterglow/magnetar varieties/n_dimensional_fireball/shapelets/band function/kilonova/SNe/TDE
Expand All @@ -16,12 +17,13 @@
# uses an analytical k-correction expression to create luminosity data if not already there.
# Can also use a numerical k-correction through CIAO
afterglow.analytical_flux_to_luminosity()
afterglow.plot_data()

# use default priors
priors = redback.priors.get_priors(model=model, data_mode='luminosity')

# alternatively can pass in some priors
# priors = {}
# alternatively can create a dictionary of priors in some priors
# priors = bilby.core.prior.PriorDict()
# priors['A_1'] = bilby.core.prior.LogUniform(1e-15, 1e15, 'A_1', latex_label = r'$A_{1}$')
# priors['alpha_1'] = bilby.core.prior.Uniform(-7, -1, 'alpha_1', latex_label = r'$\alpha_{1}$')
# priors['p0'] = bilby.core.prior.Uniform(0.7e-3, 0.1, 'p0', latex_label = r'$P_{0} [s]$')
Expand All @@ -33,7 +35,7 @@


# Call redback.fit_model to run the sampler and obtain GRB result object
result = redback.fit_model(name=GRB, model=model, sampler='dynesty', nlive=200, transient=afterglow,
prior=priors, data_mode='luminosity', sample='rslice')
result = redback.fit_model(model=model, sampler='dynesty', nlive=200, transient=afterglow,
prior=priors, sample='rslice', resume=True)

result.plot_lightcurve(random_models=1000)
result.plot_lightcurve(random_models=100)
4 changes: 2 additions & 2 deletions examples/prompt_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
priors = redback.priors.get_priors(model=model, data_mode='counts', times=prompt.time,
y=prompt.counts, yerr=prompt.counts_err, dt=prompt.bin_size)

result = redback.fit_model(source_type='prompt', name=name, model=model, transient=prompt, nlive=500,
sampler=sampler, prior=priors, data_mode='counts', outdir="GRB_results", sample='rslice')
result = redback.fit_model(source_type='prompt', model=model, transient=prompt, nlive=500,
sampler=sampler, prior=priors, outdir="GRB_results", sample='rslice')
# returns a GRB prompt result object
result.plot_lightcurve(random_models=1000)
result.plot_corner()
15 changes: 7 additions & 8 deletions examples/supernova_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,17 @@

data = redback.get_data.get_supernova_data_from_open_transient_catalog_data(sne)

supernova = redback.supernova.Supernova.from_open_access_catalogue(name=sne, data_mode='flux_density')
fig, axes = plt.subplots(2, 2, sharex=True, sharey=True, figsize=(12, 8))
bands = ["g", "i"]
supernova.plot_multiband(figure=fig, axes=axes, filters=["J", "H", "g", "i"])
supernova = redback.supernova.Supernova.from_open_access_catalogue(name=sne, data_mode='flux_density', active_bands=["g", "i"])
supernova.plot_multiband(filters=["J", "H", "g", "i"])

# use default priors
priors = redback.priors.get_priors(model=model)
priors['redshift'] = 0.677
model_kwargs = dict(frequencies=redback.utils.bands_to_frequencies(bands), output_format='flux_density')
model_kwargs = dict(frequency=supernova.filtered_frequencies, output_format='flux_density')

# returns a supernova result object
result = redback.fit_model(name=sne, transient=supernova, model=model, sampler=sampler, model_kwargs=model_kwargs,
prior=priors, data_mode='flux_density', sample='rslice', nlive=200, resume=False)
result = redback.fit_model(transient=supernova, model=model, sampler=sampler, model_kwargs=model_kwargs,
prior=priors, sample='rslice', nlive=200, resume=True)
result.plot_corner()
result.plot_lightcurve(random_models=1000)
result.plot_lightcurve(random_models=100)
result.plot_multiband_lightcurve()
15 changes: 7 additions & 8 deletions examples/tde_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,10 @@

data = redback.get_data.get_tidal_disruption_event_data_from_open_transient_catalog_data(tde)

tidal_disruption_event = redback.tde.TDE.from_open_access_catalogue(tidal_disruption_event, data_mode='flux_density')
tidal_disruption_event = redback.tde.TDE.from_open_access_catalogue(tde, data_mode='flux_density')

# lets make a plot of the data
fig, axes = plt.subplots(2, 2, sharex=True, sharey=True, figsize=(12, 8))
tidal_disruption_event.plot_multiband(figure=fig, axes=axes, filters=["J", "H", "g", "i"])
tidal_disruption_event.plot_multiband(filters=["V", "r", "g", "i"])

# we are now only going to fit u and r bands. We set this using the transient object and the active bands attribute.
# By default all data is used, this is just for speed in the example or if you only trust some of the data/physics.
Expand All @@ -23,14 +22,14 @@
priors = redback.priors.get_priors(model=model)
# we know the redshift for PS18kh so we just fix the prior for the redshift to the known value.
# We can do this through the metadata that was downloaded alongside the data, or if you just know it.
priors['redshift'] = tidal_disruption_event.redshift
priors['redshift'] = 0.07

model_kwargs = dict(frequencies=redback.utils.bands_to_frequencies(bands), output_format='flux_density')
model_kwargs = dict(frequency=tidal_disruption_event.filtered_frequencies, output_format='flux_density')

# returns a tde result object
result = redback.fit_model(name=tde, transient=tidal_disruption_event, model=model, sampler=sampler, model_kwargs=model_kwargs,
prior=priors, data_mode='flux_density', sample='rslice', nlive=200, resume=False)
result = redback.fit_model(transient=tidal_disruption_event, model=model, sampler=sampler,
model_kwargs=model_kwargs, prior=priors, sample='rslice', nlive=200, resume=False)

result.plot_corner()

result.plot_lightcurve(random_models=1000)
result.plot_lightcurve(random_models=100)
3 changes: 2 additions & 1 deletion optional_requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ sncosmo
lalsimulation
nestle
sherpa
kilonova-heating-rate
kilonova-heating-rate
PyQt5
2 changes: 0 additions & 2 deletions redback/get_data/directory.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,9 @@ def afterglow_directory_structure(grb: str, data_mode: str, instrument: str = 'B
if instrument == 'XRT':
raw_file_path = f'{path}_xrt_rawSwiftData.csv'
processed_file_path = f'{path}_xrt.csv'
logger.warning('You are only downloading XRT data, you may not capture the tail of the prompt emission.')
else:
raw_file_path = f'{path}_rawSwiftData.csv'
processed_file_path = f'{path}.csv'
logger.warning('You are downloading BAT and XRT data, you will need to truncate the data for some models.')

return DirectoryStructure(
directory_path=directory_path, raw_file_path=raw_file_path, processed_file_path=processed_file_path)
Expand Down
1 change: 1 addition & 0 deletions redback/get_data/open_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ def convert_raw_data_to_csv(self) -> Union[pd.DataFrame, None]:
magnitude_error=data['e_magnitude'].values,
reference_flux=3631,
magnitude_system='AB')
data['band'] = [b.replace("'", "") for b in data["band"]]
metadata = pd.read_csv(f"{self.directory_path}{self.transient}_metadata.csv")
metadata.replace(r'^\s+$', np.nan, regex=True)
time_of_event = self.get_time_of_event(data=data, metadata=metadata)
Expand Down
Loading

0 comments on commit f8cde80

Please sign in to comment.