Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
template_obswavelength)
# Numerator
num_right = normalization * template_obswavelength.flux
num = observed_spectrum.flux - num_right
# Denominator
denom = observed_spectrum.uncertainty.array * observed_spectrum.flux.unit
# Get chi square
result = (num/denom)**2
chi2 = np.sum(result.value)
# Create normalized template spectrum, which will be returned with
# corresponding chi2
normalized_template_spectrum = Spectrum1D(
spectral_axis=template_spectrum.spectral_axis,
flux=template_spectrum.flux*normalization)
return normalized_template_spectrum, chi2
A new Spectrum1D object which incorporates the template_spectrum with a spectral_axis
that has been redshifted using the final_redshift.
chi2_list : `list`
A list with the chi2 values corresponding to each input redshift value.
"""
chi2_min = None
final_redshift = None
chi2_list = []
redshift = np.array(redshift).reshape((np.array(redshift).size,))
# Loop which goes through available redshift values and finds the smallest chi2
for rs in redshift:
# Create new redshifted spectrum and run it through the chi2 method
redshifted_spectrum = Spectrum1D(spectral_axis=template_spectrum.spectral_axis*(1+rs),
flux=template_spectrum.flux, uncertainty=template_spectrum.uncertainty,
meta=template_spectrum.meta)
normalized_spectral_template, chi2 = _chi_square_for_templates(
observed_spectrum, redshifted_spectrum, "flux_conserving")
chi2_list.append(chi2)
# Set new chi2_min if suitable replacement is found
if not np.isnan(chi2) and (chi2_min is None or chi2 < chi2_min):
chi2_min = chi2
final_redshift = rs
return final_redshift, redshifted_spectrum, chi2_list
if flux.ndim != 1:
raise ValueError("Currently only 1D data structures may be "
"returned from slice operations.")
spectral_axis = self.spectral_axis[key]
uncertainty = None if self.uncertainty is None else self.uncertainty[key]
wcs = None if self.wcs is None else self.wcs[key]
mask = None if self.mask is None else self.mask[key]
if self.meta is None:
meta = None
else:
try:
meta = self.meta[key]
except KeyError:
meta = self.meta
return Spectrum1D(flux=flux, spectral_axis=spectral_axis,
uncertainty=uncertainty, wcs=wcs, mask=mask,
meta=meta)
def __init__(self, flux=None, spectral_axis=None, wcs=None,
velocity_convention=None, rest_value=None, redshift=None,
radial_velocity=None, **kwargs):
# Check for pre-defined entries in the kwargs dictionary.
unknown_kwargs = set(kwargs).difference(
{'data', 'unit', 'uncertainty', 'meta', 'mask', 'copy'})
if len(unknown_kwargs) > 0:
raise ValueError("Initializer contains unknown arguments(s): {}."
"".format(', '.join(map(str, unknown_kwargs))))
# If the flux (data) argument is a subclass of nddataref (as it would
# be for internal arithmetic operations), avoid setup entirely.
if isinstance(flux, NDDataRef):
super(Spectrum1D, self).__init__(flux)
return
# Ensure that the flux argument is an astropy quantity
if flux is not None:
if not isinstance(flux, u.Quantity):
raise ValueError("Flux must be a `Quantity` object.")
elif flux.isscalar:
flux = u.Quantity([flux])
# Ensure that only one or neither of these parameters is set
if redshift is not None and radial_velocity is not None:
raise ValueError("Cannot set both radial_velocity and redshift at "
"the same time.")
# In cases of slicing, new objects will be initialized with `data`
# instead of ``flux``. Ensure we grab the `data` argument.
(dispersion <= window[1]))
# in this case the window is spectral regions that determine where
# to fit.
elif window is not None and isinstance(window, SpectralRegion):
idx1, idx2 = window.bounds
if idx1 == idx2:
raise IndexError("Tried to fit a region containing no pixels.")
# HACK WARNING! This uses the extract machinery to create a set of
# indices by making an "index spectrum"
# note that any unit will do but Jy is at least flux-y
# TODO: really the spectral region machinery should have the power
# to create a mask, and we'd just use that...
idxarr = np.arange(spectrum.flux.size).reshape(spectrum.flux.shape)
index_spectrum = Spectrum1D(spectral_axis=spectrum.spectral_axis,
flux=u.Quantity(idxarr, u.Jy, dtype=int))
extracted_regions = extract_region(index_spectrum, window)
if isinstance(extracted_regions, list):
if len(extracted_regions) == 0:
raise ValueError('The whole spectrum is windowed out!')
window_indices = np.concatenate([s.flux.value.astype(int) for s in extracted_regions])
else:
if len(extracted_regions.flux) == 0:
raise ValueError('The whole spectrum is windowed out!')
window_indices = extracted_regions.flux.value.astype(int)
if window_indices is not None:
dispersion = dispersion[window_indices]
flux = flux[window_indices]
if mask is not None:
window_indices = extracted_regions.flux.value.astype(int)
if window_indices is not None:
dispersion = dispersion[window_indices]
flux = flux[window_indices]
if mask is not None:
mask = mask[window_indices]
if weights is not None:
weights = weights[window_indices]
if flux is None or len(flux) == 0:
raise Exception("Spectrum flux is empty or None.")
input_spectrum = spectrum
spectrum = Spectrum1D(
flux=flux.value * flux_unit,
spectral_axis=dispersion,
wcs=input_spectrum.wcs,
velocity_convention=input_spectrum.velocity_convention,
rest_value=input_spectrum.rest_value)
#
# Compound models with units can not be fit.
#
# Convert the model initial guess to the spectral
# units and then remove the units
#
model_unitless, dispersion_unitless, flux_unitless = \
_strip_units_from_model(model, spectrum, convert=not ignore_units)
self.label_status.setStyleSheet('color: red')
self.label_status.setText("Component name already exists.")
self.button_ok.setEnabled(False)
elif self._get_raw_command() == "":
self.label_status.setText("")
self.button_ok.setEnabled(False)
else:
try:
dict_map = {x.name: "self._item_from_name('{}')".format(x.name)
for x in self._equation_editor.hub.data_items}
raw_str = self._get_raw_command()
self.evaluated_arith = eval(raw_str.format(**dict_map))
if not isinstance(self.evaluated_arith,
specutils.spectra.spectrum1d.Spectrum1D):
raise ValueError("Arithmetic Editor must return ",
"Spectrum1D object not {}".\
format(type(self.evaluated_arith)))
except SyntaxError:
self.label_status.setStyleSheet('color: red')
self.label_status.setText("Incomplete or invalid syntax")
self.button_ok.setEnabled(False)
except Exception as exc:
self.label_status.setStyleSheet('color: red')
self.label_status.setText(str(exc))
self.button_ok.setEnabled(False)
else:
self.label_status.setStyleSheet('color: green')
self.label_status.setText("Valid expression")
self.button_ok.setEnabled(True)