Coder Social home page Coder Social logo

kthohr / optim Goto Github PK

View Code? Open in Web Editor NEW
772.0 38.0 130.0 11.99 MB

OptimLib: a lightweight C++ library of numerical optimization methods for nonlinear functions

Home Page: https://optimlib.readthedocs.io/en/latest/

License: Apache License 2.0

Makefile 0.94% C++ 96.74% Shell 2.32%
optim evolutionary-algorithms differential-evolution particle-swarm-optimization bfgs cpp cpp11 lbfgs optimization optimization-algorithms

optim's Introduction

OptimLib   Build Status Coverage Status License Documentation Status

OptimLib is a lightweight C++ library of numerical optimization methods for nonlinear functions.

Features:

  • A C++11/14/17 library of local and global optimization algorithms, as well as root finding techniques.
  • Derivative-free optimization using advanced, parallelized metaheuristic methods.
  • Constrained optimization routines to handle simple box constraints, as well as systems of nonlinear constraints.
  • For fast and efficient matrix-based computation, OptimLib supports the following templated linear algebra libraries:
  • Automatic differentiation functionality is available through use of the Autodiff library
  • OpenMP-accelerated algorithms for parallel computation.
  • Straightforward linking with parallelized BLAS libraries, such as OpenBLAS.
  • Available as a single precision (float) or double precision (double) library.
  • Available as a header-only library, or as a compiled shared library.
  • Released under a permissive, non-GPL license.

Contents:

Algorithms

A list of currently available algorithms includes:

  • Broyden's Method (for root finding)
  • Newton's method, BFGS, and L-BFGS
  • Gradient descent: basic, momentum, Adam, AdaMax, Nadam, NadaMax, and more
  • Nonlinear Conjugate Gradient
  • Nelder-Mead
  • Differential Evolution (DE)
  • Particle Swarm Optimization (PSO)

Documentation

Full documentation is available online:

Documentation Status

A PDF version of the documentation is available here.

API

The OptimLib API follows a relatively simple convention, with most algorithms called in the following manner:

algorithm_id(<initial/final values>, <objective function>, <objective function data>);

The inputs, in order, are:

  • A writable vector of initial values to define the starting point of the algorithm. In the event of successful completion, the initial values will be overwritten by the solution vector.
  • The 'objective function' is the user-defined function to be minimized (or zeroed-out in the case of root finding methods).
  • The final input is optional: it is any object that contains additional parameters necessary to evaluate the objective function.

For example, the BFGS algorithm is called using

bfgs(ColVec_t& init_out_vals, std::function<double (const ColVec_t& vals_inp, ColVec_t* grad_out, void* opt_data)> opt_objfn, void* opt_data);

where ColVec_t is used to represent, e.g., arma::vec or Eigen::VectorXd types.

Installation

OptimLib is available as a compiled shared library, or as header-only library, for Unix-alike systems only (e.g., popular Linux-based distros, as well as macOS). Use of this library with Windows-based systems, with or without MSVC, is not supported.

Requirements

OptimLib requires either the Armadillo or Eigen C++ linear algebra libraries. (Note that Eigen version 3.4.0 requires a C++14-compatible compiler.)

Before including the header files, define one of the following:

#define OPTIM_ENABLE_ARMA_WRAPPERS
#define OPTIM_ENABLE_EIGEN_WRAPPERS

Example:

#define OPTIM_ENABLE_EIGEN_WRAPPERS
#include "optim.hpp"

Installation Method 1: Shared Library

The library can be installed on Unix-alike systems via the standard ./configure && make method.

First clone the library and any necessary submodules:

# clone optim into the current directory
git clone https://github.com/kthohr/optim ./optim

# change directory
cd ./optim

# clone necessary submodules
git submodule update --init

Set (one) of the following environment variables before running configure:

export ARMA_INCLUDE_PATH=/path/to/armadillo
export EIGEN_INCLUDE_PATH=/path/to/eigen

Finally:

# build and install with Eigen
./configure -i "/usr/local" -l eigen -p
make
make install

The final command will install OptimLib into /usr/local.

Configuration options (see ./configure -h):

      Primary

  • -h print help
  • -i installation path; default: the build directory
  • -f floating-point precision mode; default: double
  • -l specify the choice of linear algebra library; choose arma or eigen
  • -m specify the BLAS and Lapack libraries to link with; for example, -m "-lopenblas" or -m "-framework Accelerate"
  • -o compiler optimization options; defaults to -O3 -march=native -ffp-contract=fast -flto -DARMA_NO_DEBUG
  • -p enable OpenMP parallelization features (recommended)

      Secondary

  • -c a coverage build (used with Codecov)
  • -d a 'development' build
  • -g a debugging build (optimization flags set to -O0 -g)

      Special

  • --header-only-version generate a header-only version of OptimLib (see below)

Installation Method 2: Header-only Library

OptimLib is also available as a header-only library (i.e., without the need to compile a shared library). Simply run configure with the --header-only-version option:

./configure --header-only-version

