How to use the lightkurve.utils.validate_method function in lightkurve

To help you get started, we’ve selected a few lightkurve examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github KeplerGO / lightkurve / lightkurve / lightcurve.py View on Github external
>>> normalized_lc.flux_err
            array([0.00026223, 0.00017739, 0.00023909])

        Returns
        -------
        normalized_lightcurve : `LightCurve`
            A new light curve object in which ``flux`` and ``flux_err`` have
            been divided by the median flux.

        Warns
        -----
        LightkurveWarning
            If the median flux is negative or within half a standard deviation
            from zero.
        """
        validate_method(unit, ['unscaled', 'percent', 'ppt', 'ppm'])
        median_flux = np.nanmedian(self.flux)
        std_flux = np.nanstd(self.flux)

        # If the median flux is within half a standard deviation from zero, the
        # light curve is likely zero-centered and normalization makes no sense.
        if (median_flux == 0) or (np.isfinite(std_flux) and (np.abs(median_flux) < 0.5*std_flux)):
            warnings.warn("The light curve appears to be zero-centered "
                          "(median={:.2e} +/- {:.2e}); `normalize()` will divide "
                          "the light curve by a value close to zero, which is "
                          "probably not what you want."
                          "".format(median_flux, std_flux),
                          LightkurveWarning)
        # If the median flux is negative, normalization will invert the light
        # curve and makes no sense.
        if median_flux < 0:
            warnings.warn("The light curve has a negative median flux ({:.2e});"
github KeplerGO / lightkurve / lightkurve / seismology / core.py View on Github external
`~lightkurve.seismology.estimate_deltanu_acf2d` function which requires
        the parameter `numax`. For details and literature references, please
        read the detailed docstring of this function by typing
        ``lightkurve.seismology.estimate_deltanu_acf2d?`` in a Python terminal or notebook.

        Parameters
        ----------
        method : str
            Method to use. Only ``"acf2d"`` is supported at this time.

        Returns
        -------
        deltanu : `~lightkurve.seismology.SeismologyQuantity`
            DeltaNu of the periodogram, including details on the units and method.
        """
        method = validate_method(method, supported_methods=["acf2d"])
        numax = self._validate_numax(numax)

        if method == "acf2d":
            from .deltanu_estimators import estimate_deltanu_acf2d
            result = estimate_deltanu_acf2d(self.periodogram, numax=numax)

        self.deltanu = result
        return result
github KeplerGO / lightkurve / lightkurve / periodogram.py View on Github external
The factor by which to bin the power spectrum, in the sense that
            the power spectrum will be smoothed by taking the mean in bins
            of size N / binsize, where N is the length of the original
            frequency array. Defaults to 10.
        method : str, one of 'mean' or 'median'
            Method to use for binning. Default is 'mean'.

        Returns
        -------
        binned_periodogram : a `Periodogram` object
            Returns a new `Periodogram` object which has been binned.
        """
        # Input validation
        if binsize < 1:
            raise ValueError('binsize must be larger than or equal to 1')
        method = validate_method(method, ['mean', 'median'])

        m = int(len(self.power) / binsize)  # length of the binned arrays
        if method == 'mean':
            binned_freq = self.frequency[:m*binsize].reshape((m, binsize)).mean(1)
            binned_power = self.power[:m*binsize].reshape((m, binsize)).mean(1)
        elif method == 'median':
            binned_freq = np.nanmedian(self.frequency[:m*binsize].reshape((m, binsize)), axis=1)
            binned_power = np.nanmedian(self.power[:m*binsize].reshape((m, binsize)), axis=1)

        binned_pg = self.copy()
        binned_pg.frequency = binned_freq
        binned_pg.power = binned_power
        return binned_pg
github KeplerGO / lightkurve / lightkurve / targetpixelfile.py View on Github external
the median flux will be used.
            Alternatively, users can pass a boolean array describing the
            aperture mask such that `True` means that the pixel will be used.
        method : 'moments' or 'quadratic'
            Defines which method to use to estimate the centroids. 'moments'
            computes the centroid based on the sample moments of the data.
            'quadratic' fits a 2D polynomial to the data and returns the
            coordinate of the peak of that polynomial.

        Returns
        -------
        columns, rows : array, array
            Arrays containing the column and row positions for the centroid
            for each cadence, or NaN for cadences where the estimation failed.
        """
        method = validate_method(method, ['moments', 'quadratic'])
        if method == 'moments':
            return self._estimate_centroids_via_moments(aperture_mask=aperture_mask)
        elif method == 'quadratic':
            return self._estimate_centroids_via_quadratic(aperture_mask=aperture_mask)
