<commit_before>#include <vector>
#include "Solvers.h"
#include "math.h"
#include "MatrixMath.h"
#include <iostream>
#include "CoolPropTools.h"
#include <Eigen/Dense>

namespace CoolProp{

/** \brief Calculate the Jacobian using numerical differentiation by column
 */
std::vector<std::vector<double> > FuncWrapperND::Jacobian(const std::vector<double> &x)
{
    double epsilon;
    std::size_t N = x.size();
    std::vector<double> r, xp;
    std::vector<std::vector<double> > J(N, std::vector<double>(N, 0));
    std::vector<double> r0 = call(x);
    // Build the Jacobian by column
    for (std::size_t i = 0; i < N; ++i)
    {
        xp = x;
        epsilon = 0.001*x[i];
        xp[i] += epsilon;
        r = call(xp);
        
        for(std::size_t j = 0; j < N; ++j)
        {
            J[j][i] = (r[j]-r0[j])/epsilon;
        }
    }
    return J;
}

/**
In this formulation of the Multi-Dimensional Newton-Raphson solver the Jacobian matrix is known.
Therefore, the dx vector can be obtained from

J(x)dx=-f(x)

for a given value of x.  The pointer to the class FuncWrapperND that is passed in must implement the call() and Jacobian()
functions, each of which take the vector x. The data is managed using std::vector<double> vectors

@param f A pointer to an subclass of the FuncWrapperND class that implements the call() and Jacobian() functions
@param x0 The initial guess value for the solution
@param tol The root-sum-square of the errors from each of the components
@param maxiter The maximum number of iterations
@param errstring  A string with the returned error.  If the length of errstring is zero, no errors were found
@returns If no errors are found, the solution.  Otherwise, _HUGE, the value for infinity
*/
std::vector<double> NDNewtonRaphson_Jacobian(FuncWrapperND *f, std::vector<double> &x0, double tol, int maxiter)
{
    int iter=0;
    f->errstring.clear();
    std::vector<double> f0,v;
    std::vector<std::vector<double> > JJ;
    Eigen::VectorXd r(x0.size());
    Eigen::Matrix2d J(x0.size(), x0.size());
    double error = 999;
    while (iter==0 || std::abs(error)>tol){
        f0 = f->call(x0);
        JJ = f->Jacobian(x0);
        
        for (std::size_t i = 0; i < x0.size(); ++i)
        {
            r(i) = f0[i];
            for (std::size_t j = 0; j < x0.size(); ++j)
            {
                J(i,j) = JJ[i][j];
            }
        }

        Eigen::Vector2d v = J.colPivHouseholderQr().solve(-r);

        // Update the guess
        for (std::size_t i = 0; i<x0.size(); i++){ x0[i] += v(i);}
        
        // Stop if the solution is not changing by more than numerical precision
        if (v.cwiseAbs().maxCoeff() < DBL_EPSILON*100){
            return x0;
        }
        error = root_sum_square(f0);
        if (iter>maxiter){
            f->errstring = "reached maximum number of iterations";
            x0[0] = _HUGE;
        }
        iter++;
    }
    return x0;
}

/**
In the newton function, a 1-D Newton-Raphson solver is implemented using exact solutions.  An initial guess for the solution is provided.

@param f A pointer to an instance of the FuncWrapper1D class that implements the call() function
@param x0 The inital guess for the solution
@param ftol The absolute value of the tolerance accepted for the objective function
@param maxiter Maximum number of iterations
@returns If no errors are found, the solution, otherwise the value _HUGE, the value for infinity
*/
double Newton(FuncWrapper1DWithDeriv* f, double x0, double ftol, int maxiter)
{
    double x, dx, fval=999;
    int iter=1;
    f->errstring.clear();
    x = x0;
    while (iter < 2 || std::abs(fval) > ftol)
    {
        fval = f->call(x);
        dx = -fval/f->deriv(x);

        if (!ValidNumber(fval)){
            throw ValueError("Residual function in newton returned invalid number");
        };

        x += dx;

        if (std::abs(dx/x) < 1e-11){
            return x;
        }

        if (iter>maxiter)
        {
            f->errstring= "reached maximum number of iterations";
            throw SolutionError(format("Newton reached maximum number of iterations"));
        }
        iter=iter+1;
    }
    return x;
}
/**
In the Halley's method solver, two derivatives of the input variable are needed, it yields the following method:

\f[
x_{n+1} = x_n - \frac {2 f(x_n) f'(x_n)} {2 {[f'(x_n)]}^2 - f(x_n) f''(x_n)}
\f]

http://en.wikipedia.org/wiki/Halley%27s_method

@param f A pointer to an instance of the FuncWrapper1DWithTwoDerivs class that implements the call() and two derivatives
@param x0 The inital guess for the solution
@param ftol The absolute value of the tolerance accepted for the objective function
@param maxiter Maximum number of iterations
@returns If no errors are found, the solution, otherwise the value _HUGE, the value for infinity
*/
double Halley(FuncWrapper1DWithTwoDerivs* f, double x0, double ftol, int maxiter)
{
    double x, dx, fval=999, dfdx, d2fdx2;
    int iter=1;
    f->errstring.clear();
    x = x0;
    while (iter < 2 || std::abs(fval) > ftol)
    {
        fval = f->call(x);
        dfdx = f->deriv(x);
        d2fdx2 = f->second_deriv(x);
        
        if (f->input_not_in_range(x)){
            throw ValueError(format("Input [%g] is out of range",x));
        }
        if (!ValidNumber(fval)){
            throw ValueError("Residual function in Halley returned invalid number");
        };
        if (!ValidNumber(dfdx)){
            throw ValueError("Derivative function in Halley returned invalid number");
        };
        
        dx = -(2*fval*dfdx)/(2*POW2(dfdx)-fval*d2fdx2);

        

        x += dx;

        if (std::abs(dx/x) < 10*DBL_EPSILON){
            return x;
        }

        if (iter>maxiter){
            f->errstring= "reached maximum number of iterations";
            throw SolutionError(format("Halley reached maximum number of iterations"));
        }
        iter=iter+1;
    }
    return x;
}

/**
In the secant function, a 1-D Newton-Raphson solver is implemented.  An initial guess for the solution is provided.

@param f A pointer to an instance of the FuncWrapper1D class that implements the call() function
@param x0 The inital guess for the solutionh
@param dx The initial amount that is added to x in order to build the numerical derivative
@param tol The absolute value of the tolerance accepted for the objective function
@param maxiter Maximum number of iterations
@returns If no errors are found, the solution, otherwise the value _HUGE, the value for infinity
*/
double Secant(FuncWrapper1D* f, double x0, double dx, double tol, int maxiter)
{
    #if defined(COOLPROP_DEEP_DEBUG)
    static std::vector<double> xlog, flog;
    xlog.clear(); flog.clear();
    #endif

    double x1=0,x2=0,x3=0,y1=0,y2=0,x,fval=999;
    int iter=1;
    f->errstring.clear();

    if (std::abs(dx)==0){ f->errstring="dx cannot be zero"; return _HUGE;}
    while (iter<=2 || std::abs(fval)>tol)
    {
        if (iter==1){x1=x0; x=x1;}
        if (iter==2){x2=x0+dx; x=x2;}
        if (iter>2) {x=x2;}

            fval = f->call(x);

            #if defined(COOLPROP_DEEP_DEBUG)
                xlog.push_back(x);
                flog.push_back(fval);
            #endif

            if (!ValidNumber(fval)){
                throw ValueError("Residual function in secant returned invalid number");
            };
        if (iter==1){y1=fval;}
        if (iter>1)
        {
            double deltax = x2-x1;
            if (std::abs(deltax)<1e-14){
                return x;
            }
            y2=fval;
            x3=x2-y2/(y2-y1)*(x2-x1);
            y1=y2; x1=x2; x2=x3;

        }
        if (iter>maxiter)
        {
            f->errstring=std::string("reached maximum number of iterations");
            throw SolutionError(format("Secant reached maximum number of iterations"));
        }
        iter=iter+1;
    }
    return x3;
}

/**
In the secant function, a 1-D Newton-Raphson solver is implemented.  An initial guess for the solution is provided.

@param f A pointer to an instance of the FuncWrapper1D class that implements the call() function
@param x0 The inital guess for the solution<commit_msg>Secant behaves properly now when y1 approx. y2; closes #1015<commit_after>#include <vector>
#include "Solvers.h"
#include "math.h"
#include "MatrixMath.h"
#include <iostream>
#include "CoolPropTools.h"
#include <Eigen/Dense>

namespace CoolProp{

/** \brief Calculate the Jacobian using numerical differentiation by column
 */
std::vector<std::vector<double> > FuncWrapperND::Jacobian(const std::vector<double> &x)
{
    double epsilon;
    std::size_t N = x.size();
    std::vector<double> r, xp;
    std::vector<std::vector<double> > J(N, std::vector<double>(N, 0));
    std::vector<double> r0 = call(x);
    // Build the Jacobian by column
    for (std::size_t i = 0; i < N; ++i)
    {
        xp = x;
        epsilon = 0.001*x[i];
        xp[i] += epsilon;
        r = call(xp);
        
        for(std::size_t j = 0; j < N; ++j)
        {
            J[j][i] = (r[j]-r0[j])/epsilon;
        }
    }
    return J;
}

/**
In this formulation of the Multi-Dimensional Newton-Raphson solver the Jacobian matrix is known.
Therefore, the dx vector can be obtained from

J(x)dx=-f(x)

for a given value of x.  The pointer to the class FuncWrapperND that is passed in must implement the call() and Jacobian()
functions, each of which take the vector x. The data is managed using std::vector<double> vectors

@param f A pointer to an subclass of the FuncWrapperND class that implements the call() and Jacobian() functions
@param x0 The initial guess value for the solution
@param tol The root-sum-square of the errors from each of the components
@param maxiter The maximum number of iterations
@param errstring  A string with the returned error.  If the length of errstring is zero, no errors were found
@returns If no errors are found, the solution.  Otherwise, _HUGE, the value for infinity
*/
std::vector<double> NDNewtonRaphson_Jacobian(FuncWrapperND *f, std::vector<double> &x0, double tol, int maxiter)
{
    int iter=0;
    f->errstring.clear();
    std::vector<double> f0,v;
    std::vector<std::vector<double> > JJ;
    Eigen::VectorXd r(x0.size());
    Eigen::Matrix2d J(x0.size(), x0.size());
    double error = 999;
    while (iter==0 || std::abs(error)>tol){
        f0 = f->call(x0);
        JJ = f->Jacobian(x0);
        
        for (std::size_t i = 0; i < x0.size(); ++i)
        {
            r(i) = f0[i];
            for (std::size_t j = 0; j < x0.size(); ++j)
            {
                J(i,j) = JJ[i][j];
            }
        }

        Eigen::Vector2d v = J.colPivHouseholderQr().solve(-r);

        // Update the guess
        for (std::size_t i = 0; i<x0.size(); i++){ x0[i] += v(i);}
        
        // Stop if the solution is not changing by more than numerical precision
        if (v.cwiseAbs().maxCoeff() < DBL_EPSILON*100){
            return x0;
        }
        error = root_sum_square(f0);
        if (iter>maxiter){
            f->errstring = "reached maximum number of iterations";
            x0[0] = _HUGE;
        }
        iter++;
    }
    return x0;
}

/**
In the newton function, a 1-D Newton-Raphson solver is implemented using exact solutions.  An initial guess for the solution is provided.

@param f A pointer to an instance of the FuncWrapper1D class that implements the call() function
@param x0 The inital guess for the solution
@param ftol The absolute value of the tolerance accepted for the objective function
@param maxiter Maximum number of iterations
@returns If no errors are found, the solution, otherwise the value _HUGE, the value for infinity
*/
double Newton(FuncWrapper1DWithDeriv* f, double x0, double ftol, int maxiter)
{
    double x, dx, fval=999;
    int iter=1;
    f->errstring.clear();
    x = x0;
    while (iter < 2 || std::abs(fval) > ftol)
    {
        fval = f->call(x);
        dx = -fval/f->deriv(x);

        if (!ValidNumber(fval)){
            throw ValueError("Residual function in newton returned invalid number");
        };

        x += dx;

        if (std::abs(dx/x) < 1e-11){
            return x;
        }

        if (iter>maxiter)
        {
            f->errstring= "reached maximum number of iterations";
            throw SolutionError(format("Newton reached maximum number of iterations"));
        }
        iter=iter+1;
    }
    return x;
}
/**
In the Halley's method solver, two derivatives of the input variable are needed, it yields the following method:

\f[
x_{n+1} = x_n - \frac {2 f(x_n) f'(x_n)} {2 {[f'(x_n)]}^2 - f(x_n) f''(x_n)}
\f]

http://en.wikipedia.org/wiki/Halley%27s_method

@param f A pointer to an instance of the FuncWrapper1DWithTwoDerivs class that implements the call() and two derivatives
@param x0 The inital guess for the solution
@param ftol The absolute value of the tolerance accepted for the objective function
@param maxiter Maximum number of iterations
@returns If no errors are found, the solution, otherwise the value _HUGE, the value for infinity
*/
double Halley(FuncWrapper1DWithTwoDerivs* f, double x0, double ftol, int maxiter)
{
    double x, dx, fval=999, dfdx, d2fdx2;
    int iter=1;
    f->errstring.clear();
    x = x0;
    while (iter < 2 || std::abs(fval) > ftol)
    {
        if (f->input_not_in_range(x)){
            throw ValueError(format("Input [%g] is out of range",x));
        }
        
        fval = f->call(x);
        dfdx = f->deriv(x);
        d2fdx2 = f->second_deriv(x);
        
        if (!ValidNumber(fval)){
            throw ValueError("Residual function in Halley returned invalid number");
        };
        if (!ValidNumber(dfdx)){
            throw ValueError("Derivative function in Halley returned invalid number");
        };
        
        dx = -(2*fval*dfdx)/(2*POW2(dfdx)-fval*d2fdx2);

        x += dx;

        if (std::abs(dx/x) < 10*DBL_EPSILON){
            return x;
        }

        if (iter>maxiter){
            f->errstring= "reached maximum number of iterations";
            throw SolutionError(format("Halley reached maximum number of iterations"));
        }
        iter=iter+1;
    }
    return x;
}

/**
In the secant function, a 1-D Newton-Raphson solver is implemented.  An initial guess for the solution is provided.

@param f A pointer to an instance of the FuncWrapper1D class that implements the call() function
@param x0 The inital guess for the solutionh
@param dx The initial amount that is added to x in order to build the numerical derivative
@param tol The absolute value of the tolerance accepted for the objective function
@param maxiter Maximum number of iterations
@returns If no errors are found, the solution, otherwise the value _HUGE, the value for infinity
*/
double Secant(FuncWrapper1D* f, double x0, double dx, double tol, int maxiter)
{
    #if defined(COOLPROP_DEEP_DEBUG)
    static std::vector<double> xlog, flog;
    xlog.clear(); flog.clear();
    #endif

    double x1=0,x2=0,x3=0,y1=0,y2=0,x,fval=999;
    int iter=1;
    f->errstring.clear();

    if (std::abs(dx)==0){ f->errstring="dx cannot be zero"; return _HUGE;}
    while (iter<=2 || std::abs(fval)>tol)
    {
        if (iter==1){x1=x0; x=x1;}
        if (iter==2){x2=x0+dx; x=x2;}
        if (iter>2) {x=x2;}
        
            if (f->input_not_in_range(x)){
                throw ValueError(format("Input [%g] is out of range",x));
            }

            fval = f->call(x);

            #if defined(COOLPROP_DEEP_DEBUG)
                xlog.push_back(x);
                flog.push_back(fval);
            #endif

            if (!ValidNumber(fval)){
                throw ValueError("Residual function in secant returned invalid number");
            };
        if (iter==1){y1=fval;}
        if (iter>1)
        {
            double deltax = x2-x1;
            if (std::abs(deltax)<1e-14){
                return x;
            }
            y2=fval;
            double deltay = y2-y1;
            if (iter > 2 && std::abs(deltay)<1e-14){
                return x;
            }
            x3=x2-y2/(y2-y1)*(x2-x1);
            y1=y2; x1=x2; x2=x3;

        }
        if (iter>maxiter)
        {
            f->errstring=std::string("reached maximum number of iterations");
            throw SolutionError(format("Secant reached maximum number of iterations"));
        }
        iter=iter+1;
    }
    return x3;
}

/**
In the secant function, a 1-D Newton-Raphson solver is implemented.  An initial guess for the solution is provided.

@param f A pointer to an instance of the FuncWrapper1D class that implements the call() function
@param x0 The inital guess for the solution
{'fraction_non_alphanumeric': 0.11937342455887648, 'fraction_numerical': 0.017764974192773977, 'mean_word_length': 2.5220883534136544, 'pattern_counts': {'":': 0, '<': 64, '<?xml version=': 0, '>': 97, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3549407', 'n_tokens_mistral': 5557, 'n_tokens_neox': 5330, 'n_words': 1746}