class StingrayObject(object):
    """This base class defines some general-purpose utilities.

    The main purpose is to have a consistent mechanism for:

    + round-tripping to and from Astropy Tables and other dataframes

    + round-tripping to files in different formats

    The idea is that any object inheriting :class:`StingrayObject` should,
    just by defining an attribute called ``main_array_attr``, be able to perform
    the operations above, with no additional effort.

    ``main_array_attr`` is, e.g. ``time`` for :class:`EventList` and
    :class:`Lightcurve`, ``freq`` for :class:`Crossspectrum`, ``energy`` for
    :class:`VarEnergySpectrum`, and so on. It is the array with wich all other
    attributes are compared: if they are of the same shape, they get saved as
    columns of the table/dataframe, otherwise as metadata.
    """

    def __init__(cls, *args, **kwargs):
        if not hasattr(cls, "main_array_attr"):
            raise RuntimeError(
                "A StingrayObject needs to have the main_array_attr attribute specified"
            )

    def array_attrs(self):
        """List the names of the array attributes of the Stingray Object.

        By array attributes, we mean the ones with the same size and shape as
        ``main_array_attr`` (e.g. ``time`` in ``EventList``)
        """

        main_attr = getattr(self, getattr(self, "main_array_attr"))
        if main_attr is None:
            return []

        return [
            attr
            for attr in dir(self)
            if (
                isinstance(getattr(self, attr), Iterable)
                and np.shape(getattr(self, attr)) == np.shape(main_attr)
            )
        ]

    def meta_attrs(self):
        """List the names of the meta attributes of the Stingray Object.

        By array attributes, we mean the ones with a different size and shape
        than ``main_array_attr`` (e.g. ``time`` in ``EventList``)
        """
        array_attrs = self.array_attrs()
        return [
            attr
            for attr in dir(self)
            if (
                attr not in array_attrs
                and not attr.startswith("_")
                # Use new assignment expression (PEP 572). I'm testing that
                # self.attribute is not callable, and assigning its value to
                # the variable attr_value for further checks
                and not callable(attr_value := getattr(self, attr))
                # a way to avoid EventLists, Lightcurves, etc.
                and not hasattr(attr_value, "meta_attrs")
            )
        ]

    def get_meta_dict(self):
        """Give a dictionary with all non-None meta attrs of the object."""
        meta_attrs = self.meta_attrs()
        meta_dict = {}
        for key in meta_attrs:
            val = getattr(self, key)
            if val is not None:
                meta_dict[key] = val
        return meta_dict

    def to_astropy_table(self):
        """Create an Astropy Table from a ``StingrayObject``

        Array attributes (e.g. ``time``, ``pi``, ``energy``, etc. for
        ``EventList``) are converted into columns, while meta attributes
        (``mjdref``, ``gti``, etc.) are saved into the ``meta`` dictionary.
        """
        data = {}
        array_attrs = self.array_attrs()

        for attr in array_attrs:
            data[attr] = np.asarray(getattr(self, attr))

        ts = Table(data)

        ts.meta.update(self.get_meta_dict())

        return ts

    @classmethod
    def from_astropy_table(cls, ts):
        """Create a Stingray Object object from data in an Astropy Table.

        The table MUST contain at least a column named like the
        ``main_array_attr``.
        The rest of columns will form the array attributes of the
        new object, while the attributes in ds.attrs will
        form the new meta attributes of the object.

        It is strongly advisable to define such attributes and columns
        using the standard attributes of the wanted StingrayObject (e.g.
        ``time``, ``pi``, etc. for ``EventList``)
        """
        cls = cls()

        if len(ts) == 0:
            # return an empty object
            return cls

        array_attrs = ts.colnames

        # Set the main attribute first
        mainarray = np.array(ts[cls.main_array_attr])
        setattr(cls, cls.main_array_attr, mainarray)

        for attr in array_attrs:
            if attr == cls.main_array_attr:
                continue
            setattr(cls, attr.lower(), np.array(ts[attr]))

        for key, val in ts.meta.items():
            setattr(cls, key.lower(), val)

        return cls

    def to_xarray(self):
        """Create an ``xarray`` Dataset from a `StingrayObject`.

        Array attributes (e.g. ``time``, ``pi``, ``energy``, etc. for
        ``EventList``) are converted into columns, while meta attributes
        (``mjdref``, ``gti``, etc.) are saved into the ``ds.attrs`` dictionary.
        """
        from xarray import Dataset

        data = {}
        array_attrs = self.array_attrs()

        for attr in array_attrs:
            data[attr] = np.asarray(getattr(self, attr))

        ts = Dataset(data)

        ts.attrs.update(self.get_meta_dict())

        return ts

    @classmethod
    def from_xarray(cls, ts):
        """Create a `StingrayObject` from data in an xarray Dataset.

        The dataset MUST contain at least a column named like the
        ``main_array_attr``.
        The rest of columns will form the array attributes of the
        new object, while the attributes in ds.attrs will
        form the new meta attributes of the object.

        It is strongly advisable to define such attributes and columns
        using the standard attributes of the wanted StingrayObject (e.g.
        ``time``, ``pi``, etc. for ``EventList``)
        """
        cls = cls()

        if len(ts[cls.main_array_attr]) == 0:
            # return an empty object
            return cls

        array_attrs = ts.coords

        # Set the main attribute first
        mainarray = np.array(ts[cls.main_array_attr])
        setattr(cls, cls.main_array_attr, mainarray)

        for attr in array_attrs:
            if attr == cls.main_array_attr:
                continue
            setattr(cls, attr, np.array(ts[attr]))

        for key, val in ts.attrs.items():
            if key not in array_attrs:
                setattr(cls, key, val)

        return cls

    def to_pandas(self):
        """Create a pandas ``DataFrame`` from a :class:`StingrayObject`.

        Array attributes (e.g. ``time``, ``pi``, ``energy``, etc. for
        ``EventList``) are converted into columns, while meta attributes
        (``mjdref``, ``gti``, etc.) are saved into the ``ds.attrs`` dictionary.
        """
        from pandas import DataFrame

        data = {}
        array_attrs = self.array_attrs()

        for attr in array_attrs:
            data[attr] = np.asarray(getattr(self, attr))

        ts = DataFrame(data)

        ts.attrs.update(self.get_meta_dict())

        return ts

    @classmethod
    def from_pandas(cls, ts):
        """Create an `StingrayObject` object from data in a pandas DataFrame.

        The dataframe MUST contain at least a column named like the
        ``main_array_attr``.
        The rest of columns will form the array attributes of the
        new object, while the attributes in ds.attrs will
        form the new meta attributes of the object.

        It is strongly advisable to define such attributes and columns
        using the standard attributes of the wanted StingrayObject (e.g.
        ``time``, ``pi``, etc. for ``EventList``)

        """
        cls = cls()

        if len(ts) == 0:
            # return an empty object
            return cls

        array_attrs = ts.columns

        # Set the main attribute first
        mainarray = np.array(ts[cls.main_array_attr])
        setattr(cls, cls.main_array_attr, mainarray)

        for attr in array_attrs:
            if attr == cls.main_array_attr:
                continue
            setattr(cls, attr, np.array(ts[attr]))

        for key, val in ts.attrs.items():
            if key not in array_attrs:
                setattr(cls, key, val)

        return cls

    @classmethod
    def read(cls, filename, fmt=None, format_=None):
        r"""Generic reader for :class`StingrayObject`

        Currently supported formats are

        * pickle (not recommended for long-term storage)
        * any other formats compatible with the writers in
          :class:`astropy.table.Table` (ascii.ecsv, hdf5, etc.)

        Files that need the :class:`astropy.table.Table` interface MUST contain
        at least a column named like the ``main_array_attr``.
        The default ascii format is enhanced CSV (ECSV). Data formats
        supporting the serialization of metadata (such as ECSV and HDF5) can
        contain all attributes such as ``mission``, ``gti``, etc with
        no significant loss of information. Other file formats might lose part
        of the metadata, so must be used with care.

        ..note::

            Complex values can be dealt with out-of-the-box in some formats
            like HDF5 or FITS, not in others (e.g. all ASCII formats).
            With these formats, and in any case when fmt is ``None``, complex
            values should be stored as two columns of real numbers, whose names
            are of the format <variablename>.real and <variablename>.imag

        Parameters
        ----------
        filename: str
            Path and file name for the file to be read.

        fmt: str
            Available options are 'pickle', 'hea', and any `Table`-supported
            format such as 'hdf5', 'ascii.ecsv', etc.

        Returns
        -------
        obj: :class:`StingrayObject` object
            The object reconstructed from file
        """
        if fmt is None and format_ is not None:
            warnings.warn(
                "The format_ keyword for read and write is deprecated. Use fmt instead",
                DeprecationWarning,
            )
            fmt = format_

        if fmt is None:
            pass
        elif fmt.lower() == "pickle":
            with open(filename, "rb") as fobj:
                return pickle.load(fobj)
        elif fmt.lower() == "ascii":
            fmt = "ascii.ecsv"

        ts = Table.read(filename, format=fmt)

        # For specific formats, and in any case when the format is not
        # specified, make sure that complex values are treated correctly.
        if fmt is None or "ascii" in fmt:
            for col in ts.colnames:
                if not (
                    (is_real := col.endswith(".real"))
                    or (is_imag := col.endswith(".imag"))
                ):
                    continue

                new_value = ts[col]

                if is_imag:
                    new_value = new_value * 1j

                # Make sure it's complex, even if we find the real part first
                new_value = new_value + 0.0j

                col_strip = col.replace(".real", "").replace(".imag", "")

                if col_strip not in ts.colnames:
                    # If the column without ".real" or ".imag" doesn't exist,
                    # define it, and make sure it's complex-valued
                    ts[col_strip] = new_value
                else:
                    # If it does exist, sum the new value to it.
                    ts[col_strip] += new_value

                ts.remove_column(col)

        return cls.from_astropy_table(ts)

    def write(self, filename, fmt=None, format_=None):
        """Generic writer for :class`StingrayObject`

        Currently supported formats are

        * pickle (not recommended for long-term storage)
        * any other formats compatible with the writers in
          :class:`astropy.table.Table` (ascii.ecsv, hdf5, etc.)

        ..note::

            Complex values can be dealt with out-of-the-box in some formats
            like HDF5 or FITS, not in others (e.g. all ASCII formats).
            With these formats, and in any case when fmt is ``None``, complex
            values will be stored as two columns of real numbers, whose names
            are of the format <variablename>.real and <variablename>.imag

        Parameters
        ----------
        filename: str
            Name and path of the file to save the object list to.

        fmt: str
            The file format to store the data in.
            Available options are ``pickle``, ``hdf5``, ``ascii``, ``fits``
        """
        if fmt is None and format_ is not None:
            warnings.warn(
                "The format_ keyword for read and write is deprecated. Use fmt instead",
                DeprecationWarning,
            )
            fmt = format_
        if fmt is None:
            pass
        elif fmt.lower() == "pickle":
            with open(filename, "wb") as fobj:
                pickle.dump(self, fobj)
            return
        elif fmt.lower() == "ascii":
            fmt = "ascii.ecsv"

        ts = self.to_astropy_table()
        if fmt is None or "ascii" in fmt:
            for col in ts.colnames:
                if np.iscomplex(ts[col][0]):
                    ts[f"{col}.real"] = ts[col].real
                    ts[f"{col}.imag"] = ts[col].imag
                    ts.remove_column(col)

        try:
            ts.write(filename, format=fmt, overwrite=True, serialize_meta=True)
        except TypeError:
            ts.write(filename, format=fmt, overwrite=True) class StingrayTimeseries(StingrayObject):
    def to_astropy_timeseries(self):
        """Save the ``StingrayTimeseries`` to an ``Astropy`` timeseries.

        Array attributes (time, pi, energy, etc.) are converted
        into columns, while meta attributes (mjdref, gti, etc.)
        are saved into the ``meta`` dictionary.

        Returns
        -------
        ts : `astropy.timeseries.TimeSeries`
            A ``TimeSeries`` object with the array attributes as columns,
            and the meta attributes in the `meta` dictionary
        """
        from astropy.timeseries import TimeSeries
        from astropy.time import TimeDelta
        from astropy import units as u

        data = {}
        array_attrs = self.array_attrs()

        for attr in array_attrs:
            if attr == "time":
                continue
            data[attr] = np.asarray(getattr(self, attr))

        if data == {}:
            data = None

        if self.time is not None and np.size(self.time) > 0:
            times = TimeDelta(self.time * u.s)
            ts = TimeSeries(data=data, time=times)
        else:
            ts = TimeSeries()

        ts.meta.update(self.get_meta_dict())

        return ts

    @classmethod
    def from_astropy_timeseries(cls, ts):
        """Create a `StingrayTimeseries` from data in an Astropy TimeSeries

        The timeseries has to define at least a column called time,
        the rest of columns will form the array attributes of the
        new event list, while the attributes in table.meta will
        form the new meta attributes of the event list.

        It is strongly advisable to define such attributes and columns
        using the standard attributes of EventList: time, pi, energy, gti etc.

        Parameters
        ----------
        ts : `astropy.timeseries.TimeSeries`
            A ``TimeSeries`` object with the array attributes as columns,
            and the meta attributes in the `meta` dictionary

        Returns
        -------
        ts : `StingrayTimeseries`
            Timeseries object
        """

        time = ts["time"]
        mjdref = None
        if "mjdref" in ts.meta:
            mjdref = ts.meta["mjdref"]

        time, mjdref = interpret_times(time, mjdref)
        cls.time = np.asarray(time)

        array_attrs = ts.colnames
        for key, val in ts.meta.items():
            setattr(cls, key, val)

        for attr in array_attrs:
            if attr == "time":
                continue
            setattr(cls, attr, ts[attr])

        return cls

    def change_mjdref(self, new_mjdref):
        """Change the MJD reference time (MJDREF) of the time series

        The times of the time series will be shifted in order to be referred to
        this new MJDREF

        Parameters
        ----------
        new_mjdref : float
            New MJDREF

        Returns
        -------
        new_lc : :class:`StingrayTimeseries` object
            The new time series, shifted by MJDREF
        """
        time_shift = (self.mjdref - new_mjdref) * 86400

        ts = self.shift(time_shift)
        ts.mjdref = new_mjdref
        return ts

    def shift(self, time_shift):
        """Shift the time and the GTIs by the same amount

        Parameters
        ----------
        time_shift: float
            The time interval by which the light curve will be shifted (in
            the same units as the time array in :class:`Lightcurve`

        Returns
        -------
        ts : ``StingrayTimeseries`` object
            The new time series shifted by ``time_shift``

        """
        ts = copy.deepcopy(self)
        ts.time = np.asarray(ts.time) + time_shift
        if hasattr(ts, "gti"):
            ts.gti = np.asarray(ts.gti) + time_shift

        return ts def get_deadtime_mask(ev_list, deadtime, bkg_ev_list=None,
                      dt_sigma=None, paralyzable=False,
                      return_all=False, verbose=False):
    """Filter an event list for a given dead time.

    Parameters
    ----------
    ev_list : array-like
        The event list
    deadtime: float
        The (mean, if not constant) value of deadtime

    Other Parameters
    ----------------
    bkg_ev_list : array-like
        A background event list that affects dead time
    dt_sigma : float
        If specified, dead time will not have a single value but it will have
        a normal distribution with mean ``deadtime`` and standard deviation
        ``dt_sigma``.

    Returns
    -------
    mask : array-like, optional
        The mask that filters the input event list and produces the output
        event list.
    additional_output : object
        Object with all the following attributes. Only returned if
        `return_all` is True
        uf_events : array-like
            Unfiltered event list (events + background)
        is_event : array-like
            Boolean values; True if event, False if background
        deadtime : array-like
            Dead time values
        bkg : array-like
            The filtered background event list

    """
    additional_output = DeadtimeFilterOutput()

    # Create the total lightcurve, and a "kind" array that keeps track
    # of the events classified as "signal" (True) and "background" (False)
    if bkg_ev_list is not None:
        tot_ev_list = np.append(ev_list, bkg_ev_list)
        ev_kind = np.append(np.ones(len(ev_list), dtype=bool),
                            np.zeros(len(bkg_ev_list), dtype=bool))
        order = np.argsort(tot_ev_list)
        tot_ev_list = tot_ev_list[order]
        ev_kind = ev_kind[order]
        del order
    else:
        tot_ev_list = ev_list
        ev_kind = np.ones(len(ev_list), dtype=bool)

    additional_output.uf_events = tot_ev_list
    additional_output.is_event = ev_kind
    additional_output.deadtime = deadtime
    additional_output.uf_mask = np.ones(tot_ev_list.size, dtype=bool)
    additional_output.bkg = tot_ev_list[np.logical_not(ev_kind)]

    if deadtime <= 0.:
        if deadtime < 0:
            raise ValueError("Dead time is less than 0. Please check.")
        retval = [np.ones(ev_list.size, dtype=bool), additional_output]
        return retval

    nevents = len(tot_ev_list)
    all_ev_kind = ev_kind.copy()

    if dt_sigma is not None:
        deadtime_values = ra.normal(deadtime, dt_sigma, nevents)
        deadtime_values[deadtime_values < 0] = 0.
    else:
        deadtime_values = np.zeros(nevents) + deadtime

    initial_len = len(tot_ev_list)

    # Note: saved_mask gives the mask that produces tot_ev_list_filt from
    # tot_ev_list. The same mask can be used to also filter all other arrays.
    if paralyzable:
        tot_ev_list_filt, saved_mask = \
            _paralyzable_dead_time(tot_ev_list, deadtime_values)

    else:
        tot_ev_list_filt, saved_mask = \
            _non_paralyzable_dead_time(tot_ev_list, deadtime_values)
    del tot_ev_list

    ev_kind = ev_kind[saved_mask]
    deadtime_values = deadtime_values[saved_mask]
    final_len = tot_ev_list_filt.size
    if verbose:
        log.info(
            'filter_for_deadtime: '
            '{0}/{1} events rejected'.format(initial_len - final_len,
                                             initial_len))

    retval = saved_mask[all_ev_kind]

    if return_all:
        # uf_events: source and background events together
        # ev_kind : kind of each event in uf_events.
        # bkg : Background events
        additional_output.uf_events = tot_ev_list_filt
        additional_output.is_event = ev_kind
        additional_output.deadtime = deadtime_values
        additional_output.bkg = tot_ev_list_filt[np.logical_not(ev_kind)]
        retval = [retval, additional_output]

    return retval def append_gtis(gti0, gti1):
    """Union of two non-overlapping GTIs.

    If the two GTIs "touch", this is tolerated and the touching GTIs are
    joined in a single one.

    Parameters
    ----------
    gti0: 2-d float array
        List of GTIs of the form ``[[gti0_0, gti0_1], [gti1_0, gti1_1], ...]``

    gti1: 2-d float array
        List of GTIs of the form ``[[gti0_0, gti0_1], [gti1_0, gti1_1], ...]``

    Returns
    -------
    gti: 2-d float array
        The newly created GTI

    Examples
    --------
    >>> np.allclose(append_gtis([[0, 1]], [[2, 3]]), [[0, 1], [2, 3]])
    True
    >>> np.allclose(append_gtis([[0, 1], [4, 5]], [[2, 3]]),
    ...             [[0, 1], [2, 3], [4, 5]])
    True
    >>> np.allclose(append_gtis([[0, 1]], [[1, 3]]), [[0, 3]])
    True
    """

    gti0 = np.asarray(gti0)
    gti1 = np.asarray(gti1)
    # Check if independently GTIs are well behaved.
    check_gtis(gti0)
    check_gtis(gti1)

    # Check if GTIs are mutually exclusive.
    if not check_separate(gti0, gti1):
        raise ValueError('In order to append, GTIs must be mutually'
                         'exclusive.')

    new_gtis = np.concatenate([gti0, gti1])
    order = np.argsort(new_gtis[:, 0])
    return join_equal_gti_boundaries(new_gtis[order]) def check_separate(gti0, gti1):
    """
    Check if two GTIs do not overlap.

    Parameters
    ----------
    gti0: 2-d float array
        List of GTIs of form ``[[gti0_0, gti0_1], [gti1_0, gti1_1], ...]``

    gti1: 2-d float array
        List of GTIs of form ``[[gti0_0, gti0_1], [gti1_0, gti1_1], ...]``

    Returns
    -------
    separate: bool
        ``True`` if GTIs are mutually exclusive, ``False`` if not

    Examples
    --------
    >>> gti0 = [[0, 10]]
    >>> gti1 = [[20, 30]]
    >>> check_separate(gti0, gti1)
    True
    >>> gti0 = [[0, 10]]
    >>> gti1 = [[0, 10]]
    >>> check_separate(gti0, gti1)
    False
    >>> gti0 = [[0, 10]]
    >>> gti1 = [[10, 20]]
    >>> check_separate(gti0, gti1)
    True
    >>> gti0 = [[0, 11]]
    >>> gti1 = [[10, 20]]
    >>> check_separate(gti0, gti1)
    False
    >>> gti0 = [[0, 11]]
    >>> gti1 = [[10, 20]]
    >>> check_separate(gti1, gti0)
    False
    >>> gti0 = [[0, 10], [30, 40]]
    >>> gti1 = [[11, 28]]
    >>> check_separate(gti0, gti1)
    True
    """

    gti0 = np.asarray(gti0)
    gti1 = np.asarray(gti1)
    if len(gti0) == 0 or len(gti1) == 0:
        return True

    # Check if independently GTIs are well behaved
    check_gtis(gti0)
    check_gtis(gti1)
    t0 = min(gti0[0, 0], gti1[0, 0])
    return _check_separate((gti0 - t0).astype(np.double),
                           (gti1 - t0).astype(np.double)) def cross_gtis(gti_list):
    """
    From multiple GTI lists, extract the common intervals *EXACTLY*.

    Parameters
    ----------
    gti_list : array-like
        List of GTI arrays, each one in the usual format ``[[gti0_0, gti0_1], [gti1_0, gti1_1], ...]``

    Returns
    -------
    gti0: 2-d float array
        ``[[gti0_0, gti0_1], [gti1_0, gti1_1], ...]``
        The newly created GTIs

    See Also
    --------
    cross_two_gtis : Extract the common intervals from two GTI lists *EXACTLY*

    Examples
    --------
    >>> gti1 = np.array([[1, 2]])
    >>> gti2 = np.array([[1, 2]])
    >>> newgti = cross_gtis([gti1, gti2])
    >>> np.allclose(newgti, [[1, 2]])
    True
    >>> gti1 = np.array([[1, 4]])
    >>> gti2 = np.array([[1, 2], [2, 4]])
    >>> newgti = cross_gtis([gti1, gti2])
    >>> np.allclose(newgti, [[1, 4]])
    True
    """
    for g in gti_list:
        check_gtis(g)

    ninst = len(gti_list)
    if ninst == 1:
        return gti_list[0]

    gti0 = gti_list[0]

    for gti in gti_list[1:]:
        gti0 = cross_two_gtis(gti0, gti)

    return gti0 def generate_indices_of_boundaries(times, gti, segment_size=None, dt=0):
    """Get index boundaries and times from different parts of the observation.

    It wraps around `generate_indices_of_gti_boundaries`,
    `generate_indices_of_segment_boundaries_binned`, and
    `generate_indices_of_segment_boundaries_unbinned` depending on:

    + ``segment_size`` being ``None`` (give GTI boundaries, segment boundaries otherwise)
    + ``dt`` being 0 or nonzero (unevenly sampled, evenly sampled otherwise)

    Examples
    --------
    >>> times = [0.1, 0.2, 0.5, 0.8, 1.1]
    >>> gtis = [[0, 0.55], [0.6, 2.1]]
    >>> vals0 = generate_indices_of_boundaries(times, gtis, segment_size=None)
    >>> vals1 = generate_indices_of_gti_boundaries(times, gtis)
    >>> check_iterables_close(vals0, vals1)
    True
    >>> vals0 = generate_indices_of_boundaries(times, gtis, segment_size=0.5)
    >>> vals1 = generate_indices_of_segment_boundaries_unbinned(times, gtis, segment_size=0.5)
    >>> check_iterables_close(vals0, vals1)
    True
    >>> times = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]
    >>> gtis = [[0.05, 0.55]]
    >>> vals0 = generate_indices_of_boundaries(times, gtis, segment_size=0.5, dt=0.1)
    >>> vals1 = generate_indices_of_segment_boundaries_binned(times, gtis, 0.5, dt=0.1)
    >>> check_iterables_close(vals0, vals1)
    True
    """
    if segment_size is not None:
        if dt is None or dt == 0:
            segment_iter = generate_indices_of_segment_boundaries_unbinned(
                times, gti, segment_size)
        else:
            segment_iter = generate_indices_of_segment_boundaries_binned(
                times, gti, segment_size, dt=dt)
    else:
        segment_iter = generate_indices_of_gti_boundaries(times, gti, dt=0)
    return segment_iter def load_events_and_gtis(
    fits_file,
    additional_columns=None,
    gtistring=None,
    gti_file=None,
    hduname=None,
    column=None,
):
    """Load event lists and GTIs from one or more files.

    Loads event list from HDU EVENTS of file fits_file, with Good Time
    intervals. Optionally, returns additional columns of data from the same
    HDU of the events.

    Parameters
    ----------
    fits_file : str

    Other parameters
    ----------------
    additional_columns: list of str, optional
        A list of keys corresponding to the additional columns to extract from
        the event HDU (ex.: ['PI', 'X'])
    gtistring : str
        Comma-separated list of accepted GTI extensions (default GTI,STDGTI),
        with or without appended integer number denoting the detector
    gti_file : str, default None
        External GTI file
    hduname : str or int, default 1
        Name of the HDU containing the event list
    column : str, default None
        The column containing the time values. If None, we use the name
        specified in the mission database, and if there is nothing there,
        "TIME"
    return_limits: bool, optional
        Return the TSTART and TSTOP keyword values

    Returns
    -------
    retvals : Object with the following attributes:
        ev_list : array-like
            Event times in Mission Epoch Time
        gti_list: [[gti0_0, gti0_1], [gti1_0, gti1_1], ...]
            GTIs in Mission Epoch Time
        additional_data: dict
            A dictionary, where each key is the one specified in additional_colums.
            The data are an array with the values of the specified column in the
            fits file.
        t_start : float
            Start time in Mission Epoch Time
        t_stop : float
            Stop time in Mission Epoch Time
        pi_list : array-like
            Raw Instrument energy channels
        cal_pi_list : array-like
            Calibrated PI channels (those that can be easily converted to energy
            values, regardless of the instrument setup.)
        energy_list : array-like
            Energy of each photon in keV (only for NuSTAR, NICER, XMM)
        instr : str
            Name of the instrument (e.g. EPIC-pn or FPMA)
        mission : str
            Name of the instrument (e.g. XMM or NuSTAR)
        mjdref : float
            MJD reference time for the mission
        header : str
            Full header of the FITS file, for debugging purposes
        detector_id : array-like, int
            Detector id for each photon (e.g. each of the CCDs composing XMM's or
            Chandra's instruments)
    """
    from astropy.io import fits as pf

    hdulist = pf.open(fits_file)
    probe_header = hdulist[0].header
    # Let's look for TELESCOP here. This is the most common keyword to be
    # found in well-behaved headers. If it is not in header 0, I take this key
    # and the remaining information from header 1.
    if "TELESCOP" not in probe_header:
        probe_header = hdulist[1].header
    mission_key = "MISSION"
    if mission_key not in probe_header:
        mission_key = "TELESCOP"
    mission = probe_header[mission_key].lower()

    db = read_mission_info(mission)
    instkey = get_key_from_mission_info(db, "instkey", "INSTRUME")
    instr = mode = None
    if instkey in probe_header:
        instr = probe_header[instkey].strip()

    modekey = get_key_from_mission_info(db, "dmodekey", None, instr)
    if modekey is not None and modekey in probe_header:
        mode = probe_header[modekey].strip()

    gtistring = get_key_from_mission_info(db, "gti", "GTI,STDGTI", instr, mode)
    if hduname is None:
        hduname = get_key_from_mission_info(db, "events", "EVENTS", instr, mode)

    if hduname not in hdulist:
        warnings.warn(f'HDU {hduname} not found. Trying first extension')
        hduname = 1

    datatable = hdulist[hduname].data
    header = hdulist[hduname].header

    ephem = timeref = timesys = None

    if "PLEPHEM" in header:
        # For the rare cases where this is a number, e.g. 200, I add `str`
        # It's supposed to be a string.
        ephem = str(header["PLEPHEM"]).strip().lstrip('JPL-').lower()
    if "TIMEREF" in header:
        timeref = header["TIMEREF"].strip().lower()
    if "TIMESYS" in header:
        timesys = header["TIMESYS"].strip().lower()

    if column is None:
        column = get_key_from_mission_info(db, "time", "TIME", instr, mode)
    ev_list = np.array(datatable.field(column), dtype=np.longdouble)

    detector_id = None
    ckey = get_key_from_mission_info(db, "ccol", "NONE", instr, mode)
    if ckey != "NONE" and ckey in datatable.columns.names:
        detector_id = datatable.field(ckey)

    det_number = None if detector_id is None else list(set(detector_id))

    timezero = np.longdouble(0.)
    if "TIMEZERO" in header:
        timezero = np.longdouble(header["TIMEZERO"])

    ev_list += timezero

    t_start = ev_list[0]
    t_stop = ev_list[-1]
    if "TSTART" in header:
        t_start = np.longdouble(header["TSTART"])
    if "TSTOP" in header:
        t_stop = np.longdouble(header["TSTOP"])

    mjdref = np.longdouble(high_precision_keyword_read(header, "MJDREF"))

    # Read and handle GTI extension
    accepted_gtistrings = gtistring.split(",")

    if gti_file is None:
        # Select first GTI with accepted name
        try:
            gti_list = get_gti_from_all_extensions(
                hdulist,
                accepted_gtistrings=accepted_gtistrings,
                det_numbers=det_number,
            )
        except Exception:  # pragma: no cover
            warnings.warn(
                "No extensions found with a valid name. "
                "Please check the `accepted_gtistrings` values.",
                AstropyUserWarning,
            )
            gti_list = np.array([[t_start, t_stop]], dtype=np.longdouble)
    else:
        gti_list = load_gtis(gti_file, gtistring)

    pi_col = get_key_from_mission_info(db, "ecol", "PI", instr, mode)
    if additional_columns is None:
        additional_columns = [pi_col]
    if pi_col not in additional_columns:
        additional_columns.append(pi_col)
    # If data were already calibrated, use this!
    if "energy" not in additional_columns:
        additional_columns.append("energy")

    additional_data = _get_additional_data(datatable, additional_columns)
    hdulist.close()
    # Sort event list
    order = np.argsort(ev_list)
    ev_list = ev_list[order]
    if detector_id is not None:
        detector_id = detector_id[order]

    additional_data = order_list_of_arrays(additional_data, order)

    pi = additional_data[pi_col].astype(np.float32)
    cal_pi = pi

    # EventReadOutput() is an empty class. We will assign a number of attributes to
    # it, like the arrival times of photons, the energies, and some information
    # from the header.
    returns = EventReadOutput()

    returns.ev_list = ev_list
    returns.gti_list = gti_list
    returns.pi_list = pi
    returns.cal_pi_list = cal_pi
    if "energy" in additional_data and np.any(additional_data["energy"] > 0.):
        returns.energy_list = additional_data["energy"]
    else:
        try:
            returns.energy_list = rough_calibration(cal_pi, mission)
        except ValueError:
            returns.energy_list = None
    returns.instr = instr.lower()
    returns.mission = mission.lower()
    returns.mjdref = mjdref
    returns.header = header.tostring()
    returns.additional_data = additional_data
    returns.t_start = t_start
    returns.t_stop = t_stop
    returns.detector_id = detector_id
    returns.ephem = ephem
    returns.timeref = timeref
    returns.timesys = timesys

    return returns class Lightcurve(StingrayTimeseries):
    """
    Make a light curve object from an array of time stamps and an
    array of counts.

    Parameters
    ----------
    time: Iterable, `:class:astropy.time.Time`, or `:class:astropy.units.Quantity` object
        A list or array of time stamps for a light curve. Must be a type that
        can be cast to `:class:np.array` or `:class:List` of floats, or that
        has a `value` attribute that does (e.g. a
        `:class:astropy.units.Quantity` or `:class:astropy.time.Time` object).

    counts: iterable, optional, default ``None``
        A list or array of the counts in each bin corresponding to the
        bins defined in `time` (note: use ``input_counts=False`` to
        input the count range, i.e. counts/second, otherwise use
        counts/bin).

    err: iterable, optional, default ``None``
        A list or array of the uncertainties in each bin corresponding to
        the bins defined in ``time`` (note: use ``input_counts=False`` to
        input the count rage, i.e. counts/second, otherwise use
        counts/bin). If ``None``, we assume the data is poisson distributed
        and calculate the error from the average of the lower and upper
        1-sigma confidence intervals for the Poissonian distribution with
        mean equal to ``counts``.

    input_counts: bool, optional, default True
        If True, the code assumes that the input data in ``counts``
        is in units of counts/bin. If False, it assumes the data
        in ``counts`` is in counts/second.

    gti: 2-d float array, default ``None``
        ``[[gti0_0, gti0_1], [gti1_0, gti1_1], ...]``
        Good Time Intervals. They are *not* applied to the data by default.
        They will be used by other methods to have an indication of the
        "safe" time intervals to use during analysis.

    err_dist: str, optional, default ``None``
        Statistical distribution used to calculate the
        uncertainties and other statistical values appropriately.
        Default makes no assumptions and keep errors equal to zero.

    mjdref: float
        MJD reference (useful in most high-energy mission data)

    skip_checks: bool
        If True, the user specifies that data are already sorted and contain no
        infinite or nan points. Use at your own risk

    low_memory: bool
        If True, all the lazily evaluated attribute (e.g., countrate and
        countrate_err if input_counts is True) will _not_ be stored in memory,
        but calculated every time they are requested.

    mission : str
        Mission that recorded the data (e.g. NICER)

    instr : str
        Instrument onboard the mission

    header : str
        The full header of the original FITS file, if relevant

    **other_kw :
        Used internally. Any other keyword arguments will be ignored

    Attributes
    ----------
    time: numpy.ndarray
        The array of midpoints of time bins.

    bin_lo: numpy.ndarray
        The array of lower time stamp of time bins.

    bin_hi: numpy.ndarray
        The array of higher time stamp of time bins.

    counts: numpy.ndarray
        The counts per bin corresponding to the bins in ``time``.

    counts_err: numpy.ndarray
        The uncertainties corresponding to ``counts``

    countrate: numpy.ndarray
        The counts per second in each of the bins defined in ``time``.

    countrate_err: numpy.ndarray
        The uncertainties corresponding to ``countrate``

    meanrate: float
        The mean count rate of the light curve.

    meancounts: float
        The mean counts of the light curve.

    n: int
        The number of data points in the light curve.

    dt: float
        The time resolution of the light curve.

    mjdref: float
        MJD reference date (``tstart`` / 86400 gives the date in MJD at the
        start of the observation)

    tseg: float
        The total duration of the light curve.

    tstart: float
        The start time of the light curve.

    gti: 2-d float array
        ``[[gti0_0, gti0_1], [gti1_0, gti1_1], ...]``
        Good Time Intervals. They indicate the "safe" time intervals
        to be used during the analysis of the light curve.

    err_dist: string
        Statistic of the Lightcurve, it is used to calculate the
        uncertainties and other statistical values appropriately.
        It propagates to Spectrum classes.

    mission : str
        Mission that recorded the data (e.g. NICER)

    instr : str
        Instrument onboard the mission

    detector_id : iterable
        The detector that recoded each photon, if relevant (e.g. XMM, Chandra)

    header : str
        The full header of the original FITS file, if relevant

    """
    main_array_attr = "time"

    def __init__(self, time, counts, err=None, input_counts=True,
                 gti=None, err_dist='poisson', mjdref=0, dt=None,
                 skip_checks=False, low_memory=False, mission=None,
                 instr=None, header=None, **other_kw):

        StingrayTimeseries.__init__(self)

        if other_kw != {}:
            warnings.warn(f"Unrecognized keywords: {list(other_kw.keys())}")

        time, mjdref = interpret_times(time, mjdref=mjdref)

        time = np.asarray(time)
        counts = np.asarray(counts)

        if err is not None:
            err = np.asarray(err)

        if not skip_checks:
            time, counts, err = self.initial_optional_checks(time, counts, err)

        if time.size != counts.size:
            raise StingrayError("time and counts array are not "
                                "of the same length!")

        if time.size <= 1:
            raise StingrayError("A single or no data points can not create "
                                "a lightcurve!")

        if err_dist.lower() not in valid_statistics:
            # err_dist set can be increased with other statistics
            raise StingrayError("Statistic not recognized."
                                "Please select one of these: ",
                                "{}".format(valid_statistics))
        elif not err_dist.lower() == 'poisson':
            simon("Stingray only uses poisson err_dist at the moment. "
                  "All analysis in the light curve will assume Poisson "
                  "errors. "
                  "Sorry for the inconvenience.")

        if err is not None:
            err = np.asarray(err)
            if not skip_checks and not np.all(np.isfinite(err)):
                raise ValueError("There are inf or NaN values in "
                                 "your err array")

        self.mjdref = mjdref
        self._time = time

        if dt is None:
            logging.info("Computing the bin time ``dt``. This can take "
                         "time. If you know the bin time, please specify it"
                         " at light curve creation")
            dt = np.median(np.diff(self._time))

        self.dt = dt
        self.err_dist = err_dist

        self.tstart = self._time[0] - 0.5 * self.dt
        self.tseg = self._time[-1] - self._time[0] + self.dt

        self._gti = None
        if gti is not None:
            self._gti = np.asarray(gti)

        self._mask = None
        self._counts = None
        self._counts_err = None
        self._countrate = None
        self._countrate_err = None
        self._meanrate = None
        self._meancounts = None
        self._bin_lo = None
        self._bin_hi = None
        self._n = None
        self.mission = mission
        self.instr = instr
        self.header = header

        self.input_counts = input_counts
        self.low_memory = low_memory
        if input_counts:
            self._counts = np.asarray(counts)
            self._counts_err = err
        else:
            self._countrate = np.asarray(counts)
            self._countrate_err = err

        if not skip_checks:
            self.check_lightcurve()
        if os.name == 'nt':
            warnings.warn(
                "On Windows, the size of an integer is 32 bits. "
                "To avoid integer overflow, I'm converting the input array to float")
            counts = counts.astype(float)

    @property
    def time(self):
        return self._time

    @time.setter
    def time(self, value):
        value = np.asarray(value)
        if not value.shape == self.time.shape:
            raise ValueError('Can only assign new times of the same shape as '
                             'the original array')
        self._time = value
        self._bin_lo = None
        self._bin_hi = None

    @property
    def gti(self):
        if self._gti is None:
            self._gti = \
                np.asarray([[self.tstart, self.tstart + self.tseg]])
        return self._gti

    @gti.setter
    def gti(self, value):
        value = np.asarray(value)
        self._gti = value
        self._mask = None

    @property
    def mask(self):
        if self._mask is None:
            self._mask = create_gti_mask(self.time, self.gti, dt=self.dt)
        return self._mask

    @property
    def n(self):
        if self._n is None:
            self._n = self.counts.shape[0]
        return self._n

    @property
    def meanrate(self):
        if self._meanrate is None:
            self._meanrate = np.mean(self.countrate[self.mask])
        return self._meanrate

    @property
    def meancounts(self):
        if self._meancounts is None:
            self._meancounts = np.mean(self.counts[self.mask])
        return self._meancounts

    @property
    def counts(self):
        counts = self._counts
        if self._counts is None:
            counts = self._countrate * self.dt
            # If not in low-memory regime, cache the values
            if not self.low_memory or self.input_counts:
                self._counts = counts

        return counts

    @counts.setter
    def counts(self, value):
        value = np.asarray(value)
        if not value.shape == self.counts.shape:
            raise ValueError('Can only assign new counts array of the same '
                             'shape as the original array')
        self._counts = value
        self._countrate = None
        self._meancounts = None
        self._meancountrate = None
        self.input_counts = True

    @property
    def counts_err(self):
        counts_err = self._counts_err
        if counts_err is None and self._countrate_err is not None:
            counts_err = self._countrate_err * self.dt
        elif counts_err is None:
            if self.err_dist.lower() == 'poisson':
                counts_err = poisson_symmetrical_errors(self.counts)
            else:
                counts_err = np.zeros_like(self.counts)

        # If not in low-memory regime, cache the values ONLY if they have
        # been changed!
        if self._counts_err is not counts_err:
            if not self.low_memory or self.input_counts:
                self._counts_err = counts_err

        return counts_err

    @counts_err.setter
    def counts_err(self, value):
        value = np.asarray(value)
        if not value.shape == self.counts.shape:
            raise ValueError('Can only assign new error array of the same '
                             'shape as the original array')
        self._counts_err = value
        self._countrate_err = None

    @property
    def countrate(self):
        countrate = self._countrate
        if countrate is None:
            countrate = self._counts / self.dt
            # If not in low-memory regime, cache the values
            if not self.low_memory or not self.input_counts:
                self._countrate = countrate

        return countrate

    @countrate.setter
    def countrate(self, value):
        value = np.asarray(value)
        if not value.shape == self.countrate.shape:
            raise ValueError('Can only assign new countrate array of the same '
                             'shape as the original array')
        self._countrate = value
        self._counts = None
        self._meancounts = None
        self._meancountrate = None
        self.input_counts = False

    @property
    def countrate_err(self):
        countrate_err = self._countrate_err
        if countrate_err is None and self._counts_err is not None:
            countrate_err = self._counts_err / self.dt
        elif countrate_err is None:
            countrate_err = 0

        # If not in low-memory regime, cache the values ONLY if they have
        # been changed!
        if countrate_err is not self._countrate_err:
            if not self.low_memory or not self.input_counts:
                self._countrate_err = countrate_err

        return countrate_err

    @countrate_err.setter
    def countrate_err(self, value):
        value = np.asarray(value)
        if not value.shape == self.countrate.shape:
            raise ValueError('Can only assign new error array of the same '
                             'shape as the original array')
        self._countrate_err = value
        self._counts_err = None

    @property
    def bin_lo(self):
        if self._bin_lo is None:
            self._bin_lo = self.time - 0.5 * self.dt
        return self._bin_lo

    @property
    def bin_hi(self):
        if self._bin_hi is None:
            self._bin_hi = self.time + 0.5 * self.dt
        return self._bin_hi

    def initial_optional_checks(self, time, counts, err):
        logging.info("Checking if light curve is well behaved. This "
                     "can take time, so if you are sure it is already "
                     "sorted, specify skip_checks=True at light curve "
                     "creation.")

        if not np.all(np.isfinite(time)):
            raise ValueError("There are inf or NaN values in "
                             "your time array!")

        if not np.all(np.isfinite(counts)):
            raise ValueError("There are inf or NaN values in "
                             "your counts array!")

        logging.info("Checking if light curve is sorted.")
        dt_array = np.diff(time)
        unsorted = np.any(dt_array < 0)

        if unsorted:
            logging.warning("The light curve is unsorted. Now, sorting...")
            order = np.argsort(time)
            time = time[order]
            counts = counts[order]
            if err is not None:
                err = err[order]
        return time, counts, err

    def check_lightcurve(self):
        """Make various checks on the lightcurve.

        It can be slow, use it if you are not sure about your
        input data.
        """
        # Issue a warning if the input time iterable isn't regularly spaced,
        # i.e. the bin sizes aren't equal throughout.

        check_gtis(self.gti)

        idxs = np.searchsorted(self.time, self.gti)
        uneven = False
        for idx in range(idxs.shape[0]):
            istart, istop = idxs[idx, 0], min(idxs[idx, 1], self.time.size - 1)

            local_diff = np.diff(self.time[istart:istop])
            if np.any(~np.isclose(local_diff, self.dt)):
                uneven = True

                break
        if uneven:
            simon("Bin sizes in input time array aren't equal throughout! "
                  "This could cause problems with Fourier transforms. "
                  "Please make the input time evenly sampled.")

    def _operation_with_other_lc(self, other, operation):
        """
        Helper method to codify an operation of one light curve with another (e.g. add, subtract, ...).
        Takes into account the GTIs correctly, and returns a new :class:`Lightcurve` object.

        Parameters
        ----------
        other : :class:`Lightcurve` object
            A second light curve object

        operation : function
            An operation between the :class:`Lightcurve` object calling this method, and ``other``,
            operating on the ``counts`` attribute in each :class:`Lightcurve` object

        Returns
        -------
        lc_new : Lightcurve object
            The new light curve calculated in ``operation``
        """
        if self.mjdref != other.mjdref:
            warnings.warn("MJDref is different in the two light curves")
            other = other.change_mjdref(self.mjdref)

        common_gti = cross_two_gtis(self.gti, other.gti)
        mask_self = create_gti_mask(self.time, common_gti, dt=self.dt)
        mask_other = create_gti_mask(other.time, common_gti, dt=other.dt)

        # ValueError is raised by Numpy while asserting np.equal over arrays
        # with different dimensions.
        try:
            diff = np.abs((self.time[mask_self] - other.time[mask_other]))
            assert np.all(diff < self.dt / 100)
        except (ValueError, AssertionError):
            raise ValueError("GTI-filtered time arrays of both light curves "
                             "must be of same dimension and equal.")

        new_time = self.time[mask_self]
        new_counts = operation(self.counts[mask_self],
                               other.counts[mask_other])

        if self.err_dist.lower() != other.err_dist.lower():
            simon("Lightcurves have different statistics!"
                  "We are setting the errors to zero to avoid complications.")
            new_counts_err = np.zeros_like(new_counts)
        elif self.err_dist.lower() in valid_statistics:
            new_counts_err = \
                np.sqrt(np.add(self.counts_err[mask_self]**2,
                               other.counts_err[mask_other]**2))
        # More conditions can be implemented for other statistics
        else:
            raise StingrayError("Statistics not recognized."
                                " Please use one of these: "
                                "{}".format(valid_statistics))

        lc_new = Lightcurve(new_time, new_counts,
                            err=new_counts_err, gti=common_gti,
                            mjdref=self.mjdref, skip_checks=True,
                            dt=self.dt)

        return lc_new

    def __add__(self, other):
        """
        Add the counts of two light curves element by element, assuming the light curves
        have the same time array.

        This magic method adds two :class:`Lightcurve` objects having the same time
        array such that the corresponding counts arrays get summed up.

        GTIs are crossed, so that only common intervals are saved.

        Examples
        --------
        >>> time = [5, 10, 15]
        >>> count1 = [300, 100, 400]
        >>> count2 = [600, 1200, 800]
        >>> gti1 = [[0, 20]]
        >>> gti2 = [[0, 25]]
        >>> lc1 = Lightcurve(time, count1, gti=gti1, dt=5)
        >>> lc2 = Lightcurve(time, count2, gti=gti2, dt=5)
        >>> lc = lc1 + lc2
        >>> np.allclose(lc.counts, [ 900, 1300, 1200])
        True
        """

        return self._operation_with_other_lc(other, np.add)

    def __sub__(self, other):
        """
        Subtract the counts/flux of one light curve from the counts/flux of another
        light curve element by element, assuming the ``time`` arrays of the light curves
        match exactly.

        This magic method takes two :class:`Lightcurve` objects having the same
        ``time`` array and subtracts the ``counts`` of one :class:`Lightcurve` with
        that of another, while also updating ``countrate``, ``counts_err`` and ``countrate_err``
        correctly.

        GTIs are crossed, so that only common intervals are saved.

        Examples
        --------
        >>> time = [10, 20, 30]
        >>> count1 = [600, 1200, 800]
        >>> count2 = [300, 100, 400]
        >>> gti1 = [[0, 35]]
        >>> gti2 = [[5, 40]]
        >>> lc1 = Lightcurve(time, count1, gti=gti1, dt=10)
        >>> lc2 = Lightcurve(time, count2, gti=gti2, dt=10)
        >>> lc = lc1 - lc2
        >>> np.allclose(lc.counts, [ 300, 1100,  400])
        True
        """

        return self._operation_with_other_lc(other, np.subtract)

    def __neg__(self):
        """
        Implement the behavior of negation of the light curve objects.

        The negation operator ``-`` is supposed to invert the sign of the count
        values of a light curve object.

        Examples
        --------
        >>> time = [1, 2, 3]
        >>> count1 = [100, 200, 300]
        >>> count2 = [200, 300, 400]
        >>> lc1 = Lightcurve(time, count1)
        >>> lc2 = Lightcurve(time, count2)
        >>> lc_new = -lc1 + lc2
        >>> np.allclose(lc_new.counts, [100, 100, 100])
        True
        """
        lc_new = Lightcurve(self.time, -1 * self.counts,
                            err=self.counts_err, gti=self.gti,
                            mjdref=self.mjdref, skip_checks=True,
                            dt=self.dt)

        return lc_new

    def __len__(self):
        """
        Return the number of time bins of a light curve.

        This method implements overrides the ``len`` function for a :class:`Lightcurve`
        object and returns the length of the ``time`` array (which should be equal to the
        length of the ``counts`` and ``countrate`` arrays).

        Examples
        --------
        >>> time = [1, 2, 3]
        >>> count = [100, 200, 300]
        >>> lc = Lightcurve(time, count, dt=1)
        >>> len(lc)
        3
        """
        return self.n

    def __getitem__(self, index):
        """
        Return the corresponding count value at the index or a new :class:`Lightcurve`
        object upon slicing.

        This method adds functionality to retrieve the count value at
        a particular index. This also can be used for slicing and generating
        a new :class:`Lightcurve` object. GTIs are recalculated based on the new light
        curve segment

        If the slice object is of kind ``start:stop:step``, GTIs are also sliced,
        and rewritten as ``zip(time - self.dt /2, time + self.dt / 2)``

        Parameters
        ----------
        index : int or slice instance
            Index value of the time array or a slice object.

        Examples
        --------
        >>> time = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        >>> count = [11, 22, 33, 44, 55, 66, 77, 88, 99]
        >>> lc = Lightcurve(time, count, dt=1)
        >>> np.isclose(lc[2], 33)
        True
        >>> np.allclose(lc[:2].counts, [11, 22])
        True
        """
        if isinstance(index, (int, np.integer)):
            return self.counts[index]
        elif isinstance(index, slice):
            start = assign_value_if_none(index.start, 0)
            stop = assign_value_if_none(index.stop, len(self.counts))
            step = assign_value_if_none(index.step, 1)

            new_counts = self.counts[start:stop:step]
            new_time = self.time[start:stop:step]

            new_gti = [[self.time[start] - 0.5 * self.dt,
                        self.time[stop - 1] + 0.5 * self.dt]]
            new_gti = np.asarray(new_gti)
            if step > 1:
                new_gt1 = np.array(list(zip(new_time - self.dt / 2,
                                            new_time + self.dt / 2)))
                new_gti = cross_two_gtis(new_gti, new_gt1)
            new_gti = cross_two_gtis(self.gti, new_gti)

            lc = Lightcurve(new_time, new_counts, mjdref=self.mjdref,
                            gti=new_gti, dt=self.dt, skip_checks=True,
                            err_dist=self.err_dist)
            if self._counts_err is not None:
                lc._counts_err = self._counts_err[start:stop:step]
            return lc
        else:
            raise IndexError("The index must be either an integer or a slice "
                             "object !")

    def __eq__(self, other_lc):
        """
        Compares two :class:`Lightcurve` objects.

        Light curves are equal only if their counts as well as times at which those counts occur equal.

        Examples
        --------
        >>> time = [1, 2, 3]
        >>> count1 = [100, 200, 300]
        >>> count2 = [100, 200, 300]
        >>> lc1 = Lightcurve(time, count1, dt=1)
        >>> lc2 = Lightcurve(time, count2, dt=1)
        >>> lc1 == lc2
        True
        """
        if not isinstance(other_lc, Lightcurve):
            raise ValueError('Lightcurve can only be compared with a Lightcurve Object')
        if (np.allclose(self.time, other_lc.time) and
                np.allclose(self.counts, other_lc.counts)):
            return True
        return False

    def baseline(self, lam, p, niter=10, offset_correction=False):
        """Calculate the baseline of the light curve, accounting for GTIs.

        Parameters
        ----------
        lam : float
            "smoothness" parameter. Larger values make the baseline stiffer
            Typically ``1e2 < lam < 1e9``
        p : float
            "asymmetry" parameter. Smaller values make the baseline more
            "horizontal". Typically ``0.001 < p < 0.1``, but not necessary.

        Other parameters
        ----------------
        offset_correction : bool, default False
            by default, this method does not align to the running mean of the
            light curve, but it goes below the light curve. Setting align to
            True, an additional step is done to shift the baseline so that it
            is shifted to the middle of the light curve noise distribution.


        Returns
        -------
        baseline : numpy.ndarray
            An array with the baseline of the light curve
        """
        baseline = np.zeros_like(self.time)
        for g in self.gti:
            good = create_gti_mask(self.time, [g], dt=self.dt)
            _, baseline[good] = \
                baseline_als(self.time[good], self.counts[good], lam, p,
                             niter, offset_correction=offset_correction,
                             return_baseline=True)

        return baseline

    @staticmethod
    def make_lightcurve(toa, dt, tseg=None, tstart=None, gti=None, mjdref=0,
                        use_hist=False):
        """
        Make a light curve out of photon arrival times, with a given time resolution ``dt``.
        Note that ``dt`` should be larger than the native time resolution of the instrument
        that has taken the data.

        Parameters
        ----------
        toa: iterable
            list of photon arrival times

        dt: float
            time resolution of the light curve (the bin width)

        tseg: float, optional, default ``None``
            The total duration of the light curve.
            If this is ``None``, then the total duration of the light curve will
            be the interval between the arrival between the first and the last
            photon in ``toa``.

                **Note**: If ``tseg`` is not divisible by ``dt`` (i.e. if ``tseg``/``dt`` is
                not an integer number), then the last fractional bin will be
                dropped!

        tstart: float, optional, default ``None``
            The start time of the light curve.
            If this is ``None``, the arrival time of the first photon will be used
            as the start time of the light curve.

        gti: 2-d float array
            ``[[gti0_0, gti0_1], [gti1_0, gti1_1], ...]``
            Good Time Intervals

        use_hist : bool
            Use ``np.histogram`` instead of ``np.bincounts``. Might be advantageous
            for very short datasets.

        Returns
        -------
        lc: :class:`Lightcurve` object
            A :class:`Lightcurve` object with the binned light curve
        """
        toa, mjdref = interpret_times(toa, mjdref=mjdref)

        toa = np.sort(np.asarray(toa))
        # tstart is an optional parameter to set a starting time for
        # the light curve in case this does not coincide with the first photon
        if tstart is None:
            # if tstart is not set, assume light curve starts with first photon
            tstart = toa[0]

        # compute the number of bins in the light curve
        # for cases where tseg/dt is not integer.
        # TODO: check that this is always consistent and that we
        # are not throwing away good events.

        if tseg is None:
            tseg = toa[-1] - tstart

        logging.info("make_lightcurve: tseg: " + str(tseg))

        timebin = int(tseg / dt)
        # If we are missing the next bin by just 1%, let's round up:
        if tseg / dt - timebin >= 0.99:
            timebin += 1

        logging.info("make_lightcurve: timebin:  " + str(timebin))

        tend = tstart + timebin * dt
        good = (tstart <= toa) & (toa < tend)
        if not use_hist:
            binned_toas = ((toa[good] - tstart) // dt).astype(np.int64)
            counts = \
                np.bincount(binned_toas, minlength=timebin)
            time = tstart + np.arange(0.5, 0.5 + len(counts)) * dt
        else:
            histbins = np.arange(tstart, tend + dt, dt)
            counts, histbins = np.histogram(toa[good], bins=histbins)
            time = histbins[:-1] + 0.5 * dt

        return Lightcurve(time, counts, gti=gti, mjdref=mjdref, dt=dt,
                          skip_checks=True, err_dist='poisson')

    def rebin(self, dt_new=None, f=None, method='sum'):
        """
        Rebin the light curve to a new time resolution. While the new
        resolution need not be an integer multiple of the previous time
        resolution, be aware that if it is not, the last bin will be cut
        off by the fraction left over by the integer division.

        Parameters
        ----------
        dt_new: float
            The new time resolution of the light curve. Must be larger than
            the time resolution of the old light curve!

        method: {``sum`` | ``mean`` | ``average``}, optional, default ``sum``
            This keyword argument sets whether the counts in the new bins
            should be summed or averaged.

        Other Parameters
        ----------------
        f: float
            the rebin factor. If specified, it substitutes ``dt_new`` with
            ``f*self.dt``

        Returns
        -------
        lc_new: :class:`Lightcurve` object
            The :class:`Lightcurve` object with the new, binned light curve.
        """

        if f is None and dt_new is None:
            raise ValueError('You need to specify at least one between f and '
                             'dt_new')
        elif f is not None:
            dt_new = f * self.dt

        if dt_new < self.dt:
            raise ValueError("New time resolution must be larger than "
                             "old time resolution!")

        bin_time, bin_counts, bin_err = [], [], []
        gti_new = []
        for g in self.gti:
            if g[1] - g[0] < dt_new:
                continue
            else:
                # find start and end of GTI segment in data
                start_ind = self.time.searchsorted(g[0])
                end_ind = self.time.searchsorted(g[1])

                t_temp = self.time[start_ind:end_ind]
                c_temp = self.counts[start_ind:end_ind]
                e_temp = self.counts_err[start_ind:end_ind]

                bin_t, bin_c, bin_e, _ = \
                    utils.rebin_data(t_temp, c_temp, dt_new,
                                     yerr=e_temp, method=method)

                bin_time.extend(bin_t)
                bin_counts.extend(bin_c)
                bin_err.extend(bin_e)
                gti_new.append(g)

        if len(gti_new) == 0:
            raise ValueError("No valid GTIs after rebin.")

        lc_new = Lightcurve(bin_time, bin_counts, err=bin_err,
                            mjdref=self.mjdref, dt=dt_new, gti=gti_new,
                            skip_checks=True)
        return lc_new

    def join(self, other, skip_checks=False):
        """
        Join two lightcurves into a single object.

        The new :class:`Lightcurve` object will contain time stamps from both the
        objects. The ``counts`` and ``countrate`` attributes in the resulting object
        will contain the union of the non-overlapping parts of the two individual objects,
        or the average in case of overlapping ``time`` arrays of both :class:`Lightcurve` objects.

        Good Time Intervals are also joined.

        Note : Ideally, the ``time`` array of both lightcurves should not overlap.

        Parameters
        ----------
        other : :class:`Lightcurve` object
            The other :class:`Lightcurve` object which is supposed to be joined with.
        skip_checks: bool
            If True, the user specifies that data are already sorted and
            contain no infinite or nan points. Use at your own risk.

        Returns
        -------
        lc_new : :class:`Lightcurve` object
            The resulting :class:`Lightcurve` object.

        Examples
        --------
        >>> time1 = [5, 10, 15]
        >>> count1 = [300, 100, 400]
        >>> time2 = [20, 25, 30]
        >>> count2 = [600, 1200, 800]
        >>> lc1 = Lightcurve(time1, count1, dt=5)
        >>> lc2 = Lightcurve(time2, count2, dt=5)
        >>> lc = lc1.join(lc2)
        >>> lc.time
        array([ 5, 10, 15, 20, 25, 30])
        >>> np.allclose(lc.counts, [ 300,  100,  400,  600, 1200,  800])
        True
        """
        if self.mjdref != other.mjdref:
            warnings.warn("MJDref is different in the two light curves")
            other = other.change_mjdref(self.mjdref)

        if self.dt != other.dt:
            utils.simon("The two light curves have different bin widths.")

        if(self.tstart < other.tstart):
            first_lc = self
            second_lc = other
        else:
            first_lc = other
            second_lc = self

        if len(np.intersect1d(self.time, other.time) > 0):

            utils.simon("The two light curves have overlapping time ranges. "
                        "In the common time range, the resulting count will "
                        "be the average of the counts in the two light "
                        "curves. If you wish to sum, use `lc_sum = lc1 + "
                        "lc2`.")
            valid_err = False

            if self.err_dist.lower() != other.err_dist.lower():
                simon("Lightcurves have different statistics!"
                      "We are setting the errors to zero.")

            elif self.err_dist.lower() in valid_statistics:
                valid_err = True
            # More conditions can be implemented for other statistics
            else:
                raise StingrayError("Statistics not recognized."
                                    " Please use one of these: "
                                    "{}".format(valid_statistics))

            from collections import Counter
            counts = Counter()
            counts_err = Counter()

            for i, time in enumerate(first_lc.time):
                counts[time] = first_lc.counts[i]
                counts_err[time] = first_lc.counts_err[i]

            for i, time in enumerate(second_lc.time):

                if counts.get(time) is not None:  # Common time
                    counts[time] = (counts[time] + second_lc.counts[i]) / 2
                    counts_err[time] = \
                        np.sqrt(((counts_err[time] ** 2) +
                                 (second_lc.counts_err[i] ** 2)) / 2)

                else:
                    counts[time] = second_lc.counts[i]
                    counts_err[time] = second_lc.counts_err[i]

            new_time = list(counts.keys())
            new_counts = list(counts.values())
            if(valid_err):
                new_counts_err = list(counts_err.values())
            else:
                new_counts_err = np.zeros_like(new_counts)

            del[counts, counts_err]

        else:

            new_time = np.concatenate([first_lc.time, second_lc.time])
            new_counts = np.concatenate([first_lc.counts, second_lc.counts])
            new_counts_err = \
                np.concatenate([first_lc.counts_err, second_lc.counts_err])

        new_time = np.asarray(new_time)
        new_counts = np.asarray(new_counts)
        new_counts_err = np.asarray(new_counts_err)
        gti = join_gtis(self.gti, other.gti)

        lc_new = Lightcurve(new_time, new_counts, err=new_counts_err, gti=gti,
                            mjdref=self.mjdref, dt=self.dt, skip_checks=skip_checks)

        return lc_new

    def truncate(self, start=0, stop=None, method="index"):
        """
        Truncate a :class:`Lightcurve` object.

        This method takes a ``start`` and a ``stop`` point (either as indices,
        or as times in the same unit as those in the ``time`` attribute, and truncates
        all bins before ``start`` and after ``stop``, then returns a new :class:`Lightcurve`
        object with the truncated light curve.

        Parameters
        ----------
        start : int, default 0
            Index (or time stamp) of the starting point of the truncation. If no value is set
            for the start point, then all points from the first element in the ``time`` array
            are taken into account.

        stop : int, default ``None``
            Index (or time stamp) of the ending point (exclusive) of the truncation. If no
            value of stop is set, then points including the last point in
            the counts array are taken in count.

        method : {``index`` | ``time``}, optional, default ``index``
            Type of the start and stop values. If set to ``index`` then
            the values are treated as indices of the counts array, or
            if set to ``time``, the values are treated as actual time values.

        Returns
        -------
        lc_new: :class:`Lightcurve` object
            The :class:`Lightcurve` object with truncated time and counts
            arrays.

        Examples
        --------
        >>> time = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        >>> count = [10, 20, 30, 40, 50, 60, 70, 80, 90]
        >>> lc = Lightcurve(time, count, dt=1)
        >>> lc_new = lc.truncate(start=2, stop=8)
        >>> np.allclose(lc_new.counts, [30, 40, 50, 60, 70, 80])
        True
        >>> lc_new.time
        array([3, 4, 5, 6, 7, 8])
        >>> # Truncation can also be done by time values
        >>> lc_new = lc.truncate(start=6, method='time')
        >>> lc_new.time
        array([6, 7, 8, 9])
        >>> np.allclose(lc_new.counts, [60, 70, 80, 90])
        True
        """

        if not isinstance(method, str):
            raise TypeError("method key word argument is not "
                            "a string !")

        if method.lower() not in ['index', 'time']:
            raise ValueError("Unknown method type " + method + ".")

        if method.lower() == 'index':
            return self._truncate_by_index(start, stop)
        else:
            return self._truncate_by_time(start, stop)

    def _truncate_by_index(self, start, stop):
        """Private method for truncation using index values."""
        time_new = self.time[start:stop]
        counts_new = self.counts[start:stop]
        counts_err_new = self.counts_err[start:stop]
        gti = \
            cross_two_gtis(self.gti,
                           np.asarray([[self.time[start] - 0.5 * self.dt,
                                        time_new[-1] + 0.5 * self.dt]]))

        return Lightcurve(time_new, counts_new, err=counts_err_new, gti=gti,
                          dt=self.dt, skip_checks=True)

    def _truncate_by_time(self, start, stop):
        """Helper method for truncation using time values.

        Parameters
        ----------
        start : float
            start time for new light curve; all time bins before this time will be discarded

        stop : float
            stop time for new light curve; all time bins after this point will be discarded

        Returns
        -------
            new_lc : Lightcurve
                A new :class:`Lightcurve` object with the truncated time bins

        """

        if stop is not None:
            if start > stop:
                raise ValueError("start time must be less than stop time!")

        if not start == 0:
            start = self.time.searchsorted(start)

        if stop is not None:
            stop = self.time.searchsorted(stop)

        return self._truncate_by_index(start, stop)

    def split(self, min_gap, min_points=1):
        """
        For data with gaps, it can sometimes be useful to be able to split
        the light curve into separate, evenly sampled objects along those
        data gaps. This method allows to do this: it finds data gaps of a
        specified minimum size, and produces a list of new `Lightcurve`
        objects for each contiguous segment.

        Parameters
        ----------
        min_gap : float
            The length of a data gap, in the same units as the `time` attribute
            of the `Lightcurve` object. Any smaller gaps will be ignored, any
            larger gaps will be identified and used to split the light curve.

        min_points : int, default 1
            The minimum number of data points in each light curve. Light
            curves with fewer data points will be ignored.

        Returns
        -------
        lc_split : iterable of `Lightcurve` objects
            The list of all contiguous light curves

        Examples
        --------
        >>> time = np.array([1, 2, 3, 6, 7, 8, 11, 12, 13])
        >>> counts = np.random.rand(time.shape[0])
        >>> lc = Lightcurve(time, counts, dt=1, skip_checks=True)
        >>> split_lc = lc.split(1.5)

        """

        # calculate the difference between time bins
        tdiff = np.diff(self.time)
        # find all distances between time bins that are larger than `min_gap`
        gap_idx = np.where(tdiff >= min_gap)[0]

        # tolerance for the newly created GTIs: Note that this seems to work
        # with a tolerance of 2, but not if I substitute 10. I don't know why
        epsilon = np.min(tdiff) / 2.0

        # calculate new GTIs
        gti_start = np.hstack([self.time[0] - epsilon, self.time[gap_idx + 1] - epsilon])
        gti_stop = np.hstack([self.time[gap_idx] + epsilon, self.time[-1] + epsilon])

        gti = np.vstack([gti_start, gti_stop]).T
        if hasattr(self, 'gti') and self.gti is not None:
            gti = cross_two_gtis(self.gti, gti)

        lc_split = self.split_by_gti(gti, min_points=min_points)
        return lc_split

    def sort(self, reverse=False):
        """
        Sort a Lightcurve object by time.

        A Lightcurve can be sorted in either increasing or decreasing order
        using this method. The time array gets sorted and the counts array is
        changed accordingly.

        Parameters
        ----------
        reverse : boolean, default False
            If True then the object is sorted in reverse order.

        Examples
        --------
        >>> time = [2, 1, 3]
        >>> count = [200, 100, 300]
        >>> lc = Lightcurve(time, count, dt=1)
        >>> lc_new = lc.sort()
        >>> lc_new.time
        array([1, 2, 3])
        >>> np.allclose(lc_new.counts, [100, 200, 300])
        True

        Returns
        -------
        lc_new: :class:`Lightcurve` object
            The :class:`Lightcurve` object with sorted time and counts
            arrays.
        """
        new_time, new_counts, new_counts_err = \
            zip(*sorted(zip(self.time, self.counts, self.counts_err),
                        reverse=reverse))
        new_time = np.asarray(new_time)
        new_counts = np.asarray(new_counts)
        new_counts_err = np.asarray(new_counts_err)

        new_lc = Lightcurve(new_time, new_counts, err=new_counts_err,
                            gti=self.gti, dt=self.dt, mjdref=self.mjdref,
                            skip_checks=True)

        return new_lc

    def sort_counts(self, reverse=False):
        """
        Sort a :class:`Lightcurve` object in accordance with its counts array.

        A :class:`Lightcurve` can be sorted in either increasing or decreasing order
        using this method. The counts array gets sorted and the time array is
        changed accordingly.

        Parameters
        ----------
        reverse : boolean, default ``False``
            If ``True`` then the object is sorted in reverse order.

        Returns
        -------
        lc_new: :class:`Lightcurve` object
            The :class:`Lightcurve` object with sorted ``time`` and ``counts``
            arrays.

        Examples
        --------
        >>> time = [1, 2, 3]
        >>> count = [200, 100, 300]
        >>> lc = Lightcurve(time, count, dt=1)
        >>> lc_new = lc.sort_counts()
        >>> lc_new.time
        array([2, 1, 3])
        >>> np.allclose(lc_new.counts, [100, 200, 300])
        True
        """

        new_counts, new_time, new_counts_err = \
            zip(*sorted(zip(self.counts, self.time, self.counts_err),
                        reverse=reverse))

        new_lc = Lightcurve(new_time, new_counts, err=new_counts_err,
                            gti=self.gti, dt=self.dt, mjdref=self.mjdref,
                            skip_checks=True)

        return new_lc

    def estimate_chunk_length(self, *args, **kwargs):
        """Deprecated alias of estimate_segment_size.
        """
        warnings.warn("This function was renamed to estimate_segment_size", DeprecationWarning)
        return self.estimate_segment_size(*args, **kwargs)

    def estimate_segment_size(self, min_total_counts=100, min_time_bins=100):
        """Estimate a reasonable segment length for chunk-by-chunk analysis.

        Choose a reasonable length for time segments, given a minimum number of total
        counts in the segment, and a minimum number of time bins in the segment.

        The user specifies a condition on the total counts in each segment and
        the minimum number of time bins.

        Other Parameters
        ----------------
        min_total_counts : int
            Minimum number of counts for each chunk
        min_time_bins : int
            Minimum number of time bins

        Returns
        -------
        segment_size : float
            The length of the light curve chunks that satisfies the conditions

        Examples
        --------
        >>> import numpy as np
        >>> time = np.arange(150)
        >>> count = np.zeros_like(time) + 3
        >>> lc = Lightcurve(time, count, dt=1)
        >>> lc.estimate_segment_size(min_total_counts=10, min_time_bins=3)
        4.0
        >>> lc.estimate_segment_size(min_total_counts=10, min_time_bins=5)
        5.0
        >>> count[2:4] = 1
        >>> lc = Lightcurve(time, count, dt=1)
        >>> lc.estimate_segment_size(min_total_counts=3, min_time_bins=1)
        3.0
        >>> # A slightly more complex example
        >>> dt=0.2
        >>> time = np.arange(0, 1000, dt)
        >>> counts = np.random.poisson(100, size=len(time))
        >>> lc = Lightcurve(time, counts, dt=dt)
        >>> lc.estimate_segment_size(100, 2)
        0.4
        >>> min_total_bins = 40
        >>> lc.estimate_segment_size(100, 40)
        8.0
        """

        rough_estimate = np.ceil(min_total_counts / self.meancounts) * self.dt

        segment_size = np.max([rough_estimate, min_time_bins * self.dt])

        keep_searching = True
        while keep_searching:
            start_times, stop_times, results = \
                self.analyze_lc_chunks(segment_size, np.sum)
            mincounts = np.min(results)
            if mincounts >= min_total_counts:
                keep_searching = False
            else:
                segment_size += self.dt

        return segment_size

    def analyze_lc_chunks(self, segment_size, func, fraction_step=1, **kwargs):
        """Analyze segments of the light curve with any function.

        Parameters
        ----------
        segment_size : float
            Length in seconds of the light curve segments
        func : function
            Function accepting a :class:`Lightcurve` object as single argument, plus
            possible additional keyword arguments, and returning a number or a
            tuple - e.g., ``(result, error)`` where both ``result`` and ``error`` are
            numbers.

        Other parameters
        ----------------
        fraction_step : float
            If the step is not a full ``segment_size`` but less (e.g. a moving window),
            this indicates the ratio between step step and ``segment_size`` (e.g.
            0.5 means that the window shifts of half ``segment_size``)
        kwargs : keyword arguments
            These additional keyword arguments, if present, they will be passed
            to ``func``

        Returns
        -------
        start_times : array
            Lower time boundaries of all time segments.
        stop_times : array
            upper time boundaries of all segments.
        result : array of N elements
            The result of ``func`` for each segment of the light curve

        Examples
        --------
        >>> import numpy as np
        >>> time = np.arange(0, 10, 0.1)
        >>> counts = np.zeros_like(time) + 10
        >>> lc = Lightcurve(time, counts, dt=0.1)
        >>> # Define a function that calculates the mean
        >>> mean_func = lambda x: np.mean(x)
        >>> # Calculate the mean in segments of 5 seconds
        >>> start, stop, res = lc.analyze_lc_chunks(5, mean_func)
        >>> len(res) == 2
        True
        >>> np.allclose(res, 10)
        True
        """
        start, stop = bin_intervals_from_gtis(self.gti, segment_size,
                                              self.time,
                                              fraction_step=fraction_step,
                                              dt=self.dt)
        start_times = self.time[start] - 0.5 * self.dt

        # Remember that stop is one element above the last element, because
        # it's defined to be used in intervals start:stop
        stop_times = self.time[stop - 1] + self.dt * 1.5

        results = []
        for i, (st, sp) in enumerate(zip(start, stop)):
            lc_filt = self[st:sp]
            res = func(lc_filt, **kwargs)
            results.append(res)

        results = np.array(results)

        if len(results.shape) == 2:
            results = [results[:, i] for i in range(results.shape[1])]
        return start_times, stop_times, results

    def to_lightkurve(self):
        """
        Returns a `lightkurve.LightCurve` object.
        This feature requires `Lightkurve
        <https://docs.lightkurve.org/index.html/>`_ to be installed
        (e.g. ``pip install lightkurve``).  An `ImportError` will
        be raised if this package is not available.

        Returns
        -------
        lightcurve : `lightkurve.LightCurve`
            A lightkurve LightCurve object.
        """
        try:
            from lightkurve import LightCurve as lk
        except ImportError:
            raise ImportError("You need to install Lightkurve to use "
                              "the Lightcurve.to_lightkurve() method.")
        time = Time(self.time / 86400 + self.mjdref, format="mjd", scale="utc")
        return lk(time=time, flux=self.counts, flux_err=self.counts_err)

    @staticmethod
    def from_lightkurve(lk, skip_checks=True):
        """
        Creates a new `Lightcurve` from a `lightkurve.LightCurve`.

        Parameters
        ----------
        lk : `lightkurve.LightCurve`
            A lightkurve LightCurve object
        skip_checks: bool
            If True, the user specifies that data are already sorted and contain no
            infinite or nan points. Use at your own risk.
        """

        return Lightcurve(time=lk.time, counts=lk.flux,
                          err=lk.flux_err, input_counts=False,
                          skip_checks=skip_checks)

    def to_astropy_timeseries(self):
        return self._to_astropy_object(kind="timeseries")

    def to_astropy_table(self):
        return self._to_astropy_object(kind="table")

    def _to_astropy_object(self, kind="table"):
        data = {}

        for attr in ['_counts', '_counts_err', '_countrate', '_countrate_err',
                     '_bin_lo', '_bin_hi']:
            if hasattr(self, attr) and getattr(self, attr) is not None:
                data[attr.lstrip('_')] = np.asarray(getattr(self, attr))

        if kind.lower() == "table":
            data['time'] = self.time
            ts = Table(data)
        elif kind.lower() == "timeseries":
            from astropy.timeseries import TimeSeries
            ts = TimeSeries(data=data, time=TimeDelta(self.time * u.s))
        else:  # pragma: no cover
            raise ValueError("Invalid kind (accepted: table or timeseries)")

        for attr in ['_gti', 'mjdref', '_meancounts', '_meancountrate',
                     'instr', 'mission', 'dt', 'err_dist']:
            if hasattr(self, attr) and getattr(self, attr) is not None:
                ts.meta[attr.lstrip('_')] = getattr(self, attr)

        return ts

    @staticmethod
    def from_astropy_timeseries(ts, **kwargs):
        return Lightcurve._from_astropy_object(ts, **kwargs)

    @staticmethod
    def from_astropy_table(ts, **kwargs):
        return Lightcurve._from_astropy_object(ts, **kwargs)

    @staticmethod
    def _from_astropy_object(
            ts, err_dist='poisson', skip_checks=True):

        if hasattr(ts, 'time'):
            time = ts.time
        else:
            time = ts['time']

        kwargs = ts.meta
        err = None
        input_counts = True

        if "counts_err" in ts.colnames:
            err = ts["counts_err"]
        elif "countrate_err" in ts.colnames:
            err = ts["countrate_err"]

        if 'counts' in ts.colnames:
            counts = ts['counts']
        elif 'countrate' in ts.colnames:
            counts = ts['countrate']
            input_counts = False
        else:
            raise ValueError('Input timeseries must contain at least a '
                             '`counts` or a `countrate` column')

        kwargs.update({'time': time, 'counts': counts, 'err': err,
                       'input_counts': input_counts,
                       'skip_checks': skip_checks})
        if 'err_dist' not in kwargs:
            kwargs['err_dist'] = err_dist

        lc = Lightcurve(**kwargs)

        return lc

    def plot(self, witherrors=False, labels=None, axis=None, title=None,
             marker='-', save=False, filename=None):
        """
        Plot the light curve using ``matplotlib``.

        Plot the light curve object on a graph ``self.time`` on x-axis and
        ``self.counts`` on y-axis with ``self.counts_err`` optionally
        as error bars.

        Parameters
        ----------
        witherrors: boolean, default False
            Whether to plot the Lightcurve with errorbars or not

        labels : iterable, default ``None``
            A list of tuple with ``xlabel`` and ``ylabel`` as strings.

        axis : list, tuple, string, default ``None``
            Parameter to set axis properties of the ``matplotlib`` figure. For example
            it can be a list like ``[xmin, xmax, ymin, ymax]`` or any other
            acceptable argument for the``matplotlib.pyplot.axis()`` method.

        title : str, default ``None``
            The title of the plot.

        marker : str, default '-'
            Line style and color of the plot. Line styles and colors are
            combined in a single format string, as in ``'bo'`` for blue
            circles. See ``matplotlib.pyplot.plot`` for more options.

        save : boolean, optional, default ``False``
            If ``True``, save the figure with specified filename.

        filename : str
            File name of the image to save. Depends on the boolean ``save``.
        """

        fig = plt.figure()
        if witherrors:
            fig = plt.errorbar(self.time, self.counts, yerr=self.counts_err,
                               fmt=marker)
        else:
            fig = plt.plot(self.time, self.counts, marker)

        if labels is not None:
            try:
                plt.xlabel(labels[0])
                plt.ylabel(labels[1])
            except TypeError:
                utils.simon("``labels`` must be either a list or tuple with "
                            "x and y labels.")
                raise
            except IndexError:
                utils.simon("``labels`` must have two labels for x and y "
                            "axes.")
                # Not raising here because in case of len(labels)==1, only
                # x-axis will be labelled.

        if axis is not None:
            plt.axis(axis)

        if title is not None:
            plt.title(title)

        if save:
            if filename is None:
                plt.savefig('out.png')
            else:
                plt.savefig(filename)
        else:
            plt.show(block=False)

    @classmethod
    def read(cls, filename, fmt=None, format_=None, err_dist='gauss',
             skip_checks=False):
        """
        Read a :class:`Lightcurve` object from file.

        Currently supported formats are

        * pickle (not recommended for long-term storage)
        * hea : FITS Light curves from HEASARC-supported missions.
        * any other formats compatible with the writers in
          :class:`astropy.table.Table` (ascii.ecsv, hdf5, etc.)

        Files that need the :class:`astropy.table.Table` interface MUST contain
        at least a ``time`` column and a ``counts`` or ``countrate`` column.
        The default ascii format is enhanced CSV (ECSV). Data formats
        supporting the serialization of metadata (such as ECSV and HDF5) can
        contain all lightcurve attributes such as ``dt``, ``gti``, etc with
        no significant loss of information. Other file formats might lose part
        of the metadata, so must be used with care.

        Parameters
        ----------
        filename: str
            Path and file name for the file to be read.

        fmt: str
            Available options are 'pickle', 'hea', and any `Table`-supported
            format such as 'hdf5', 'ascii.ecsv', etc.

        Other parameters
        ----------------

        err_dist: str, default='gauss'
            Default error distribution if not specified in the file (e.g. for
            ASCII files). The default is 'gauss' just because it is likely
            that people using ASCII light curves will want to specify Gaussian
            error bars, if any.
        skip_checks : bool
            See :class:`Lightcurve` documentation

        Returns
        --------
        lc : :class:`Lightcurve` object
        """
        if fmt is None and format_ is not None:
            warnings.warn(
                "The format_ keyword for read and write is deprecated. "
                "Use fmt instead", DeprecationWarning)
            fmt = format_

        if fmt.lower() in ('hea', 'ogip'):
            data = lcurve_from_fits(filename)
            data.update({'err_dist': err_dist, 'skip_checks': skip_checks})
            return Lightcurve(**data)

        return super().read(filename=filename, fmt=fmt)

    def split_by_gti(self, gti=None, min_points=2):
        """
        Split the current :class:`Lightcurve` object into a list of :class:`Lightcurve` objects, one
        for each continuous GTI segment as defined in the ``gti`` attribute.

        Parameters
        ----------
        min_points : int, default 1
            The minimum number of data points in each light curve. Light
            curves with fewer data points will be ignored.

        Returns
        -------
        list_of_lcs : list
            A list of :class:`Lightcurve` objects, one for each GTI segment
        """

        if gti is None:
            gti = self.gti

        list_of_lcs = []

        start_bins, stop_bins = gti_border_bins(gti, self.time, self.dt)
        for i in range(len(start_bins)):
            start = start_bins[i]
            stop = stop_bins[i]

            if np.isclose(stop - start, 1):
                logging.warning("Segment with a single time bin! Ignoring this segment!")
                continue
            if (stop - start) < min_points:
                continue

            # Note: GTIs are consistent with default in this case!
            new_lc = Lightcurve(self.time[start:stop], self.counts[start:stop],
                                err=self.counts_err[start:stop],
                                mjdref=self.mjdref, gti=[gti[i]],
                                dt=self.dt, err_dist=self.err_dist,
                                skip_checks=True)
            list_of_lcs.append(new_lc)

        return list_of_lcs

    def apply_gtis(self):
        """
        Apply GTIs to a light curve. Filters the ``time``, ``counts``,
        ``countrate``, ``counts_err`` and ``countrate_err`` arrays for all bins
        that fall into Good Time Intervals and recalculates mean countrate
        and the number of bins.
        """
        check_gtis(self.gti)

        good = self.mask

        # nota bene: We set the private properties, otherwise we'll get a
        # ValueError from changing the shape of the arrays.
        self._time = self.time[good]
        self._counts = self.counts[good]
        if self._counts_err is not None:
            self._counts_err = self._counts_err[good]
        self._countrate = None
        self._countrate_err = None
        self._mask = None

        self._meanrate = None
        self._meancounts = None
        self._n = None
        self.tseg = np.max(self.gti) - np.min(self.gti)
        self.tstart = self.time - 0.5 * self.dt     HAS_PYFFTW = True
    HAS_PYFFTW = False
HAS_NUMBA = False
    HAS_NUMBA = True
    L = len(y)
    D = sparse.csc_matrix(np.diff(np.eye(L), 2))
        W = sparse.spdiags(w, 0, L, L)
        Z = W + lam * D.dot(D.transpose())
    N = len(lc.counts)
    N = abs(N)
        H = np.lib.format.open_memmap(
            tmp, mode="w+", dtype=dtype, shape=shape
        )
        H = np.zeros(shape, dtype=dtype)
    H = _allocate_array_or_memmap(bins, np.uint64, use_memmap=use_memmap, tmp=tmp)
    H = _allocate_array_or_memmap(bins, np.uint64, use_memmap=use_memmap, tmp=tmp)
    H = _allocate_array_or_memmap(bins, np.double, use_memmap=use_memmap, tmp=tmp)
    H = _allocate_array_or_memmap(bins, np.double, use_memmap=use_memmap, tmp=tmp)
    H = _allocate_array_or_memmap(bins, np.uint64, use_memmap=use_memmap, tmp=tmp)
    class jit(object):
    class njit(object):
    class vectorize(object):
        def __init__(self, *args, **kwargs):
        def __call__(self, func):
            def wrapped_f(*args, **kwargs):
        def __init__(self, *args, **kwargs):
        def __call__(self, func):
            def wrapped_f(*args, **kwargs):
        def __init__(self, *args, **kwargs):
        def __call__(self, func):
    def generic(x, y=None):
    def prange(x):
    def show_progress(a):
    def mad(data, c=0.6745, axis=None):
def _root_squared_mean(array):
def simon(message, **kwargs):
def rebin_data(x, y, dx_new, yerr=None, method='sum', dx=None):
def rebin_data_log(x, y, f, y_err=None, dx=None):
def apply_function_if_none(variable, value, func):
def assign_value_if_none(value, default):
def look_for_array_in_array(array1, array2):
def is_string(s):
def is_iterable(var):
def order_list_of_arrays(data, order):
def optimal_bin_time(fftlen, tbin):
def contiguous_regions(condition):
def is_int(obj):
def get_random_state(random_state=None):
def _offset(x, off):
def offset_fit(x, y, offset_start=0):
def _als(y, lam, p, niter=10):
def baseline_als(x, y, lam=None, p=None, niter=10, return_baseline=False,
                 offset_correction=False):
def excess_variance(lc, normalization='fvar'):
def create_window(N, window_type='uniform'):
def poisson_symmetrical_errors(counts):
def standard_error(xs, mean):
def nearest_power_of_two(x):
def find_nearest(array, value):
def genDataPath(dir_path):
def check_iterables_close(iter0, iter1, **kwargs):
def compute_bin(x, bin_edges):
def _hist1d_numba_seq(H, tracks, bins, ranges):
def _allocate_array_or_memmap(shape, dtype, use_memmap=False, tmp=None):
def hist1d_numba_seq(a, bins, ranges, use_memmap=False, tmp=None):
def _hist2d_numba_seq(H, tracks, bins, ranges):
def hist2d_numba_seq(x, y, bins, ranges, use_memmap=False, tmp=None):
def _hist3d_numba_seq(H, tracks, bins, ranges):
def hist3d_numba_seq(tracks, bins, ranges, use_memmap=False, tmp=None):
def _hist2d_numba_seq_weight(H, tracks, weights, bins, ranges):
def hist2d_numba_seq_weight(x, y, weights, bins, ranges, use_memmap=False, tmp=None):
def _hist3d_numba_seq_weight(H, tracks, weights, bins, ranges):
def hist3d_numba_seq_weight(tracks, weights, bins, ranges, use_memmap=False, tmp=None):
def _index_arr(a, ix_arr):
def _index_set_arr(a, ix_arr, val):
def _histnd_numba_seq(H, tracks, bins, ranges, slice_int):
def histnd_numba_seq(tracks, bins, ranges, use_memmap=False, tmp=None):
    def histogram2d(*args, **kwargs):
    def histogram(*args, **kwargs):
    def histogram2d(*args, **kwargs):
    def histogram(*args, **kwargs):
def equal_count_energy_ranges(energies, n_ranges, emin=None, emax=None):
def sum_if_not_none_or_initialize(A, B):
def assign_if_not_finite(value, default):
import copy
import pickle
import warnings
import numpy as np
import numpy.random as ra
from collections.abc import Iterable
from astropy.table import Table
from .base import StingrayObject, StingrayTimeseries
from .filters import get_deadtime_mask
from .gti import append_gtis, check_separate, cross_gtis, generate_indices_of_boundaries
from .io import load_events_and_gtis
from .lightcurve import Lightcurve
from .utils import assign_value_if_none, simon, interpret_times
        from .simulator.base import simulate_times
        from .simulator.base import simulate_with_inverse_cdf
"""
Definition of :class:`EventList`.

:class:`EventList` is used to handle photon arrival times.
"""




__all__ = ['EventList']



class EventList(StingrayTimeseries):