//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/Model/Mini/MinimizerItems.h
//! @brief     Defines class MinimizerItem and children.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2018
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#ifndef BORNAGAIN_GUI_MODEL_MINI_MINIMIZERITEMS_H
#define BORNAGAIN_GUI_MODEL_MINI_MINIMIZERITEMS_H

#include "GUI/Model/Descriptor/ComboProperty.h"
#include "GUI/Model/Descriptor/DoubleProperty.h"

class GSLLMAMinimizerItem;
class GSLMultiMinimizerItem;
class GeneticMinimizerItem;
class IMinimizer;
class MinuitMinimizerItem;
class ObjectiveMetric;
class SimAnMinimizerItem;

enum class MinimizerType { Minuit2, GSLMultiMin, GSLLMA, GSLSimAn, Genetic };

//! Returns a string representation of the minimizer type
QString minimizerTypeToName(MinimizerType type);

//! Base class to store minimizer settings.

class MinimizerItem {
public:
    virtual ~MinimizerItem() = default;

    virtual std::unique_ptr<IMinimizer> createMinimizer() const = 0;

    virtual void writeTo(QXmlStreamWriter* w) const = 0;
    virtual void readFrom(QXmlStreamReader* r) = 0;
};

//! Holds collection of minimizers and allows switching between them.

class MinimizerContainerItem : public MinimizerItem {
public:
    MinimizerContainerItem();
    ~MinimizerContainerItem() override;

    MinuitMinimizerItem* minimizerItemMinuit() const;
    GSLMultiMinimizerItem* minimizerItemGSLMulti() const;
    GeneticMinimizerItem* minimizerItemGenetic() const;
    SimAnMinimizerItem* minimizerItemSimAn() const;
    GSLLMAMinimizerItem* minimizerItemGSLLMA() const;

    MinimizerItem* currentMinimizerItem() const;

    QString currentMinimizer() const;
    void setCurrentMinimizer(const QString& name);

    bool algorithmHasMinimizer(const QString& name);
    void setCurrentCommonAlgorithm(const QString& name);
    ComboProperty commonAlgorithmCombo() const { return m_algorithm; }
    void applyAlgorithmToMinimizer(const QString& name);

    // Objective metric to use for estimating distance between simulated and experimental data
    QString currentObjectiveMetric() const;
    void setCurrentObjectiveMetric(const QString& name);
    ComboProperty objectiveMetricCombo() const { return m_metric; }

    // Normalization to use for estimating distance between simulated and experimental data
    QString currentNormFunction() const;
    void setCurrentNormFunction(const QString& name);
    ComboProperty normFunctionCombo() const { return m_norm; }

    std::unique_ptr<IMinimizer> createMinimizer() const override;
    std::unique_ptr<ObjectiveMetric> createMetric() const;

    void writeTo(QXmlStreamWriter* w) const override;
    void readFrom(QXmlStreamReader* r) override;

private:
    // hold them all for storing their internal settings.
    std::unique_ptr<MinuitMinimizerItem> m_MinuitMinimizer;
    std::unique_ptr<GSLMultiMinimizerItem> m_GSLMultiMinimizer;
    std::unique_ptr<GeneticMinimizerItem> m_GeneticMinimizer;
    std::unique_ptr<SimAnMinimizerItem> m_SimAnMinimizer;
    std::unique_ptr<GSLLMAMinimizerItem> m_GSLLMAMinimizer;

    ComboProperty m_algorithm;
    ComboProperty m_minimizer;
    ComboProperty m_metric;
    ComboProperty m_norm;
};

//! Holds settings for ROOT Minuit2 minimizer.

class MinuitMinimizerItem : public MinimizerItem {
public:
    MinuitMinimizerItem();
    ~MinuitMinimizerItem() override;

    QString currentAlgorithm() const;
    void setCurrentAlgorithm(const QString& name);

    // Minimization strategy (0-low, 1-medium, 2-high quality)
    int strategy() const { return m_strategy; }
    void setStrategy(int v) { m_strategy = v; }

    // Error definition factor for parameter error calculation
    DoubleProperty& errorDefinition() { return m_error_def; }
    const DoubleProperty& errorDefinition() const { return m_error_def; }
    void setErrorDefinition(double v) { m_error_def.setDVal(v); }

    // Tolerance on the function value at the minimum
    DoubleProperty& tolerance() { return m_tolerance; }
    const DoubleProperty& tolerance() const { return m_tolerance; }
    void setTolerance(double v) { m_tolerance.setDVal(v); }

    // Relative floating point arithmetic precision
    DoubleProperty& precision() { return m_precision; }
    const DoubleProperty& precision() const { return m_precision; }
    void setPrecision(double v) { m_precision.setDVal(v); }

    // Maximum number of function calls
    int maxFuncCalls() const { return m_max_func_calls; }
    void setMaxFuncCalls(int v) { m_max_func_calls = v; }

    std::unique_ptr<IMinimizer> createMinimizer() const override;

    void writeTo(QXmlStreamWriter* w) const override;
    void readFrom(QXmlStreamReader* r) override;

private:
    ComboProperty m_algorithm;
    int m_strategy;
    DoubleProperty m_error_def;
    DoubleProperty m_tolerance;
    DoubleProperty m_precision;
    int m_max_func_calls;
};