This will create a new directory, header_only_version, containing a copy of OptimLib, modified to work on an inline basis. With this header-only version, simply include the header files (#include "optim.hpp) and set the include path to the head_only_version directory (e.g.,-I/path/to/optimlib/header_only_version).

R Compatibility

To use OptimLib with an R package, first generate a header-only version of the library (see above). Then simply add a compiler definition before including the OptimLib files.

  • For RcppArmadillo:
#define OPTIM_USE_RCPP_ARMADILLO
#include "optim.hpp"
  • For RcppEigen:
#define OPTIM_USE_RCPP_EIGEN
#include "optim.hpp"

Examples

To illustrate OptimLib at work, consider searching for the global minimum of the Ackley function:

Ackley

This is a well-known test function with many local minima. Newton-type methods (such as BFGS) are sensitive to the choice of initial values, and will perform rather poorly here. As such, we will employ a global search method--in this case: Differential Evolution.

Code:

#define OPTIM_ENABLE_EIGEN_WRAPPERS
#include "optim.hpp"
        
#define OPTIM_PI 3.14159265358979

double 
ackley_fn(const Eigen::VectorXd& vals_inp, Eigen::VectorXd* grad_out, void* opt_data)
{
    const double x = vals_inp(0);
    const double y = vals_inp(1);

    const double obj_val = 20 + std::exp(1) - 20*std::exp( -0.2*std::sqrt(0.5*(x*x + y*y)) ) - std::exp( 0.5*(std::cos(2 * OPTIM_PI * x) + std::cos(2 * OPTIM_PI * y)) );
            
    return obj_val;
}
        
int main()
{
    Eigen::VectorXd x = 2.0 * Eigen::VectorXd::Ones(2); // initial values: (2,2)
        
    bool success = optim::de(x, ackley_fn, nullptr);
        
    if (success) {
        std::cout << "de: Ackley test completed successfully." << std::endl;
    } else {
        std::cout << "de: Ackley test completed unsuccessfully." << std::endl;
    }
        
    std::cout << "de: solution to Ackley test:\n" << x << std::endl;
        
    return 0;
}

On x86-based computers, this example can be compiled using:

g++ -Wall -std=c++14 -O3 -march=native -ffp-contract=fast -I/path/to/eigen -I/path/to/optim/include optim_de_ex.cpp -o optim_de_ex.out -L/path/to/optim/lib -loptim

Output:

de: Ackley test completed successfully.
elapsed time: 0.028167s

de: solution to Ackley test:
  -1.2702e-17
  -3.8432e-16

On a standard laptop, OptimLib will compute a solution to within machine precision in a fraction of a second.

The Armadillo-based version of this example:

#define OPTIM_ENABLE_ARMA_WRAPPERS
#include "optim.hpp"
        
#define OPTIM_PI 3.14159265358979

double 
ackley_fn(const arma::vec& vals_inp, arma::vec* grad_out, void* opt_data)
{
    const double x = vals_inp(0);
    const double y = vals_inp(1);

    const double obj_val = 20 + std::exp(1) - 20*std::exp( -0.2*std::sqrt(0.5*(x*x + y*y)) ) - std::exp( 0.5*(std::cos(2 * OPTIM_PI * x) + std::cos(2 * OPTIM_PI * y)) );
            
    return obj_val;
}
        
int main()
{
    arma::vec x = arma::ones(2,1) + 1.0; // initial values: (2,2)
        
    bool success = optim::de(x, ackley_fn, nullptr);
        
    if (success) {
        std::cout << "de: Ackley test completed successfully." << std::endl;
    } else {
        std::cout << "de: Ackley test completed unsuccessfully." << std::endl;
    }
        
    arma::cout << "de: solution to Ackley test:\n" << x << arma::endl;
        
    return 0;
}

Compile and run:

g++ -Wall -std=c++11 -O3 -march=native -ffp-contract=fast -I/path/to/armadillo -I/path/to/optim/include optim_de_ex.cpp -o optim_de_ex.out -L/path/to/optim/lib -loptim
./optim_de_ex.out

Check the /tests directory for additional examples, and https://optimlib.readthedocs.io/en/latest/ for a detailed description of each algorithm.

Logistic regression

For a data-based example, consider maximum likelihood estimation of a logit model, common in statistics and machine learning. In this case we have closed-form expressions for the gradient and hessian. We will employ a popular gradient descent method, Adam (Adaptive Moment Estimation), and compare to a pure Newton-based algorithm.

#define OPTIM_ENABLE_ARMA_WRAPPERS
#include "optim.hpp"

// sigmoid function

inline
arma::mat sigm(const arma::mat& X)
{
    return 1.0 / (1.0 + arma::exp(-X));
}

// log-likelihood function data

struct ll_data_t
{
    arma::vec Y;
    arma::mat X;
};

// log-likelihood function with hessian

double ll_fn_whess(const arma::vec& vals_inp, arma::vec* grad_out, arma::mat* hess_out, void* opt_data)
{
    ll_data_t* objfn_data = reinterpret_cast<ll_data_t*>(opt_data);

    arma::vec Y = objfn_data->Y;
    arma::mat X = objfn_data->X;

    arma::vec mu = sigm(X*vals_inp);

    const double norm_term = static_cast<double>(Y.n_elem);

    const double obj_val = - arma::accu( Y%arma::log(mu) + (1.0-Y)%arma::log(1.0-mu) ) / norm_term;

    //

    if (grad_out)
    {
        *grad_out = X.t() * (mu - Y) / norm_term;
    }

    //

    if (hess_out)
    {
        arma::mat S = arma::diagmat( mu%(1.0-mu) );
        *hess_out = X.t() * S * X / norm_term;
    }

    //

    return obj_val;
}

// log-likelihood function for Adam

double ll_fn(const arma::vec& vals_inp, arma::vec* grad_out, void* opt_data)
{
    return ll_fn_whess(vals_inp,grad_out,nullptr,opt_data);
}

//

int main()
{
    int n_dim = 5;     // dimension of parameter vector
    int n_samp = 4000; // sample length

    arma::mat X = arma::randn(n_samp,n_dim);
    arma::vec theta_0 = 1.0 + 3.0*arma::randu(n_dim,1);

    arma::vec mu = sigm(X*theta_0);

    arma::vec Y(n_samp);

    for (int i=0; i < n_samp; i++)
    {
        Y(i) = ( arma::as_scalar(arma::randu(1)) < mu(i) ) ? 1.0 : 0.0;
    }

    // fn data and initial values

    ll_data_t opt_data;
    opt_data.Y = std::move(Y);
    opt_data.X = std::move(X);

    arma::vec x = arma::ones(n_dim,1) + 1.0; // initial values

    // run Adam-based optim

    optim::algo_settings_t settings;

    settings.gd_method = 6;
    settings.gd_settings.step_size = 0.1;

    std::chrono::time_point<std::chrono::system_clock> start = std::chrono::system_clock::now();

    bool success = optim::gd(x,ll_fn,&opt_data,settings);

    std::chrono::time_point<std::chrono::system_clock> end = std::chrono::system_clock::now();
    std::chrono::duration<double> elapsed_seconds = end-start;

    //

    if (success) {
        std::cout << "Adam: logit_reg test completed successfully.\n"
                  << "elapsed time: " << elapsed_seconds.count() << "s\n";
    } else {
        std::cout << "Adam: logit_reg test completed unsuccessfully." << std::endl;
    }

    arma::cout << "\nAdam: true values vs estimates:\n" << arma::join_rows(theta_0,x) << arma::endl;

    //
    // run Newton-based optim

    x = arma::ones(n_dim,1) + 1.0; // initial values

    start = std::chrono::system_clock::now();

    success = optim::newton(x,ll_fn_whess,&opt_data);

    end = std::chrono::system_clock::now();
    elapsed_seconds = end-start;

    //

    if (success) {
        std::cout << "newton: logit_reg test completed successfully.\n"
                  << "elapsed time: " << elapsed_seconds.count() << "s\n";
    } else {
        std::cout << "newton: logit_reg test completed unsuccessfully." << std::endl;
    }

    arma::cout << "\nnewton: true values vs estimates:\n" << arma::join_rows(theta_0,x) << arma::endl;

    return 0;
}

Output:

Adam: logit_reg test completed successfully.
elapsed time: 0.025128s

Adam: true values vs estimates:
   2.7850   2.6993
   3.6561   3.6798
   2.3379   2.3860
   2.3167   2.4313
   2.2465   2.3064

newton: logit_reg test completed successfully.
elapsed time: 0.255909s

newton: true values vs estimates:
   2.7850   2.6993
   3.6561   3.6798
   2.3379   2.3860
   2.3167   2.4313
   2.2465   2.3064

Automatic Differentiation

By combining Eigen with the Autodiff library, OptimLib provides experimental support for automatic differentiation.

Example using forward-mode automatic differentiation with BFGS for the Sphere function:

#define OPTIM_ENABLE_EIGEN_WRAPPERS
#include "optim.hpp"

#include <autodiff/forward/real.hpp>
#include <autodiff/forward/real/eigen.hpp>

//

autodiff::real
opt_fnd(const autodiff::ArrayXreal& x)
{
    return x.cwiseProduct(x).sum();
}

double
opt_fn(const Eigen::VectorXd& x, Eigen::VectorXd* grad_out, void* opt_data)
{
    autodiff::real u;
    autodiff::ArrayXreal xd = x.eval();

    if (grad_out) {
        Eigen::VectorXd grad_tmp = autodiff::gradient(opt_fnd, autodiff::wrt(xd), autodiff::at(xd), u);

        *grad_out = grad_tmp;
    } else {
        u = opt_fnd(xd);
    }

    return u.val();
}

int main()
{
    Eigen::VectorXd x(5);
    x << 1, 2, 3, 4, 5;

    bool success = optim::bfgs(x, opt_fn, nullptr);

    if (success) {
        std::cout << "bfgs: forward-mode autodiff test completed successfully.\n" << std::endl;
    } else {
        std::cout << "bfgs: forward-mode autodiff test completed unsuccessfully.\n" << std::endl;
    }

    std::cout << "solution: x = \n" << x << std::endl;

    return 0;
}

Compile with:

g++ -Wall -std=c++17 -O3 -march=native -ffp-contract=fast -I/path/to/eigen -I/path/to/autodiff -I/path/to/optim/include optim_autodiff_ex.cpp -o optim_autodiff_ex.out -L/path/to/optim/lib -loptim

See the documentation for more details on this topic.

Author

Keith O'Hara

License

Apache Version 2

optim's People

Contributors

basilegraf avatar chazeon avatar kthohr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

optim's Issues

Header-Only-Version Internal Namespace

I've only been using this library for a couple of days (and enjoying it so far), but I ran into an issue during integration that I didn't see in a quick scan here on github. I wanted to use a header only version of the library for quick integration into an existing codebase, but ran into a bunch of 'identifier not found' compiler errors.

After a little bit of inspection, the problem seemed to be that the configure script removes the internal:: namespace labels from everywhere in the library, which causes most of the internal functions in the script to disassociate from their forward declarations.

For example, look at line_search_mt in more_thuente.hpp. This calls mt_step in several places, with no internal namespace prefix. When line_search_mt is correctly defined as being in the internal namespace, the compiler correctly infers that mt_step is also in the internal namespace. However, by killing the internal:: from the definition, the compiler won't be looking in the right namespace for its forward declarations.

Fortunately, I found an easy fix for this: remove the replacement of internal:: from the sed in the header-only-version part of the configure script, so that it reads as follows.
sed -e '1,/\[OPTIM_BEGIN\]/ d' $WDIR/src/"$dir_"/"$file_".cpp | sed -e "s|optimlib_inline|inline|" -e "s|optim::||" >> "$file_".hpp

Boundaries do not work

I have a number of initial parameters. For each one I have specified an upper and lower boundary.When the algorithm is complete some results are outside the boundaries.

` optim::algo_settings_t settings;

arma::vec lb = {-1,-1, -2,-2,-2,  -2,-2,-2};
arma::vec ub = {1,1,    2,2,2,     2,2,2, };
settings.pso_initial_lb = lb;
settings.pso_initial_ub = ub;
settings.pso_n_gen = 1000;

bool success = optim::pso(x, optimF,&optim_data,settings);`

Same when i use "de"

PSO center_particle

First, I would like to thank you for making this library available.

However, I was trying to use the PSO method with upper and lower bounds.
For example, the Ackley function with

X= [0.75 , 0.75]
Lower = [0.5, 0.5]
Upper = [1, 1]

After some tests I understood that I should send the pso_settings.initial_ub and pso_settings.initial_lb, because the default broke the bound limits. So that was not a big issue. (I used 0.05 instead of 0.5)

However, I think the center_particle option is a big issue with the bounds (At least in the initialize loop).
In line 147

 P.row(i) = BMO_MATOPS_COLWISE_SUM( BMO_MATOPS_MIDDLE_ROWS(P, 0, n_pop-2) ) / static_cast<fp_t>(n_pop-1); // center vector

It gets the center position of the particles using matrix P.
However, in line 162

if (vals_bound) {
      P.row(i) = transform<RowVec_t>(P.row(i), bounds_type, lower_bounds, upper_bounds);
}

The lines of P are rewritten with some values that are not inside the bounds.
So the center vector is not inside as well.

With the center_particle activated the results are very odd. After I deactivated it, the result is always good.

Header-only version doesn't work with Eigen 3.3.9

Hi,

The header-only version doesn't seem to work with Eigen 3.3.9. gcc prints two errors:

/home/dburov/.local/include/optimlib/unconstrained/nm.hpp: In function ‘bool optim::internal::nm_impl(optim::Vec_t&, std::function<double(const Eigen::Matrix<double, -1, 1>&, Eigen::Matrix<double, -1, 1>*, void*)>, void*, optim::algo_settings_t*)’:
/home/dburov/.local/include/optimlib/unconstrained/nm.hpp:202:69: error: no match for call to ‘(optim::Vec_t {aka Eigen::Matrix<double, -1, 1>}) (optim::VecInt_t&)’
  202 |         simplex_fn_vals = OPTIM_MATOPS_EVAL(simplex_fn_vals(sort_vec));

and

/home/dburov/.local/include/optimlib/misc/matrix_ops/access.hpp:35:50: error: ‘all’ is not a member of ‘Eigen’
   35 |     #define OPTIM_MATOPS_ROWS(x, v) (x)(v,Eigen::all) // v is a vector

The second error is relatively well-known: all is only defined in Eigen's master branch (maybe the latest RC) but not in the latest stable version, which currently is 3.3.9.

The first one is not quite clear to me. It seems like it's trying to convert vector of ints into an int, and fails (output from one of the candidates):

include/eigen3/Eigen/src/Core/DenseCoeffsBase.h:178:22: note:   no known conversion for argument 1 from ‘optim::VecInt_t’ {aka ‘Eigen::Matrix<int, -1, 1>’} to ‘Eigen::Index’ {aka ‘long int’}
  178 |     operator()(Index index) const

Unrelated, is there any way to NOT use Eigen or Arma? Those are horrible, clumsy, bloated libraries that I try to avoid like the plague. Thanks!

Metaheuristic Optimization (DE, PSO) do not preserve vals_bound

Setting Optim::algo_settings_t::vals_bound = true and setting lower_bounds & upper_bounds works well with ::ne() optimizer. The values are correctly resticted within the ranges defined.

Changeing optimizer to ::de() or ::pso() leads to results which are far out of the bounds defined. For example some values are restricted to 0.0 .. 1.0 range and results are in negative part.

Should ::de() & ::pso() preserve the limits? Are there some special requirements for that?

Using OptimLib as header only. Set-up with CMake

Hi!

Thank you for your code. I would really like to test use some of your implementations in my software. However, I am struggling to link your library. If you have time please take a look at my following CMake files:

cmake_minimum_required (VERSION 2.8.8)

# set the project name and version
project(local-order-parameter)
# set the custom modules path
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/Modules/")

#add_definitions(-DOPTIM_ENABLE_EIGEN_WRAPPERS)
# resolve dependencies
find_package(Git REQUIRED)
find_package(MPI REQUIRED)
if (MPI_FOUND)
    message("MPI found!")
else (MPI_FOUND)
    message(SEND_ERROR "This application cannot compile without MPI")
endif (MPI_FOUND)
# fetch external dependencies
include(FetchEigen)
include(FetchOptim)

include_directories(${CMAKE_SOURCE_DIR}/src)
include_directories(${CMAKE_SOURCE_DIR}/include)
include_directories(${MPI_INCLUDE_PATH})
include_directories(${MPI_CXX_INCLUDE_PATH})
add_definitions(${MPI_CXX_COMPILE_FLAGS})

set(CMAKE_CXX_STANDARD 11)
add_executable(GeM
    src/main.cpp
    src/Pattern.cpp
    )
add_dependencies(GeM eigen)
add_dependencies(GeM optim)
target_link_libraries(GeM ${MPI_CXX_LIBRARIES})

Fetching is done in the following way:

set(OPTIM_REPOSITORY "https://github.com/kthohr/optim.git")
set(OPTIM_TAG master)
include(ExternalProject)
ExternalProject_Add(optim
DOWNLOAD_COMMAND ${GIT_EXECUTABLE} clone --branch=${OPTIM_TAG} ${OPTIM_REPOSITORY}
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
BUILD_COMMAND ${CMAKE_COMMAND} -E copy_directory
<SOURCE_DIR>/include ${CMAKE_CURRENT_SOURCE_DIR}/include/optim
INSTALL_COMMAND ""
LOG_DOWNLOAD ON
LOG_UPDATE ON

Unfortunately, when I run a script with

#define OPTIM_ENABLE_EIGEN_WRAPPERS
#include "optim/optim.hpp"

using any function, e.g. optim::cg(), I receive the following error:

Undefined symbols for architecture x86_64:
  "optim::cg(Eigen::Matrix<double, -1, 1, 0, -1, 1>&, std::__1::function<double (Eigen::Matrix<double, -1, 1, 0, -1, 1> const&, Eigen::Matrix<double, -1, 1, 0, -1, 1>*, void*)>, void*)", referenced from:
      _main in main.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [GeM] Error 1
make[1]: *** [CMakeFiles/GeM.dir/all] Error 2
make: *** [all] Error 2

bfgs with approximate numerical gradient?

Hi,

Is it possible to perform bfgs without known the explicit expression of the derivative? In other words, derivatives are approximated numerically.

Thank you,
Tao

PSO parameter bounds causes error

I‘m really a newbie to c++/Rcpp. Thus, I‘m not sure what causes my problem. I'm running a simulation in Rcpp using PSO to optimize parameter of an ode system in order to match my measured data.
If I use the PSO with an unbounded parameter space everything works fine. However, if the parameter space is restricted part of the parameter passed to the objective function are “nan“. Any suggestion what the problem could be?

Many thanks in advance for your help.

Compiler issue using Eigen Wrappers

Hello,

I happen to have the following issue when I try to compile the library using Eigen.
I have the same issue if I try to compile the header-only or the shared-library.

It looks like there is a mismatch with Eigen and optim.

I am using Eigen 3.3.4 version.

/home/user/project/src/../header_only_version/unconstrained/nm.hpp:202:69 error: no match for call to ‘(optim::Vec_t {aka Eigen::Matrix<double, -1, 1>}) (optim::VecInt_t&)’
         simplex_fn_vals = OPTIM_MATOPS_EVAL(simplex_fn_vals(sort_vec));

/home/user/project/src/../header_only_version/misc/matrix_ops/eval.hpp:30:35: note: in definition of macro ‘OPTIM_MATOPS_EVAL’
     #define OPTIM_MATOPS_EVAL(x) (x).eval()
                                   ^
In file included from /usr/include/eigen3/Eigen/Core:414:0,
                 from /usr/include/eigen3/Eigen/StdVector:14,
                 from /usr/include/pcl-1.8/pcl/point_cloud.h:46,
                 from /usr/include/pcl-1.8/pcl/io/pcd_io.h:43,
                 from /home/kfavre/git_repository/3d-vision/recalage/PCL/mutual_information/src/mutual_information.cpp:12:
/usr/include/eigen3/Eigen/src/Core/DenseCoeffsBase.h:115:41: note: candidate: Eigen::DenseCoeffsBase<Derived, 0>::CoeffReturnType Eigen::DenseCoeffsBase<Derived, 0>::operator()(Eigen::Index, Eigen::Index) const [with Derived = Eigen::Matrix<double, -1, 1>; Eigen::DenseCoeffsBase<Derived, 0>::CoeffReturnType = const double&; Eigen::Index = long int]
     EIGEN_STRONG_INLINE CoeffReturnType operator()(Index row, Index col) const


etc....


/home/user/project/src/../header_only_version/misc/matrix_ops/access.hpp:35:50: error: ‘all’ is not a member of ‘Eigen’
     #define OPTIM_MATOPS_ROWS(x, v) (x)(v,Eigen::all) // v is a vector
                                                  ^
/home/user/project/src/../header_only_version/misc/matrix_ops/eval.hpp:30:35: note: in definition of macro ‘OPTIM_MATOPS_EVAL’
     #define OPTIM_MATOPS_EVAL(x) (x).eval()

Here is the code that I want to execute (which is pretty simple):

#define OPTIM_ENABLE_EIGEN_WRAPPERS
#include "../header_only_version/optim.hpp"
  double ackley_fn(const Eigen::VectorXd& vals_inp, Eigen::VectorXd* grad_out, void* opt_data)
  {
      const double x = vals_inp(0);
      const double y = vals_inp(1);

      double obj_val = -20*std::exp( -0.2*std::sqrt(0.5*(x*x + y*y)) ) - std::exp( 0.5*(std::cos(2*M_PI*x) + std::cos(2*M_PI*y)) ) + 22.718282L;

      return obj_val;
  }

int main (int argc, char** argv)
{
// initial values:
		Eigen::VectorXd x = Eigen::VectorXd::Zero(2,1); // (2,2)
		x[0] = 1.3;
		x[1] = 1.4;

	    bool success = optim::de(x,ackley_fn,nullptr);
            std::cout << "\nde: solution to Ackley test:\n" << x << std::endl;
}

Do not hesitate to ask if I can give any more precisions.
Thank you in advance for your help!

Building Error

I build OpenBlas 0.3.3 from sourceforge through cmake on Win7. But when building optim, There are 16 unresolved external symbols.

logit_reg.obj: error: LNK2001: unresolved external symbol dgesv
bfgs.obj: error: LNK2001: unresolved external symbol dposv_
lbfgs.obj: error: LNK2001: unresolved external symbol dgesdd_
D:\Project\Opti\Opti\optim\Bin\optim.exe: error: LNK1120: 16 unresolved external symbol_

Error in header-only-library

After configuring to header-only-library version, there are include path errors in misc/optim_misc.hpp.

Currently, the first two includes are

// structs
#include "misc/optim_structs.hpp"

// trace
#include "misc/optim_trace.hpp"

Which gives include errors when compiling. The errors are fixed by changing these lines to:

// structs
#include "optim_structs.hpp"

// trace
#include "optim_trace.hpp"

error configure header-only

When i try to create the Header-only Library i get this error: "error: unrecognized linear algebra library". Eigen is installed.
I installed the eigen library 3.4.0 via cmake/make install on debian. Eigen exist in folder /usr/local/include/eigen3/
Any idea to solve the problem? Thanks.

Add basic example for Eigen

The Ackley function example in the readme is very helpful for testing a fresh installation and getting started. Especially for people who have never used Armadillo before.

It would be nice to have something for Eigen as well. A simple example, without autodiff. Maybe even an equivalent Ackley function example but with Eigen?

Can not install the package successfully

local@MacBook-Pro optim % ./configure -l arma -p

OptimLib Configuration

Summary:

  • OS: darwin19

  • C++ compiler: g++

  • Build version: release

  • OPTIM_LINEAR_ALG_LIB set to: arma

  • OPTIM_MATLIB_INCLUDE_PATH set to:
    /Users/local/armadillo-code

  • BLAS and Lapack libraries set to:
    -framework Accelerate

  • OpenMP features: enabled

  • optimization flags:
    -O3 -march=native -ffp-contract=fast -flto -DNDEBUG -fopenmp

  • OptimLib install path:
    /Users/local/optim

  • Additional notes:

Configuration completed. Creating Makefile... done.

local@MacBook-Pro optim % make
g++ -std=c++11 -Wall -O3 -march=native -ffp-contract=fast -flto -DNDEBUG -fopenmp -DOPTIM_ENABLE_ARMA_WRAPPERS -DARMA_NO_DEBUG -I/Users/local/armadillo-code -I./include src/line_search/more_thuente.cpp -c -o src/line_search/more_thuente.o`

I am currently working on some constraint quadratic optimization problem and just try to install your repo on my Mac. However, when i tried to install it, there are some error message about
"clang: error: unsupported option '-fopenmp'
make: *** [src/line_search/more_thuente.o] Error 1".

It will be really helpful if you could help me take a look or give me any guidance. Thanks so much for your time and looking forward to hearing from you.

preconditioning

May I know the possibility to extend some implemented methods with preconditioning?

compilation probleme due to include path

Hi,

I'm trying to install optim-master and I got the following error after the make command :

g++ -std=c++14 -Wall -fPIC -march=native -O3 -ffp-contract=fast -flto -DNDEBUG -fopenmp -DOPTIM_FPN_TYPE=double -DOPTIM_ENABLE_EIGEN_WRAPPERS -I/usr/include/eigen3 -I./include src/line_search/more_thuente.cpp -c -o src/line_search/more_thuente.o
In file included from src/line_search/more_thuente.cpp:27:
./include/optim.hpp:28:14: fatal error: BaseMatrixOps/include/BaseMatrixOps.hpp: Aucun fichier ou dossier de ce type
#include "BaseMatrixOps/include/BaseMatrixOps.hpp"
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
make: *** [Makefile:54: src/line_search/more_thuente.o] Error 1

I used the configure method and everything seems to be fine before :

~/Outils/optim-master$ ./configure -i "/home/d07876/Outils/optim-master" -l eigen -p

OptimLib Configuration

Summary:

  • OS: linux-gnu

  • Arch: x86_64

  • C++ compiler: g++

  • Build version: release

  • OPTIM_LINEAR_ALG_LIB set to: eigen

  • OPTIM_MATLIB_INCLUDE_PATH set to:
    /usr/include/eigen3

  • BLAS and Lapack libraries set to:
    -lblas -llapack

  • OpenMP features: enabled

  • floating-point number type: double

  • optimization flags:
    -fPIC -march=native -O3 -ffp-contract=fast -flto -DNDEBUG -fopenmp

  • OptimLib install path:
    /home/d07876/Outils/optim-master

  • Additional notes:

Configuration completed. Creating Makefile... done.

Could you tell me if I missed something during the installation
Thank you

How to use the library with real dynamic systems or async calls

I'm trying to use this library with real dynamics systems, right now I'm facing a problem to use the API with this type of systems, because It the "optimized function" depends of a real hardware that takes time to answer and give a feedback for the next interaction. There is any plan to accomplish such thing with this library ?

"err" not being updated

Hi,

I have observed that in optim/src/unconstrained/pso.cpp, in its loop line 143, the variable "err" is not being updated. This cause err_tol value inoperative, thus the loop never stops if error becomes less than err_tol. I assume it should be updated at line 201 by the following line:

err = global_best_val;

Please check and correct me if I am wrong. I have tried this and now err_tol values have an impact on the loop. I doubt, this issue is present in other algorithms too.

Parallelization only part-time

Hello,

when I want multithreaded parallel function evaluations for 8 Threads i do this:
#define OPTIM_USE_OMP
omp_set_dynamic(false); // omp setting
omp_set_num_threads(8); // omp setting

I have very expensive functions and some parameters take much longer than others. The problem is that often not all threads are used. Overall, this makes the optimization much longer because the CPU is often only used to 1/8 of its capacity. Therefore the effect of parallelization is only part-time.
It gives the impression that the parallelization is interrupted as soon as a "slow function execution" occurs in the overall process. As if the execution of new threads would have to wait.

What is the reason for this and is there a possibility that all 8 threads are always used and therefore the cpu is used at full capacity? This would significantly accelerate the total optimisation process.

Greetings

cannot build it with eigen

./configure -i "usr/local" -l eigen -p
return
Summary:

  • OS: linux-gnu

  • C++ compiler: g++

  • Build version: release

  • OPTIM_LINEAR_ALG_LIB set to: eigen

  • OPTIM_MATLIB_INCLUDE_PATH set to:

  • BLAS and Lapack libraries set to:
    -lblas -llapack

  • OpenMP features: enabled

  • optimization flags:
    -fPIC -O3 -march=native -ffp-contract=fast -flto -DNDEBUG -fopenmp

  • OptimLib install path:
    usr/local

  • Additional notes:

Configuration completed. Creating Makefile... done.

but when I run make, it fails, return
g++ -std=c++11 -Wall -fPIC -O3 -march=native -ffp-contract=fast -flto -DNDEBUG -fopenmp -DOPTIM_ENABLE_EIGEN_WRAPPERS -I -I./include src/line_search/more_thuente.cpp -c -o src/line_search/more_thuente.o
src/line_search/more_thuente.cpp:27:10: fatal error: optim.hpp: no such file
#include "optim.hpp"
^~~~~~~~~~~
compilation terminated.
make: *** [Makefile:54:src/line_search/more_thuente.o]

How do we disable the transforming of bounds/parameters (LBFGS with val_bounds)

Ive noticed theres a (log) transformation of the bounds which causes my parameters to become negative, whereby my parameters are strictly positive and Ive implemented this transformation external to the optmizer.
In lbfgs.hpp

// Line 200
    if (vals_bound) { // should we transform the parameters?
        x = transform(x, bounds_type, lower_bounds, upper_bounds);
    }

I mean sure, I could comment it out, but is there an external way to disable this? without having to change the source code?
Thanks

feature request: custom initialization of simplex for Nelder-Mead

Hi!

I would like to be able to provide an initial simplex where I can consider some background information that I have about the optimization problem. I would also like to be able to stop the optimization, continue another optimization somewhere else and then pick up where I left, continuing from the last simplex.
Would you consider implementing this?
Otherwise I can fork the library and do it myself but it would be nicer to work with the official version :)

Hessian at the optimal point

Hi,

If the objective function doesn't define a hessian (neither a gradiant eventually), is there a way to get an approximate of the hessian matrix at the optimal point?

Best regards

Different optimization results

Hello,

I've faced a problem trying to optimize my cost function with the NM optimizer. The problem is that most of the time it returns true results, but sometimes they are wrong (still small but not right). I'm sure that the input data is the same (checked with hash functions) and I've set random seeds of both std and arma to 0 just to be sure. I have a guess that it somehow related to the fact that my cost function is really rough and there may take place a rounding error. How can I overcome the problem?

Thank you in advance!

Passing "optim::algo_settings_t" object makes the optimizer crash

Hi,

First I'd like to thank you for creating such a wonderful library. I have created a simple example to learn how to use your library the right way. For example, I tried to estimate the parameters of the quadratic function y = 2 * x ^ 2 - 3 * x + 7 So the weights should be estimated as [2 -3 7]

When I use the line bool success = optim::bfgs(w, quadratic, &data); everything seems to be working correctly and the weights are estimated as expected. Yet when I try to manipulate the optimization settings by simply using the block below

optim::algo_settings_t settings;
settings.iter_max = 500;
bool success = optim::bfgs(w, quadratic, &data, settings);

the program crashes without even returning a success flag. The following is the code I have written. I would very much appreciate your help.

Thanks,
Davar

#include "optim.hpp"
#include <iostream> 

using std::cout;
using std::endl;
using std::vector;

struct Data {
    arma::vec x;
    arma::vec y;
};

double quadratic(const arma::vec& w, arma::vec* grad, void* opt_data) {

    Data* data = reinterpret_cast<Data*>(opt_data);
    arma::vec x = data->x;
    arma::vec y = data->y;

    double f = 0;
    (*grad)(0) = (*grad)(1) = (*grad)(2) = 0;

    for (int i = 0; i < x.n_elem; i++) {

        double t = y(i) - (w(0) * pow(x(i), 2) + w(1) * x(i) + w(2));
        f += pow(t, 2);

        (*grad)(0) += -2 * pow(x(i), 2) * t;
        (*grad)(1) += -2 * x(i) * t;
        (*grad)(2) += -2 * t;

    }

    return f;
}

int main(){

    int numOfObservations = 100;
    arma::vec x(numOfObservations, arma::fill::randn);
    arma::vec y(numOfObservations);
    for (int i = 0; i < numOfObservations; i++) {
        y(i) = 2 * pow(x[i], 2) - 3 * x[i] + 7;
    }
    Data data;
    data.x = std::move(x);
    data.y = std::move(y);

    int numOfDims = 3;
    arma::vec w(numOfDims, arma::fill::zeros);

    bool success = optim::bfgs(w, quadratic, &data);

    //optim::algo_settings_t settings;
    //settings.iter_max = 500;
    //bool success = optim::bfgs(w, quadratic, &data, settings);

    cout << "success = " << success << " --> w = " << w.t() << endl;

    return 0;
}


Wrapping optimLib to an Rcpp/RcppArmadillo R package

Hi,

I have being installing your library with no difficulty on a Linux/Ubuntu system and manage to run both examples (Ackley's function and logistic regression) : thank you very much for your work.

Now, I would like to access optim for developing R packages with Rcpp/RcppArmadillo. I am thus trying to wrap your library to R via an R package, in an attempt that can be found there. I hope it is ok to you.

To do that, I put the headers of optim into inst/include/ and the cpp files into src/. Then I tried to link everything in the src/Makevars files, and the package installation (including compilation of optim) is fine (at least, the package can be installed). The Makevars can be found there :

https://github.com/jchiquet/optimLibR/blob/414015b08a5e316de17b1e0b5385718abd23da6a/src/Makevars#L1-L41

Then I tried to create two small Rcpp functions for both Ackley and logit examples, starting with the following lines

// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::plugins(cpp11)]]
#define USE_RCPP_ARMADILLO
#include "optim.hpp"

However, when I call the corresponding R functions, I get the following Armadillo errors in R which I do not have wheh running them in 'pure' C++ (I am pretty sure it is not a syntax problem, the Rcpp code and the original C++ code are hopefully identical, except for the headers).

> library(optimLibR)
> ackley_function()

error: arma::memory::acquire(): out of memory
> library(optimLibR)
> logit_optimLib()

error: Mat::init(): requested size is not compatible with column vector layout

If you could have a quick glance, at least to check that the flag and libs in the Makevars are correctly set for optimr equirements, it would help a lot and I would be happy to use your library in my future R packages.

Thanks for your time

Error of example in the document

Hello I want to implement the constrained function but there seem to be some errors in the document. In that case, I don't know how to implement the constrained problem. Could anyone help fix it?

Build fail on msys2

Following the guide, make fails.

$ make
g++ -std=c++11 -Wall -march=native -O3 -ffp-contract=fast -flto -DNDEBUG -fopenmp -DOPTIM_ENABLE_ARMA_WRAPPERS -DARMA_NO_DEBUG -I/mingw64/include -I./include src/line_search/more_thuente.cpp -c -o src/line_search/more_thuente.o
In file included from /mingw64/include/armadillo:68,
                 from ./include/misc/optim_options.hpp:78,
                 from ./include/optim.hpp:24,
                 from src/line_search/more_thuente.cpp:27:
/mingw64/include/armadillo_bits/compiler_setup.hpp:81:30: fatal error: C:/msys64/mingw64/include/hdf5.h: No such file or directory
   81 | #define ARMA_INCFILE_WRAP(x) <x>
      |                              ^
compilation terminated.
make: *** [Makefile:54: src/line_search/more_thuente.o] Error 1

Seems to be the same as msys2/MINGW-packages#6715

All packages up to date on msys.

Levenberg Marquardt algorithm implementation

Hi,

I'm trying to collect info on different numerical optimization libraries in C++ and I just came across yours.
Do you have an implementation of the Levenberg Marquardt algorithm in your library?

Thank you

Last step of GD leads to crash (eigen version)

The problem is in "error_reporting.ipp", line 80

//settings_inp->opt_fn_value     = opt_objfn(x_p,nullptr,opt_data);

https://drive.google.com/file/d/1XyAOyllOcnY3q10nHETtd6gvrWqGU4ov/view?usp=sharing
https://drive.google.com/file/d/12qemu3_UEhJGcZ21mwypk5RPIFuXCXgf/view?usp=sharing

Seems something was "std::moved" out of memory. Probably this is Eigen problem but may be you can work around it.

Ubuntu 21.10.
PS: could provide the full source if needed
Btw: many thanks for the library )

Add per-iteration best-fit result reporting

I wondered if you’d have any suggestions as to how to report the best guess at each iteration of the fitting loop for your NelderMead implementation? I'm interested for the purpose of investigating how our solution space is being explored but simply reporting simplex_points.row(0) (from my understanding that is the current lowest-error guess?) does not appear to yield the same results that are returned for the final iteration at the end of the method.

How easy would a feature that enables this diagnostic ability be to implement?

NM Eigen Aliasing Bug

See line 149 of nm.cpp which currently reads as follows.
simplex_points = OPTIM_MATOPS_ROWS(simplex_points, sort_vec);

If using Eigen as a linear algebra library, this presents an aliasing problem, which makes the result of this operation dramatically incorrect. For example, try it with the Booth demo listed in the documentation. It will give something like (0,0.25), far away from the correct (1,3).

Fortunately, there's a pretty easy fix. Just add an eval to the line as follows to force Eigen to behave as expected.
simplex_points = OPTIM_MATOPS_EVAL(OPTIM_MATOPS_ROWS(simplex_points, sort_vec));

Getting error on MSVC - optim_options.hpp

Hello,

Trying to compile the examples in VS 2022, C++17. Geting error C1017 - Invalid integer constant expression in optim_options.hpp at line 78.
The error is somewhere in this block. Based on MS documentation about this error at C1017
it says : Constants defined using #define must have values that evaluate to an integer constant if they are used in an #if, #elif, or #else directive.
Any idea how to fix this?

Thank you.

// floating point number type

#ifndef OPTIM_FPN_TYPE
#define OPTIM_FPN_TYPE double
#endif

#if OPTIM_FPN_TYPE == float //this is line 78
#undef OPTIM_FPN_SMALL_NUMBER
#define OPTIM_FPN_SMALL_NUMBER fp_t(1e-05)
#elif OPTIM_FPN_TYPE == double
#undef OPTIM_FPN_SMALL_NUMBER
#define OPTIM_FPN_SMALL_NUMBER fp_t(1e-08)
#else
#error floating-point number type must be 'float' or 'double'
#endif

Incorrect value transfer

If I pass an Arma::vector (init_vals) to an optimization function with zeros only, values unequal to zero are passed.
There are values like 0.02678 etc.

Cannot build Header Only

Hi, I was just going to try this library and got this error:
$ ./configure --header-only-version
sed: can't read optim-master/src/unconstrained/optim_unconstrained.cpp: No such file or directory
sed: can't read optim-master/src/zeros/optim_zeros.cpp: No such file or directory

Incorrect sampling bounds?

X_next.row(i) = OPTIM_MATOPS_TRANSPOSE( OPTIM_MATOPS_HADAMARD_PROD( (par_initial_lb + (par_initial_ub - par_initial_lb)), OPTIM_MATOPS_RANDU_VEC(n_vals) ) );

Unless I'm misreading something, it seems like the sampling bounds for DE are currently (0, (LB + (UB-LB))) = (0, UB) (while they should be (LB, UB) obviously). I think line 99 should be

        X_next.row(i) = OPTIM_MATOPS_TRANSPOSE( par_initial_lb + OPTIM_MATOPS_HADAMARD_PROD( par_initial_ub - par_initial_lb, OPTIM_MATOPS_RANDU_VEC(n_vals) ) );

In addition, it'd be safer to enforce par_initial_ub =< upper_bound and par_initial_lb >= lower_bound if users are using upper and lower bounds. I'm getting NaN errors with non-zero upper and lower bounds after X_next is log-transformed for box constraining.

Use on Windows

Is there a possibility to use the library on Windows ?
I have built a header only version on a Linux system with the command "./configure --header-only-version". I copied it to Windows and want to use it now. With the compiler msvc2015.
I also have Armadillo only as a header only variant. This is also in the program directory of my software.

How do I get OptimLib to use Armadillo from the same workdirectory and get it running in general ?

Since there is no DLL or LIB file available, the library should be included everywhere and compiler independent.

BaseMatrixOps is empty when installing header files only

When trying to install with header files only, the directory BaseMatrixOps is empty. The following shell command demonstrates the issue, since the last ls statement shows that the directory is empty.

git clone https://github.com/kthohr/optim.git && cd optim && \
./configure --header-only-version && ls header_only_version/BaseMatrixOps

This further causes the following error when trying to compile with #include "optim.hpp"

fatal error: 'BaseMatrixOps/include/BaseMatrixOps.hpp' file not found
#include "BaseMatrixOps/include/BaseMatrixOps.hpp"
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Presumably the error message occurs because of this line, i.e., optim.hpp requires the BaseMatrixOps directory to not be empty.

#include "BaseMatrixOps/include/BaseMatrixOps.hpp"

Draw optimization path

Hello,
Would you please consider adding a function that will draw the optimization path?
Thank you for reading.

settings parameters not working

Hi,

I am running your example of pso with bounded values. I have notices that if I set:

settings.iter_max = 1;
settings.err_tol = 1000;
settings.opt_iter = 1;

Nothing works. The algorithm still runs for iterations more than 1, and it reaches the global minimum (when correct upper and lower bounds are set). I would like to stop the optimization loop at specific number of iterations. Can you help in this please?

Nelder-Mead example not available in examples or in documentation

Hello, I would like to use this library to optimize a non-linear function with the opt_data feature to be passed as arguments to the function using Nelder-Mead. I could not find any example for it here. Since I'm a newbie in c++, I wasn't able to replicate it by seeing other examples in the library. Can someone help me here?

Using header-only-version with Eigen failed to compile

System: macOS
Compile cmd: g++ -DOPTIM_ENABLE_EIGEN_WRAPPERS --std=c++11 aa.cpp -I./header_only_version/ -I ./eigen-3.3.8/

compiler output:
In file included from aa.cpp:1:
In file included from ./header_only_version/optim.hpp:51:
./header_only_version/unconstrained/nm.hpp:201:45: error: no matching function for call to object of type 'optim::Vec_t' (aka 'Matrix<double, Dynamic, 1>')
simplex_fn_vals = OPTIM_MATOPS_EVAL(simplex_fn_vals(sort_vec));
^~~~~~~~~~~~~~~
./header_only_version/misc/matrix_ops/eval.hpp:30:35: note: expanded from macro 'OPTIM_MATOPS_EVAL'
#define OPTIM_MATOPS_EVAL(x) (x).eval()
^
./eigen-3.3.8/Eigen/src/Core/DenseCoeffsBase.h:423:5: note: candidate function not viable: no known conversion from 'optim::VecInt_t' (aka 'Matrix<int, Dynamic, 1>') to 'Eigen::Index' (aka 'long') for 1st argument
operator()(Index index)
^
./eigen-3.3.8/Eigen/src/Core/DenseCoeffsBase.h:178:5: note: candidate function not viable: no known conversion from 'optim::VecInt_t' (aka 'Matrix<int, Dynamic, 1>') to 'Eigen::Index' (aka 'long') for 1st argument
operator()(Index index) const
^
./eigen-3.3.8/Eigen/src/Core/DenseCoeffsBase.h:115:41: note: candidate function not viable: requires 2 arguments, but 1 was provided
EIGEN_STRONG_INLINE CoeffReturnType operator()(Index row, Index col) const
^
./eigen-3.3.8/Eigen/src/Core/DenseCoeffsBase.h:362:5: note: candidate function not viable: requires 2 arguments, but 1 was provided
operator()(Index row, Index col)
^
In file included from aa.cpp:1:
In file included from ./header_only_version/optim.hpp:51:
./header_only_version/unconstrained/nm.hpp:202:44: error: no member named 'all' in namespace 'Eigen'
simplex_points = OPTIM_MATOPS_EVAL(OPTIM_MATOPS_ROWS(simplex_points, sort_vec));
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
./header_only_version/misc/matrix_ops/access.hpp:35:50: note: expanded from macro 'OPTIM_MATOPS_ROWS'
#define OPTIM_MATOPS_ROWS(x, v) (x)(v,Eigen::all) // v is a vector
~~~~~~~^
./header_only_version/misc/matrix_ops/eval.hpp:30:35: note: expanded from macro 'OPTIM_MATOPS_EVAL'
#define OPTIM_MATOPS_EVAL(x) (x).eval()
^
aa.cpp:3:24: error: use of undeclared identifier 'arma'
double sphere_fn(const arma::vec& vals_inp, arma::vec* grad_out, void* opt_data)
^
aa.cpp:3:45: error: use of undeclared identifier 'arma'
double sphere_fn(const arma::vec& vals_inp, arma::vec* grad_out, void* opt_data)
^
aa.cpp:5:22: error: use of undeclared identifier 'arma'
double obj_val = arma::dot(vals_inp,vals_inp);
^
aa.cpp:14:23: error: use of undeclared identifier 'arma'
double booth_fn(const arma::vec& vals_inp, arma::vec* grad_out, void* opt_data)
^
aa.cpp:14:44: error: use of undeclared identifier 'arma'
double booth_fn(const arma::vec& vals_inp, arma::vec* grad_out, void* opt_data)
^
aa.cpp:36:5: error: use of undeclared identifier 'arma'
arma::vec x = arma::ones(test_dim,1); // initial values (1,1,...,1)
^
aa.cpp:36:19: error: use of undeclared identifier 'arma'
arma::vec x = arma::ones(test_dim,1); // initial values (1,1,...,1)
^
aa.cpp:46:5: error: use of undeclared identifier 'arma'
arma::cout << "lbfgs: solution to sphere test:\n" << x << arma::endl;
^
aa.cpp:46:63: error: use of undeclared identifier 'arma'
arma::cout << "lbfgs: solution to sphere test:\n" << x << arma::endl;
^
aa.cpp:51:5: error: use of undeclared identifier 'arma'
arma::vec x_2 = arma::zeros(2,1); // initial values (0,0)
^
aa.cpp:51:21: error: use of undeclared identifier 'arma'
arma::vec x_2 = arma::zeros(2,1); // initial values (0,0)
^
aa.cpp:61:5: error: use of undeclared identifier 'arma'
arma::cout << "lbfgs: solution to Booth test:\n" << x_2 << arma::endl;
^
aa.cpp:61:64: error: use of undeclared identifier 'arma'
arma::cout << "lbfgs: solution to Booth test:\n" << x_2 << arma::endl;
^
15 errors generated.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.