// Created with MonoDevelop
//
//    Copyright (C) 2017 Hiperscan GmbH Dresden, Germany
//
//    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 3 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, see <http://www.gnu.org/licenses/>.

using System;

using Hiperscan.Unix;

using MathNet.Numerics.LinearAlgebra.Double;


namespace Hiperscan.Spectroscopy.Math
{

    public partial class LevenbergMarquardt
    {

        public class Match2DQuadraticLinearSlopeFit : Hiperscan.Spectroscopy.Math.LevenbergMarquardt.BaseFit
        {
            public Match2DQuadraticLinearSlopeFit(DataSet fit_data, DataSet ref_data, double direction) : base(fit_data, ref_data, direction)
            {
                if (fit_data.Count != ref_data.Count)
                    throw new ArgumentException(Catalog.GetString("Dimension of fit data and reference data must not be different."));

                this.InitCoefficients = new double[6] { 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 };
            }

            public override Vector FunctionVector(double[] coeff)
            {
                double[] p = new double[3];
                Array.Copy(coeff, 0, p, 0, 3);
                WavelengthCorrection wlc = new WavelengthCorrection(p);
                DataSet fit = wlc.CorrectedSpectrum(this.FitData).Interpolate(this.RefData.X);

                Vector fvec = new DenseVector(this.FitData.X.Count);
                for (int ix = 0; ix < fit.Count; ++ix)
                {
                    fvec[ix] = coeff[3] + coeff[4] * fit.Y[ix] + coeff[5] * fit.X[ix];
                }
                return fvec;
            }

            public override void NormalizeFitData()
            {
                this.FitData *= this.Direction;
            }

            public override double[] UnNormalizeCoefficients(double[] coeff)
            {
                return coeff;
            }
        }
    }
}

