# *****************************************************************************
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Module authors:
#   Markus Zolliker <markus.zolliker@psi.ch>
#
# *****************************************************************************
"""interpolation, mainly used for pid tables"""

import numpy as np


class Interpolation(list):
    def __init__(self, table, logx=None, logy=None):
        """initialize table

        :param table: sequence of tuple (x, y)
        :param logx, logy: True/False: whether to apply log for interpolation
            None: automatic (choose log when all values are positive)
        :return: interpolated y value
        """
        table = np.array(sorted(table))
        super().__init__(table)
        if len(table) == 0:
            return
        logx = table[0][0] > 0 if logx is None else logx
        logy = min(table[:,1]) > 0 if logy is None else logy
        self.fwd = np.log if logx else np.array
        self.xvalues = self.fwd(table[:,0])
        self.rev = np.exp if logy else np.array
        self.yvalues = np.log(table[:,1]) if logy else table[:,1]

    def __call__(self, x):
        return self.rev(np.interp(self.fwd(x), self.xvalues, self.yvalues))
