<commit_before>#!/usr/bin/env python
# encoding: utf-8
#
# spectrum.py
#
# Licensed under a 3-clause BSD license.

# Revision history:
#     13 Apr 2016 <NAME>
#       Initial version


from __future__ import division
from __future__ import print_function
from __future__ import absolute_import

import numpy as np
import matplotlib.pyplot as plt
from astropy.units import Quantity, dimensionless_unscaled

from marvin.utils.general import _sort_dir

class Spectrum(Quantity):
    """A class representing an spectrum with extra functionality.

    Parameters:
        flux (array-like):
            The 1-D array contianing the spectrum.
        unit (astropy.unit.Unit, optional):
            The unit of the flux spectrum.
        scale (float, optional):
            The scale factor of the spectrum flux.
        ivar (array-like, optional):
            The inverse variance array for ``spectrum``. Must have the same
            number of elements.
        mask (array-like, optional):
            The mask array for ``spectrum``. Must have the same number of
            elements.
        wavelength (array-like, optional):
            The wavelength solution for ``spectrum``. Must have the same number
            of elements.
        wavelength_unit (astropy.unit.Unit, optional):
            The units of the wavelength solution.

    Returns:
        spectrum:
            An astropy Quantity-like object that contains the spectrum, as well
            as inverse variance, mask, and wavelengh (itself a Quantity array).

    """

    def __new__(cls, flux, scale=1, unit=dimensionless_unscaled,
                wavelength_unit=dimensionless_unscaled, ivar=None, mask=None,
                wavelength=None, dtype=None, copy=True, **kwargs):

        flux = np.array(flux) * scale

        obj = Quantity(flux, unit=unit, dtype=dtype, copy=copy)
        obj = obj.view(cls)
        obj._set_unit(unit)

        obj.ivar = (np.array(ivar) / (scale ** 2)) if ivar is not None else None
        obj.mask = np.array(mask) if mask is not None else None

        if wavelength is None:
            obj.wavelength = None
        else:
            if wavelength_unit:
                obj.wavelength = Quantity(np.array(wavelength), unit=wavelength_unit)
            else:
                obj.wavelength = np.array(wavelength)

        return obj

    def __array_finalize__(self, obj):

        if obj is None:
            return

        self.ivar = getattr(obj, 'ivar', None)
        self.mask = getattr(obj, 'mask', None)
        self.wavelength = getattr(obj, 'wavelength', None)

    def __getitem__(self, sl):

        new_obj = super(Spectrum, self).__getitem__(sl)

        if type(new_obj) is not type(self):
            new_obj = self._new_view(new_obj)

        new_obj._set_unit(self.unit)

        new_obj.ivar = self.ivar.__getitem__(sl) if self.ivar is not None else self.ivar
        new_obj.mask = self.mask.__getitem__(sl) if self.mask is not None else self.mask
        new_obj.wavelength = self.wavelength.__getitem__(sl) \
            if self.wavelength is not None else self.wavelength

        return new_obj

    def __dir__(self):
        return_list = _sort_dir(self, Spectrum)
        return_list += ['value']
        return return_list

    @property
    def error(self):
        """The standard deviation of the measurement."""

        if self.ivar is None:
            return None

        np.seterr(divide='ignore')

        return np.sqrt(1. / self.ivar) * self.unit

    @property
    def snr(self):
        """The signal to noise of the measurement."""

        if self.ivar is None:
            return None

        return np.abs(self.value * np.sqrt(self.ivar))

    @property
    def masked(self):
        """Returns a masked array."""

        return np.ma.array(self.value, mask=self.mask > 0)

    def plot(self, array='flux', xlim=None, ylim=(0, None), mask_color=None,
             xlabel=None, ylabel=None, figure=None, return_figure=False, **kwargs):
        """Plots a spectrum using matplotlib.

        Returns a |axes|_ object with a representation of this spectrum.
        The returned ``axes`` object can then be showed, modified, or saved to
        a file. If running Marvin from an iPython console and
        `matplotlib.pyplot.ion()
        <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.ion>`_,
        the plot will be displayed interactivelly.

        Parameters:<commit_msg>accepts standard deviation as input, and creates CompositeUnit if scale<commit_after>#!/usr/bin/env python
# encoding: utf-8
#
# spectrum.py
#
# Licensed under a 3-clause BSD license.

# Revision history:
#     13 Apr 2016 <NAME>
#       Initial version


from __future__ import division
from __future__ import print_function
from __future__ import absolute_import

import numpy as np
import matplotlib.pyplot as plt
from astropy.units import CompositeUnit, Quantity, dimensionless_unscaled

from marvin.utils.general import _sort_dir


class Spectrum(Quantity):
    """A class representing an spectrum with extra functionality.

    Parameters:
        value (array-like):
            The 1-D array contianing the spectrum.
        unit (astropy.unit.Unit, optional):
            The unit of the spectrum.
        scale (float, optional):
            The scale factor of the spectrum value.
        ivar (array-like, optional):
            The inverse variance array for ``value``.
        std (array-like, optional):
            The standard deviation associated with ``value``.
        mask (array-like, optional):
            The mask array for ``value``.
        wavelength (array-like, optional):
            The wavelength solution for ``value``.
        wavelength_unit (astropy.unit.Unit, optional):
            The units of the wavelength solution.

    Returns:
        spectrum:
            An astropy Quantity-like object that contains the spectrum, as well
            as inverse variance, mask, and wavelengh (itself a Quantity array).

    """

    def __new__(cls, flux, scale=None, unit=dimensionless_unscaled,
                wavelength_unit=dimensionless_unscaled, ivar=None, std=None,
                mask=None, wavelength=None, dtype=None, copy=True, **kwargs):

        flux = np.array(flux)

        # If the scale is defined, creates a new composite unit with the input scale.
        if scale is not None:
            unit = CompositeUnit(unit.scale * scale, unit.bases, unit.powers)

        obj = Quantity(flux, unit=unit, dtype=dtype, copy=copy)
        obj = obj.view(cls)
        obj._set_unit(unit)

        obj.ivar = np.array(ivar) if ivar is not None else None
        obj.mask = np.array(mask) if mask is not None else None

        if std is not None:
            assert ivar is None, 'std and ivar cannot be used at the same time.'
            obj._std = np.array(std)

        if wavelength is None:
            obj.wavelength = None
        else:
            if wavelength_unit:
                obj.wavelength = Quantity(np.array(wavelength), unit=wavelength_unit)
            else:
                obj.wavelength = np.array(wavelength)

        return obj

    def __array_finalize__(self, obj):

        if obj is None:
            return

        self.ivar = getattr(obj, 'ivar', None)
        self._std = getattr(obj, '_std', None)
        self.mask = getattr(obj, 'mask', None)
        self.wavelength = getattr(obj, 'wavelength', None)

    def __getitem__(self, sl):

        new_obj = super(Spectrum, self).__getitem__(sl)

        if type(new_obj) is not type(self):
            new_obj = self._new_view(new_obj)

        new_obj._set_unit(self.unit)

        new_obj.ivar = self.ivar.__getitem__(sl) if self.ivar is not None else self.ivar
        new_obj._std = self._std.__getitem__(sl) if self._std is not None else self._std
        new_obj.mask = self.mask.__getitem__(sl) if self.mask is not None else self.mask
        new_obj.wavelength = self.wavelength.__getitem__(sl) \
            if self.wavelength is not None else self.wavelength

        return new_obj

    def __dir__(self):
        return_list = _sort_dir(self, Spectrum)
        return_list += ['value']
        return return_list

    @property
    def error(self):
        """The standard deviation of the measurement."""

        if self._std is not None:
            return self._std

        if self.ivar is None:
            return None

        np.seterr(divide='ignore')

        return np.sqrt(1. / self.ivar) * self.unit

    @property
    def std(self):
        """The standard deviation of the measurement."""

        return self.error

    @property
    def snr(self):
        """The signal to noise of the measurement."""

        if self.ivar is None:
            return None

        return np.abs(self.value * np.sqrt(self.ivar))

    @property
    def masked(self):
        """Returns a masked array."""

        return np.ma.array(self.value, mask=self.mask > 0)

    def plot(self, array='flux', xlim=None, ylim=(0, None), mask_color=None,
             xlabel=None, ylabel=None, figure=None, return_figure=False, **kwargs):
        """Plots a spectrum using matplotlib.

        Returns a |axes|_ object with a representation of this spectrum.
        The returned ``axes`` object can then be showed, modified, or saved to
        a file. If running Marvin from an iPython console and
        `matplotlib.pyplot.ion()
        <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.ion>`_,
        the plot will be displayed interactivelly.

        Parameters:
{'fraction_non_alphanumeric': 0.09174599853541165, 'fraction_numerical': 0.0027199497855424208, 'mean_word_length': 2.3033863165169315, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '965698', 'n_tokens_mistral': 2823, 'n_tokens_neox': 2675, 'n_words': 877}