github KeplerGO / lightkurve / lightkurve / lightcurve.py View on Github external
A new light curve which has been binned.

        Notes
        -----
        - If the ratio between the lightcurve length and the binsize is not
          a whole number, then the remainder of the data points will be
          ignored.
        - If the original light curve contains flux uncertainties (``flux_err``),
          the binned lightcurve will report the root-mean-square error.
          If no uncertainties are included, the binned curve will return the
          standard deviation of the data.
        - If the original lightcurve contains a quality attribute, then the
          bitwise OR of the quality flags will be returned per bin.
        """
        # Validate user input
        method = validate_method(method, supported_methods=['mean', 'median'])
        if (binsize is None) and (bins is None):
            binsize = 13
        elif (binsize is not None) and (bins is not None):
            raise ValueError('Both binsize and bins kwargs were passed to '
                             '`.bin()`.  Must assign only one of these.')

        # Only recent versions of AstroPy (>Dec 2018) provide ``calculate_bin_edges``
        if bins is not None:
            try:
                from astropy.stats import calculate_bin_edges
            except ImportError:
                from astropy import __version__ as astropy_version
                raise ImportError("The `bins=` parameter requires astropy >=3.1 or >=2.10, "
                                  "you currently have astropy version {}. "
                                  "Update astropy or use the `binsize` argument instead."
                                  "".format(astropy_version))
github KeplerGO / lightkurve / lightkurve / periodogram.py View on Github external
Default: `'amplitude'`. The desired normalization of the spectrum.
            Can be either power spectral density (`'psd'`) or amplitude
            (`'amplitude'`).
        ls_method : str
            Default: `'fast'`. Passed to the `method` keyword of
            `astropy.stats.LombScargle()`.
        kwargs : dict
            Keyword arguments passed to `astropy.stats.LombScargle()`

        Returns
        -------
        Periodogram : `Periodogram` object
            Returns a Periodogram object extracted from the lightcurve.
        """
        # Input validation
        normalization = validate_method(normalization, ['psd', 'amplitude'])

        # Setting default frequency units
        if freq_unit is None:
            freq_unit = 1/u.day if normalization == 'amplitude' else u.microhertz

        # Default oversample factor
        if oversample_factor is None:
            oversample_factor = 5. if normalization == 'amplitude' else 1.

        if "min_period" in kwargs:
            warnings.warn("`min_period` keyword is deprecated, "
                          "please use `minimum_period` instead.",
                          LightkurveWarning)
            minimum_period = kwargs.pop("min_period", None)
        if "max_period" in kwargs:
            warnings.warn("`max_period` keyword is deprecated, "
github KeplerGO / lightkurve / lightkurve / periodogram.py View on Github external
----------
        method : str, one of 'boxkernel' or 'logmedian'
            The smoothing method to use. Defaults to 'boxkernel'.
        filter_width : float
            If `method` = 'boxkernel', this is the width of the smoothing filter
            in units of frequency.
            If method = `logmedian`, this is the width of the smoothing filter
            in log10(frequency) space.

        Returns
        -------
        smoothed_pg : `Periodogram` object
            Returns a new `Periodogram` object in which the power spectrum
            has been smoothed.
        """
        method = validate_method(method, ['boxkernel', 'logmedian'])

        if method == 'boxkernel':
            if filter_width <= 0.:
                raise ValueError("the `filter_width` parameter must be "
                                 "larger than 0 for the 'boxkernel' method.")
            try:
                filter_width = u.Quantity(filter_width, self.frequency.unit)
            except u.UnitConversionError:
                raise ValueError("the `filter_width` parameter must have "
                                 "frequency units.")

            # Check to see if we have a grid of evenly spaced periods instead.
            fs = np.mean(np.diff(self.frequency))
            if not np.isclose(np.median(np.diff(self.frequency.value)), fs.value):
                raise ValueError("the 'boxkernel' method requires the periodogram "
                                 "to have a grid of evenly spaced frequencies.")
github KeplerGO / lightkurve / lightkurve / lightcurve.py View on Github external
Use the Lomb Scargle or Box Least Squares (BLS) method to
            extract the power spectrum. Defaults to ``'lombscargle'``.
            ``'ls'`` and ``'bls'`` are shorthands for ``'lombscargle'``
            and ``'boxleastsquares'``.
        kwargs : dict
            Keyword arguments passed to either
            `~lightkurve.periodogram.LombScarglePeriodogram` or
            `~lightkurve.periodogram.BoxLeastSquaresPeriodogram`.

        Returns
        -------
        Periodogram : `~lightkurve.periodogram.Periodogram` object
            The power spectrum object extracted from the light curve.
        """
        supported_methods = ["ls", "bls", "lombscargle", "boxleastsquares"]
        method = validate_method(method.replace(' ', ''), supported_methods)
        if method in ["bls", "boxleastsquares"]:
            from . import BoxLeastSquaresPeriodogram
            return BoxLeastSquaresPeriodogram.from_lightcurve(lc=self, **kwargs)
        else:
            from . import LombScarglePeriodogram
            return LombScarglePeriodogram.from_lightcurve(lc=self, **kwargs)