# Path: sedfitter/utils/interpolate.py
# @check_bounds
# def interp1d_fast(x, y, xval):
#     """On-the-fly linear interpolator"""
#     if len(x) != len(y):
#         raise Exception("x and y should have the same length")
#     ipos = np.searchsorted(x, xval)
#     return (xval - x[ipos - 1]) \
#         / (x[ipos] - x[ipos - 1]) \
#         * (y[ipos] - y[ipos - 1]) \
#         + y[ipos - 1]


import numpy as np
from .interpolate import interp1d_fast




def integrate_subset(x, y, xmin, xmax):
    """
    Perform trapezium integration of a set of points (x,y) between bounds xmin
    and xmax. The interpolation between the points is done in linear space, so
    this is designed for functions that are piecewise linear in linear space.
    """

    # Swap arrays if necessary
    if x[-1] < x[0]:
        x = x[::-1]
        y = y[::-1]

    # Swap limits if necessary
    if xmin > xmax:
        xmin, xmax = xmax, xmin
    elif xmin == xmax:
        return 0.

    # Find the subset of points to use and the value of the function at the
    # end-points of the integration

    if xmin == x[0]:
        i1 = 1
        ymin = y[0]
    else:
        i1 = np.searchsorted(x, xmin)

# Path: sedfitter/utils/interpolate.py
# @check_bounds
# def interp1d_fast(x, y, xval):
#     """On-the-fly linear interpolator"""
#     if len(x) != len(y):
#         raise Exception("x and y should have the same length")
#     ipos = np.searchsorted(x, xval)
#     return (xval - x[ipos - 1]) \
#         / (x[ipos] - x[ipos - 1]) \
#         * (y[ipos] - y[ipos - 1]) \
#         + y[ipos - 1]


# Path: sedfitter/utils/integrate.py
import numpy as np
from .interpolate import interp1d_fast





def integrate_subset(x, y, xmin, xmax):
    """
    Perform trapezium integration of a set of points (x,y) between bounds xmin
    and xmax. The interpolation between the points is done in linear space, so
    this is designed for functions that are piecewise linear in linear space.
    """

    # Swap arrays if necessary
    if x[-1] < x[0]:
        x = x[::-1]
        y = y[::-1]

    # Swap limits if necessary
    if xmin > xmax:
        xmin, xmax = xmax, xmin
    elif xmin == xmax:
        return 0.

    # Find the subset of points to use and the value of the function at the
    # end-points of the integration

    if xmin == x[0]:
        i1 = 1
        ymin = y[0]
    else:
        i1 = np.searchsorted(x, xmin)

        ymin = interp1d_fast(x[i1 - 1:i1 + 1], y[i1 - 1:i1 + 1], xmin)