/***************************************************************************
**
**  This file is part of QGpCoreMath.
**
**  QGpCoreMath 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 3 of the License, or
**  (at your option) any later version.
**
**  QGpCoreMath 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 Foobar.  If not, see <http://www.gnu.org/licenses/>
**
**  See http://www.geopsy.org for more information.
**
**  Created: 2020-06-04
**  Copyright: 2020
**    Marc Wathelet (ISTerre, Grenoble, France)
**
***************************************************************************/

#include "LeastSquare.h"

namespace QGpCoreMath {

  /*!
    \class LeastSquare LeastSquare.h
    \brief Brief description of class still missing

    Full description of class still missing
  */

  /*!
    Description of constructor still missing
  */
  LeastSquare::LeastSquare(int dataCount, int order)
  {
    ASSERT(dataCount>0);
    if(dataCount<=order) {
      order=dataCount-1; // Reduce order if not enough data points
    }
    _a=new DoubleMatrix(dataCount, order+1);
    _b=new DoubleMatrix(dataCount, 1);
    _x=new DoubleMatrix(order+1, 1);
    _scaleType=SamplingParameters::Linear;
  }

  LeastSquare::~LeastSquare()
  {
    delete _a;
    delete _b;
    delete _x;
  }

  void LeastSquare::setData(int index, double x, double y)
  {
    double x0=1.0;
    for(int t=_x->rowCount()-1; t>=0; t--) {
      _a->at(index, t)=x0;
      x0*=x;
    }
    switch(_scaleType) {
    case SamplingParameters::Linear:
      _b->at(index, 0)=y;
      break;
    case SamplingParameters::Log:
      _b->at(index, 0)=::log10(y);
      break;
    }
  }

  double LeastSquare::value(double x) const
  {
    double x0=1.0;
    double sum=0.0;
    for(int t=_x->rowCount()-1; t>=0; t--) {
      sum+=_x->at(t, 0)*x0;
      x0*=x;
    }
    switch(_scaleType) {
    case SamplingParameters::Linear:
      break;
    case SamplingParameters::Log:
      return ::pow(10.0, sum);
      break;
    }
    return sum;
  }

} // namespace QGpCoreMath

