-
-
Notifications
You must be signed in to change notification settings - Fork 424
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Refactor spectrum #729
Merged
Merged
Refactor spectrum #729
Changes from 4 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
9da43d1
Refactor TARDISSpectrum
yeganer 9e45a76
PEP8 fixes
yeganer 6cd9bdb
Add test_spectrum
yeganer ae46cc3
Fix PEP8 issues
yeganer 95141c1
Add warning to MontecarloRunner.spectrum_virtual
yeganer f028d62
Plot luminosity_density_lambda instead of flux_lambda
yeganer 5e04ec3
Add DeprecationWarning to flux_nu and flux_lambda
yeganer 4f0e7b5
Convert unneeded properties to attributes
yeganer 6167a7c
Add test for DeprecationWarning
yeganer c019d5f
Remove decorator and write down explicitly
yeganer File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,99 +1,121 @@ | ||
import os | ||
import numpy as np | ||
from astropy import constants, units as u | ||
|
||
from tardis.io.util import to_hdf | ||
from astropy import units as u | ||
|
||
|
||
def require_field(name): | ||
def _require_field(f): | ||
def wrapper(self, *args, **kwargs): | ||
if not getattr(self, name, None): | ||
raise AttributeError( | ||
'{} is required as attribute of' | ||
'{} to calculate {}'.format( | ||
name, | ||
self.__class__.__name__, | ||
f.__name__ | ||
) | ||
) | ||
else: | ||
return f(self, *args, **kwargs) | ||
return wrapper | ||
return _require_field | ||
|
||
|
||
class TARDISSpectrum(object): | ||
""" | ||
TARDIS Spectrum object | ||
""" | ||
TARDISSpectrum(_frequency, luminosity) | ||
|
||
def __init__(self, frequency, distance=None): | ||
self._frequency = frequency | ||
self.wavelength = self.frequency.to('angstrom', u.spectral()) | ||
_frequency: astropy.units.Quantity with unit 'Hz' or a length | ||
These are bin edges of frequency or wavelenght bins for the spectrum. | ||
|
||
self.distance = distance | ||
luminosity: astropy.units.Quantity with unit Energy per second | ||
The luminosity in each bin of the spectrum. | ||
|
||
After manually adding a distance attribute, the properties 'flux_nu' and | ||
'flux_lambda' become available | ||
""" | ||
|
||
def __init__(self, _frequency, luminosity): | ||
if not _frequency.shape[0] == luminosity.shape[0] + 1: | ||
raise ValueError( | ||
"shape of '_frequency' and 'luminosity' are not compatible" | ||
": '{}' and '{}'".format( | ||
_frequency.shape[0], | ||
luminosity.shape[0]) | ||
) | ||
self._frequency = _frequency.to('Hz', u.spectral()) | ||
self.luminosity = luminosity.to('erg / s') | ||
|
||
self.delta_frequency = frequency[1] - frequency[0] | ||
@property | ||
def frequency(self): | ||
return self._frequency[:-1] | ||
|
||
self._flux_nu = np.zeros_like(frequency.value) * u.Unit('erg / (s Hz cm^2)') | ||
self._flux_lambda = np.zeros_like(frequency.value) * u.Unit('erg / (s Angstrom cm^2)') | ||
@property | ||
def delta_frequency(self): | ||
return self.frequency[1] - self.frequency[0] | ||
|
||
self.luminosity_density_nu = np.zeros_like(self.frequency) * u.Unit('erg / (s Hz)') | ||
self.luminosity_density_lambda = np.zeros_like(self.frequency) * u.Unit('erg / (s Angstrom)') | ||
@property | ||
def wavelength(self): | ||
return self.frequency.to('angstrom', u.spectral()) | ||
|
||
@property | ||
def frequency(self): | ||
return self._frequency[:-1] | ||
def luminosity_density_nu(self): | ||
return (self.luminosity / self.delta_frequency).to('erg / (s Hz)') | ||
|
||
@property | ||
def luminosity_density_lambda(self): | ||
return self.f_nu_to_f_lambda( | ||
self.luminosity_density_nu, | ||
) | ||
|
||
@property | ||
@require_field('distance') | ||
def flux_nu(self): | ||
if self.distance is None: | ||
raise AttributeError('supernova distance not supplied - flux calculation impossible') | ||
else: | ||
return self._flux_nu | ||
return self.luminosity_to_flux( | ||
self.luminosity_density_nu, | ||
self.distance) | ||
|
||
@property | ||
@require_field('distance') | ||
def flux_lambda(self): | ||
if self.distance is None: | ||
raise AttributeError('supernova distance not supplied - flux calculation impossible') | ||
return self._flux_lambda | ||
|
||
def update_luminosity(self, spectrum_luminosity): | ||
self.luminosity_density_nu = (spectrum_luminosity / self.delta_frequency).to('erg / (s Hz)') | ||
self.luminosity_density_lambda = self.f_nu_to_f_lambda(self.luminosity_density_nu.value) \ | ||
* u.Unit('erg / (s Angstrom)') | ||
return self.luminosity_to_flux( | ||
self.luminosity_density_lambda, | ||
self.distance | ||
) | ||
|
||
if self.distance is not None: | ||
self._flux_nu = (self.luminosity_density_nu / (4 * np.pi * self.distance.to('cm')**2)) | ||
|
||
self._flux_lambda = self.f_nu_to_f_lambda(self.flux_nu.value) * u.Unit('erg / (s Angstrom cm^2)') | ||
@staticmethod | ||
def luminosity_to_flux(luminosity, distance): | ||
return luminosity / (4 * np.pi * distance.to('cm')**2) | ||
|
||
def f_nu_to_f_lambda(self, f_nu): | ||
return f_nu * self.frequency.value**2 / constants.c.cgs.value / 1e8 | ||
|
||
return f_nu * self.frequency / self.wavelength | ||
|
||
def plot(self, ax, mode='wavelength'): | ||
if mode == 'wavelength': | ||
ax.plot(self.wavelength.value, self.flux_lambda.value) | ||
ax.set_xlabel('Wavelength [%s]' % self.wavelength.unit._repr_latex_()) | ||
ax.set_xlabel('Wavelength [{}]'.format( | ||
self.wavelength.unit._repr_latex_()) | ||
) | ||
ax.set_ylabel('Flux [%s]' % self.flux_lambda.unit._repr_latex_()) | ||
|
||
def to_ascii(self, fname, mode='luminosity_density'): | ||
if mode == 'luminosity_density': | ||
np.savetxt(fname, zip(self.wavelength.value, self.luminosity_density_lambda.value)) | ||
np.savetxt( | ||
fname, zip( | ||
self.wavelength.value, | ||
self.luminosity_density_lambda.value)) | ||
elif mode == 'flux': | ||
np.savetxt(fname, zip(self.wavelength.value, self.flux_lambda.value)) | ||
np.savetxt( | ||
fname, | ||
zip(self.wavelength.value, self.flux_lambda.value)) | ||
else: | ||
raise NotImplementedError('only mode "luminosity_density" and "flux" are implemented') | ||
|
||
def to_hdf(self, path_or_buf, path='', name=''): | ||
""" | ||
Store the spectrum to an HDF structure. | ||
|
||
Parameters | ||
---------- | ||
path_or_buf | ||
Path or buffer to the HDF store | ||
path : str | ||
Path inside the HDF store to store the spectrum | ||
name : str, optional | ||
A different name than 'spectrum', if needed. | ||
|
||
Returns | ||
------- | ||
None | ||
|
||
""" | ||
if not name: | ||
name = 'spectrum' | ||
spectrum_path = os.path.join(path, name) | ||
properties = ['luminosity_density_nu', 'delta_frequency', 'wavelength', | ||
'luminosity_density_lambda'] | ||
to_hdf(path_or_buf, spectrum_path, {name: getattr(self, name) for name | ||
in properties}) | ||
raise NotImplementedError( | ||
'only mode "luminosity_density"' | ||
'and "flux" are implemented') | ||
|
||
def to_hdf(self, path_or_buf, path): | ||
pass | ||
|
||
@classmethod | ||
def from_hdf(cls, path_or_buf, path): | ||
pass |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
add warning