Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
from __future__ import absolute_import, division, print_function
from astropy import units as u
from marvin.utils.datamodel.maskbit import get_maskbits
from .base import RSS, DataCube, DRPCubeDataModel, DRPCubeDataModelList, Spectrum
spaxel_unit = u.Unit('spaxel', represents=u.pixel, doc='A spectral pixel', parse_strict='silent')
fiber_unit = u.Unit('fiber', represents=u.pixel, doc='Spectroscopic fibre', parse_strict='silent')
MPL4_datacubes = [
DataCube('flux', 'FLUX', 'WAVE', extension_ivar='IVAR',
extension_mask='MASK', unit=u.erg / u.s / (u.cm ** 2) / u.Angstrom / spaxel_unit,
scale=1e-17, formats={'string': 'Flux'},
description='3D rectified cube')
]
MPL4_spectra = [
Spectrum('spectral_resolution', 'SPECRES', extension_wave='WAVE', extension_std='SPECRESD',
unit=u.Angstrom, scale=1, formats={'string': 'Median spectral resolution'},
description='Median spectral resolution as a function of wavelength '
'for the fibers in this IFU'),
]
MPL6_datacubes = [
DataCube('dispersion', 'DISP', 'WAVE', extension_ivar=None,
extension_mask='MASK', unit=u.Angstrom,
scale=1, formats={'string': 'Dispersion'},
description='Broadened dispersion solution (1sigma LSF)'),
An iterable of Quantities representing line rest frequencies
vmin / vmax : Quantity
Velocity-equivalent quantities specifying the velocity range to average
over
average : function
A function that can operate over a list of numpy arrays (and accepts
``axis=0``) to average the spectra. `numpy.nanmean` is the default,
though one might consider `numpy.mean` or `numpy.median` as other
options.
convolve_beam : None
If the cube is a VaryingResolutionSpectralCube, a convolution beam is
required to put the cube onto a common grid prior to spectral
interpolation.
"""
line_cube = cube.with_spectral_unit(u.km/u.s,
velocity_convention='radio',
rest_value=linelist[0])
if isinstance(line_cube, VaryingResolutionSpectralCube):
if convolve_beam is None:
raise ValueError("When stacking VaryingResolutionSpectralCubes, "
"you must specify a target beam size with the "
"keyword `convolve_beam`")
reference_cube = line_cube.spectral_slab(vmin, vmax).convolve_to(convolve_beam)
else:
reference_cube = line_cube.spectral_slab(vmin, vmax)
cutout_cubes = [reference_cube.filled_data[:].value]
for restval in linelist[1:]:
line_cube = cube.with_spectral_unit(u.km/u.s,
velocity_convention='radio',
# ------------
# Here is an example plot of the model:
import matplotlib.pyplot as plt
from astropy import units as u
from gammapy.modeling.models import (
Models,
SkyModel,
SmoothBrokenPowerLawSpectralModel,
)
energy_range = [0.1, 100] * u.TeV
model = SmoothBrokenPowerLawSpectralModel(
index1=1.5 * u.Unit(""),
index2=2.5 * u.Unit(""),
amplitude=4 / u.cm ** 2 / u.s / u.TeV,
ebreak=0.5 * u.TeV,
reference=1 * u.TeV,
beta=1,
)
model.plot(energy_range)
plt.grid(which="both");
# %%
# YAML representation
# -------------------
# Here is an example YAML file using the model:
model = SkyModel(spectral_model=model, name="smooth-broken-power-law-model")
models = Models([model])
print(models.to_yaml())
\exp \left( \frac{E_0 - E}{E_{C}} \right)
"""
# %%
# Example plot
# ------------
# Here is an example plot of the model:
from astropy import units as u
import matplotlib.pyplot as plt
from gammapy.modeling.models import ExpCutoffPowerLaw3FGLSpectralModel, Models, SkyModel
energy_range = [0.1, 100] * u.TeV
model = ExpCutoffPowerLaw3FGLSpectralModel(
index=2.3 * u.Unit(""),
amplitude=4 / u.cm ** 2 / u.s / u.TeV,
reference=1 * u.TeV,
ecut=10 * u.TeV,
)
model.plot(energy_range)
plt.grid(which="both")
# %%
# YAML representation
# -------------------
# Here is an example YAML file using the model:
model = SkyModel(spectral_model=model, name="exp-cutoff-power-law-3fgl-model")
models = Models([model])
print(models.to_yaml())
def _get_spectrum_type(y_unit):
"""
:param y_unit: an astropy unit
:return: str indicating the type of unit desired
"""
pht_flux_unit = 1. / (u.cm ** 2 * u.s)
flux_unit = u.erg / (u.cm ** 2 * u.s)
vfv_unit = u.erg ** 2 / (u.cm ** 2 * u.s)
# Try to convert to base units. If it works then return that unit type
try:
y_unit.to(pht_flux_unit)
return "phtflux"
except(u.UnitConversionError):
try:
y_unit.to(flux_unit)
return "eneflux"
if time is None and time_start is None:
raise TypeError("Either 'time' or 'time_start' should be specified")
elif time is not None and time_start is not None:
raise TypeError("Cannot specify both 'time' and 'time_start'")
if time is not None and not isinstance(time, Time):
time = Time(time)
if time_start is not None and not isinstance(time_start, Time):
time_start = Time(time_start)
if time_delta is not None and not isinstance(time_delta, (Quantity, TimeDelta)):
raise TypeError("'time_delta' should be a Quantity or a TimeDelta")
if isinstance(time_delta, TimeDelta):
time_delta = time_delta.sec * u.s
if time_start is not None:
# We interpret this as meaning that time is that of the first
# sample and that the interval is given by time_delta.
if time_delta is None:
raise TypeError("'time' is scalar, so 'time_delta' is required")
if time_delta.isscalar:
time_delta = np.repeat(time_delta, n_samples)
time_delta = np.cumsum(time_delta)
time_delta = np.roll(time_delta, 1)
time_delta[0] = 0. * u.s
Returns:
An estimate of the semi-amplitude of each planet in units of ``m/s``.
"""
if yerr is None:
ivar = np.ones_like(y)
else:
ivar = 1.0 / yerr ** 2
periods = u.Quantity(np.atleast_1d(periods), unit=u.day)
if t0s is not None:
t0s = u.Quantity(np.atleast_1d(t0s), unit=u.day).value
x = u.Quantity(np.atleast_1d(x), unit=u.day)
y = u.Quantity(np.atleast_1d(y), unit=u.m / u.s)
ivar = u.Quantity(np.atleast_1d(ivar), unit=(u.s / u.m) ** 2)
D = _get_design_matrix(periods.value, t0s, x.value)
w = np.linalg.solve(
np.dot(D.T, D * ivar.value[:, None]), np.dot(D.T, y.value * ivar.value)
)
if t0s is not None:
K = w[:-1]
else:
w = w[:-1]
K = np.sqrt(w[::2] ** 2 + w[1::2] ** 2)
return K
def set_Lum(self):
""" Set all the Luminosities from the SFR.
"""
const = self.const
self.L_Lya = (self.SFR / (9.1e-43 * const)).to(u.erg / u.s)
self.L_Ha = (self.SFR / (7.9e-42 * const)).to(u.erg / u.s)
self.L_OII = (self.SFR / (1.4e-41 * const)).to(u.erg / u.s)
self.L_UV = (self.SFR / (1.4e-28 * u.M_sun / u.yr /
(u.erg / u.s / u.Hz))).to(u.erg / u.s / u.Hz)
self.L_FIR = (self.SFR / (4.5e-44 * const)).to(u.erg / u.s)
def calculate_time_results(
time_start, trigger_time,
):
"""Calculate and return the sample time"""
return {
# FIXME Why divided by two here?
"sample_time": u.Quantity((trigger_time - time_start) / 2, u.s),
"sample_time_min": u.Quantity(time_start, u.s),
"sample_time_max": u.Quantity(trigger_time, u.s),
}
def __init__(self, dict):
"""An object which describes a single observation.
Args:
dict (dictionary): a dictionary describing the observation as read from
the YAML file.
"""
self.config = load_config()
## master_exptime (assumes units of seconds, defaults to 120 seconds)
try:
self.master_exptime = dict['master_exptime'] * u.s
except:
self.master_exptime = 120 * u.s
## master_nexp (defaults to 1)
try:
self.master_nexp = int(dict['master_nexp'])
except:
self.master_nexp = 1
## master_filter
try:
self.master_filter = int(dict['master_filter'])
except:
self.master_filter = None
## analyze (defaults to False)
try:
self.analyze = dict['master_filter'] in ['True', 'true', 'Yes', 'yes', 'Y', 'y', 'T', 't']
except:
self.analyze = False