//! Holds settings for GSL MultiMin minimizer family.

class GSLMultiMinimizerItem : public MinimizerItem {
public:
    GSLMultiMinimizerItem();
    ~GSLMultiMinimizerItem() override;

    QString currentAlgorithm() const;
    void setCurrentAlgorithm(const QString& name);

    // Maximum number of iterations
    int maxIterations() const { return m_max_iterations; }
    void setMaxIterations(int v) { m_max_iterations = v; }

    std::unique_ptr<IMinimizer> createMinimizer() const override;

    void writeTo(QXmlStreamWriter* w) const override;
    void readFrom(QXmlStreamReader* r) override;

private:
    ComboProperty m_algorithm;
    int m_max_iterations;
};

//! Holds settings for TMVA/Genetic minimizer.

class GeneticMinimizerItem : public MinimizerItem {
public:
    GeneticMinimizerItem();
    ~GeneticMinimizerItem() override;

    // Tolerance on the function value at the minimum
    DoubleProperty& tolerance() { return m_tolerance; }
    const DoubleProperty& tolerance() const { return m_tolerance; }
    void setTolerance(double v) { m_tolerance.setDVal(v); }

    // Maximum number of iterations
    int maxIterations() const { return m_max_iterations; }
    void setMaxIterations(int v) { m_max_iterations = v; }

    // Population size
    int populationSize() const { return m_population_size; }
    void setPopulationSize(int v) { m_population_size = v; }

    // Random seed
    int randomSeed() const { return m_random_seed; }
    void setRandomSeed(int v) { m_random_seed = v; }

    std::unique_ptr<IMinimizer> createMinimizer() const override;

    void writeTo(QXmlStreamWriter* w) const override;
    void readFrom(QXmlStreamReader* r) override;

private:
    DoubleProperty m_tolerance;
    int m_max_iterations;
    int m_population_size;
    int m_random_seed;
};

//! Holds settings for GSL's simulated annealing minimizer.

class SimAnMinimizerItem : public MinimizerItem {
public:
    SimAnMinimizerItem();
    ~SimAnMinimizerItem() override;

    // Number of points to try for each step
    int maxIterations() const { return m_max_iterations; }
    void setMaxIterations(int v) { m_max_iterations = v; }

    // Number of iterations at each temperature
    int iterationsAtEachTemp() const { return m_iterations_at_temp; }
    void setIterationsAtEachTemp(int v) { m_iterations_at_temp = v; }

    // Max step size used in random walk
    DoubleProperty& stepSize() { return m_step_size; }
    const DoubleProperty& stepSize() const { return m_step_size; }
    void setStepSize(double v) { m_step_size.setDVal(v); }

    // Boltzmann k
    DoubleProperty& boltzmanK() { return m_boltzmann_K; }
    const DoubleProperty& boltzmanK() const { return m_boltzmann_K; }
    void setBoltzmanK(double v) { m_boltzmann_K.setDVal(v); }

    // Boltzmann initial temperature
    DoubleProperty& boltzmanInitT() { return m_boltzmann_T_init; }
    const DoubleProperty& boltzmanInitT() const { return m_boltzmann_T_init; }
    void setBoltzmanInitT(double v) { m_boltzmann_T_init.setDVal(v); }

    // Boltzmann mu
    DoubleProperty& boltzmanMu() { return m_boltzmann__mu; }
    const DoubleProperty& boltzmanMu() const { return m_boltzmann__mu; }
    void setBoltzmanMu(double v) { m_boltzmann__mu.setDVal(v); }

    // Boltzmann minimal temperature
    DoubleProperty& boltzmanMinT() { return m_boltzmann_T_min; }
    const DoubleProperty& boltzmanMinT() const { return m_boltzmann_T_min; }
    void setBoltzmanMinT(double v) { m_boltzmann_T_min.setDVal(v); }

    std::unique_ptr<IMinimizer> createMinimizer() const override;

    void writeTo(QXmlStreamWriter* w) const override;
    void readFrom(QXmlStreamReader* r) override;

private:
    int m_max_iterations;
    int m_iterations_at_temp;
    DoubleProperty m_step_size;
    DoubleProperty m_boltzmann_K;
    DoubleProperty m_boltzmann_T_init;
    DoubleProperty m_boltzmann__mu;
    DoubleProperty m_boltzmann_T_min;
};

//! Holds settings for GSL's version of Levenberg-Marquardt.

class GSLLMAMinimizerItem : public MinimizerItem {
public:
    GSLLMAMinimizerItem();
    ~GSLLMAMinimizerItem() override;

    // Tolerance on the function value at the minimum
    DoubleProperty& tolerance() { return m_tolerance; }
    const DoubleProperty& tolerance() const { return m_tolerance; }
    void setTolerance(double v) { m_tolerance.setDVal(v); }

    // Maximum number of iterations
    int maxIterations() const { return m_max_iterations; }
    void setMaxIterations(int v) { m_max_iterations = v; }

    std::unique_ptr<IMinimizer> createMinimizer() const override;

    void writeTo(QXmlStreamWriter* w) const override;
    void readFrom(QXmlStreamReader* r) override;

private:
    DoubleProperty m_tolerance;
    int m_max_iterations;
};

#endif // BORNAGAIN_GUI_MODEL_MINI_MINIMIZERITEMS_H
