external folder

This commit is contained in:
George Hotz
2020-01-17 10:33:21 -08:00
parent 23c2d02682
commit 6abffe0ede
578 changed files with 140675 additions and 0 deletions
Vendored Executable
BIN
View File
Binary file not shown.
+25
View File
@@ -0,0 +1,25 @@
wget 'https://www.coin-or.org/download/source/Ipopt/Ipopt-3.12.8.zip'
7z x Ipopt-3.12.8.zip
cd Ipopt-3.12.8/
pushd ThirdParty/Blas
./get.Blas
mkdir build && cd build
../configure --prefix="$HOME/one/external/ipopt" --disable-shared --with-pic
make install
popd
pushd ThirdParty/Lapack
./get.Lapack
mkdir build && cd build
../configure --prefix="$HOME/one/external/ipopt" --disable-shared --with-pic --with-blas="$HOME/one/external/ipopt/lib/libcoinblas.a -lgfortran"
make install
popd
(cd ThirdParty/ASL && ./get.ASL)
(cd ThirdParty/Mumps && ./get.Mumps)
./configure --prefix="$HOME/one/external/ipopt" coin_skip_warn_cxxflags=yes --with-blas="$HOME/one/external/ipopt/lib/libcoinblas.a -lgfortran" --with-lapack="$HOME/one/external/ipopt/lib/libcoinlapack.a" --disable-shared --with-pic
make
make test
make -j1 install
+569
View File
@@ -0,0 +1,569 @@
// Copyright (C) 2004, 2009 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: AmplTNLP.hpp 2242 2013-04-24 19:26:30Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPAMPLTNLP_HPP__
#define __IPAMPLTNLP_HPP__
#include "IpUtils.hpp"
#include "IpTNLP.hpp"
#include "IpJournalist.hpp"
#include "IpOptionsList.hpp"
#include <map>
#include <string>
/* non Ipopt forward declaration */
struct ASL_pfgh;
struct SufDecl;
struct SufDesc;
namespace Ipopt
{
class AmplSuffixHandler : public ReferencedObject
{
public:
AmplSuffixHandler();
~AmplSuffixHandler();
enum Suffix_Type
{
Index_Type,
Number_Type
};
enum Suffix_Source
{
Variable_Source,
Constraint_Source,
Objective_Source,
Problem_Source
};
void AddAvailableSuffix(std::string suffix_string, Suffix_Source source, Suffix_Type type)
{
suffix_ids_.push_back(suffix_string);
suffix_types_.push_back(type);
suffix_sources_.push_back(source);
// suffix_values_.push_back();
}
const Index* GetIntegerSuffixValues(std::string suffix_string, Suffix_Source source) const;
const Number* GetNumberSuffixValues(std::string suffix_string, Suffix_Source source) const;
std::vector<Index> GetIntegerSuffixValues(Index n, std::string suffix_string, Suffix_Source source) const;
std::vector<Number> GetNumberSuffixValues(Index n, std::string suffix_string, Suffix_Source source) const;
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
//AmplSuffixHandler();
/** Copy Constructor */
AmplSuffixHandler(const AmplSuffixHandler&);
/** Overloaded Equals Operator */
void operator=(const AmplSuffixHandler&);
//@}
mutable ASL_pfgh* asl_;
SufDecl* suftab_;
std::vector<std::string> suffix_ids_;
std::vector<Suffix_Type> suffix_types_;
std::vector<Suffix_Source> suffix_sources_;
/** Method called by AmplTNLP to prepare the asl for the suffixes */
void PrepareAmplForSuffixes(ASL_pfgh* asl);
/** Method called by AmplTNLP to retrieve the suffixes from asl */
// void RetrieveSuffixesFromAmpl(ASL_pfgh* asl);
friend class AmplTNLP;
};
/** Class for storing a number of AMPL options that should be
* registered to the AMPL Solver library interface */
class AmplOptionsList : public ReferencedObject
{
public:
enum AmplOptionType {
String_Option,
Number_Option,
Integer_Option,
WS_Option, /* this is for AMPL's internal wantsol callback */
HaltOnError_Option /* this is for our setting of the nerror_ member */
};
/** Ampl Option class, contains name, type and description for an
* AMPL option */
class AmplOption : public ReferencedObject
{
public:
AmplOption(const std::string ipopt_option_name,
AmplOptionType type,
const std::string description);
~AmplOption()
{
delete [] description_;
}
const std::string& IpoptOptionName() const
{
return ipopt_option_name_;
}
AmplOptionType Type() const
{
return type_;
}
char* Description() const
{
return description_;
}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
AmplOption();
/** Copy Constructor */
AmplOption(const AmplOption&);
/** Overloaded Equals Operator */
void operator=(const AmplOption&);
//@}
const std::string ipopt_option_name_;
const AmplOptionType type_;
char* description_;
};
class PrivatInfo
{
public:
PrivatInfo(const std::string ipopt_name,
SmartPtr<OptionsList> options,
SmartPtr<const Journalist> jnlst,
void** nerror = NULL)
:
ipopt_name_(ipopt_name),
options_(options),
jnlst_(jnlst),
nerror_(nerror)
{}
const std::string& IpoptName() const
{
return ipopt_name_;
}
const SmartPtr<OptionsList>& Options() const
{
return options_;
}
const SmartPtr<const Journalist>& Jnlst() const
{
return jnlst_;
}
void** NError()
{
return nerror_;
}
private:
const std::string ipopt_name_;
const SmartPtr<OptionsList> options_;
const SmartPtr<const Journalist> jnlst_;
void** nerror_;
};
public:
/** Default Constructor */
AmplOptionsList()
:
keywds_(NULL),
nkeywds_(0)
{}
/** Destructor */
~AmplOptionsList();
/** Adding a new AMPL Option */
void AddAmplOption(const std::string ampl_option_name,
const std::string ipopt_option_name,
AmplOptionsList::AmplOptionType type,
const std::string description)
{
SmartPtr<AmplOption> new_option =
new AmplOption(ipopt_option_name, type, description);
ampl_options_map_[ampl_option_name] = ConstPtr(new_option);
}
/** Number of AMPL Options */
Index NumberOfAmplOptions()
{
return (Index)ampl_options_map_.size();
}
/** ASL keywords list for the stored options. */
void* Keywords(const SmartPtr<OptionsList>& options,
SmartPtr<const Journalist> jnlst,
void** nerror);
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
//AmplOptionsList();
/** Copy Constructor */
AmplOptionsList(const AmplOptionsList&);
/** Overloaded Equals Operator */
void operator=(const AmplOptionsList&);
//@}
void MakeValidLatexString(std::string source, std::string& dest) const;
void PrintLatex(SmartPtr<const Journalist> jnlst);
/** map for storing registered AMPL options */
std::map<std::string, SmartPtr<const AmplOption> > ampl_options_map_;
// AW: I think it should be with const like in the following line
// but with const the AIX compiler fails
// std::map<const std::string, SmartPtr<const AmplOption> > ampl_options_map_;
/** pointer to the keywords */
void* keywds_;
/** Number of entries stored in keywds_ */
Index nkeywds_;
};
/** Ampl Interface.
* Ampl Interface, implemented as a TNLP.
*/
class AmplTNLP : public TNLP
{
public:
/**@name Constructors/Destructors */
//@{
/** Constructor. */
AmplTNLP(const SmartPtr<const Journalist>& jnlst,
const SmartPtr<OptionsList> options,
char**& argv, SmartPtr<AmplSuffixHandler>
suffix_handler = NULL, bool allow_discrete = false,
SmartPtr<AmplOptionsList> ampl_options_list = NULL,
const char* ampl_option_string = NULL,
const char* ampl_invokation_string = NULL,
const char* ampl_banner_string = NULL,
std::string* nl_file_content = NULL);
/** Default destructor */
virtual ~AmplTNLP();
//@}
/** Exceptions */
DECLARE_STD_EXCEPTION(NONPOSITIVE_SCALING_FACTOR);
/**@name methods to gather information about the NLP. These
* methods are overloaded from TNLP. See TNLP for their more
* detailed documentation. */
//@{
/** returns dimensions of the nlp. Overloaded from TNLP */
virtual bool get_nlp_info(Index& n, Index& m, Index& nnz_jac_g,
Index& nnz_h_lag, IndexStyleEnum& index_style);
/** returns names and other meta data for the variables and constraints
* Overloaded from TNLP */
virtual bool get_var_con_metadata(Index n,
StringMetaDataMapType& var_string_md,
IntegerMetaDataMapType& var_integer_md,
NumericMetaDataMapType& var_numeric_md,
Index m,
StringMetaDataMapType& con_string_md,
IntegerMetaDataMapType& con_integer_md,
NumericMetaDataMapType& con_numeric_md);
/** returns bounds of the nlp. Overloaded from TNLP */
virtual bool get_bounds_info(Index n, Number* x_l, Number* x_u,
Index m, Number* g_l, Number* g_u);
/** Returns the constraint linearity.
* array will be alocated with length n. (default implementation
* just return false and does not fill the array). */
virtual bool get_constraints_linearity(Index m,
LinearityType* const_types);
/** provides a starting point for the nlp variables. Overloaded
from TNLP */
virtual bool get_starting_point(Index n, bool init_x, Number* x,
bool init_z, Number* z_L, Number* z_U,
Index m, bool init_lambda, Number* lambda);
/** evaluates the objective value for the nlp. Overloaded from TNLP */
virtual bool eval_f(Index n, const Number* x, bool new_x,
Number& obj_value);
/** evaluates the gradient of the objective for the
nlp. Overloaded from TNLP */
virtual bool eval_grad_f(Index n, const Number* x, bool new_x,
Number* grad_f);
/** evaluates the constraint residuals for the nlp. Overloaded from TNLP */
virtual bool eval_g(Index n, const Number* x, bool new_x,
Index m, Number* g);
/** specifies the jacobian structure (if values is NULL) and
* evaluates the jacobian values (if values is not NULL) for the
* nlp. Overloaded from TNLP */
virtual bool eval_jac_g(Index n, const Number* x, bool new_x,
Index m, Index nele_jac, Index* iRow,
Index *jCol, Number* values);
/** specifies the structure of the hessian of the lagrangian (if
* values is NULL) and evaluates the values (if values is not
* NULL). Overloaded from TNLP */
virtual bool eval_h(Index n, const Number* x, bool new_x,
Number obj_factor, Index m, const Number* lambda,
bool new_lambda, Index nele_hess, Index* iRow,
Index* jCol, Number* values);
/** retrieve the scaling parameters for the variables, objective
* function, and constraints. */
virtual bool get_scaling_parameters(Number& obj_scaling,
bool& use_x_scaling, Index n,
Number* x_scaling,
bool& use_g_scaling, Index m,
Number* g_scaling);
//@}
/** @name Solution Methods */
//@{
virtual void finalize_solution(SolverReturn status,
Index n, const Number* x, const Number* z_L, const Number* z_U,
Index m, const Number* g, const Number* lambda,
Number obj_value,
const IpoptData* ip_data,
IpoptCalculatedQuantities* ip_cq);
//@}
/** @name Method for quasi-Newton approximation information. */
//@{
virtual Index get_number_of_nonlinear_variables();
virtual bool get_list_of_nonlinear_variables(Index num_nonlin_vars,
Index* pos_nonlin_vars);
//@}
/**@name Ampl specific methods */
//@{
/** Return the ampl solver object (ASL*) */
ASL_pfgh* AmplSolverObject()
{
return asl_;
}
/** Write the solution file. This is a wrapper for AMPL's
* write_sol. TODO Maybe this should be at a different place, or
* collect the numbers itself? */
void write_solution_file(const std::string& message) const;
/** ampl orders the variables like (continuous, binary, integer).
* This method gives the number of binary and integer variables.
* For details, see Tables 3 and 4 in "Hooking Your Solver to
* AMPL"
*/
void get_discrete_info(Index& nlvb_,
Index& nlvbi_,
Index& nlvc_,
Index& nlvci_,
Index& nlvo_,
Index& nlvoi_,
Index& nbv_,
Index& niv_) const;
//@}
/** A method for setting the index of the objective function to be
* considered. This method must be called after the constructor,
* and before anything else is called. It can only be called
* once, and if there is more than one objective function in the
* AMPL model, it MUST be called. */
void set_active_objective(Index obj_no);
/**@name Methods to set meta data for the variables
* and constraints. These values will be passed on
* to the TNLP in get_var_con_meta_data
*/
//@{
void set_string_metadata_for_var(std::string tag, std::vector<std::string> meta_data)
{
var_string_md_[tag] = meta_data;
}
void set_integer_metadata_for_var(std::string tag, std::vector<Index> meta_data)
{
var_integer_md_[tag] = meta_data;
}
void set_numeric_metadata_for_var(std::string tag, std::vector<Number> meta_data)
{
var_numeric_md_[tag] = meta_data;
}
void set_string_metadata_for_con(std::string tag, std::vector<std::string> meta_data)
{
con_string_md_[tag] = meta_data;
}
void set_integer_metadata_for_con(std::string tag, std::vector<Index> meta_data)
{
con_integer_md_[tag] = meta_data;
}
void set_numeric_metadata_for_con(std::string tag, std::vector<Number> meta_data)
{
con_numeric_md_[tag] = meta_data;
}
//@}
/** Method for returning the suffix handler */
SmartPtr<AmplSuffixHandler> get_suffix_handler()
{
return suffix_handler_;
}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
AmplTNLP();
/** Copy Constructor */
AmplTNLP(const AmplTNLP&);
/** Overloaded Equals Operator */
void operator=(const AmplTNLP&);
//@}
/** Journlist */
SmartPtr<const Journalist> jnlst_;
/** pointer to the main ASL structure */
ASL_pfgh* asl_;
/** Sign of the objective fn (1 for min, -1 for max) */
double obj_sign_;
/**@name Problem Size Data*/
//@{
Index nz_h_full_; // number of nonzeros in the full_x hessian
/* the rest of the problem size data is available easily through the ampl variables */
//@}
/**@name Internal copies of data */
//@{
/** Solution Vectors */
Number* x_sol_;
Number* z_L_sol_;
Number* z_U_sol_;
Number* g_sol_;
Number* lambda_sol_;
Number obj_sol_;
//@}
/**@name Flags to track internal state */
//@{
/** true when the objective value has been calculated with the
* current x, set to false in apply_new_x, and set to true in
* internal_objval */
bool objval_called_with_current_x_;
/** true when the constraint values have been calculated with the
* current x, set to false in apply_new_x, and set to true in
* internal_conval */
bool conval_called_with_current_x_;
/** true when we have called hesset */
bool hesset_called_;
/** true when set_active_objective has been called */
bool set_active_objective_called_;
//@}
/** Pointer to the Oinfo structure */
void* Oinfo_ptr_;
/** nerror flag passed to ampl calls - set to NULL to halt on error */
void* nerror_;
/** Suffix Handler */
SmartPtr<AmplSuffixHandler> suffix_handler_;
/** Make the objective call to ampl */
bool internal_objval(const Number* x, Number& obj_val);
/** Make the constraint call to ampl*/
bool internal_conval(const Number* x, Index m, Number* g=NULL);
/** Internal function to update the internal and ampl state if the
* x value changes */
bool apply_new_x(bool new_x, Index n, const Number* x);
/** Method for obtaining the name of the NL file and the options
* set from AMPL. Returns a pointer to a char* with the name of
* the stub */
char* get_options(const SmartPtr<OptionsList>& options,
SmartPtr<AmplOptionsList>& ampl_options_list,
const char* ampl_option_string,
const char* ampl_invokation_string,
const char* ampl_banner_string, char**& argv);
/** returns true if the ampl nerror code is ok */
bool nerror_ok(void* nerror);
/** calls hesset ASL function */
void call_hesset();
/** meta data to pass on to TNLP */
StringMetaDataMapType var_string_md_;
IntegerMetaDataMapType var_integer_md_;
NumericMetaDataMapType var_numeric_md_;
StringMetaDataMapType con_string_md_;
IntegerMetaDataMapType con_integer_md_;
NumericMetaDataMapType con_numeric_md_;
};
} // namespace Ipopt
#endif
+378
View File
@@ -0,0 +1,378 @@
/* Copyright (C) 2008, 2011 GAMS Development and others
All Rights Reserved.
This code is published under the Eclipse Public License.
$Id: HSLLoader.h 2317 2013-06-01 13:16:07Z stefan $
Author: Stefan Vigerske
*/
#ifndef HSLLOADER_H_
#define HSLLOADER_H_
#include "IpoptConfig.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifndef ma77_default_control
#define ma77_control ma77_control_d
#define ma77_info ma77_info_d
#define ma77_default_control ma77_default_control_d
#define ma77_open_nelt ma77_open_nelt_d
#define ma77_open ma77_open_d
#define ma77_input_vars ma77_input_vars_d
#define ma77_input_reals ma77_input_reals_d
#define ma77_analyse ma77_analyse_d
#define ma77_factor ma77_factor_d
#define ma77_factor_solve ma77_factor_solve_d
#define ma77_solve ma77_solve_d
#define ma77_resid ma77_resid_d
#define ma77_scale ma77_scale_d
#define ma77_enquire_posdef ma77_enquire_posdef_d
#define ma77_enquire_indef ma77_enquire_indef_d
#define ma77_alter ma77_alter_d
#define ma77_restart ma77_restart_d
#define ma77_finalise ma77_finalise_d
#endif
struct ma77_control;
struct ma77_info;
typedef double ma77pkgtype_d_;
#ifndef ma86_default_control
#define ma86_control ma86_control_d
#define ma86_info ma86_info_d
#define ma86_default_control ma86_default_control_d
#define ma86_analyse ma86_analyse_d
#define ma86_factor ma86_factor_d
#define ma86_factor_solve ma86_factor_solve_d
#define ma86_solve ma86_solve_d
#define ma86_finalise ma86_finalise_d
#endif
struct ma86_control;
struct ma86_info;
typedef double ma86pkgtype_d_;
typedef double ma86realtype_d_;
#ifndef ma97_default_control
#define ma97_control ma97_control_d
#define ma97_info ma97_info_d
#define ma97_default_control ma97_default_control_d
#define ma97_analyse ma97_analyse_d
#define ma97_factor ma97_factor_d
#define ma97_factor_solve ma97_factor_solve_d
#define ma97_solve ma97_solve_d
#define ma97_finalise ma97_finalise_d
#define ma97_free_akeep ma97_free_akeep_d
#endif
struct ma97_control;
struct ma97_info;
typedef double ma97pkgtype_d_;
typedef double ma97realtype_d_;
struct mc68_control_i;
struct mc68_info_i;
#ifndef __IPTYPES_HPP__
/* Type of Fortran integer translated into C */
typedef FORTRAN_INTEGER_TYPE ipfint;
#endif
typedef void (*ma27ad_t)(ipfint *N, ipfint *NZ, const ipfint *IRN, const ipfint* ICN,
ipfint *IW, ipfint* LIW, ipfint* IKEEP, ipfint *IW1,
ipfint* NSTEPS, ipfint* IFLAG, ipfint* ICNTL,
double* CNTL, ipfint *INFO, double* OPS);
typedef void (*ma27bd_t)(ipfint *N, ipfint *NZ, const ipfint *IRN, const ipfint* ICN,
double* A, ipfint* LA, ipfint* IW, ipfint* LIW,
ipfint* IKEEP, ipfint* NSTEPS, ipfint* MAXFRT,
ipfint* IW1, ipfint* ICNTL, double* CNTL,
ipfint* INFO);
typedef void (*ma27cd_t)(ipfint *N, double* A, ipfint* LA, ipfint* IW,
ipfint* LIW, double* W, ipfint* MAXFRT,
double* RHS, ipfint* IW1, ipfint* NSTEPS,
ipfint* ICNTL, double* CNTL);
typedef void (*ma27id_t)(ipfint* ICNTL, double* CNTL);
typedef void (*ma28ad_t)(void* nsize, void* nz, void* rw, void* licn, void* iw,
void* lirn, void* iw2, void* pivtol, void* iw3, void* iw4, void* rw2, void* iflag);
typedef void (*ma57ad_t) (
ipfint *n, /* Order of matrix. */
ipfint *ne, /* Number of entries. */
const ipfint *irn, /* Matrix nonzero row structure */
const ipfint *jcn, /* Matrix nonzero column structure */
ipfint *lkeep, /* Workspace for the pivot order of lenght 3*n */
ipfint *keep, /* Workspace for the pivot order of lenght 3*n */
/* Automatically iflag = 0; ikeep pivot order iflag = 1 */
ipfint *iwork, /* Integer work space. */
ipfint *icntl, /* Integer Control parameter of length 30*/
ipfint *info, /* Statistical Information; Integer array of length 20 */
double *rinfo); /* Double Control parameter of length 5 */
typedef void (*ma57bd_t) (
ipfint *n, /* Order of matrix. */
ipfint *ne, /* Number of entries. */
double *a, /* Numerical values. */
double *fact, /* Entries of factors. */
ipfint *lfact, /* Length of array `fact'. */
ipfint *ifact, /* Indexing info for factors. */
ipfint *lifact, /* Length of array `ifact'. */
ipfint *lkeep, /* Length of array `keep'. */
ipfint *keep, /* Integer array. */
ipfint *iwork, /* Workspace of length `n'. */
ipfint *icntl, /* Integer Control parameter of length 20. */
double *cntl, /* Double Control parameter of length 5. */
ipfint *info, /* Statistical Information; Integer array of length 40. */
double *rinfo); /* Statistical Information; Real array of length 20. */
typedef void (*ma57cd_t) (
ipfint *job, /* Solution job. Solve for... */
ipfint *n, /* Order of matrix. */
double *fact, /* Entries of factors. */
ipfint *lfact, /* Length of array `fact'. */
ipfint *ifact, /* Indexing info for factors. */
ipfint *lifact, /* Length of array `ifact'. */
ipfint *nrhs, /* Number of right hand sides. */
double *rhs, /* Numerical Values. */
ipfint *lrhs, /* Leading dimensions of `rhs'. */
double *work, /* Real workspace. */
ipfint *lwork, /* Length of `work', >= N*NRHS. */
ipfint *iwork, /* Integer array of length `n'. */
ipfint *icntl, /* Integer Control parameter array of length 20. */
ipfint *info); /* Statistical Information; Integer array of length 40. */
typedef void (*ma57ed_t) (
ipfint *n,
ipfint *ic, /* 0: copy real array. >=1: copy integer array. */
ipfint *keep,
double *fact,
ipfint *lfact,
double *newfac,
ipfint *lnew,
ipfint *ifact,
ipfint *lifact,
ipfint *newifc,
ipfint *linew,
ipfint *info);
typedef void (*ma57id_t) (double *cntl, ipfint *icntl);
typedef void (*ma77_default_control_t)(struct ma77_control_d *control);
typedef void (*ma77_open_nelt_t)(const int n, const char* fname1, const char* fname2,
const char *fname3, const char *fname4, void **keep,
const struct ma77_control_d *control, struct ma77_info_d *info,
const int nelt);
typedef void (*ma77_open_t)(const int n, const char* fname1, const char* fname2,
const char *fname3, const char *fname4, void **keep,
const struct ma77_control_d *control, struct ma77_info_d *info);
typedef void (*ma77_input_vars_t)(const int idx, const int nvar, const int list[],
void **keep, const struct ma77_control_d *control, struct ma77_info_d *info);
typedef void (*ma77_input_reals_t)(const int idx, const int length,
const double reals[], void **keep, const struct ma77_control_d *control,
struct ma77_info_d *info);
typedef void (*ma77_analyse_t)(const int order[], void **keep,
const struct ma77_control_d *control, struct ma77_info_d *info);
typedef void (*ma77_factor_t)(const int posdef, void **keep,
const struct ma77_control_d *control, struct ma77_info_d *info,
const double *scale);
typedef void (*ma77_factor_solve_t)(const int posdef, void **keep,
const struct ma77_control_d *control, struct ma77_info_d *info,
const double *scale, const int nrhs, const int lx,
double rhs[]);
typedef void (*ma77_solve_t)(const int job, const int nrhs, const int lx, double x[],
void **keep, const struct ma77_control_d *control, struct ma77_info_d *info,
const double *scale);
typedef void (*ma77_resid_t)(const int nrhs, const int lx, const double x[],
const int lresid, double resid[], void **keep,
const struct ma77_control_d *control, struct ma77_info_d *info,
double *anorm_bnd);
typedef void (*ma77_scale_t)(double scale[], void **keep,
const struct ma77_control_d *control, struct ma77_info_d *info,
double *anorm);
typedef void (*ma77_enquire_posdef_t)(double d[], void **keep,
const struct ma77_control_d *control, struct ma77_info_d *info);
typedef void (*ma77_enquire_indef_t)(int piv_order[], double d[], void **keep,
const struct ma77_control_d *control, struct ma77_info_d *info);
typedef void (*ma77_alter_t)(const double d[], void **keep,
const struct ma77_control_d *control, struct ma77_info_d *info);
typedef void (*ma77_restart_t)(const char *restart_file, const char *fname1,
const char *fname2, const char *fname3, const char *fname4, void **keep,
const struct ma77_control_d *control, struct ma77_info_d *info);
typedef void (*ma77_finalise_t)(void **keep, const struct ma77_control_d *control,
struct ma77_info_d *info);
typedef void (*ma86_default_control_t)(struct ma86_control *control);
typedef void (*ma86_analyse_t)(const int n, const int ptr[], const int row[],
int order[], void **keep, const struct ma86_control *control,
struct ma86_info *info);
typedef void (*ma86_factor_t)(const int n, const int ptr[], const int row[],
const ma86pkgtype_d_ val[], const int order[], void **keep,
const struct ma86_control *control, struct ma86_info *info,
const ma86pkgtype_d_ scale[]);
typedef void (*ma86_factor_solve_t)(const int n, const int ptr[],
const int row[], const ma86pkgtype_d_ val[], const int order[], void **keep,
const struct ma86_control *control, struct ma86_info *info, const int nrhs,
const int ldx, ma86pkgtype_d_ x[], const ma86pkgtype_d_ scale[]);
typedef void (*ma86_solve_t)(const int job, const int nrhs, const int ldx,
ma86pkgtype_d_ *x, const int order[], void **keep,
const struct ma86_control *control, struct ma86_info *info,
const ma86pkgtype_d_ scale[]);
typedef void (*ma86_finalise_t)(void **keep,
const struct ma86_control *control);
typedef void (*ma97_default_control_t)(struct ma97_control *control);
typedef void (*ma97_analyse_t)(const int check, const int n, const int ptr[],
const int row[], ma97pkgtype_d_ val[], void **akeep,
const struct ma97_control *control, struct ma97_info *info, int order[]);
typedef void (*ma97_factor_t)(const int matrix_type, const int ptr[],
const int row[], const ma97pkgtype_d_ val[], void **akeep, void **fkeep,
const struct ma97_control *control, struct ma97_info *info,
const ma97pkgtype_d_ scale[]);
typedef void (*ma97_factor_solve_t)(const int matrix_type, const int ptr[],
const int row[], const ma97pkgtype_d_ val[], const int nrhs,
ma97pkgtype_d_ x[], const int ldx, void **akeep, void **fkeep,
const struct ma97_control *control, struct ma97_info *info,
const ma97pkgtype_d_ scale[]);
typedef void (*ma97_solve_t)(const int job, const int nrhs, ma97pkgtype_d_ *x,
const int ldx, void **akeep, void **fkeep,
const struct ma97_control *control, struct ma97_info *info);
typedef void (*ma97_finalise_t)(void **akeep, void **fkeep);
typedef void (*ma97_free_akeep_t)(void **akeep);
typedef void (*mc19ad_t)(ipfint *N, ipfint *NZ, double* A, ipfint *IRN, ipfint* ICN, float* R, float* C, float* W);
typedef void (*mc68_default_control_t)(struct mc68_control_i *control);
typedef void (*mc68_order_t)(int ord, int n, const int ptr[],
const int row[], int perm[], const struct mc68_control_i *control,
struct mc68_info_i *info);
/** Tries to load a dynamically linked library with HSL routines.
* Also tries to load symbols for those HSL routines that are not linked into Ipopt, i.e., HAVE_... is not defined.
* Return a failure if the library cannot be loaded, but not if a symbol is not found.
* @see LSL_isMA27available
* @see LSL_isMA28available
* @see LSL_isMA57available
* @see LSL_isMA77available
* @see LSL_isMA86available
* @see LSL_isMA97available
* @see LSL_isMC19available
* @param libname The name under which the HSL lib can be found, or NULL to use a default name (libhsl.SHAREDLIBEXT).
* @param msgbuf A buffer where we can store a failure message. Assumed to be NOT NULL!
* @param msglen Length of the message buffer.
* @return Zero on success, nonzero on failure.
*/
int LSL_loadHSL(const char* libname, char* msgbuf, int msglen);
/** Unloads a loaded HSL library.
* @return Zero on success, nonzero on failure.
*/
int LSL_unloadHSL();
/** Indicates whether a HSL library has been loaded.
* @return Zero if not loaded, nonzero if handle is loaded
*/
int LSL_isHSLLoaded();
/** Indicates whether a HSL library is loaded and all symbols necessary to use MA27 have been found.
* @return Zero if not available, nonzero if MA27 is available in the loaded library.
*/
int LSL_isMA27available();
/** Indicates whether a HSL library is loaded and all symbols necessary to use MA28 have been found.
* @return Zero if not available, nonzero if MA28 is available in the loaded library.
*/
int LSL_isMA28available();
/** Indicates whether a HSL library is loaded and all symbols necessary to use MA57 have been found.
* @return Zero if not available, nonzero if MA57 is available in the loaded library.
*/
int LSL_isMA57available();
/** Indicates whether a HSL library is loaded and all symbols necessary to use MA77 have been found.
* @return Zero if not available, nonzero if HSL_MA77 is available in the loaded library.
*/
int LSL_isMA77available();
/** Indicates whether a HSL library is loaded and all symbols necessary to use HSL_MA86 have been found.
* @return Zero if not available, nonzero if HSL_MA86 is available in the loaded library.
*/
int LSL_isMA86available();
/** Indicates whether a HSL library is loaded and all symbols necessary to use HSL_MA97 have been found.
* @return Zero if not available, nonzero if HSL_MA97 is available in the loaded library.
*/
int LSL_isMA97available();
/** Indicates whether a HSL library is loaded and all symbols necessary to use MA57 have been found.
* @return Zero if not available, nonzero if MC19 is available in the loaded library.
*/
int LSL_isMC19available();
/** Indicates whether a HSL library is loaded and all symbols necessary to use HSL_MC68 have been found.
* @return Zero if not available, nonzero if MC68 is available in the loaded library.
*/
int LSL_isMC68available();
/** Returns name of the shared library that should contain HSL */
char* LSL_HSLLibraryName();
/** sets pointers to MA27 functions */
void LSL_setMA27(ma27ad_t ma27ad, ma27bd_t ma27bd, ma27cd_t ma27cd, ma27id_t ma27id);
/** sets pointers to MA28 functions */
void LSL_setMA28(ma28ad_t ma28ad);
/** sets pointers to MA57 functions */
void LSL_setMA57(ma57ad_t ma57ad, ma57bd_t ma57bd, ma57cd_t ma57cd, ma57ed_t ma57ed, ma57id_t ma57id);
/** sets pointers to MA77 functions */
void LSL_setMA77(ma77_default_control_t ma77_default_control,
ma77_open_nelt_t ma77_open_nelt,
ma77_open_t ma77_open,
ma77_input_vars_t ma77_input_vars,
ma77_input_reals_t ma77_input_reals,
ma77_analyse_t ma77_analyse,
ma77_factor_t ma77_factor,
ma77_factor_solve_t ma77_factor_solve,
ma77_solve_t ma77_solve,
ma77_resid_t ma77_resid,
ma77_scale_t ma77_scale,
ma77_enquire_posdef_t ma77_enquire_posdef,
ma77_enquire_indef_t ma77_enquire_indef,
ma77_alter_t ma77_alter,
ma77_restart_t ma77_restart,
ma77_finalise_t ma77_finalise);
/** sets pointers to MA86 functions */
void LSL_setMA86(ma86_default_control_t ma86_default_control,
ma86_analyse_t ma86_analyse,
ma86_factor_t ma86_factor,
ma86_factor_solve_t ma86_factor_solve,
ma86_solve_t ma86_solve,
ma86_finalise_t ma86_finalise);
/** sets pointers to MA97 functions */
void LSL_setMA97(ma97_default_control_t ma97_default_control,
ma97_analyse_t ma97_analyse,
ma97_factor_t ma97_factor,
ma97_factor_solve_t ma97_factor_solve,
ma97_solve_t ma97_solve,
ma97_finalise_t ma97_finalise,
ma97_free_akeep_t ma97_free_akeep);
/** sets pointer to MC19 function */
void LSL_setMC19(mc19ad_t mc19ad);
/** sets pointers to MC68 functions */
void LSL_setMC68(mc68_default_control_t mc68_default_control, mc68_order_t mc68_order);
#ifdef __cplusplus
}
#endif
#endif /*HSLLOADER_H_*/
+360
View File
@@ -0,0 +1,360 @@
// Copyright (C) 2004, 2007 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpAlgBuilder.hpp 2666 2016-07-20 16:02:55Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-09-29
#ifndef __IPALGBUILDER_HPP__
#define __IPALGBUILDER_HPP__
#include "IpIpoptAlg.hpp"
#include "IpReferenced.hpp"
#include "IpAugSystemSolver.hpp"
#include "IpPDSystemSolver.hpp"
namespace Ipopt
{
// forward declarations
class IterationOutput;
class HessianUpdater;
class ConvergenceCheck;
class SearchDirectionCalculator;
class EqMultiplierCalculator;
class IterateInitializer;
class LineSearch;
class MuUpdate;
/** Builder for creating a complete IpoptAlg object. This object
* contains all subelements (such as line search objects etc). How
* the resulting IpoptAlg object is built can be influenced by the
* options.
*
* More advanced customization can be achieved by subclassing this
* class and overloading the virtual methods that build the
* individual parts. The advantage of doing this is that it allows
* one to reuse the extensive amount of options processing that
* takes place, for instance, when generating the symmetric linear
* system solver. Another method for customizing the algorithm is
* using the optional custom_solver argument, which allows the
* expert user to provide a specialized linear solver for the
* augmented system (e.g., type GenAugSystemSolver), possibly for
* user-defined matrix objects. The optional custom_solver constructor
* argument is likely obsolete, however, as more control over this
* this process can be achieved by implementing a subclass of this
* AlgBuilder (e.g., by overloading the AugSystemSolverFactory method).
*/
class AlgorithmBuilder : public ReferencedObject
{
public:
/**@name Constructors/Destructors */
//@{
/** Constructor */
AlgorithmBuilder(SmartPtr<AugSystemSolver> custom_solver=NULL);
/** Destructor */
virtual ~AlgorithmBuilder()
{}
//@}
/** Methods for IpoptTypeInfo */
//@{
/** register the options used by the algorithm builder */
static void RegisterOptions(SmartPtr<RegisteredOptions> roptions);
//@}
/** @name Convenience methods for building solvers without having
* to duplicate the significant amount of preprocessor flag and
* option checking that takes place. These solvers are used to
* create a number of core algorithm components across the
* different Build* methods, but depending on what options are
* chosen, the first method requiring the solver to be used can
* vary. Therefore, each of the Factory methods below is paired
* with a Getter method, which is called by all parts of this
* algorithm builder to ensure the Factory is only called once. */
//@{
/** Create a solver that can be used to solve a symmetric linear
* system.
* Dependencies: None
*/
virtual SmartPtr<SymLinearSolver>
SymLinearSolverFactory(const Journalist& jnlst,
const OptionsList& options,
const std::string& prefix);
/** Get the symmetric linear system solver for this
* algorithm. This method will call the SymLinearSolverFactory
* exactly once (the first time it is used), and store its
* instance on SymSolver_ for use in subsequent calls.
*/
SmartPtr<SymLinearSolver> GetSymLinearSolver(const Journalist& jnlst,
const OptionsList& options,
const std::string& prefix);
/** Create a solver that can be used to solve an
* augmented system.
* Dependencies:
* -> GetSymLinearSolver()
* -> SymLinearSolverFactory()
* -> custom_solver_
*/
virtual SmartPtr<AugSystemSolver>
AugSystemSolverFactory(const Journalist& jnlst,
const OptionsList& options,
const std::string& prefix);
/** Get the augmented system solver for this algorithm. This
* method will call the AugSystemSolverFactory exactly once (the
* first time it is used), and store its instance on AugSolver_
* for use in subsequent calls.
*/
SmartPtr<AugSystemSolver> GetAugSystemSolver(const Journalist& jnlst,
const OptionsList& options,
const std::string& prefix);
/** Create a solver that can be used to solve a
* primal-dual system.
* Dependencies:
* -> GetAugSystemSolver()
* -> AugSystemSolverFactory()
* -> GetSymLinearSolver()
* -> SymLinearSolverFactory()
* -> custom_solver_
*/
virtual SmartPtr<PDSystemSolver>
PDSystemSolverFactory(const Journalist& jnlst,
const OptionsList& options,
const std::string& prefix);
/** Get the primal-dual system solver for this algorithm. This
* method will call the PDSystemSolverFactory exactly once (the
* first time it is used), and store its instance on PDSolver_
* for use in subsequent calls.
*/
SmartPtr<PDSystemSolver> GetPDSystemSolver(const Journalist& jnlst,
const OptionsList& options,
const std::string& prefix);
//@}
/** @name Methods to build parts of the algorithm */
//@{
/** Allocates memory for the IpoptNLP, IpoptData, and
* IpoptCalculatedQuanties arguments.
* Dependencies: None
*/
virtual void BuildIpoptObjects(const Journalist& jnlst,
const OptionsList& options,
const std::string& prefix,
const SmartPtr<NLP>& nlp,
SmartPtr<IpoptNLP>& ip_nlp,
SmartPtr<IpoptData>& ip_data,
SmartPtr<IpoptCalculatedQuantities>& ip_cq);
/** Creates an instance of the IpoptAlgorithm class by building
* each of its required constructor arguments piece-by-piece. The
* default algorithm can be customized by overloading this method
* or by overloading one or more of the Build* methods called in
* this method's default implementation. Additional control can
* be achieved by overloading any of the *SolverFactory methods.
* This method will call (in this order):
* -> BuildIterationOutput()
* -> BuildHessianUpdater()
* -> BuildConvergenceCheck()
* -> BuildSearchDirectionCalculator()
* -> BuildEqMultiplierCalculator()
* -> BuildIterateInitializer()
* -> BuildLineSearch()
* -> BuildMuUpdate()
*/
virtual SmartPtr<IpoptAlgorithm> BuildBasicAlgorithm(const Journalist& jnlst,
const OptionsList& options,
const std::string& prefix);
/** Creates an instance of the IterationOutput class. This method
* is called in the default implementation of
* BuildBasicAlgorithm. It can be overloaded to customize that
* portion the default algorithm.
* Dependencies: None
*/
virtual SmartPtr<IterationOutput>
BuildIterationOutput(const Journalist& jnlst,
const OptionsList& options,
const std::string& prefix);
/** Creates an instance of the HessianUpdater class. This method
* is called in the default implementation of
* BuildBasicAlgorithm. It can be overloaded to customize that
* portion the default algorithm.
* Dependencies: None
*/
virtual SmartPtr<HessianUpdater>
BuildHessianUpdater(const Journalist& jnlst,
const OptionsList& options,
const std::string& prefix);
/** Creates an instance of the ConvergenceCheck class. This method
* is called in the default implementation of
* BuildBasicAlgorithm. It can be overloaded to customize that
* portion the default algorithm.
* Dependencies: None
*/
virtual SmartPtr<ConvergenceCheck>
BuildConvergenceCheck(const Journalist& jnlst,
const OptionsList& options,
const std::string& prefix);
/** Creates an instance of the SearchDirectionCalculator
* class. This method is called in the default implementation of
* BuildBasicAlgorithm. It can be overloaded to customize that
* portion the default algorithm.
* Dependencies:
* -> GetPDSystemSolver()
* -> PDSystemSolverFactory()
* -> GetAugSystemSolver()
* -> AugSystemSolverFactory()
* -> GetSymLinearSolver()
* -> SymLinearSolverFactory()
* -> custom_solver_
*/
virtual SmartPtr<SearchDirectionCalculator>
BuildSearchDirectionCalculator(const Journalist& jnlst,
const OptionsList& options,
const std::string& prefix);
/** Creates an instance of the EqMultiplierCalculator class. This
* method is called in the default implementation of
* BuildBasicAlgorithm. It can be overloaded to customize that
* portion the default algorithm.
* Dependencies:
* -> GetAugSystemSolver()
* -> AugSystemSolverFactory()
* -> GetSymLinearSolver()
* -> SymLinearSolverFactory()
* -> custom_solver_
*/
virtual SmartPtr<EqMultiplierCalculator>
BuildEqMultiplierCalculator(const Journalist& jnlst,
const OptionsList& options,
const std::string& prefix);
/** Creates an instance of the IterateInitializer class. This
* method is called in the default implementation of
* BuildBasicAlgorithm. It can be overloaded to customize that
* portion the default algorithm.
* Dependencies:
* -> EqMultCalculator_
* -> GetAugSystemSolver()
* -> AugSystemSolverFactory()
* -> GetSymLinearSolver()
* -> SymLinearSolverFactory()
* -> custom_solver_
*/
virtual SmartPtr<IterateInitializer>
BuildIterateInitializer(const Journalist& jnlst,
const OptionsList& options,
const std::string& prefix);
/** Creates an instance of the LineSearch class. This method is
* called in the default implementation of BuildBasicAlgorithm.
* It can be overloaded to customize that portion the default
* algorithm.
* Dependencies:
* -> EqMultCalculator_
* -> ConvCheck_
* -> GetAugSystemSolver()
* -> AugSystemSolverFactory()
* -> GetSymLinearSolver()
* -> SymLinearSolverFactory()
* -> custom_solver_
* -> GetPDSystemSolver()
* -> PDSystemSolverFactory()
* -> GetAugSystemSolver()
* -> AugSystemSolverFactory()
* -> GetSymLinearSolver()
* -> SymLinearSolverFactory()
* -> custom_solver_
*/
virtual SmartPtr<LineSearch> BuildLineSearch(const Journalist& jnlst,
const OptionsList& options,
const std::string& prefix);
/** Creates an instance of the MuUpdate class. This method is
* called in the default implementation of BuildBasicAlgorithm.
* It can be overloaded to customize that portion the default
* algorithm.
* Dependencies:
* -> LineSearch_
* -> EqMultCalculator_
* -> ConvCheck_
* -> GetPDSystemSolver()
* -> PDSystemSolverFactory()
* -> GetAugSystemSolver()
* -> AugSystemSolverFactory()
* -> GetSymLinearSolver()
* -> SymLinearSolverFactory()
* -> custom_solver_
*/
virtual SmartPtr<MuUpdate> BuildMuUpdate(const Journalist& jnlst,
const OptionsList& options,
const std::string& prefix);
//@}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
//AlgorithmBuilder();
/** Copy Constructor */
AlgorithmBuilder(const AlgorithmBuilder&);
/** Overloaded Equals Operator */
void operator=(const AlgorithmBuilder&);
//@}
/** @name IpoptAlgorithm constructor arguments.
* These components are built in separate Build
* methods in the order defined by BuildBasicAlgorithm.
* A single core component may require one or more
* other core components in its constructor, so the
* this class holds pointers to each component for use
* between the separate Build methods. */
//@{
SmartPtr<IterationOutput> IterOutput_;
SmartPtr<HessianUpdater> HessUpdater_;
SmartPtr<ConvergenceCheck> ConvCheck_;
SmartPtr<SearchDirectionCalculator> SearchDirCalc_;
SmartPtr<EqMultiplierCalculator> EqMultCalculator_;
SmartPtr<IterateInitializer> IterInitializer_;
SmartPtr<LineSearch> LineSearch_;
SmartPtr<MuUpdate> MuUpdate_;
//@}
/** @name Commonly used solver components
* for building core algorithm components. Each
* of these members is paired with a Factory/Getter
* method. */
//@{
SmartPtr<SymLinearSolver> SymSolver_;
SmartPtr<AugSystemSolver> AugSolver_;
SmartPtr<PDSystemSolver> PDSolver_;
//@}
/** Optional pointer to AugSystemSolver. If this is set in the
* contructor, we will use this to solve the linear systems. */
SmartPtr<AugSystemSolver> custom_solver_;
};
} // namespace Ipopt
#endif
+185
View File
@@ -0,0 +1,185 @@
// Copyright (C) 2004, 2006 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpAlgStrategy.hpp 1861 2010-12-21 21:34:47Z andreasw $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPALGSTRATEGY_HPP__
#define __IPALGSTRATEGY_HPP__
#include "IpOptionsList.hpp"
#include "IpJournalist.hpp"
#include "IpIpoptCalculatedQuantities.hpp"
#include "IpIpoptNLP.hpp"
#include "IpIpoptData.hpp"
namespace Ipopt
{
/** This is the base class for all algorithm strategy objects. The
* AlgorithmStrategyObject base class implements a common interface
* for all algorithm strategy objects. A strategy object is a
* component of the algorithm for which different alternatives or
* implementations exists. It allows to compose the algorithm
* before execution for a particular configuration, without the
* need to call alternatives based on enums. For example, the
* LineSearch object is a strategy object, since different line
* search options might be used for different runs.
*
* This interface is used for
* things that are done to all strategy objects, like
* initialization and setting options.
*/
class AlgorithmStrategyObject : public ReferencedObject
{
public:
/**@name Constructors/Destructors */
//@{
/** Default Constructor */
AlgorithmStrategyObject()
:
initialize_called_(false)
{}
/** Default Destructor */
virtual ~AlgorithmStrategyObject()
{}
//@}
/** This method is called every time the algorithm starts again -
* it is used to reset any internal state. The pointers to the
* Journalist, as well as to the IpoptNLP, IpoptData, and
* IpoptCalculatedQuantities objects should be stored in the
* instanciation of this base class. This method is also used to
* get all required user options from the OptionsList. Here, if
* prefix is given, each tag (identifying the options) is first
* looked for with the prefix in front, and if not found, without
* the prefix. Note: you should not cue off of the iteration
* count to indicate the "start" of an algorithm!
*
* Do not overload this method, since it does some general
* initialization that is common for all strategy objects.
* Overload the protected InitializeImpl method instead.
*/
bool Initialize(const Journalist& jnlst,
IpoptNLP& ip_nlp,
IpoptData& ip_data,
IpoptCalculatedQuantities& ip_cq,
const OptionsList& options,
const std::string& prefix)
{
initialize_called_ = true;
// Copy the pointers for the problem defining objects
jnlst_ = &jnlst;
ip_nlp_ = &ip_nlp;
ip_data_ = &ip_data;
ip_cq_ = &ip_cq;
bool retval = InitializeImpl(options, prefix);
if (!retval) {
initialize_called_ = false;
}
return retval;
}
/** Reduced version of the Initialize method, which does not
* require special Ipopt information. This is useful for
* algorithm objects that could be used outside Ipopt, such as
* linear solvers. */
bool ReducedInitialize(const Journalist& jnlst,
const OptionsList& options,
const std::string& prefix)
{
initialize_called_ = true;
// Copy the pointers for the problem defining objects
jnlst_ = &jnlst;
ip_nlp_ = NULL;
ip_data_ = NULL;
ip_cq_ = NULL;
bool retval = InitializeImpl(options, prefix);
if (!retval) {
initialize_called_ = false;
}
return retval;
}
protected:
/** Implementation of the initialization method that has to be
* overloaded by for each derived class. */
virtual bool InitializeImpl(const OptionsList& options,
const std::string& prefix)=0;
/** @name Accessor methods for the problem defining objects.
* Those should be used by the derived classes. */
//@{
const Journalist& Jnlst() const
{
DBG_ASSERT(initialize_called_);
return *jnlst_;
}
IpoptNLP& IpNLP() const
{
DBG_ASSERT(initialize_called_);
DBG_ASSERT(IsValid(ip_nlp_));
return *ip_nlp_;
}
IpoptData& IpData() const
{
DBG_ASSERT(initialize_called_);
DBG_ASSERT(IsValid(ip_data_));
return *ip_data_;
}
IpoptCalculatedQuantities& IpCq() const
{
DBG_ASSERT(initialize_called_);
DBG_ASSERT(IsValid(ip_cq_));
return *ip_cq_;
}
bool HaveIpData() const
{
return IsValid(ip_data_);
}
//@}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
//AlgorithmStrategyObject();
/** Copy Constructor */
AlgorithmStrategyObject(const AlgorithmStrategyObject&);
/** Overloaded Equals Operator */
void operator=(const AlgorithmStrategyObject&);
//@}
/** @name Pointers to objects defining a particular optimization
* problem */
//@{
SmartPtr<const Journalist> jnlst_;
SmartPtr<IpoptNLP> ip_nlp_;
SmartPtr<IpoptData> ip_data_;
SmartPtr<IpoptCalculatedQuantities> ip_cq_;
//@}
/** flag indicating if Initialize method has been called (for
* debugging) */
bool initialize_called_;
};
} // namespace Ipopt
#endif
+66
View File
@@ -0,0 +1,66 @@
// Copyright (C) 2005, 2010 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpAlgTypes.hpp 2551 2015-02-13 02:51:47Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2005-07-19
#ifndef __IPALGTYPES_HPP__
#define __IPALGTYPES_HPP__
#include "IpTypes.hpp"
#include "IpException.hpp"
namespace Ipopt
{
/**@name Enumerations */
//@{
/** enum for the return from the optimize algorithm
* (obviously we need to add more) */
enum SolverReturn {
SUCCESS,
MAXITER_EXCEEDED,
CPUTIME_EXCEEDED,
STOP_AT_TINY_STEP,
STOP_AT_ACCEPTABLE_POINT,
LOCAL_INFEASIBILITY,
USER_REQUESTED_STOP,
FEASIBLE_POINT_FOUND,
DIVERGING_ITERATES,
RESTORATION_FAILURE,
ERROR_IN_STEP_COMPUTATION,
INVALID_NUMBER_DETECTED,
TOO_FEW_DEGREES_OF_FREEDOM,
INVALID_OPTION,
OUT_OF_MEMORY,
INTERNAL_ERROR,
UNASSIGNED
};
//@}
/** @name Some exceptions used in multiple places */
//@{
DECLARE_STD_EXCEPTION(LOCALLY_INFEASIBLE);
DECLARE_STD_EXCEPTION(TOO_FEW_DOF);
DECLARE_STD_EXCEPTION(TINY_STEP_DETECTED);
DECLARE_STD_EXCEPTION(ACCEPTABLE_POINT_REACHED);
DECLARE_STD_EXCEPTION(FEASIBILITY_PROBLEM_SOLVED);
DECLARE_STD_EXCEPTION(INVALID_WARMSTART);
DECLARE_STD_EXCEPTION(INTERNAL_ABORT);
DECLARE_STD_EXCEPTION(NO_FREE_VARIABLES_BUT_FEASIBLE);
DECLARE_STD_EXCEPTION(NO_FREE_VARIABLES_AND_INFEASIBLE);
DECLARE_STD_EXCEPTION(INCONSISTENT_BOUNDS);
/** Exception FAILED_INITIALIZATION for problem during
* initialization of a strategy object (or other problems). This
* is thrown by a strategy object, if a problem arises during
* initialization, such as a value out of a feasible range.
*/
DECLARE_STD_EXCEPTION(FAILED_INITIALIZATION);
//@}
}
#endif
+200
View File
@@ -0,0 +1,200 @@
// Copyright (C) 2004, 2006 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpAugSystemSolver.hpp 2269 2013-05-05 11:32:40Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IP_AUGSYSTEMSOLVER_HPP__
#define __IP_AUGSYSTEMSOLVER_HPP__
#include "IpSymMatrix.hpp"
#include "IpSymLinearSolver.hpp"
#include "IpAlgStrategy.hpp"
namespace Ipopt
{
DECLARE_STD_EXCEPTION(FATAL_ERROR_IN_LINEAR_SOLVER);
/** Base class for Solver for the augmented system. This is the
* base class for linear solvers that solve the augmented system,
* which is defined as
*
* \f$\left[\begin{array}{cccc}
* W + D_x + \delta_xI & 0 & J_c^T & J_d^T\\
* 0 & D_s + \delta_sI & 0 & -I \\
* J_c & 0 & D_c - \delta_cI & 0\\
* J_d & -I & 0 & D_d - \delta_dI
* \end{array}\right]
* \left(\begin{array}{c}sol_x\\sol_s\\sol_c\\sol_d\end{array}\right)=
* \left(\begin{array}{c}rhs_x\\rhs_s\\rhs_c\\rhs_d\end{array}\right)\f$
*
* Since this system might be solved repeatedly for different right
* hand sides, it is desirable to step the factorization of a
* direct linear solver if possible.
*/
class AugSystemSolver: public AlgorithmStrategyObject
{
public:
/**@name Constructors/Destructors */
//@{
/** Default constructor. */
AugSystemSolver()
{}
/** Default destructor */
virtual ~AugSystemSolver()
{}
//@}
/** overloaded from AlgorithmStrategyObject */
virtual bool InitializeImpl(const OptionsList& options,
const std::string& prefix) = 0;
/** Set up the augmented system and solve it for a given right hand
* side. If desired (i.e. if check_NegEVals is true), then the
* solution is only computed if the number of negative eigenvalues
* matches numberOfNegEVals.
*
* The return value is the return value of the linear solver object.
*/
virtual ESymSolverStatus Solve(
const SymMatrix* W,
double W_factor,
const Vector* D_x,
double delta_x,
const Vector* D_s,
double delta_s,
const Matrix* J_c,
const Vector* D_c,
double delta_c,
const Matrix* J_d,
const Vector* D_d,
double delta_d,
const Vector& rhs_x,
const Vector& rhs_s,
const Vector& rhs_c,
const Vector& rhs_d,
Vector& sol_x,
Vector& sol_s,
Vector& sol_c,
Vector& sol_d,
bool check_NegEVals,
Index numberOfNegEVals)
{
std::vector<SmartPtr<const Vector> > rhs_xV(1);
rhs_xV[0] = &rhs_x;
std::vector<SmartPtr<const Vector> > rhs_sV(1);
rhs_sV[0] = &rhs_s;
std::vector<SmartPtr<const Vector> > rhs_cV(1);
rhs_cV[0] = &rhs_c;
std::vector<SmartPtr<const Vector> > rhs_dV(1);
rhs_dV[0] = &rhs_d;
std::vector<SmartPtr<Vector> > sol_xV(1);
sol_xV[0] = &sol_x;
std::vector<SmartPtr<Vector> > sol_sV(1);
sol_sV[0] = &sol_s;
std::vector<SmartPtr<Vector> > sol_cV(1);
sol_cV[0] = &sol_c;
std::vector<SmartPtr<Vector> > sol_dV(1);
sol_dV[0] = &sol_d;
return MultiSolve(W, W_factor, D_x, delta_x, D_s, delta_s, J_c, D_c, delta_c,
J_d, D_d, delta_d, rhs_xV, rhs_sV, rhs_cV, rhs_dV,
sol_xV, sol_sV, sol_cV, sol_dV, check_NegEVals,
numberOfNegEVals);
}
/** Like Solve, but for multiple right hand sides. The inheriting
* class has to be overload at least one of Solve and
* MultiSolve. */
virtual ESymSolverStatus MultiSolve(
const SymMatrix* W,
double W_factor,
const Vector* D_x,
double delta_x,
const Vector* D_s,
double delta_s,
const Matrix* J_c,
const Vector* D_c,
double delta_c,
const Matrix* J_d,
const Vector* D_d,
double delta_d,
std::vector<SmartPtr<const Vector> >& rhs_xV,
std::vector<SmartPtr<const Vector> >& rhs_sV,
std::vector<SmartPtr<const Vector> >& rhs_cV,
std::vector<SmartPtr<const Vector> >& rhs_dV,
std::vector<SmartPtr<Vector> >& sol_xV,
std::vector<SmartPtr<Vector> >& sol_sV,
std::vector<SmartPtr<Vector> >& sol_cV,
std::vector<SmartPtr<Vector> >& sol_dV,
bool check_NegEVals,
Index numberOfNegEVals)
{
// Solve for one right hand side after the other
Index nrhs = (Index)rhs_xV.size();
DBG_ASSERT(nrhs>0);
DBG_ASSERT(nrhs==(Index)rhs_sV.size());
DBG_ASSERT(nrhs==(Index)rhs_cV.size());
DBG_ASSERT(nrhs==(Index)rhs_dV.size());
DBG_ASSERT(nrhs==(Index)sol_xV.size());
DBG_ASSERT(nrhs==(Index)sol_sV.size());
DBG_ASSERT(nrhs==(Index)sol_cV.size());
DBG_ASSERT(nrhs==(Index)sol_dV.size());
ESymSolverStatus retval=SYMSOLVER_SUCCESS;
for (Index i=0; i<nrhs; i++) {
retval = Solve(W, W_factor, D_x, delta_x, D_s, delta_s, J_c, D_c, delta_c,
J_d, D_d, delta_d,
*rhs_xV[i], *rhs_sV[i], *rhs_cV[i], *rhs_dV[i],
*sol_xV[i], *sol_sV[i], *sol_cV[i], *sol_dV[i],
check_NegEVals, numberOfNegEVals);
if (retval!=SYMSOLVER_SUCCESS) {
break;
}
}
return retval;
}
/** Number of negative eigenvalues detected during last
* solve. Returns the number of negative eigenvalues of
* the most recent factorized matrix. This must not be called if
* the linear solver does not compute this quantities (see
* ProvidesInertia).
*/
virtual Index NumberOfNegEVals() const =0;
/** Query whether inertia is computed by linear solver.
* Returns true, if linear solver provides inertia.
*/
virtual bool ProvidesInertia() const =0;
/** Request to increase quality of solution for next solve. Ask
* underlying linear solver to increase quality of solution for
* the next solve (e.g. increase pivot tolerance). Returns
* false, if this is not possible (e.g. maximal pivot tolerance
* already used.)
*/
virtual bool IncreaseQuality() =0;
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Copy Constructor */
AugSystemSolver(const AugSystemSolver&);
/** Overloaded Equals Operator */
void operator=(const AugSystemSolver&);
//@}
};
} // namespace Ipopt
#endif
+78
View File
@@ -0,0 +1,78 @@
// Copyright (C) 2004, 2006 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpBlas.hpp 1861 2010-12-21 21:34:47Z andreasw $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPBLAS_HPP__
#define __IPBLAS_HPP__
#include "IpUtils.hpp"
namespace Ipopt
{
// If CBLAS is not available, this is our own interface to the Fortran
// implementation
/** Wrapper for BLAS function DDOT. Compute dot product of vector x
and vector y */
Number IpBlasDdot(Index size, const Number *x, Index incX, const Number *y,
Index incY);
/** Wrapper for BLAS function DNRM2. Compute 2-norm of vector x*/
Number IpBlasDnrm2(Index size, const Number *x, Index incX);
/** Wrapper for BLAS function DASUM. Compute 1-norm of vector x*/
Number IpBlasDasum(Index size, const Number *x, Index incX);
/** Wrapper for BLAS function IDAMAX. Compute index for largest
absolute element of vector x */
Index IpBlasIdamax(Index size, const Number *x, Index incX);
/** Wrapper for BLAS subroutine DCOPY. Copying vector x into vector
y */
void IpBlasDcopy(Index size, const Number *x, Index incX, Number *y,
Index incY);
/** Wrapper for BLAS subroutine DAXPY. Adding the alpha multiple of
vector x to vector y */
void IpBlasDaxpy(Index size, Number alpha, const Number *x, Index incX,
Number *y, Index incY);
/** Wrapper for BLAS subroutine DSCAL. Scaling vector x by scalar
alpha */
void IpBlasDscal(Index size, Number alpha, Number *x, Index incX);
/** Wrapper for BLAS subroutine DGEMV. Multiplying a matrix with a
vector. */
void IpBlasDgemv(bool trans, Index nRows, Index nCols, Number alpha,
const Number* A, Index ldA, const Number* x,
Index incX, Number beta, Number* y, Index incY);
/** Wrapper for BLAS subroutine DSYMV. Multiplying a symmetric
matrix with a vector. */
void IpBlasDsymv(Index n, Number alpha, const Number* A, Index ldA,
const Number* x, Index incX, Number beta, Number* y,
Index incY);
/** Wrapper for BLAS subroutine DGEMM. Multiplying two matrices */
void IpBlasDgemm(bool transa, bool transb, Index m, Index n, Index k,
Number alpha, const Number* A, Index ldA, const Number* B,
Index ldB, Number beta, Number* C, Index ldC);
/** Wrapper for BLAS subroutine DSYRK. Adding a high-rank update to
* a matrix */
void IpBlasDsyrk(bool trans, Index ndim, Index nrank,
Number alpha, const Number* A, Index ldA,
Number beta, Number* C, Index ldC);
/** Wrapper for BLAS subroutine DTRSM. Backsolve for a lower triangular
* matrix. */
void IpBlasDtrsm(bool trans, Index ndim, Index nrhs, Number alpha,
const Number* A, Index ldA, Number* B, Index ldB);
} // namespace Ipopt
#endif
+779
View File
@@ -0,0 +1,779 @@
// Copyright (C) 2004, 2011 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpCachedResults.hpp 2472 2014-04-05 17:47:20Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPCACHEDRESULTS_HPP__
#define __IPCACHEDRESULTS_HPP__
#include "IpTaggedObject.hpp"
#include "IpObserver.hpp"
#include <algorithm>
#include <vector>
#include <list>
namespace Ipopt
{
#if COIN_IPOPT_CHECKLEVEL > 2
# define IP_DEBUG_CACHE
#endif
#ifdef IP_DEBUG_CACHE
# include "IpDebug.hpp"
#endif
// Forward Declarations
template <class T>
class DependentResult;
// AW: I'm taking this out, since this is by far the most used
// class. We should keep it as simple as possible.
// /** Cache Priority Enum */
// enum CachePriority
// {
// CP_Lowest,
// CP_Standard,
// CP_Trial,
// CP_Iterate
// };
/** Templated class for Cached Results. This class stores up to a
* given number of "results", entities that are stored here
* together with identifiers, that can be used to later retrieve the
* information again.
*
* Typically, T is a SmartPtr for some calculated quantity that
* should be stored (such as a Vector). The identifiers (or
* dependencies) are a (possibly varying) number of Tags from
* TaggedObjects, and a number of Numbers. Results are added to
* the cache using the AddCachedResults methods, and the can be
* retrieved with the GetCachedResults methods. The second set of
* methods checks whether a result has been cached for the given
* identifiers. If a corresponding result is found, a copy of it
* is returned and the method evaluates to true, otherwise it
* evaluates to false.
*
* Note that cached results can become "stale", namely when a
* TaggedObject that is used to identify this CachedResult is
* changed. When this happens, the cached result can never be
* asked for again, so that there is no point in storing it any
* longer. For this purpose, a cached result, which is stored as a
* DependentResult, inherits off an Observer. This Observer
* retrieves notification whenever a TaggedObject dependency has
* changed. Stale results are later removed from the cache.
*/
template <class T>
class CachedResults
{
public:
#ifdef IP_DEBUG_CACHE
/** (Only if compiled in DEBUG mode): debug verbosity level */
static const Index dbg_verbosity;
#endif
/** @name Constructors and Destructors. */
//@{
/** Constructor, where max_cache_size is the maximal number of
* results that should be cached. If max_cache_size is negative,
* we allow an infinite amount of cache.
*/
CachedResults(Int max_cache_size);
/** Destructor */
virtual ~CachedResults();
//@}
/** @name Generic methods for adding and retrieving cached results. */
//@{
/** Generic method for adding a result to the cache, given a
* std::vector of TaggesObjects and a std::vector of Numbers.
*/
void AddCachedResult(const T& result,
const std::vector<const TaggedObject*>& dependents,
const std::vector<Number>& scalar_dependents);
/** Generic method for retrieving a cached results, given the
* dependencies as a std::vector of TaggesObjects and a
* std::vector of Numbers.
*/
bool GetCachedResult(T& retResult,
const std::vector<const TaggedObject*>& dependents,
const std::vector<Number>& scalar_dependents) const;
/** Method for adding a result, providing only a std::vector of
* TaggedObjects.
*/
void AddCachedResult(const T& result,
const std::vector<const TaggedObject*>& dependents);
/** Method for retrieving a cached result, providing only a
* std::vector of TaggedObjects.
*/
bool GetCachedResult(T& retResult,
const std::vector<const TaggedObject*>& dependents) const;
//@}
/** @name Pointer-based methods for adding and retrieving cached
* results, providing dependencies explicitly.
*/
//@{
/** Method for adding a result to the cache, proving one
* dependency as a TaggedObject explicitly.
*/
void AddCachedResult1Dep(const T& result,
const TaggedObject* dependent1);
/** Method for retrieving a cached result, proving one dependency
* as a TaggedObject explicitly.
*/
bool GetCachedResult1Dep(T& retResult, const TaggedObject* dependent1);
/** Method for adding a result to the cache, proving two
* dependencies as a TaggedObject explicitly.
*/
void AddCachedResult2Dep(const T& result,
const TaggedObject* dependent1,
const TaggedObject* dependent2);
/** Method for retrieving a cached result, proving two
* dependencies as a TaggedObject explicitly.
*/
bool GetCachedResult2Dep(T& retResult,
const TaggedObject* dependent1,
const TaggedObject* dependent2);
/** Method for adding a result to the cache, proving three
* dependencies as a TaggedObject explicitly.
*/
void AddCachedResult3Dep(const T& result,
const TaggedObject* dependent1,
const TaggedObject* dependent2,
const TaggedObject* dependent3);
/** Method for retrieving a cached result, proving three
* dependencies as a TaggedObject explicitly.
*/
bool GetCachedResult3Dep(T& retResult,
const TaggedObject* dependent1,
const TaggedObject* dependent2,
const TaggedObject* dependent3);
/** @name Pointer-free version of the Add and Get methods */
//@{
bool GetCachedResult1Dep(T& retResult, const TaggedObject& dependent1)
{
return GetCachedResult1Dep(retResult, &dependent1);
}
bool GetCachedResult2Dep(T& retResult,
const TaggedObject& dependent1,
const TaggedObject& dependent2)
{
return GetCachedResult2Dep(retResult, &dependent1, &dependent2);
}
bool GetCachedResult3Dep(T& retResult,
const TaggedObject& dependent1,
const TaggedObject& dependent2,
const TaggedObject& dependent3)
{
return GetCachedResult3Dep(retResult, &dependent1, &dependent2, &dependent3);
}
void AddCachedResult1Dep(const T& result,
const TaggedObject& dependent1)
{
AddCachedResult1Dep(result, &dependent1);
}
void AddCachedResult2Dep(const T& result,
const TaggedObject& dependent1,
const TaggedObject& dependent2)
{
AddCachedResult2Dep(result, &dependent1, &dependent2);
}
void AddCachedResult3Dep(const T& result,
const TaggedObject& dependent1,
const TaggedObject& dependent2,
const TaggedObject& dependent3)
{
AddCachedResult3Dep(result, &dependent1, &dependent2, &dependent3);
}
//@}
/** Invalidates the result for given dependencies. Sets the stale
* flag for the corresponding cached result to true if it is
* found. Returns true, if the result was found. */
bool InvalidateResult(const std::vector<const TaggedObject*>& dependents,
const std::vector<Number>& scalar_dependents);
/** Invalidates all cached results */
void Clear();
/** Invalidate all cached results and changes max_cache_size */
void Clear(Int max_cache_size);
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
CachedResults();
/** Copy Constructor */
CachedResults(const CachedResults&);
/** Overloaded Equals Operator */
void operator=(const CachedResults&);
//@}
/** maximum number of cached results */
Int max_cache_size_;
/** list of currently cached results. */
mutable std::list<DependentResult<T>*>* cached_results_;
/** internal method for removing stale DependentResults from the
* list. It is called at the beginning of every
* GetDependentResult method.
*/
void CleanupInvalidatedResults() const;
/** Print list of currently cached results */
void DebugPrintCachedResults() const;
};
/** Templated class which stores one entry for the CachedResult
* class. It stores the result (of type T), together with its
* dependencies (vector of TaggedObjects and vector of Numbers).
* It also stores a priority.
*/
template <class T>
class DependentResult : public Observer
{
public:
#ifdef IP_DEBUG_CACHE
static const Index dbg_verbosity;
#endif
/** @name Constructor, Destructors */
//@{
/** Constructor, given all information about the result. */
DependentResult(const T& result, const std::vector<const TaggedObject*>& dependents,
const std::vector<Number>& scalar_dependents);
/** Destructor. */
~DependentResult();
//@}
/** @name Accessor method. */
//@{
/** This returns true, if the DependentResult is no longer valid. */
bool IsStale() const;
/** Invalidates the cached result. */
void Invalidate();
/** Returns the cached result. */
const T& GetResult() const;
//@}
/** This method returns true if the dependencies provided to this
* function are identical to the ones stored with the
* DependentResult.
*/
bool DependentsIdentical(const std::vector<const TaggedObject*>& dependents,
const std::vector<Number>& scalar_dependents) const;
/** Print information about this DependentResults. */
void DebugPrint() const;
protected:
/** This method is overloading the pure virtual method from the
* Observer base class. This method is called when a Subject
* registered for this Observer sends a notification. In this
* particular case, if this method is called with
* notify_type==NT_Changed or NT_BeingDeleted, then this results
* is marked as stale.
*/
virtual void RecieveNotification(NotifyType notify_type, const Subject* subject);
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
DependentResult();
/** Copy Constructor */
DependentResult(const DependentResult&);
/** Overloaded Equals Operator */
void operator=(const DependentResult&);
//@}
/** Flag indicating, if the cached result is still valid. A
result becomes invalid, if the RecieveNotification method is
called with NT_Changed */
bool stale_;
/** The value of the dependent results */
const T result_;
/** Dependencies in form of TaggedObjects */
std::vector<TaggedObject::Tag> dependent_tags_;
/** Dependencies in form a Numbers */
std::vector<Number> scalar_dependents_;
};
#ifdef IP_DEBUG_CACHE
template <class T>
const Index CachedResults<T>::dbg_verbosity = 0;
template <class T>
const Index DependentResult<T>::dbg_verbosity = 0;
#endif
template <class T>
DependentResult<T>::DependentResult(
const T& result,
const std::vector<const TaggedObject*>& dependents,
const std::vector<Number>& scalar_dependents)
:
stale_(false),
result_(result),
dependent_tags_(dependents.size()),
scalar_dependents_(scalar_dependents)
{
#ifdef IP_DEBUG_CACHE
DBG_START_METH("DependentResult<T>::DependentResult()", dbg_verbosity);
#endif
for (Index i=0; i<(Index)dependents.size(); i++) {
if (dependents[i]) {
// Call the RequestAttach method of the Observer base class.
// This will add this dependent result in the Observer list
// for the Subject dependents[i]. As a consequence, the
// RecieveNotification method of this DependentResult will be
// called with notify_type=NT_Changed, whenever the
// TaggedResult dependents[i] is changed (i.e. its HasChanged
// method is called).
RequestAttach(NT_Changed, dependents[i]);
dependent_tags_[i] = dependents[i]->GetTag();
}
else {
dependent_tags_[i] = 0;
}
}
}
template <class T>
DependentResult<T>::~DependentResult()
{
#ifdef IP_DEBUG_CACHE
DBG_START_METH("DependentResult<T>::~DependentResult()", dbg_verbosity);
//DBG_ASSERT(stale_ == true);
#endif
// Nothing to be done here, destructor
// of T should sufficiently remove
// any memory, etc.
}
template <class T>
bool DependentResult<T>::IsStale() const
{
return stale_;
}
template <class T>
void DependentResult<T>::Invalidate()
{
stale_ = true;
}
template <class T>
void DependentResult<T>::RecieveNotification(NotifyType notify_type, const Subject* subject)
{
#ifdef IP_DEBUG_CACHE
DBG_START_METH("DependentResult<T>::RecieveNotification", dbg_verbosity);
#endif
if (notify_type == NT_Changed || notify_type==NT_BeingDestroyed) {
stale_ = true;
// technically, I could unregister the notifications here, but they
// aren't really hurting anything
}
}
template <class T>
bool DependentResult<T>::DependentsIdentical(const std::vector<const TaggedObject*>& dependents,
const std::vector<Number>& scalar_dependents) const
{
#ifdef IP_DEBUG_CACHE
DBG_START_METH("DependentResult<T>::DependentsIdentical", dbg_verbosity);
DBG_ASSERT(stale_ == false);
DBG_ASSERT(dependents.size() == dependent_tags_.size());
#endif
bool retVal = true;
if (dependents.size() != dependent_tags_.size()
|| scalar_dependents.size() != scalar_dependents_.size()) {
retVal = false;
}
else {
for (Index i=0; i<(Index)dependents.size(); i++) {
if ( (dependents[i] && dependents[i]->GetTag() != dependent_tags_[i])
|| (!dependents[i] && dependent_tags_[i] != 0) ) {
retVal = false;
break;
}
}
if (retVal) {
for (Index i=0; i<(Index)scalar_dependents.size(); i++) {
if (scalar_dependents[i] != scalar_dependents_[i]) {
retVal = false;
break;
}
}
}
}
return retVal;
}
template <class T>
const T& DependentResult<T>::GetResult() const
{
#ifdef IP_DEBUG_CACHE
DBG_START_METH("DependentResult<T>::GetResult()", dbg_verbosity);
DBG_ASSERT(stale_ == false);
#endif
return result_;
}
template <class T>
void DependentResult<T>::DebugPrint() const
{
#ifdef IP_DEBUG_CACHE
DBG_START_METH("DependentResult<T>::DebugPrint", dbg_verbosity);
#endif
}
template <class T>
CachedResults<T>::CachedResults(Int max_cache_size)
:
max_cache_size_(max_cache_size),
cached_results_(NULL)
{
#ifdef IP_DEBUG_CACHE
DBG_START_METH("CachedResults<T>::CachedResults", dbg_verbosity);
#endif
}
template <class T>
CachedResults<T>::~CachedResults()
{
#ifdef IP_DEBUG_CACHE
DBG_START_METH("CachedResults<T>::!CachedResults()", dbg_verbosity);
#endif
if (cached_results_) {
for (typename std::list< DependentResult<T>* >::iterator iter = cached_results_->
begin();
iter != cached_results_->end();
iter++) {
delete *iter;
}
delete cached_results_;
}
/*
while (!cached_results_.empty()) {
DependentResult<T>* result = cached_results_.back();
cached_results_.pop_back();
delete result;
}
*/
}
template <class T>
void CachedResults<T>::AddCachedResult(const T& result,
const std::vector<const TaggedObject*>& dependents,
const std::vector<Number>& scalar_dependents)
{
#ifdef IP_DEBUG_CACHE
DBG_START_METH("CachedResults<T>::AddCachedResult", dbg_verbosity);
#endif
CleanupInvalidatedResults();
// insert the new one here
DependentResult<T>* newResult = new DependentResult<T>(result, dependents, scalar_dependents);
if (!cached_results_) {
cached_results_ = new std::list<DependentResult<T>*>;
}
cached_results_->push_front(newResult);
// keep the list small enough
if (max_cache_size_ >= 0) { // if negative, allow infinite cache
// non-negative - limit size of list to max_cache_size
DBG_ASSERT((Int)cached_results_->size()<=max_cache_size_+1);
if ((Int)cached_results_->size() > max_cache_size_) {
delete cached_results_->back();
cached_results_->pop_back();
}
}
#ifdef IP_DEBUG_CACHE
DBG_EXEC(2, DebugPrintCachedResults());
#endif
}
template <class T>
void CachedResults<T>::AddCachedResult(const T& result,
const std::vector<const TaggedObject*>& dependents)
{
std::vector<Number> scalar_dependents;
AddCachedResult(result, dependents, scalar_dependents);
}
template <class T>
bool CachedResults<T>::GetCachedResult(T& retResult, const std::vector<const TaggedObject*>& dependents,
const std::vector<Number>& scalar_dependents) const
{
#ifdef IP_DEBUG_CACHE
DBG_START_METH("CachedResults<T>::GetCachedResult", dbg_verbosity);
#endif
if (!cached_results_)
return false;
CleanupInvalidatedResults();
bool retValue = false;
typename std::list< DependentResult<T>* >::const_iterator iter;
for (iter = cached_results_->begin(); iter != cached_results_->end(); iter++) {
if ((*iter)->DependentsIdentical(dependents, scalar_dependents)) {
retResult = (*iter)->GetResult();
retValue = true;
break;
}
}
#ifdef IP_DEBUG_CACHE
DBG_EXEC(2, DebugPrintCachedResults());
#endif
return retValue;
}
template <class T>
bool CachedResults<T>::GetCachedResult(
T& retResult, const std::vector<const TaggedObject*>& dependents) const
{
std::vector<Number> scalar_dependents;
return GetCachedResult(retResult, dependents, scalar_dependents);
}
template <class T>
void CachedResults<T>::AddCachedResult1Dep(const T& result,
const TaggedObject* dependent1)
{
#ifdef IP_DEBUG_CACHE
DBG_START_METH("CachedResults<T>::AddCachedResult1Dep", dbg_verbosity);
#endif
std::vector<const TaggedObject*> dependents(1);
dependents[0] = dependent1;
AddCachedResult(result, dependents);
}
template <class T>
bool CachedResults<T>::GetCachedResult1Dep(T& retResult, const TaggedObject* dependent1)
{
#ifdef IP_DEBUG_CACHE
DBG_START_METH("CachedResults<T>::GetCachedResult1Dep", dbg_verbosity);
#endif
std::vector<const TaggedObject*> dependents(1);
dependents[0] = dependent1;
return GetCachedResult(retResult, dependents);
}
template <class T>
void CachedResults<T>::AddCachedResult2Dep(const T& result, const TaggedObject* dependent1,
const TaggedObject* dependent2)
{
#ifdef IP_DEBUG_CACHE
DBG_START_METH("CachedResults<T>::AddCachedResult2dDep", dbg_verbosity);
#endif
std::vector<const TaggedObject*> dependents(2);
dependents[0] = dependent1;
dependents[1] = dependent2;
AddCachedResult(result, dependents);
}
template <class T>
bool CachedResults<T>::GetCachedResult2Dep(T& retResult, const TaggedObject* dependent1, const TaggedObject* dependent2)
{
#ifdef IP_DEBUG_CACHE
DBG_START_METH("CachedResults<T>::GetCachedResult2Dep", dbg_verbosity);
#endif
std::vector<const TaggedObject*> dependents(2);
dependents[0] = dependent1;
dependents[1] = dependent2;
return GetCachedResult(retResult, dependents);
}
template <class T>
void CachedResults<T>::AddCachedResult3Dep(const T& result, const TaggedObject* dependent1,
const TaggedObject* dependent2,
const TaggedObject* dependent3)
{
#ifdef IP_DEBUG_CACHE
DBG_START_METH("CachedResults<T>::AddCachedResult2dDep", dbg_verbosity);
#endif
std::vector<const TaggedObject*> dependents(3);
dependents[0] = dependent1;
dependents[1] = dependent2;
dependents[2] = dependent3;
AddCachedResult(result, dependents);
}
template <class T>
bool CachedResults<T>::GetCachedResult3Dep(T& retResult, const TaggedObject* dependent1,
const TaggedObject* dependent2,
const TaggedObject* dependent3)
{
#ifdef IP_DEBUG_CACHE
DBG_START_METH("CachedResults<T>::GetCachedResult2Dep", dbg_verbosity);
#endif
std::vector<const TaggedObject*> dependents(3);
dependents[0] = dependent1;
dependents[1] = dependent2;
dependents[2] = dependent3;
return GetCachedResult(retResult, dependents);
}
template <class T>
bool CachedResults<T>::InvalidateResult(const std::vector<const TaggedObject*>& dependents,
const std::vector<Number>& scalar_dependents)
{
if (!cached_results_)
return false;
CleanupInvalidatedResults();
bool retValue = false;
typename std::list< DependentResult<T>* >::const_iterator iter;
for (iter = cached_results_->begin(); iter != cached_results_->end();
iter++) {
if ((*iter)->DependentsIdentical(dependents, scalar_dependents)) {
(*iter)->Invalidate();
retValue = true;
break;
}
}
return retValue;
}
template <class T>
void CachedResults<T>::Clear()
{
if (!cached_results_)
return;
typename std::list< DependentResult<T>* >::const_iterator iter;
for (iter = cached_results_->begin(); iter != cached_results_->end();
iter++) {
(*iter)->Invalidate();
}
CleanupInvalidatedResults();
}
template <class T>
void CachedResults<T>::Clear(Int max_cache_size)
{
Clear();
max_cache_size_ = max_cache_size;
}
template <class T>
void CachedResults<T>::CleanupInvalidatedResults() const
{
#ifdef IP_DEBUG_CACHE
DBG_START_METH("CachedResults<T>::CleanupInvalidatedResults", dbg_verbosity);
#endif
if (!cached_results_)
return;
typename std::list< DependentResult<T>* >::iterator iter;
iter = cached_results_->begin();
while (iter != cached_results_->end()) {
if ((*iter)->IsStale()) {
typename std::list< DependentResult<T>* >::iterator
iter_to_remove = iter;
iter++;
DependentResult<T>* result_to_delete = (*iter_to_remove);
cached_results_->erase(iter_to_remove);
delete result_to_delete;
}
else {
iter++;
}
}
}
template <class T>
void CachedResults<T>::DebugPrintCachedResults() const
{
#ifdef IP_DEBUG_CACHE
DBG_START_METH("CachedResults<T>::DebugPrintCachedResults", dbg_verbosity);
if (DBG_VERBOSITY()>=2 ) {
if (!cached_results_) {
DBG_PRINT((2,"Currentlt no cached results:\n"));
}
else {
typename std::list< DependentResult<T>* >::const_iterator iter;
DBG_PRINT((2,"Current set of cached results:\n"));
for (iter = cached_results_->begin(); iter != cached_results_->end(); iter++) {
DBG_PRINT((2," DependentResult:0x%x\n", (*iter)));
}
}
}
#endif
}
} // namespace Ipopt
#endif
+340
View File
@@ -0,0 +1,340 @@
// Copyright (C) 2004, 2009 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpCompoundMatrix.hpp 2269 2013-05-05 11:32:40Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPCOMPOUNDMATRIX_HPP__
#define __IPCOMPOUNDMATRIX_HPP__
#include "IpUtils.hpp"
#include "IpMatrix.hpp"
namespace Ipopt
{
/* forward declarations */
class CompoundMatrixSpace;
/** Class for Matrices consisting of other matrices. This matrix is
* a matrix that consists of zero, one or more Matrices's which are
* arranged like this: \f$ M_{\rm compound} =
* \left(\begin{array}{cccc}M_{00} & M_{01} & \ldots & M_{0,{\rm
* ncomp\_cols}-1} \\ \dots &&&\dots \\ M_{{\rm ncomp\_rows}-1,0} &
* M_{{\rm ncomp\_rows}-1,1} & \dots & M_{{\rm ncomp\_rows}-1,{\rm
* ncomp\_cols}-1}\end{array}\right)\f$. The individual components
* can be associated to different MatrixSpaces. The individual
* components can also be const and non-const Matrices. If a
* component is not set (i.e., it's pointer is NULL), then this
* components is treated like a zero-matrix of appropriate
* dimensions.
*/
class CompoundMatrix : public Matrix
{
public:
/**@name Constructors / Destructors */
//@{
/** Constructor, taking the owner_space. The owner_space has to
* be defined, so that at each block row and column contain at
* least one non-NULL component. The individual components can
* be set afterwards with the SeteComp and SetCompNonConst
* methods.
*/
CompoundMatrix(const CompoundMatrixSpace* owner_space);
/** Destructor */
virtual ~CompoundMatrix();
//@}
/** Method for setting an individual component at position (irow,
* icol) in the compound matrix. The counting of indices starts
* at 0. */
void SetComp(Index irow, Index jcol, const Matrix& matrix);
/** Method to set a non-const Matrix entry */
void SetCompNonConst(Index irow, Index jcol, Matrix& matrix);
/** Method to create a new matrix from the space for this block */
void CreateBlockFromSpace(Index irow, Index jcol);
/** Method for retrieving one block from the compound matrix as a
* const Matrix.
*/
SmartPtr<const Matrix> GetComp(Index irow, Index jcol) const
{
return ConstComp(irow, jcol);
}
/** Method for retrieving one block from the compound matrix as a
* non-const Matrix. Note that calling this method with mark the
* CompoundMatrix as changed. Therefore, only use this method if
* you are intending to change the Matrix that you receive. */
SmartPtr<Matrix> GetCompNonConst(Index irow, Index jcol)
{
ObjectChanged();
return Comp(irow, jcol);
}
/** Number of block rows of this compound matrix. */
inline Index NComps_Rows() const;
/** Number of block colmuns of this compound matrix. */
inline Index NComps_Cols() const;
protected:
/**@name Methods overloaded from Matrix */
//@{
virtual void MultVectorImpl(Number alpha, const Vector& x,
Number beta, Vector& y) const;
virtual void TransMultVectorImpl(Number alpha, const Vector& x,
Number beta, Vector& y) const;
/** X = beta*X + alpha*(Matrix S^{-1} Z). Specialized implementation.
*/
virtual void AddMSinvZImpl(Number alpha, const Vector& S, const Vector& Z,
Vector& X) const;
/** X = S^{-1} (r + alpha*Z*M^Td). Specialized implementation.
*/
virtual void SinvBlrmZMTdBrImpl(Number alpha, const Vector& S,
const Vector& R, const Vector& Z,
const Vector& D, Vector& X) const;
/** Method for determining if all stored numbers are valid (i.e.,
* no Inf or Nan). */
virtual bool HasValidNumbersImpl() const;
virtual void ComputeRowAMaxImpl(Vector& rows_norms, bool init) const;
virtual void ComputeColAMaxImpl(Vector& cols_norms, bool init) const;
virtual void PrintImpl(const Journalist& jnlst,
EJournalLevel level,
EJournalCategory category,
const std::string& name,
Index indent,
const std::string& prefix) const;
//@}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
CompoundMatrix();
/** Copy Constructor */
CompoundMatrix(const CompoundMatrix&);
/** Overloaded Equals Operator */
void operator=(const CompoundMatrix&);
//@}
/** Matrix of matrix's containing the components */
std::vector<std::vector<SmartPtr<Matrix> > > comps_;
/** Matrix of const matrix's containing the components */
std::vector<std::vector<SmartPtr<const Matrix> > > const_comps_;
/** Copy of the owner_space ptr as a CompoundMatrixSpace instead
* of MatrixSpace */
const CompoundMatrixSpace* owner_space_;
/** boolean indicating if the compound matrix is in a "valid" state */
mutable bool matrices_valid_;
/** Method to check whether or not the matrices are valid */
bool MatricesValid() const;
inline const Matrix* ConstComp(Index irow, Index jcol) const;
inline Matrix* Comp(Index irow, Index jcol);
};
/** This is the matrix space for CompoundMatrix. Before a CompoundMatrix
* can be created, at least one MatrixSpace has to be set per block
* row and column. Individual component MatrixSpace's can be set
* with the SetComp method.
*/
class CompoundMatrixSpace : public MatrixSpace
{
public:
/** @name Constructors / Destructors */
//@{
/** Constructor, given the number of row and columns blocks, as
* well as the totel number of rows and columns.
*/
CompoundMatrixSpace(Index ncomps_rows,
Index ncomps_cols,
Index total_nRows,
Index total_nCols);
/** Destructor */
~CompoundMatrixSpace()
{}
//@}
/** @name Methods for setting information about the components. */
//@{
/** Set the number nrows of rows in row-block number irow. */
void SetBlockRows(Index irow, Index nrows);
/** Set the number ncols of columns in column-block number jcol. */
void SetBlockCols(Index jcol, Index ncols);
/** Get the number nrows of rows in row-block number irow. */
Index GetBlockRows(Index irow) const;
/** Set the number ncols of columns in column-block number jcol. */
Index GetBlockCols(Index jcol) const;
/** Set the component MatrixSpace. If auto_allocate is true, then
* a new CompoundMatrix created later with MakeNew will have this
* component automatically created with the Matrix's MakeNew.
* Otherwise, the corresponding component will be NULL and has to
* be set with the SetComp methods of the CompoundMatrix.
*/
void SetCompSpace(Index irow, Index jcol,
const MatrixSpace& mat_space,
bool auto_allocate = false);
//@}
/** Obtain the component MatrixSpace in block row irow and block
* column jcol.
*/
SmartPtr<const MatrixSpace> GetCompSpace(Index irow, Index jcol) const
{
DBG_ASSERT(irow<NComps_Rows());
DBG_ASSERT(jcol<NComps_Cols());
return comp_spaces_[irow][jcol];
}
/** @name Accessor methods */
//@{
/** Number of block rows */
Index NComps_Rows() const
{
return ncomps_rows_;
}
/** Number of block columns */
Index NComps_Cols() const
{
return ncomps_cols_;
}
/** True if the blocks lie on the diagonal - can make some operations faster */
bool Diagonal() const
{
return diagonal_;
}
//@}
/** Method for creating a new matrix of this specific type. */
CompoundMatrix* MakeNewCompoundMatrix() const;
/** Overloaded MakeNew method for the MatrixSpace base class.
*/
virtual Matrix* MakeNew() const
{
return MakeNewCompoundMatrix();
}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default constructor */
CompoundMatrixSpace();
/** Copy Constructor */
CompoundMatrixSpace(const CompoundMatrixSpace&);
/** Overloaded Equals Operator */
CompoundMatrixSpace& operator=(const CompoundMatrixSpace&);
//@}
/** Number of block rows */
Index ncomps_rows_;
/** Number of block columns */
Index ncomps_cols_;
/** Store whether or not the dimensions are valid */
mutable bool dimensions_set_;
/** 2-dim std::vector of matrix spaces for the components */
std::vector<std::vector<SmartPtr<const MatrixSpace> > > comp_spaces_;
/** 2-dim std::vector of booleans deciding whether to
* allocate a new matrix for the blocks automagically */
std::vector<std::vector< bool > > allocate_block_;
/** Vector of the number of rows in each comp column */
std::vector<Index> block_rows_;
/** Vector of the number of cols in each comp row */
std::vector<Index> block_cols_;
/** true if the CompoundMatrixSpace only has Matrix spaces along the diagonal.
* this means that the CompoundMatrix will only have matrices along the
* diagonal and it could make some operations more efficient
*/
bool diagonal_;
/** Auxilliary function for debugging to set if all block
* dimensions have been set. */
bool DimensionsSet() const;
};
/* inline methods */
inline
Index CompoundMatrix::NComps_Rows() const
{
return owner_space_->NComps_Rows();
}
inline
Index CompoundMatrix::NComps_Cols() const
{
return owner_space_->NComps_Cols();
}
inline
const Matrix* CompoundMatrix::ConstComp(Index irow, Index jcol) const
{
DBG_ASSERT(irow < NComps_Rows());
DBG_ASSERT(jcol < NComps_Cols());
if (IsValid(comps_[irow][jcol])) {
return GetRawPtr(comps_[irow][jcol]);
}
else if (IsValid(const_comps_[irow][jcol])) {
return GetRawPtr(const_comps_[irow][jcol]);
}
return NULL;
}
inline
Matrix* CompoundMatrix::Comp(Index irow, Index jcol)
{
DBG_ASSERT(irow < NComps_Rows());
DBG_ASSERT(jcol < NComps_Cols());
return GetRawPtr(comps_[irow][jcol]);
}
} // namespace Ipopt
#endif
+283
View File
@@ -0,0 +1,283 @@
// Copyright (C) 2004, 2008 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpCompoundSymMatrix.hpp 2269 2013-05-05 11:32:40Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPCOMPOUNDSYMMATRIX_HPP__
#define __IPCOMPOUNDSYMMATRIX_HPP__
#include "IpUtils.hpp"
#include "IpSymMatrix.hpp"
namespace Ipopt
{
/* forward declarations */
class CompoundSymMatrixSpace;
/** Class for symmetric matrices consisting of other matrices.
* Here, the lower left block of the matrix is stored.
*/
class CompoundSymMatrix : public SymMatrix
{
public:
/**@name Constructors / Destructors */
//@{
/** Constructor, taking only the number for block components into the
* row and column direction. The owner_space has to be defined, so
* that at each block row and column contain at least one non-NULL
* component.
*/
CompoundSymMatrix(const CompoundSymMatrixSpace* owner_space);
/** Destructor */
~CompoundSymMatrix();
//@}
/** Method for setting an individual component at position (irow,
* icol) in the compound matrix. The counting of indices starts
* at 0. Since this only the lower left components are stored, we need
* to have jcol<=irow, and if irow==jcol, the matrix must be a SymMatrix */
void SetComp(Index irow, Index jcol, const Matrix& matrix);
/** Non const version of the same method */
void SetCompNonConst(Index irow, Index jcol, Matrix& matrix);
/** Method for retrieving one block from the compound matrix.
* Since this only the lower left components are stored, we need
* to have jcol<=irow */
SmartPtr<const Matrix> GetComp(Index irow, Index jcol) const
{
return ConstComp(irow,jcol);
}
/** Non const version of GetComp. You should only use this method
* if you are intending to change the matrix you receive, since
* this CompoundSymMatrix will be marked as changed. */
SmartPtr<Matrix> GetCompNonConst(Index irow, Index jcol)
{
ObjectChanged();
return Comp(irow,jcol);
}
/** Method for creating a new matrix of this specific type. */
SmartPtr<CompoundSymMatrix> MakeNewCompoundSymMatrix() const;
// The following don't seem to be necessary
/* Number of block rows of this compound matrix. */
// Index NComps_NRows() const { return NComps_Dim(); }
/* Number of block colmuns of this compound matrix. */
// Index NComps_NCols() const { return NComps_Dim(); }
/** Number of block rows and columns */
Index NComps_Dim() const;
protected:
/**@name Methods overloaded from matrix */
//@{
virtual void MultVectorImpl(Number alpha, const Vector& x,
Number beta, Vector& y) const;
/** Method for determining if all stored numbers are valid (i.e.,
* no Inf or Nan). */
virtual bool HasValidNumbersImpl() const;
virtual void ComputeRowAMaxImpl(Vector& rows_norms, bool init) const;
virtual void PrintImpl(const Journalist& jnlst,
EJournalLevel level,
EJournalCategory category,
const std::string& name,
Index indent,
const std::string& prefix) const;
//@}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
CompoundSymMatrix();
/** Copy Constructor */
CompoundSymMatrix(const CompoundSymMatrix&);
/** Overloaded Equals Operator */
void operator=(const CompoundSymMatrix&);
//@}
/** Vector of vectors containing the components */
std::vector<std::vector<SmartPtr<Matrix> > > comps_;
/** Vector of vectors containing the const components */
std::vector<std::vector<SmartPtr<const Matrix> > > const_comps_;
/** Copy of the owner_space ptr as a CompoundSymMatrixSpace */
const CompoundSymMatrixSpace* owner_space_;
/** boolean indicating if the compound matrix is in a "valid" state */
mutable bool matrices_valid_;
/** method to check wether or not the matrices are valid */
bool MatricesValid() const;
/** Internal method to return a const pointer to one of the comps */
const Matrix* ConstComp(Index irow, Index jcol) const
{
DBG_ASSERT(irow < NComps_Dim());
DBG_ASSERT(jcol <= irow);
if (IsValid(comps_[irow][jcol])) {
return GetRawPtr(comps_[irow][jcol]);
}
else if (IsValid(const_comps_[irow][jcol])) {
return GetRawPtr(const_comps_[irow][jcol]);
}
return NULL;
}
/** Internal method to return a non-const pointer to one of the comps */
Matrix* Comp(Index irow, Index jcol)
{
DBG_ASSERT(irow < NComps_Dim());
DBG_ASSERT(jcol <= irow);
// We shouldn't be asking for a non-const if this entry holds a
// const one...
DBG_ASSERT(IsNull(const_comps_[irow][jcol]));
if (IsValid(comps_[irow][jcol])) {
return GetRawPtr(comps_[irow][jcol]);
}
return NULL;
}
};
/** This is the matrix space for CompoundSymMatrix. Before a
* CompoundSymMatrix can be created, at least one SymMatrixSpace has
* to be set per block row and column. Individual component
* SymMatrixSpace's can be set with the SetComp method.
*/
class CompoundSymMatrixSpace : public SymMatrixSpace
{
public:
/** @name Constructors / Destructors */
//@{
/** Constructor, given the number of blocks (same for rows and
* columns), as well as the total dimension of the matrix.
*/
CompoundSymMatrixSpace(Index ncomp_spaces, Index total_dim);
/** Destructor */
~CompoundSymMatrixSpace()
{}
//@}
/** @name Methods for setting information about the components. */
//@{
/** Set the dimension dim for block row (or column) irow_jcol */
void SetBlockDim(Index irow_jcol, Index dim);
/** Get the dimension dim for block row (or column) irow_jcol */
Index GetBlockDim(Index irow_jcol) const;
/** Set the component SymMatrixSpace. If auto_allocate is true, then
* a new CompoundSymMatrix created later with MakeNew will have this
* component automatically created with the SymMatrix's MakeNew.
* Otherwise, the corresponding component will be NULL and has to
* be set with the SetComp methods of the CompoundSymMatrix.
*/
void SetCompSpace(Index irow, Index jcol,
const MatrixSpace& mat_space,
bool auto_allocate = false);
//@}
/** Obtain the component MatrixSpace in block row irow and block
* column jcol.
*/
SmartPtr<const MatrixSpace> GetCompSpace(Index irow, Index jcol) const
{
DBG_ASSERT(irow<ncomp_spaces_);
DBG_ASSERT(jcol<=irow);
return comp_spaces_[irow][jcol];
}
/** @name Accessor methods */
//@{
Index NComps_Dim() const
{
return ncomp_spaces_;
}
//@}
/** Method for creating a new matrix of this specific type. */
CompoundSymMatrix* MakeNewCompoundSymMatrix() const;
/** Overloaded MakeNew method for the SymMatrixSpace base class.
*/
virtual SymMatrix* MakeNewSymMatrix() const
{
return MakeNewCompoundSymMatrix();
}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default constructor */
CompoundSymMatrixSpace();
/** Copy Constructor */
CompoundSymMatrixSpace(const CompoundSymMatrix&);
/** Overloaded Equals Operator */
CompoundSymMatrixSpace& operator=(const CompoundSymMatrixSpace&);
//@}
/** Number of components per row and column */
Index ncomp_spaces_;
/** Vector of the number of rows in each comp column,
* Since this is symmetric, this is also the number
* of columns in each row, hence, it is the dimension
* each of the diagonals */
std::vector<Index> block_dim_;
/** 2-dim std::vector of matrix spaces for the components. Only
* the lower right part is stored. */
std::vector<std::vector<SmartPtr<const MatrixSpace> > > comp_spaces_;
/** 2-dim std::vector of booleans deciding whether to
* allocate a new matrix for the blocks automagically */
std::vector<std::vector< bool > > allocate_block_;
/** boolean indicating if the compound matrix space is in a "valid" state */
mutable bool dimensions_set_;
/** Method to check whether or not the spaces are valid */
bool DimensionsSet() const;
};
inline
SmartPtr<CompoundSymMatrix> CompoundSymMatrix::MakeNewCompoundSymMatrix() const
{
return owner_space_->MakeNewCompoundSymMatrix();
}
} // namespace Ipopt
#endif
+339
View File
@@ -0,0 +1,339 @@
// Copyright (C) 2004, 2006 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpCompoundVector.hpp 2269 2013-05-05 11:32:40Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPCOMPOUNDVECTOR_HPP__
#define __IPCOMPOUNDVECTOR_HPP__
#include "IpUtils.hpp"
#include "IpVector.hpp"
#include <vector>
namespace Ipopt
{
/* forward declarations */
class CompoundVectorSpace;
/** Class of Vectors consisting of other vectors. This vector is a
* vector that consists of zero, one or more Vector's which are
* stacked on each others: \f$ x_{\rm compound} =
* \left(\begin{array}{c}x_0\\\dots\\x_{{\rm
* ncomps} - 1}\end{array}\right)\f$. The individual components can be
* associated to different VectorSpaces. The individual components
* can also be const and non-const Vectors.
*/
class CompoundVector : public Vector
{
public:
/**@name Constructors/Destructors */
//@{
/** Constructor, given the corresponding CompoundVectorSpace.
* Before this constructor can be called, all components of the
* CompoundVectorSpace have to be set, so that the constructors
* for the individual components can be called. If the flag
* create_new is true, then the individual components of the new
* CompoundVector are initialized with the MakeNew methods of
* each VectorSpace (and are non-const). Otherwise, the
* individual components can later be set using the SetComp and
* SetCompNonConst method.
*/
CompoundVector(const CompoundVectorSpace* owner_space, bool create_new);
/** Default destructor */
virtual ~CompoundVector();
//@}
/** Method for setting the pointer for a component that is a const
* Vector
*/
void SetComp(Index icomp, const Vector& vec);
/** Method for setting the pointer for a component that is a
* non-const Vector
*/
void SetCompNonConst(Index icomp, Vector& vec);
/** Number of components of this compound vector */
inline Index NComps() const;
/** Check if a particular component is const or not */
bool IsCompConst(Index i) const
{
DBG_ASSERT(i > 0 && i < NComps());
DBG_ASSERT(IsValid(comps_[i]) || IsValid(const_comps_[i]));
if (IsValid(const_comps_[i])) {
return true;
}
return false;
}
/** Check if a particular component is null or not */
bool IsCompNull(Index i) const
{
DBG_ASSERT(i >= 0 && i < NComps());
if (IsValid(comps_[i]) || IsValid(const_comps_[i])) {
return false;
}
return true;
}
/** Return a particular component (const version) */
SmartPtr<const Vector> GetComp(Index i) const
{
return ConstComp(i);
}
/** Return a particular component (non-const version). Note that
* calling this method with mark the CompoundVector as changed.
* Therefore, only use this method if you are intending to change
* the Vector that you receive.
*/
SmartPtr<Vector> GetCompNonConst(Index i)
{
ObjectChanged();
return Comp(i);
}
protected:
/** @name Overloaded methods from Vector base class */
//@{
/** Copy the data of the vector x into this vector (DCOPY). */
virtual void CopyImpl(const Vector& x);
/** Scales the vector by scalar alpha (DSCAL) */
virtual void ScalImpl(Number alpha);
/** Add the multiple alpha of vector x to this vector (DAXPY) */
virtual void AxpyImpl(Number alpha, const Vector &x);
/** Computes inner product of vector x with this (DDOT) */
virtual Number DotImpl(const Vector &x) const;
/** Computes the 2-norm of this vector (DNRM2) */
virtual Number Nrm2Impl() const;
/** Computes the 1-norm of this vector (DASUM) */
virtual Number AsumImpl() const;
/** Computes the max-norm of this vector (based on IDAMAX) */
virtual Number AmaxImpl() const;
/** Set each element in the vector to the scalar alpha. */
virtual void SetImpl(Number value);
/** Element-wise division \f$y_i \gets y_i/x_i\f$.*/
virtual void ElementWiseDivideImpl(const Vector& x);
/** Element-wise multiplication \f$y_i \gets y_i*x_i\f$.*/
virtual void ElementWiseMultiplyImpl(const Vector& x);
/** Element-wise max against entries in x */
virtual void ElementWiseMaxImpl(const Vector& x);
/** Element-wise min against entries in x */
virtual void ElementWiseMinImpl(const Vector& x);
/** Element-wise reciprocal */
virtual void ElementWiseReciprocalImpl();
/** Element-wise absolute values */
virtual void ElementWiseAbsImpl();
/** Element-wise square-root */
virtual void ElementWiseSqrtImpl();
/** Replaces entries with sgn of the entry */
virtual void ElementWiseSgnImpl();
/** Add scalar to every component of the vector.*/
virtual void AddScalarImpl(Number scalar);
/** Max value in the vector */
virtual Number MaxImpl() const;
/** Min value in the vector */
virtual Number MinImpl() const;
/** Computes the sum of the lements of vector */
virtual Number SumImpl() const;
/** Computes the sum of the logs of the elements of vector */
virtual Number SumLogsImpl() const;
/** @name Implemented specialized functions */
//@{
/** Add two vectors (a * v1 + b * v2). Result is stored in this
vector. */
void AddTwoVectorsImpl(Number a, const Vector& v1,
Number b, const Vector& v2, Number c);
/** Fraction to the boundary parameter. */
Number FracToBoundImpl(const Vector& delta, Number tau) const;
/** Add the quotient of two vectors, y = a * z/s + c * y. */
void AddVectorQuotientImpl(Number a, const Vector& z, const Vector& s,
Number c);
//@}
/** Method for determining if all stored numbers are valid (i.e.,
* no Inf or Nan). */
virtual bool HasValidNumbersImpl() const;
/** @name Output methods */
//@{
/* Print the entire vector with padding */
virtual void PrintImpl(const Journalist& jnlst,
EJournalLevel level,
EJournalCategory category,
const std::string& name,
Index indent,
const std::string& prefix) const;
//@}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called.
*/
//@{
/** Default Constructor */
CompoundVector();
/** Copy Constructor */
CompoundVector(const CompoundVector&);
/** Overloaded Equals Operator */
void operator=(const CompoundVector&);
//@}
/** Components of the compound vector. The components
* are stored by SmartPtrs in a std::vector
*/
std::vector< SmartPtr<Vector> > comps_;
std::vector< SmartPtr<const Vector> > const_comps_;
const CompoundVectorSpace* owner_space_;
bool vectors_valid_;
bool VectorsValid();
inline const Vector* ConstComp(Index i) const;
inline Vector* Comp(Index i);
};
/** This vectors space is the vector space for CompoundVector.
* Before a CompoundVector can be created, all components of this
* CompoundVectorSpace have to be set. When calling the constructor,
* the number of component has to be specified. The individual
* VectorSpaces can be set with the SetComp method.
*/
class CompoundVectorSpace : public VectorSpace
{
public:
/** @name Constructors/Destructors. */
//@{
/** Constructor, has to be given the number of components and the
* total dimension of all components combined. */
CompoundVectorSpace(Index ncomp_spaces, Index total_dim);
/** Destructor */
~CompoundVectorSpace()
{}
//@}
/** Method for setting the individual component VectorSpaces */
virtual void SetCompSpace(Index icomp /** Number of the component to be set */ ,
const VectorSpace& vec_space /** VectorSpace for component icomp */
);
/** Method for obtaining an individual component VectorSpace */
SmartPtr<const VectorSpace> GetCompSpace(Index icomp) const;
/** Accessor method to obtain the number of components */
Index NCompSpaces() const
{
return ncomp_spaces_;
}
/** Method for creating a new vector of this specific type. */
virtual CompoundVector* MakeNewCompoundVector(bool create_new = true) const
{
return new CompoundVector(this, create_new);
}
/** Overloaded MakeNew method for the VectorSpace base class.
*/
virtual Vector* MakeNew() const
{
return MakeNewCompoundVector();
}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default constructor */
CompoundVectorSpace();
/** Copy Constructor */
CompoundVectorSpace(const CompoundVectorSpace&);
/** Overloaded Equals Operator */
CompoundVectorSpace& operator=(const CompoundVectorSpace&);
//@}
/** Number of components */
const Index ncomp_spaces_;
/** std::vector of vector spaces for the components */
std::vector< SmartPtr<const VectorSpace> > comp_spaces_;
};
/* inline methods */
inline
Index CompoundVector::NComps() const
{
return owner_space_->NCompSpaces();
}
inline
const Vector* CompoundVector::ConstComp(Index i) const
{
DBG_ASSERT(i < NComps());
DBG_ASSERT(IsValid(comps_[i]) || IsValid(const_comps_[i]));
if (IsValid(comps_[i])) {
return GetRawPtr(comps_[i]);
}
else if (IsValid(const_comps_[i])) {
return GetRawPtr(const_comps_[i]);
}
DBG_ASSERT(false && "shouldn't be here");
return NULL;
}
inline
Vector* CompoundVector::Comp(Index i)
{
DBG_ASSERT(i < NComps());
DBG_ASSERT(IsValid(comps_[i]));
return GetRawPtr(comps_[i]);
}
} // namespace Ipopt
#endif
+87
View File
@@ -0,0 +1,87 @@
// Copyright (C) 2004, 2009 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpConvCheck.hpp 1861 2010-12-21 21:34:47Z andreasw $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPCONVCHECK_HPP__
#define __IPCONVCHECK_HPP__
#include "IpAlgStrategy.hpp"
namespace Ipopt
{
/** Base class for checking the algorithm
* termination criteria.
*/
class ConvergenceCheck : public AlgorithmStrategyObject
{
public:
/**@name Constructors/Destructors */
//@{
/** Constructor */
ConvergenceCheck()
{}
/** Default destructor */
virtual ~ConvergenceCheck()
{}
//@}
/** Convergence return enum */
enum ConvergenceStatus {
CONTINUE,
CONVERGED,
CONVERGED_TO_ACCEPTABLE_POINT,
MAXITER_EXCEEDED,
CPUTIME_EXCEEDED,
DIVERGING,
USER_STOP,
FAILED
};
/** overloaded from AlgorithmStrategyObject */
virtual bool InitializeImpl(const OptionsList& options,
const std::string& prefix) = 0;
/** Pure virtual method for performing the convergence test. If
* call_intermediate_callback is true, the user callback method
* in the NLP should be called in order to see if the user
* requests an early termination. */
virtual ConvergenceStatus
CheckConvergence(bool call_intermediate_callback = true) = 0;
/** Method for testing if the current iterate is considered to
* satisfy the "accptable level" of accuracy. The idea is that
* if the desired convergence tolerance cannot be achieved, the
* algorithm might stop after a number of acceptable points have
* been encountered. */
virtual bool CurrentIsAcceptable()=0;
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
// ConvergenceCheck();
/** Copy Constructor */
ConvergenceCheck(const ConvergenceCheck&);
/** Overloaded Equals Operator */
void operator=(const ConvergenceCheck&);
//@}
};
} // namespace Ipopt
#endif
+150
View File
@@ -0,0 +1,150 @@
// Copyright (C) 2004, 2007 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpDebug.hpp 2005 2011-06-06 12:55:16Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPDEBUG_HPP__
#define __IPDEBUG_HPP__
#include "IpoptConfig.h"
#include "IpTypes.hpp"
#ifdef COIN_IPOPT_CHECKLEVEL
#ifdef HAVE_CASSERT
# include <cassert>
#else
# ifdef HAVE_ASSERT_H
# include <assert.h>
# else
# error "don't have header file for assert"
# endif
#endif
#else
#define COIN_IPOPT_CHECKLEVEL 0
#endif
#if COIN_IPOPT_CHECKLEVEL > 0
# ifdef NDEBUG
# undef NDEBUG
# endif
# define DBG_ASSERT(test) assert(test)
# define DBG_ASSERT_EXCEPTION(__condition, __except_type, __msg) \
ASSERT_EXCEPTION( (__condition), __except_type, __msg);
# define DBG_DO(__cmd) __cmd
#else
# define DBG_ASSERT(test)
# define DBG_ASSERT_EXCEPTION(__condition, __except_type, __msg)
# define DBG_DO(__cmd)
#endif
#ifndef COIN_IPOPT_VERBOSITY
#define COIN_IPOPT_VERBOSITY 0
#endif
#if COIN_IPOPT_VERBOSITY < 1
# define DBG_START_FUN(__func_name, __verbose_level)
# define DBG_START_METH(__func_name, __verbose_level)
# define DBG_PRINT(__printf_args)
# define DBG_PRINT_VECTOR(__verbose_level, __vec_name, __vec)
# define DBG_PRINT_MATRIX(__verbose_level, __mat_name, __mat)
# define DBG_EXEC(__verbosity, __cmd)
# define DBG_VERBOSITY() 0
#else
#include <string>
namespace Ipopt
{
// forward definition
class Journalist;
/** Class that lives throughout the execution of a method or
* function for which debug output is to be generated. The output
* is sent to the unique debug journalist that is set with
* SetJournalist at the beginning of program execution. */
class DebugJournalistWrapper
{
public:
/** @name Constructors/Destructors. */
//@{
DebugJournalistWrapper(std::string func_name, Index verbose_level);
DebugJournalistWrapper(std::string func_name, Index verbose_level,
const void* const method_owner);
~DebugJournalistWrapper();
//@}
/** @name accessor methods */
//@{
Index Verbosity()
{
return verbose_level_;
}
const Journalist* Jnlst()
{
return jrnl_;
}
Index IndentationLevel()
{
return indentation_level_;
}
//@}
/** Printing */
void DebugPrintf(Index verbosity, const char* pformat, ...);
/* Method for initialization of the static GLOBAL journalist,
* through with all debug printout is to be written. This needs
* to be set before any debug printout can be done. */
static void SetJournalist(Journalist* jrnl);
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** default constructor */
DebugJournalistWrapper();
/** copy contructor */
DebugJournalistWrapper(const DebugJournalistWrapper&);
/** Overloaded Equals Operator */
DebugJournalistWrapper& operator=(const DebugJournalistWrapper&);
//@}
static Index indentation_level_;
std::string func_name_;
Index verbose_level_;
const void* method_owner_;
static Journalist* jrnl_;
};
}
# define DBG_START_FUN(__func_name, __verbose_level) \
DebugJournalistWrapper dbg_jrnl((__func_name), (__verbose_level)); \
# define DBG_START_METH(__func_name, __verbose_level) \
DebugJournalistWrapper dbg_jrnl((__func_name), (__verbose_level), this);
# define DBG_PRINT(__args) \
dbg_jrnl.DebugPrintf __args;
# define DBG_EXEC(__verbose_level, __cmd) \
if (dbg_jrnl.Verbosity() >= (__verbose_level)) { \
(__cmd); \
}
# define DBG_VERBOSITY() \
dbg_jrnl.Verbosity()
#endif
#endif
+550
View File
@@ -0,0 +1,550 @@
// Copyright (C) 2004, 2009 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpDenseVector.hpp 2269 2013-05-05 11:32:40Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPDENSEVECTOR_HPP__
#define __IPDENSEVECTOR_HPP__
#include "IpUtils.hpp"
#include "IpVector.hpp"
#include <map>
namespace Ipopt
{
/* forward declarations */
class DenseVectorSpace;
/** @name Exceptions */
//@{
DECLARE_STD_EXCEPTION(METADATA_ERROR);
//@}
/** Dense Vector Implementation. This is the default Vector class
* in Ipopt. It stores vectors in contiguous Number arrays, unless
* the vector has the same value in all entires. In the latter
* case, we call the vector "homogeneous", and we store only the
* values that is repeated in all elements. If you want to obtain
* the values of vector, use the IsHomogeneous() method to find out
* what status the vector is in, and then use either Values() const
* or Scalar() const methods to get the values. To set the values
* of a homogeneous method, use the Set method. To set the values
* of a non-homogeneous vector, use the SetValues method, or use
* the non-const Values method to get an array that you can
* overwrite. In the latter case, storage is ensured.
*/
class DenseVector : public Vector
{
public:
/**@name Constructors / Destructors */
//@{
/** Default Constructor
*/
DenseVector(const DenseVectorSpace* owner_space);
/** Destructor
*/
virtual ~DenseVector();
//@}
/** @name Additional public methods not in Vector base class. */
//@{
/** Create a new DenseVector from same VectorSpace */
SmartPtr<DenseVector> MakeNewDenseVector() const;
/** Set elements in the vector to the Number array x. */
void SetValues(const Number *x);
/** Obtain pointer to the internal Number array with vector
* elements with the indention to change the vector data (USE
* WITH CARE!). This does not produce a copy, and lifetime is not
* guaranteed!.
*/
inline Number* Values();
/** Obtain pointer to the internal Number array with vector
* elements without the intention to change the vector data (USE
* WITH CARE!). This does not produce a copy, and lifetime is not
* guaranteed! IMPORTANT: If this method is currently
* homogeneous (i.e. IsHomogeneous returns true), then you cannot
* call this method. Instead, you need to use the Scalar()
* method.
*/
inline const Number* Values() const;
/** The same as the const version of Values, but we ensure that we
* always return a valid array, even if IsHomogeneous returns
* true. */
const Number* ExpandedValues() const;
/** This is the same as Values, but we add it here so that
* ExpandedValues can also be used for the non-const case. */
inline Number* ExpandedValues()
{
return Values();
}
/** Indicates if the vector is homogeneous (i.e., all entries have
* the value Scalar() */
bool IsHomogeneous() const
{
return homogeneous_;
}
/** Scalar value of all entries in a homogeneous vector */
Number Scalar() const
{
DBG_ASSERT(homogeneous_);
return scalar_;
}
//@}
/** @name Modifying subranges of the vector. */
//@{
/** Copy the data in x into the subrange of this vector starting
* at position Pos in this vector. Position count starts at 0.
*/
void CopyToPos(Index Pos, const Vector& x);
/** Copy a subrange of x, starting at Pos, into the full data of
* this vector. Position count starts at 0.
*/
void CopyFromPos(Index Pos, const Vector& x);
//@}
protected:
/** @name Overloaded methods from Vector base class */
//@{
/** Copy the data of the vector x into this vector (DCOPY). */
virtual void CopyImpl(const Vector& x);
/** Scales the vector by scalar alpha (DSCAL) */
virtual void ScalImpl(Number alpha);
/** Add the multiple alpha of vector x to this vector (DAXPY) */
virtual void AxpyImpl(Number alpha, const Vector &x);
/** Computes inner product of vector x with this (DDOT) */
virtual Number DotImpl(const Vector &x) const;
/** Computes the 2-norm of this vector (DNRM2) */
virtual Number Nrm2Impl() const;
/** Computes the 1-norm of this vector (DASUM) */
virtual Number AsumImpl() const;
/** Computes the max-norm of this vector (based on IDAMAX) */
virtual Number AmaxImpl() const;
/** Set each element in the vector to the scalar alpha. */
virtual void SetImpl(Number value);
/** Element-wise division \f$y_i \gets y_i/x_i\f$.*/
virtual void ElementWiseDivideImpl(const Vector& x);
/** Element-wise multiplication \f$y_i \gets y_i*x_i\f$.*/
virtual void ElementWiseMultiplyImpl(const Vector& x);
/** Set entry to max of itself and the corresponding element in x */
virtual void ElementWiseMaxImpl(const Vector& x);
/** Set entry to min of itself and the corresponding element in x */
virtual void ElementWiseMinImpl(const Vector& x);
/** reciprocates the elements of the vector */
virtual void ElementWiseReciprocalImpl();
/** take abs of the elements of the vector */
virtual void ElementWiseAbsImpl();
/** take square-root of the elements of the vector */
virtual void ElementWiseSqrtImpl();
/** Changes each entry in the vector to its sgn value */
virtual void ElementWiseSgnImpl();
/** Add scalar to every component of the vector.*/
virtual void AddScalarImpl(Number scalar);
/** Max value in the vector */
virtual Number MaxImpl() const;
/** Min value in the vector */
virtual Number MinImpl() const;
/** Computes the sum of the lements of vector */
virtual Number SumImpl() const;
/** Computes the sum of the logs of the elements of vector */
virtual Number SumLogsImpl() const;
/** @name Implemented specialized functions */
//@{
/** Add two vectors (a * v1 + b * v2). Result is stored in this
vector. */
void AddTwoVectorsImpl(Number a, const Vector& v1,
Number b, const Vector& v2, Number c);
/** Fraction to the boundary parameter. */
Number FracToBoundImpl(const Vector& delta, Number tau) const;
/** Add the quotient of two vectors, y = a * z/s + c * y. */
void AddVectorQuotientImpl(Number a, const Vector& z, const Vector& s,
Number c);
//@}
/** @name Output methods */
//@{
/* Print the entire vector with padding */
virtual void PrintImpl(const Journalist& jnlst,
EJournalLevel level,
EJournalCategory category,
const std::string& name,
Index indent,
const std::string& prefix) const
{
PrintImplOffset(jnlst, level, category, name, indent, prefix, 1);
}
/* Print the entire vector with padding, and start counting with
an offset. */
void PrintImplOffset(const Journalist& jnlst,
EJournalLevel level,
EJournalCategory category,
const std::string& name,
Index indent,
const std::string& prefix,
Index offset) const;
//@}
friend class ParVector;
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
DenseVector();
/** Copy Constructor */
DenseVector(const DenseVector&);
/** Overloaded Equals Operator */
void operator=(const DenseVector&);
//@}
/** Copy of the owner_space ptr as a DenseVectorSpace instead
* of a VectorSpace
*/
const DenseVectorSpace* owner_space_;
/** Dense Number array of vector values. */
Number* values_;
/** Dense Number array pointer that is used for ExpandedValues */
mutable Number* expanded_values_;
/** Method of getting the internal values array, making sure that
* memory has been allocated */
inline
Number* values_allocated();
/** Flag for Initialization. This flag is false, if the data has
not yet been initialized. */
bool initialized_;
/** Flag indicating whether the vector is currently homogeneous
* (that is, all elements have the same value). This flag is used
* to determine whether the elements of the vector are stored in
* values_ or in scalar_ */
bool homogeneous_;
/** Homogeneous value of all elements if the vector is currently
* homogenous */
Number scalar_;
/** Auxilliary method for setting explicitly all elements in
* values_ to the current scalar value. */
void set_values_from_scalar();
};
/** typedefs for the map variables that define meta data for the
* DenseVectorSpace
*/
typedef std::map<std::string, std::vector<std::string> > StringMetaDataMapType;
typedef std::map<std::string, std::vector<Index> > IntegerMetaDataMapType;
typedef std::map<std::string, std::vector<Number> > NumericMetaDataMapType;
/** This vectors space is the vector space for DenseVector.
*/
class DenseVectorSpace : public VectorSpace
{
public:
/** @name Constructors/Destructors. */
//@{
/** Constructor, requires dimension of all vector for this
* VectorSpace
*/
DenseVectorSpace(Index dim)
:
VectorSpace(dim)
{}
/** Destructor */
~DenseVectorSpace()
{}
//@}
/** Method for creating a new vector of this specific type. */
inline
DenseVector* MakeNewDenseVector() const
{
return new DenseVector(this);
}
/** Instantiation of the generate MakeNew method for the
* VectorSpace base class.
*/
virtual Vector* MakeNew() const
{
return MakeNewDenseVector();
}
/**@name Methods called by DenseVector for memory management.
* This could allow to have sophisticated memory management in the
* VectorSpace.
*/
//@{
/** Allocate internal storage for the DenseVector */
inline
Number* AllocateInternalStorage() const;
/** Deallocate internal storage for the DenseVector */
inline
void FreeInternalStorage(Number* values) const;
//@}
/**@name Methods for dealing with meta data on the vector
*/
//@{
/** Check if string meta exists for tag */
inline
bool HasStringMetaData(const std::string tag) const;
/** Check if Integer meta exists for tag */
inline
bool HasIntegerMetaData(const std::string tag) const;
/** Check if Numeric meta exists for tag */
inline
bool HasNumericMetaData(const std::string tag) const;
/** Get meta data of type std::string by tag */
inline
const std::vector<std::string>& GetStringMetaData(const std::string& tag) const;
/** Get meta data of type Index by tag */
inline
const std::vector<Index>& GetIntegerMetaData(const std::string& tag) const;
/** Get meta data of type Number by tag */
inline
const std::vector<Number>& GetNumericMetaData(const std::string& tag) const;
/** Set meta data of type std::string by tag */
inline
void SetStringMetaData(std::string tag, std::vector<std::string> meta_data);
/** Set meta data of type Index by tag */
inline
void SetIntegerMetaData(std::string tag, std::vector<Index> meta_data);
/** Set meta data of type Number by tag */
inline
void SetNumericMetaData(std::string tag, std::vector<Number> meta_data);
/** Get map of meta data of type Number */
inline
const StringMetaDataMapType& GetStringMetaData() const;
/** Get map of meta data of type Number */
inline
const IntegerMetaDataMapType& GetIntegerMetaData() const;
/** Get map of meta data of type Number */
inline
const NumericMetaDataMapType& GetNumericMetaData() const;
//@}
private:
// variables to store vector meta data
StringMetaDataMapType string_meta_data_;
IntegerMetaDataMapType integer_meta_data_;
NumericMetaDataMapType numeric_meta_data_;
};
// inline functions
inline Number* DenseVector::Values()
{
// Here we assume that every time someone requests this direct raw
// pointer, the data is going to change and the Tag for this
// vector has to be updated.
if (initialized_ && homogeneous_) {
// If currently the vector is a homogeneous vector, set all elements
// explicitly to this value
set_values_from_scalar();
}
ObjectChanged();
initialized_= true;
homogeneous_ = false;
return values_allocated();
}
inline const Number* DenseVector::Values() const
{
DBG_ASSERT(initialized_ && (Dim()==0 || values_));
return values_;
}
inline Number* DenseVector::values_allocated()
{
if (values_==NULL) {
values_ = owner_space_->AllocateInternalStorage();
}
return values_;
}
inline
Number* DenseVectorSpace::AllocateInternalStorage() const
{
if (Dim()>0) {
return new Number[Dim()];
}
else {
return NULL;
}
}
inline
void DenseVectorSpace::FreeInternalStorage(Number* values) const
{
delete [] values;
}
inline
SmartPtr<DenseVector> DenseVector::MakeNewDenseVector() const
{
return owner_space_->MakeNewDenseVector();
}
inline
bool DenseVectorSpace::HasStringMetaData(const std::string tag) const
{
StringMetaDataMapType::const_iterator iter;
iter = string_meta_data_.find(tag);
if (iter != string_meta_data_.end()) {
return true;
}
return false;
}
inline
bool DenseVectorSpace::HasIntegerMetaData(const std::string tag) const
{
IntegerMetaDataMapType::const_iterator iter;
iter = integer_meta_data_.find(tag);
if (iter != integer_meta_data_.end()) {
return true;
}
return false;
}
inline
bool DenseVectorSpace::HasNumericMetaData(const std::string tag) const
{
NumericMetaDataMapType::const_iterator iter;
iter = numeric_meta_data_.find(tag);
if (iter != numeric_meta_data_.end()) {
return true;
}
return false;
}
inline
const std::vector<std::string>& DenseVectorSpace::GetStringMetaData(const std::string& tag) const
{
DBG_ASSERT(HasStringMetaData(tag));
StringMetaDataMapType::const_iterator iter;
iter = string_meta_data_.find(tag);
return iter->second;
}
inline
const std::vector<Index>& DenseVectorSpace::GetIntegerMetaData(const std::string& tag) const
{
DBG_ASSERT(HasIntegerMetaData(tag));
IntegerMetaDataMapType::const_iterator iter;
iter = integer_meta_data_.find(tag);
return iter->second;
}
inline
const std::vector<Number>& DenseVectorSpace::GetNumericMetaData(const std::string& tag) const
{
DBG_ASSERT(HasNumericMetaData(tag));
NumericMetaDataMapType::const_iterator iter;
iter = numeric_meta_data_.find(tag);
return iter->second;
}
inline
void DenseVectorSpace::SetStringMetaData(std::string tag, std::vector<std::string> meta_data)
{
string_meta_data_[tag] = meta_data;
}
inline
void DenseVectorSpace::SetIntegerMetaData(std::string tag, std::vector<Index> meta_data)
{
integer_meta_data_[tag] = meta_data;
}
inline
void DenseVectorSpace::SetNumericMetaData(std::string tag, std::vector<Number> meta_data)
{
numeric_meta_data_[tag] = meta_data;
}
inline
const StringMetaDataMapType& DenseVectorSpace::GetStringMetaData() const
{
return string_meta_data_;
}
inline
const IntegerMetaDataMapType& DenseVectorSpace::GetIntegerMetaData() const
{
return integer_meta_data_;
}
inline
const NumericMetaDataMapType& DenseVectorSpace::GetNumericMetaData() const
{
return numeric_meta_data_;
}
} // namespace Ipopt
#endif
+141
View File
@@ -0,0 +1,141 @@
// Copyright (C) 2004, 2008 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpDiagMatrix.hpp 2269 2013-05-05 11:32:40Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPDIAGMATRIX_HPP__
#define __IPDIAGMATRIX_HPP__
#include "IpUtils.hpp"
#include "IpSymMatrix.hpp"
namespace Ipopt
{
/** Class for diagonal matrices. The diagonal is stored as a
* Vector. */
class DiagMatrix : public SymMatrix
{
public:
/**@name Constructors / Destructors */
//@{
/** Constructor, given the corresponding matrix space. */
DiagMatrix(const SymMatrixSpace* owner_space);
/** Destructor */
~DiagMatrix();
//@}
/** Method for setting the diagonal elements (as a Vector). */
void SetDiag(const Vector& diag)
{
diag_ = &diag;
}
/** Method for setting the diagonal elements. */
SmartPtr<const Vector> GetDiag() const
{
return diag_;
}
protected:
/**@name Methods overloaded from matrix */
//@{
virtual void MultVectorImpl(Number alpha, const Vector& x,
Number beta, Vector& y) const;
/** Method for determining if all stored numbers are valid (i.e.,
* no Inf or Nan). */
virtual bool HasValidNumbersImpl() const;
virtual void ComputeRowAMaxImpl(Vector& rows_norms, bool init) const;
virtual void PrintImpl(const Journalist& jnlst,
EJournalLevel level,
EJournalCategory category,
const std::string& name,
Index indent,
const std::string& prefix) const;
//@}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
DiagMatrix();
/** Copy Constructor */
DiagMatrix(const DiagMatrix&);
/** Overloaded Equals Operator */
void operator=(const DiagMatrix&);
//@}
/** Vector storing the diagonal elements */
SmartPtr<const Vector> diag_;
};
/** This is the matrix space for DiagMatrix. */
class DiagMatrixSpace : public SymMatrixSpace
{
public:
/** @name Constructors / Destructors */
//@{
/** Constructor, given the dimension of the matrix. */
DiagMatrixSpace(Index dim)
:
SymMatrixSpace(dim)
{}
/** Destructor */
virtual ~DiagMatrixSpace()
{}
//@}
/** Overloaded MakeNew method for the SymMatrixSpace base class.
*/
virtual SymMatrix* MakeNewSymMatrix() const
{
return MakeNewDiagMatrix();
}
/** Method for creating a new matrix of this specific type. */
DiagMatrix* MakeNewDiagMatrix() const
{
return new DiagMatrix(this);
}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
DiagMatrixSpace();
/** Copy Constructor */
DiagMatrixSpace(const DiagMatrixSpace&);
/** Overloaded Equals Operator */
void operator=(const DiagMatrixSpace&);
//@}
};
} // namespace Ipopt
#endif
+64
View File
@@ -0,0 +1,64 @@
// Copyright (C) 2004, 2006 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpEqMultCalculator.hpp 1861 2010-12-21 21:34:47Z andreasw $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-09-23
#ifndef __IPEQMULTCALCULATOR_HPP__
#define __IPEQMULTCALCULATOR_HPP__
#include "IpUtils.hpp"
#include "IpAlgStrategy.hpp"
namespace Ipopt
{
/** Base Class for objects that compute estimates for the equality
* constraint multipliers y_c and y_d. For example, this is the
* base class for objects for computing least square multipliers or
* coordinate multipliers. */
class EqMultiplierCalculator: public AlgorithmStrategyObject
{
public:
/**@name Constructors/Destructors */
//@{
/** Default Constructor. */
EqMultiplierCalculator()
{}
/** Default destructor */
virtual ~EqMultiplierCalculator()
{}
//@}
/** overloaded from AlgorithmStrategyObject */
virtual bool InitializeImpl(const OptionsList& options,
const std::string& prefix) = 0;
/** This method computes the estimates for y_c and y_d at the
* current point. If the estimates cannot be computed (e.g. some
* linear system is singular), the return value of this method is
* false. */
virtual bool CalculateMultipliers(Vector& y_c,
Vector& y_d) = 0;
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Copy Constructor */
EqMultiplierCalculator(const EqMultiplierCalculator&);
/** Overloaded Equals Operator */
void operator=(const EqMultiplierCalculator&);
//@}
};
} // namespace Ipopt
#endif
+147
View File
@@ -0,0 +1,147 @@
// Copyright (C) 2004, 2006 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpException.hpp 2023 2011-06-18 18:49:49Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPEXCEPTION_HPP__
#define __IPEXCEPTION_HPP__
#include "IpUtils.hpp"
#include "IpJournalist.hpp"
/* This file contains a base class for all exceptions
* and a set of macros to help with exceptions
*/
namespace Ipopt
{
/** This is the base class for all exceptions. The easiest way to
* use this class is by means of the following macros:
*
* \verbatim
DECLARE_STD_EXCEPTION(ExceptionType);
\endverbatim
*
* This macro defines a new class with the name ExceptionType,
* inherited from the base class IpoptException. After this,
* exceptions of this type can be thrown using
*
* \verbatim
THROW_EXCEPTION(ExceptionType, Message);
\endverbatim
*
* where Message is a std::string with a message that gives an
* indication of what caused the exception. Exceptions can also be
* thrown using the macro
*
* \verbatim
ASSERT_EXCEPTION(Condition, ExceptionType, Message);
\endverbatim
*
* where Conditions is an expression. If Condition evaluates to
* false, then the exception of the type ExceptionType is thrown
* with Message.
*
* When an exception is caught, the method ReportException can be
* used to write the information about the exception to the
* Journalist, using the level J_ERROR and the category J_MAIN.
*
*/
class IpoptException
{
public:
/**@name Constructors/Destructors */
//@{
/** Constructor */
IpoptException(std::string msg, std::string file_name, Index line_number, std::string type="IpoptException")
:
msg_(msg),
file_name_(file_name),
line_number_(line_number),
type_(type)
{}
/** Copy Constructor */
IpoptException(const IpoptException& copy)
:
msg_(copy.msg_),
file_name_(copy.file_name_),
line_number_(copy.line_number_),
type_(copy.type_)
{}
/** Default destructor */
virtual ~IpoptException()
{}
//@}
/** Method to report the exception to a journalist */
void ReportException(const Journalist& jnlst,
EJournalLevel level = J_ERROR) const
{
jnlst.Printf(level, J_MAIN,
"Exception of type: %s in file \"%s\" at line %d:\n Exception message: %s\n",
type_.c_str(), file_name_.c_str(), line_number_, msg_.c_str());
}
const std::string& Message() const
{
return msg_;
}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
IpoptException();
/** Overloaded Equals Operator */
void operator=(const IpoptException&);
//@}
std::string msg_;
std::string file_name_;
Index line_number_;
std::string type_;
};
} // namespace Ipopt
#define THROW_EXCEPTION(__except_type, __msg) \
throw __except_type( (__msg), (__FILE__), (__LINE__) );
#define ASSERT_EXCEPTION(__condition, __except_type, __msg) \
if (! (__condition) ) { \
std::string newmsg = #__condition; \
newmsg += " evaluated false: "; \
newmsg += __msg; \
throw __except_type( (newmsg), (__FILE__), (__LINE__) ); \
}
#define DECLARE_STD_EXCEPTION(__except_type) \
class __except_type : public Ipopt::IpoptException \
{ \
public: \
__except_type(std::string msg, std::string fname, Ipopt::Index line) \
: Ipopt::IpoptException(msg,fname,line, #__except_type) {} \
__except_type(const __except_type& copy) \
: Ipopt::IpoptException(copy) {} \
private: \
__except_type(); \
void operator=(const __except_type&); \
}
#endif
+212
View File
@@ -0,0 +1,212 @@
// Copyright (C) 2004, 2009 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpExpansionMatrix.hpp 2269 2013-05-05 11:32:40Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPEXPANSIONMATRIX_HPP__
#define __IPEXPANSIONMATRIX_HPP__
#include "IpUtils.hpp"
#include "IpMatrix.hpp"
namespace Ipopt
{
/** forward declarations */
class ExpansionMatrixSpace;
/** Class for expansion/projection matrices. These matrices allow
* to lift a vector to a vector with larger dimension, keeping
* some elements of the larger vector zero. This operation is achieved
* by the MultVector operation. The transpose operation then
* filters some elements from a large vector into a smaller vector.
*/
class ExpansionMatrix : public Matrix
{
public:
/**@name Constructors / Destructors */
//@{
/** Constructor, taking the owner_space.
*/
ExpansionMatrix(const ExpansionMatrixSpace* owner_space);
/** Destructor */
~ExpansionMatrix();
//@}
/** Return the vector of indices marking the expanded position.
* The result is the Index array (of length NSmallVec=NCols())
* that stores the mapping from the small vector to the large
* vector. For each element i=0,..,NSmallVec in the small
* vector, ExpandedPosIndices()[i] give the corresponding index
* in the large vector.
*/
const Index* ExpandedPosIndices() const;
/** Return the vector of indices marking the compressed position.
* The result is the Index array (of length NLargeVec=NRows())
* that stores the mapping from the large vector to the small
* vector. For each element i=0,..,NLargeVec in the large
* vector, CompressedPosIndices()[i] gives the corresponding
* index in the small vector, unless CompressedPosIndices()[i] is
* negative.
*/
const Index* CompressedPosIndices() const;
protected:
/**@name Overloaded methods from Matrix base class*/
//@{
virtual void MultVectorImpl(Number alpha, const Vector &x, Number beta,
Vector &y) const;
virtual void TransMultVectorImpl(Number alpha, const Vector& x,
Number beta, Vector& y) const;
/** X = beta*X + alpha*(Matrix S^{-1} Z). Specialized implementation.
*/
virtual void AddMSinvZImpl(Number alpha, const Vector& S, const Vector& Z,
Vector& X) const;
/** X = S^{-1} (r + alpha*Z*M^Td). Specialized implementation.
*/
virtual void SinvBlrmZMTdBrImpl(Number alpha, const Vector& S,
const Vector& R, const Vector& Z,
const Vector& D, Vector& X) const;
virtual void ComputeRowAMaxImpl(Vector& rows_norms, bool init) const;
virtual void ComputeColAMaxImpl(Vector& cols_norms, bool init) const;
virtual void PrintImpl(const Journalist& jnlst,
EJournalLevel level,
EJournalCategory category,
const std::string& name,
Index indent,
const std::string& prefix) const
{
PrintImplOffset(jnlst, level, category, name, indent, prefix, 1, 1);
}
//@}
void PrintImplOffset(const Journalist& jnlst,
EJournalLevel level,
EJournalCategory category,
const std::string& name,
Index indent,
const std::string& prefix,
Index row_offset,
Index col_offset) const;
friend class ParExpansionMatrix;
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
ExpansionMatrix();
/** Copy Constructor */
ExpansionMatrix(const ExpansionMatrix&);
/** Overloaded Equals Operator */
void operator=(const ExpansionMatrix&);
//@}
const ExpansionMatrixSpace* owner_space_;
};
/** This is the matrix space for ExpansionMatrix.
*/
class ExpansionMatrixSpace : public MatrixSpace
{
public:
/** @name Constructors / Destructors */
//@{
/** Constructor, given the list of elements of the large vector
* (of size NLargeVec) to be filtered into the small vector (of
* size NSmallVec). For each i=0..NSmallVec-1 the i-th element
* of the small vector will be put into the ExpPos[i] position of
* the large vector. The position counting in the vector is
* assumed to start at 0 (C-like array notation).
*/
ExpansionMatrixSpace(Index NLargeVec,
Index NSmallVec,
const Index *ExpPos,
const int offset = 0);
/** Destructor */
~ExpansionMatrixSpace()
{
delete [] compressed_pos_;
delete [] expanded_pos_;
}
//@}
/** Method for creating a new matrix of this specific type. */
ExpansionMatrix* MakeNewExpansionMatrix() const
{
return new ExpansionMatrix(this);
}
/** Overloaded MakeNew method for the MatrixSpace base class.
*/
virtual Matrix* MakeNew() const
{
return MakeNewExpansionMatrix();
}
/** Accessor Method to obtain the Index array (of length
* NSmallVec=NCols()) that stores the mapping from the small
* vector to the large vector. For each element i=0,..,NSmallVec
* in the small vector, ExpandedPosIndices()[i] give the
* corresponding index in the large vector.
*/
const Index* ExpandedPosIndices() const
{
return expanded_pos_;
}
/** Accessor Method to obtain the Index array (of length
* NLargeVec=NRows()) that stores the mapping from the large
* vector to the small vector. For each element i=0,..,NLargeVec
* in the large vector, CompressedPosIndices()[i] gives the
* corresponding index in the small vector, unless
* CompressedPosIndices()[i] is negative.
*/
const Index* CompressedPosIndices() const
{
return compressed_pos_;
}
private:
Index *expanded_pos_;
Index *compressed_pos_;
};
/* inline methods */
inline
const Index* ExpansionMatrix::ExpandedPosIndices() const
{
return owner_space_->ExpandedPosIndices();
}
inline
const Index* ExpansionMatrix::CompressedPosIndices() const
{
return owner_space_->CompressedPosIndices();
}
} // namespace Ipopt
#endif
+264
View File
@@ -0,0 +1,264 @@
// Copyright (C) 2004, 2009 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpGenTMatrix.hpp 2269 2013-05-05 11:32:40Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPGENTMATRIX_HPP__
#define __IPGENTMATRIX_HPP__
#include "IpUtils.hpp"
#include "IpMatrix.hpp"
namespace Ipopt
{
/* forward declarations */
class GenTMatrixSpace;
/** Class for general matrices stored in triplet format. In the
* triplet format, the nonzeros elements of a general matrix is
* stored in three arrays, Irow, Jcol, and Values, all of length
* Nonzeros. The first two arrays indicate the location of a
* non-zero element (row and column indices), and the last array
* stores the value at that location. If nonzero elements are
* listed more than once, their values are added.
*
* The structure of the nonzeros (i.e. the arrays Irow and Jcol)
* cannot be changed after the matrix can been initialized. Only
* the values of the nonzero elements can be modified.
*
* Note that the first row and column of a matrix has index 1, not
* 0.
*/
class GenTMatrix : public Matrix
{
public:
/**@name Constructors / Destructors */
//@{
/** Constructor, taking the owner_space.
*/
GenTMatrix(const GenTMatrixSpace* owner_space);
/** Destructor */
~GenTMatrix();
//@}
/**@name Changing the Values.*/
//@{
/** Set values of nonzero elements. The values of the nonzero
* elements are copied from the incoming Number array. Important:
* It is assume that the order of the values in Values
* corresponds to the one of Irn and Jcn given to one of the
* constructors above. */
void SetValues(const Number* Values);
//@}
/** @name Accessor Methods */
//@{
/** Number of nonzero entries */
Index Nonzeros() const;
/** Array with Row indices (counting starts at 1) */
const Index* Irows() const;
/** Array with Column indices (counting starts at 1) */
const Index* Jcols() const;
/** Array with nonzero values (const version). */
const Number* Values() const
{
return values_;
}
/** Array with the nonzero values of this matrix (non-const
* version). Use this method only if you are intending to change
* the values, because the GenTMatrix will be marked as changed.
*/
Number* Values()
{
ObjectChanged();
initialized_ = true;
return values_;
}
//@}
protected:
/**@name Overloaded methods from Matrix base class*/
//@{
virtual void MultVectorImpl(Number alpha, const Vector &x, Number beta,
Vector &y) const;
virtual void TransMultVectorImpl(Number alpha, const Vector& x, Number beta,
Vector& y) const;
/** Method for determining if all stored numbers are valid (i.e.,
* no Inf or Nan). */
virtual bool HasValidNumbersImpl() const;
virtual void ComputeRowAMaxImpl(Vector& rows_norms, bool init) const;
virtual void ComputeColAMaxImpl(Vector& cols_norms, bool init) const;
virtual void PrintImpl(const Journalist& jnlst,
EJournalLevel level,
EJournalCategory category,
const std::string& name,
Index indent,
const std::string& prefix) const
{
PrintImplOffset(jnlst, level, category, name, indent, prefix, 0);
}
//@}
void PrintImplOffset(const Journalist& jnlst,
EJournalLevel level,
EJournalCategory category,
const std::string& name,
Index indent,
const std::string& prefix,
Index offset) const;
friend class ParGenMatrix;
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
GenTMatrix();
/** Copy Constructor */
GenTMatrix(const GenTMatrix&);
/** Overloaded Equals Operator */
void operator=(const GenTMatrix&);
//@}
/** Copy of the owner space as a GenTMatrixSpace instead of
* a MatrixSpace
*/
const GenTMatrixSpace* owner_space_;
/** Values of nonzeros */
Number* values_;
/** Flag for Initialization */
bool initialized_;
};
/** This is the matrix space for a GenTMatrix with fixed sparsity
* structure. The sparsity structure is stored here in the matrix
* space.
*/
class GenTMatrixSpace : public MatrixSpace
{
public:
/** @name Constructors / Destructors */
//@{
/** Constructor, given the number of rows and columns, as well as
* the number of nonzeros and the position of the nonzero
* elements. Note that the counting of the nonzeros starts a 1,
* i.e., iRows[i]==1 and jCols[i]==1 refers to the first element
* in the first row. This is in accordance with the HSL data
* structure.
*/
GenTMatrixSpace(Index nRows, Index nCols,
Index nonZeros,
const Index* iRows, const Index* jCols);
/** Destructor */
~GenTMatrixSpace()
{
delete [] iRows_;
delete [] jCols_;
}
//@}
/** Method for creating a new matrix of this specific type. */
GenTMatrix* MakeNewGenTMatrix() const
{
return new GenTMatrix(this);
}
/** Overloaded MakeNew method for the MatrixSpace base class.
*/
virtual Matrix* MakeNew() const
{
return MakeNewGenTMatrix();
}
/**@name Methods describing Matrix structure */
//@{
/** Number of non-zeros in the sparse matrix */
Index Nonzeros() const
{
return nonZeros_;
}
/** Row index of each non-zero element (counting starts at 1) */
const Index* Irows() const
{
return iRows_;
}
/** Column index of each non-zero element (counting starts at 1) */
const Index* Jcols() const
{
return jCols_;
}
//@}
private:
/** @name Sparsity structure of matrices generated by this matrix
* space.
*/
//@{
const Index nonZeros_;
Index* jCols_;
Index* iRows_;
//@}
/** This method is only for the GenTMatrix to call in order
* to allocate internal storage */
Number* AllocateInternalStorage() const;
/** This method is only for the GenTMatrix to call in order
* to de-allocate internal storage */
void FreeInternalStorage(Number* values) const;
friend class GenTMatrix;
};
/* inline methods */
inline
Index GenTMatrix::Nonzeros() const
{
return owner_space_->Nonzeros();
}
inline
const Index* GenTMatrix::Irows() const
{
return owner_space_->Irows();
}
inline
const Index* GenTMatrix::Jcols() const
{
return owner_space_->Jcols();
}
} // namespace Ipopt
#endif
+65
View File
@@ -0,0 +1,65 @@
// Copyright (C) 2005, 2006 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpHessianUpdater.hpp 1861 2010-12-21 21:34:47Z andreasw $
//
// Authors: Andreas Waechter IBM 2005-12-26
#ifndef __IPHESSIANUPDATER_HPP__
#define __IPHESSIANUPDATER_HPP__
#include "IpAlgStrategy.hpp"
namespace Ipopt
{
/** Abstract base class for objects responsible for updating the
* Hessian information. This can be done using exact second
* derivatives from the NLP, or by a quasi-Newton Option. The
* result is put into the W field in IpData.
*/
class HessianUpdater : public AlgorithmStrategyObject
{
public:
/**@name Constructors/Destructors */
//@{
/** Default Constructor */
HessianUpdater()
{}
/** Default destructor */
virtual ~HessianUpdater()
{}
//@}
/** overloaded from AlgorithmStrategyObject */
virtual bool InitializeImpl(const OptionsList& options,
const std::string& prefix) = 0;
/** Update the Hessian based on the current information in IpData,
* and possibly on information from previous calls.
*/
virtual void UpdateHessian() = 0;
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Copy Constructor */
HessianUpdater(const HessianUpdater&);
/** Overloaded Equals Operator */
void operator=(const HessianUpdater&);
//@}
};
} // namespace Ipopt
#endif
+149
View File
@@ -0,0 +1,149 @@
// Copyright (C) 2004, 2008 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpIdentityMatrix.hpp 2269 2013-05-05 11:32:40Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPIDENTITYMATRIX_HPP__
#define __IPIDENTITYMATRIX_HPP__
#include "IpUtils.hpp"
#include "IpSymMatrix.hpp"
namespace Ipopt
{
/** Class for Matrices which are multiples of the identity matrix.
*
*/
class IdentityMatrix : public SymMatrix
{
public:
/**@name Constructors / Destructors */
//@{
/** Constructor, initializing with dimensions of the matrix
* (true identity matrix).
*/
IdentityMatrix(const SymMatrixSpace* owner_space);
/** Destructor */
~IdentityMatrix();
//@}
/** Method for setting the factor for the identity matrix. */
void SetFactor(Number factor)
{
factor_ = factor;
}
/** Method for getting the factor for the identity matrix. */
Number GetFactor() const
{
return factor_;
}
/** Method for obtaining the dimention of the matrix. */
Index Dim() const;
protected:
/**@name Methods overloaded from matrix */
//@{
virtual void MultVectorImpl(Number alpha, const Vector& x,
Number beta, Vector& y) const;
virtual void AddMSinvZImpl(Number alpha, const Vector& S,
const Vector& Z, Vector& X) const;
/** Method for determining if all stored numbers are valid (i.e.,
* no Inf or Nan). */
virtual bool HasValidNumbersImpl() const;
virtual void ComputeRowAMaxImpl(Vector& rows_norms, bool init) const;
virtual void PrintImpl(const Journalist& jnlst,
EJournalLevel level,
EJournalCategory category,
const std::string& name,
Index indent,
const std::string& prefix) const;
//@}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
IdentityMatrix();
/** Copy Constructor */
IdentityMatrix(const IdentityMatrix&);
/** Overloaded Equals Operator */
void operator=(const IdentityMatrix&);
//@}
/** Scaling factor for this identity matrix */
Number factor_;
};
/** This is the matrix space for IdentityMatrix. */
class IdentityMatrixSpace : public SymMatrixSpace
{
public:
/** @name Constructors / Destructors */
//@{
/** Constructor, given the dimension of the matrix. */
IdentityMatrixSpace(Index dim)
:
SymMatrixSpace(dim)
{}
/** Destructor */
virtual ~IdentityMatrixSpace()
{}
//@}
/** Overloaded MakeNew method for the SymMatrixSpace base class.
*/
virtual SymMatrix* MakeNewSymMatrix() const
{
return MakeNewIdentityMatrix();
}
/** Method for creating a new matrix of this specific type. */
IdentityMatrix* MakeNewIdentityMatrix() const
{
return new IdentityMatrix(this);
}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
IdentityMatrixSpace();
/** Copy Constructor */
IdentityMatrixSpace(const IdentityMatrixSpace&);
/** Overloaded Equals Operator */
void operator=(const IdentityMatrixSpace&);
//@}
};
} // namespace Ipopt
#endif
+224
View File
@@ -0,0 +1,224 @@
// Copyright (C) 2004, 2010 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpIpoptAlg.hpp 2167 2013-03-08 11:15:38Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPIPOPTALG_HPP__
#define __IPIPOPTALG_HPP__
#include "IpIpoptNLP.hpp"
#include "IpAlgStrategy.hpp"
#include "IpSearchDirCalculator.hpp"
#include "IpLineSearch.hpp"
#include "IpMuUpdate.hpp"
#include "IpConvCheck.hpp"
#include "IpOptionsList.hpp"
#include "IpIterateInitializer.hpp"
#include "IpIterationOutput.hpp"
#include "IpAlgTypes.hpp"
#include "IpHessianUpdater.hpp"
#include "IpEqMultCalculator.hpp"
namespace Ipopt
{
/** @name Exceptions */
//@{
DECLARE_STD_EXCEPTION(STEP_COMPUTATION_FAILED);
//@}
/** The main ipopt algorithm class.
* Main Ipopt algorithm class, contains the main optimize method,
* handles the execution of the optimization.
* The constructor initializes the data structures through the nlp,
* and the Optimize method then assumes that everything is
* initialized and ready to go.
* After an optimization is complete, the user can access the
* solution through the passed in ip_data structure.
* Multiple calls to the Optimize method are allowed as long as the
* structure of the problem remains the same (i.e. starting point
* or nlp parameter changes only).
*/
class IpoptAlgorithm : public AlgorithmStrategyObject
{
public:
/**@name Constructors/Destructors */
//@{
/** Constructor. (The IpoptAlgorithm uses smart pointers for these
* passed-in pieces to make sure that a user of IpoptAlgoroithm
* cannot pass in an object created on the stack!)
*/
IpoptAlgorithm(const SmartPtr<SearchDirectionCalculator>& search_dir_calculator,
const SmartPtr<LineSearch>& line_search,
const SmartPtr<MuUpdate>& mu_update,
const SmartPtr<ConvergenceCheck>& conv_check,
const SmartPtr<IterateInitializer>& iterate_initializer,
const SmartPtr<IterationOutput>& iter_output,
const SmartPtr<HessianUpdater>& hessian_updater,
const SmartPtr<EqMultiplierCalculator>& eq_multiplier_calculator = NULL);
/** Default destructor */
virtual ~IpoptAlgorithm();
//@}
/** overloaded from AlgorithmStrategyObject */
virtual bool InitializeImpl(const OptionsList& options,
const std::string& prefix);
/** Main solve method. */
SolverReturn Optimize(bool isResto = false);
/** Methods for IpoptType */
//@{
static void RegisterOptions(SmartPtr<RegisteredOptions> roptions);
//@}
/**@name Access to internal strategy objects */
//@{
SmartPtr<SearchDirectionCalculator> SearchDirCalc()
{
return search_dir_calculator_;
}
//@}
static void print_copyright_message(const Journalist& jnlst);
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
IpoptAlgorithm();
/** Copy Constructor */
IpoptAlgorithm(const IpoptAlgorithm&);
/** Overloaded Equals Operator */
void operator=(const IpoptAlgorithm&);
//@}
/** @name Strategy objects */
//@{
SmartPtr<SearchDirectionCalculator> search_dir_calculator_;
SmartPtr<LineSearch> line_search_;
SmartPtr<MuUpdate> mu_update_;
SmartPtr<ConvergenceCheck> conv_check_;
SmartPtr<IterateInitializer> iterate_initializer_;
SmartPtr<IterationOutput> iter_output_;
SmartPtr<HessianUpdater> hessian_updater_;
/** The multipler calculator (for y_c and y_d) has to be set only
* if option recalc_y is set to true */
SmartPtr<EqMultiplierCalculator> eq_multiplier_calculator_;
//@}
/** @name Main steps of the algorthim */
//@{
/** Method for updating the current Hessian. This can either just
* evaluate the exact Hessian (based on the current iterate), or
* perform a quasi-Newton update.
*/
void UpdateHessian();
/** Method to update the barrier parameter. Returns false, if the
* algorithm can't continue with the regular procedure and needs
* to revert to a fallback mechanism in the line search (such as
* restoration phase) */
bool UpdateBarrierParameter();
/** Method to setup the call to the PDSystemSolver. Returns
* false, if the algorithm can't continue with the regular
* procedure and needs to revert to a fallback mechanism in the
* line search (such as restoration phase) */
bool ComputeSearchDirection();
/** Method computing the new iterate (usually vialine search).
* The acceptable point is the one in trial after return.
*/
void ComputeAcceptableTrialPoint();
/** Method for accepting the trial point as the new iteration,
* possibly after adjusting the variable bounds in the NLP. */
void AcceptTrialPoint();
/** Do all the output for one iteration */
void OutputIteration();
/** Sets up initial values for the iterates,
* Corrects the initial values for x and s (force in bounds)
*/
void InitializeIterates();
/** Print the problem size statistics */
void PrintProblemStatistics();
/** Compute the Lagrangian multipliers for a feasibility problem*/
void ComputeFeasibilityMultipliers();
//@}
/** @name internal flags */
//@{
/** Flag indicating if the statistic should not be printed */
bool skip_print_problem_stats_;
//@}
/** @name Algorithmic parameters */
//@{
/** safeguard factor for bound multipliers. If value >= 1, then
* the dual variables will never deviate from the primal estimate
* by more than the factors kappa_sigma and 1./kappa_sigma.
*/
Number kappa_sigma_;
/** Flag indicating whether the y multipliers should be
* recalculated with the eq_mutliplier_calculator object for each
* new point. */
bool recalc_y_;
/** Feasibility threshold for recalc_y */
Number recalc_y_feas_tol_;
/** Flag indicating if we want to do Mehrotras's algorithm. This
* means that a number of options are ignored, or have to be set
* (or are automatically set) to certain values. */
bool mehrotra_algorithm_;
/** String specifying linear solver */
std::string linear_solver_;
//@}
/** @name auxiliary functions */
//@{
void calc_number_of_bounds(
const Vector& x,
const Vector& x_L,
const Vector& x_U,
const Matrix& Px_L,
const Matrix& Px_U,
Index& n_tot,
Index& n_only_lower,
Index& n_both,
Index& n_only_upper);
/** Method for ensuring that the trial multipliers are not too far
* from the primal estime. If a correction is made, new_trial_z
* is a pointer to the corrected multiplier, and the return value
* of this method give the magnitutde of the largest correction
* that we done. If no correction was made, new_trial_z is just
* a pointer to trial_z, and the return value is zero.
*/
Number correct_bound_multiplier(const Vector& trial_z,
const Vector& trial_slack,
const Vector& trial_compl,
SmartPtr<const Vector>& new_trial_z);
//@}
};
} // namespace Ipopt
#endif
+300
View File
@@ -0,0 +1,300 @@
// Copyright (C) 2004, 2010 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpIpoptApplication.hpp 2690 2017-06-12 10:28:36Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPIPOPTAPPLICATION_HPP__
#define __IPIPOPTAPPLICATION_HPP__
#ifndef IPOPT_EXPORT
#ifdef _MSC_VER
#ifdef IPOPT_DLL
#define IPOPT_EXPORT(type) __declspec(dllexport) type __cdecl
#else
#define IPOPT_EXPORT(type) type __cdecl
#endif
#else
#define IPOPT_EXPORT(type) type
#endif
#endif
#include <iostream>
#include "IpJournalist.hpp"
#include "IpTNLP.hpp"
#include "IpNLP.hpp"
/* Return codes for the Optimize call for an application */
#include "IpReturnCodes.hpp"
namespace Ipopt
{
DECLARE_STD_EXCEPTION(IPOPT_APPLICATION_ERROR);
/* forward declarations */
class IpoptAlgorithm;
class IpoptNLP;
class IpoptData;
class IpoptCalculatedQuantities;
class AlgorithmBuilder;
class RegisteredOptions;
class OptionsList;
class SolveStatistics;
/** This is the main application class for making calls to Ipopt. */
class IpoptApplication : public ReferencedObject
{
public:
IpoptApplication(bool create_console_out = true,
bool create_empty = false);
/** Another constructor that assumes that the code in the
* (default) constructor has already been executed */
IpoptApplication(SmartPtr<RegisteredOptions> reg_options,
SmartPtr<OptionsList> options,
SmartPtr<Journalist> jnlst);
virtual ~IpoptApplication();
/** Method for creating a new IpoptApplication that uses the same
* journalist and registered options, and a copy of the options
list. */
virtual SmartPtr<IpoptApplication> clone();
/** Initialization method. This method reads options from the
* input stream and initializes the journalists. It returns
* something other than Solve_Succeeded if there was a
* problem in the initialization (such as an invalid option).
* You should call one of the initialization methods at some
* point before the first optimize call.
* Set @par allow_clobber to true if you want to allow
* overwriting options that are set by the input stream.
*/
virtual ApplicationReturnStatus Initialize(std::istream& is, bool allow_clobber = false);
/** Initialization method. This method reads options from the
* params file and initializes the journalists. It returns
* something other than Solve_Succeeded if there was a
* problem in the initialization (such as an invalid option).
* You should call one of the initialization methods at some
* point before the first optimize call.
* Note: You can skip the processing of a params file by
* setting params_file to "".
* Set @par allow_clobber to true if you want to allow
* overwriting options that are set by the params file.
*/
virtual ApplicationReturnStatus Initialize(std::string params_file, bool allow_clobber = false);
/** Initialization method. This method reads options from the
* params file and initializes the journalists. It returns
* something other than Solve_Succeeded if there was a
* problem in the initialization (such as an invalid option).
* You should call one of the initialization methods at some
* point before the first optimize call.
* Note: You can skip the processing of a params file by
* setting params_file to "".
* Set @par allow_clobber to true if you want to allow
* overwriting options that are set by the params file.
*/
virtual ApplicationReturnStatus Initialize(const char* params_file, bool allow_clobber = false)
{
return Initialize(std::string(params_file), allow_clobber);
}
/** Initialize method. This method reads the options file specified
* by the option_file_name option and initializes the journalists.
* You should call this method at some point before the first optimize
* call.
* It returns something other than Solve_Succeeded if there was a
* problem in the initialization (such as an invalid option).
* Set @par allow_clobber to true if you want to allow
* overwriting options that are set by the options file.
*/
virtual ApplicationReturnStatus Initialize(bool allow_clobber = false);
/**@name Solve methods */
//@{
/** Solve a problem that inherits from TNLP */
virtual ApplicationReturnStatus OptimizeTNLP(const SmartPtr<TNLP>& tnlp);
/** Solve a problem that inherits from NLP */
virtual ApplicationReturnStatus OptimizeNLP(const SmartPtr<NLP>& nlp);
/** Solve a problem that inherits from NLP */
virtual ApplicationReturnStatus OptimizeNLP(const SmartPtr<NLP>& nlp, SmartPtr<AlgorithmBuilder>& alg_builder);
/** Solve a problem (that inherits from TNLP) for a repeated time.
* The OptimizeTNLP method must have been called before. The
* TNLP must be the same object, and the structure (number of
* variables and constraints and position of nonzeros in Jacobian
* and Hessian must be the same). */
virtual ApplicationReturnStatus ReOptimizeTNLP(const SmartPtr<TNLP>& tnlp);
/** Solve a problem (that inherits from NLP) for a repeated time.
* The OptimizeNLP method must have been called before. The
* NLP must be the same object, and the structure (number of
* variables and constraints and position of nonzeros in Jacobian
* and Hessian must be the same). */
virtual ApplicationReturnStatus ReOptimizeNLP(const SmartPtr<NLP>& nlp);
//@}
/** Method for opening an output file with given print_level.
* Returns false if there was a problem. */
virtual bool OpenOutputFile(std::string file_name, EJournalLevel print_level);
/**@name Accessor methods */
//@{
/** Get the Journalist for printing output */
virtual SmartPtr<Journalist> Jnlst()
{
return jnlst_;
}
/** Get a pointer to RegisteredOptions object to
* add new options */
virtual SmartPtr<RegisteredOptions> RegOptions()
{
return reg_options_;
}
/** Get the options list for setting options */
virtual SmartPtr<OptionsList> Options()
{
return options_;
}
/** Get the options list for setting options (const version) */
virtual SmartPtr<const OptionsList> Options() const
{
return ConstPtr(options_);
}
/** Get the object with the statistics about the most recent
* optimization run. */
virtual SmartPtr<SolveStatistics> Statistics();
/** Get the IpoptNLP Object */
virtual SmartPtr<IpoptNLP> IpoptNLPObject();
/** Get the IpoptData Object */
SmartPtr<IpoptData> IpoptDataObject();
/** Get the IpoptCQ Object */
virtual SmartPtr<IpoptCalculatedQuantities> IpoptCQObject();
/** Get the Algorithm Object */
SmartPtr<IpoptAlgorithm> AlgorithmObject();
//@}
/** Method for printing Ipopt copyright message now instead of
* just before the optimization. If you want to have the copy
* right message printed earlier than by default, call this
* method at the convenient time. */
void PrintCopyrightMessage();
/** Method to set whether non-ipopt non-bad_alloc exceptions
* are rethrown by Ipopt.
* By default, non-Ipopt and non-std::bad_alloc exceptions are
* caught by Ipopts initialization and optimization methods
* and the status NonIpopt_Exception_Thrown is returned.
* This function allows to enable rethrowing of such exceptions.
*
* @return Returns whether non-ipopt exceptions were rethrown before.
*/
bool RethrowNonIpoptException(bool dorethrow)
{
bool oldval = rethrow_nonipoptexception_;
rethrow_nonipoptexception_ = dorethrow;
return oldval;
}
/** @name Methods for IpoptTypeInfo */
//@{
static void RegisterOptions(SmartPtr<RegisteredOptions> roptions);
//@}
/** Method to registering all Ipopt options. */
static void
RegisterAllIpoptOptions(const SmartPtr<RegisteredOptions>& roptions);
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
// IpoptApplication();
/** Copy Constructor */
IpoptApplication(const IpoptApplication&);
/** Overloaded Equals Operator */
void operator=(const IpoptApplication&);
//@}
/** Method for the actual optimize call of the Ipopt algorithm.
* This is used both for Optimize and ReOptimize */
ApplicationReturnStatus call_optimize();
/**@name Variables that customize the application behavior */
//@{
/** Decide whether or not the ipopt.opt file should be read */
bool read_params_dat_;
/** Decide whether non-ipopt non-bad_alloc exceptions should be rethrown */
bool rethrow_nonipoptexception_;
//@}
/** Journalist for reporting output */
SmartPtr<Journalist> jnlst_;
/** RegisteredOptions */
SmartPtr<RegisteredOptions> reg_options_;
/** OptionsList used for the application */
SmartPtr<OptionsList> options_;
/** Object for storing statistics about the most recent
* optimization run. */
SmartPtr<SolveStatistics> statistics_;
/** Object with the algorithm sceleton.
*/
SmartPtr<IpoptAlgorithm> alg_;
/** IpoptNLP Object for the NLP. We keep this around for a
* ReOptimize warm start. */
SmartPtr<IpoptNLP> ip_nlp_;
/** IpoptData Object for the NLP. We keep this around for a
* ReOptimize warm start.
*/
SmartPtr<IpoptData> ip_data_;
/** IpoptCalculatedQuantities Object for the NLP. We keep this
* around for a ReOptimize warm start.
*/
SmartPtr<IpoptCalculatedQuantities> ip_cq_;
/** Pointer to the TNLPAdapter used to convert the TNLP to an NLP.
* We keep this around for the ReOptimizerTNLP call. */
SmartPtr<NLP> nlp_adapter_;
/** @name Algorithmic parameters */
//@{
/** Flag indicating if we are to use the inexact linear solver option */
bool inexact_algorithm_;
/** Flag indicating if all bounds should be replaced by inequality
* constraints. This is necessary for the inexact algorithm. */
bool replace_bounds_;
//@}
};
} // namespace Ipopt
extern "C" IPOPT_EXPORT(class Ipopt::IpoptApplication *) IpoptApplicationFactory();
#endif
@@ -0,0 +1,751 @@
// Copyright (C) 2004, 2011 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpIpoptCalculatedQuantities.hpp 2020 2011-06-16 20:46:16Z andreasw $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPIPOPTCALCULATEDQUANTITIES_HPP__
#define __IPIPOPTCALCULATEDQUANTITIES_HPP__
#include "IpSmartPtr.hpp"
#include "IpCachedResults.hpp"
#include <string>
namespace Ipopt
{
class IpoptNLP;
class IpoptData;
class Vector;
class Matrix;
class SymMatrix;
class Journalist;
class OptionsList;
class RegisteredOptions;
/** Norm types */
enum ENormType {
NORM_1=0,
NORM_2,
NORM_MAX
};
/** Base class for additional calculated quantities that is special
* to a particular type of algorithm, such as the CG penalty
* function, or using iterative linear solvers. The regular
* IpoptCalculatedQuantities object should be given a derivation of
* this base class when it is created. */
class IpoptAdditionalCq : public ReferencedObject
{
public:
/**@name Constructors/Destructors */
//@{
/** Default Constructor */
IpoptAdditionalCq()
{}
/** Default destructor */
virtual ~IpoptAdditionalCq()
{}
//@}
/** This method is called to initialize the global algorithmic
* parameters. The parameters are taken from the OptionsList
* object. */
virtual bool Initialize(const Journalist& jnlst,
const OptionsList& options,
const std::string& prefix) = 0;
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Copy Constructor */
IpoptAdditionalCq(const IpoptAdditionalCq&);
/** Overloaded Equals Operator */
void operator=(const IpoptAdditionalCq&);
//@}
};
/** Class for all IPOPT specific calculated quantities.
*
*/
class IpoptCalculatedQuantities : public ReferencedObject
{
public:
/**@name Constructors/Destructors */
//@{
/** Constructor */
IpoptCalculatedQuantities(const SmartPtr<IpoptNLP>& ip_nlp,
const SmartPtr<IpoptData>& ip_data);
/** Default destructor */
virtual ~IpoptCalculatedQuantities();
//@}
/** Method for setting pointer for additional calculated
* quantities. This needs to be called before Initialized. */
void SetAddCq(SmartPtr<IpoptAdditionalCq> add_cq)
{
DBG_ASSERT(!HaveAddCq());
add_cq_ = add_cq;
}
/** Method detecting if additional object for calculated
* quantities has already been set */
bool HaveAddCq()
{
return IsValid(add_cq_);
}
/** This method must be called to initialize the global
* algorithmic parameters. The parameters are taken from the
* OptionsList object. */
bool Initialize(const Journalist& jnlst,
const OptionsList& options,
const std::string& prefix);
/** @name Slacks */
//@{
/** Slacks for x_L (at current iterate) */
SmartPtr<const Vector> curr_slack_x_L();
/** Slacks for x_U (at current iterate) */
SmartPtr<const Vector> curr_slack_x_U();
/** Slacks for s_L (at current iterate) */
SmartPtr<const Vector> curr_slack_s_L();
/** Slacks for s_U (at current iterate) */
SmartPtr<const Vector> curr_slack_s_U();
/** Slacks for x_L (at trial point) */
SmartPtr<const Vector> trial_slack_x_L();
/** Slacks for x_U (at trial point) */
SmartPtr<const Vector> trial_slack_x_U();
/** Slacks for s_L (at trial point) */
SmartPtr<const Vector> trial_slack_s_L();
/** Slacks for s_U (at trial point) */
SmartPtr<const Vector> trial_slack_s_U();
/** Indicating whether or not we "fudged" the slacks */
Index AdjustedTrialSlacks();
/** Reset the flags for "fudged" slacks */
void ResetAdjustedTrialSlacks();
//@}
/** @name Objective function */
//@{
/** Value of objective function (at current point) */
virtual Number curr_f();
/** Unscaled value of the objective function (at the current point) */
virtual Number unscaled_curr_f();
/** Value of objective function (at trial point) */
virtual Number trial_f();
/** Unscaled value of the objective function (at the trial point) */
virtual Number unscaled_trial_f();
/** Gradient of objective function (at current point) */
SmartPtr<const Vector> curr_grad_f();
/** Gradient of objective function (at trial point) */
SmartPtr<const Vector> trial_grad_f();
//@}
/** @name Barrier Objective Function */
//@{
/** Barrier Objective Function Value
* (at current iterate with current mu)
*/
virtual Number curr_barrier_obj();
/** Barrier Objective Function Value
* (at trial point with current mu)
*/
virtual Number trial_barrier_obj();
/** Gradient of barrier objective function with respect to x
* (at current point with current mu) */
SmartPtr<const Vector> curr_grad_barrier_obj_x();
/** Gradient of barrier objective function with respect to s
* (at current point with current mu) */
SmartPtr<const Vector> curr_grad_barrier_obj_s();
/** Gradient of the damping term with respect to x (times
* kappa_d) */
SmartPtr<const Vector> grad_kappa_times_damping_x();
/** Gradient of the damping term with respect to s (times
* kappa_d) */
SmartPtr<const Vector> grad_kappa_times_damping_s();
//@}
/** @name Constraints */
//@{
/** c(x) (at current point) */
SmartPtr<const Vector> curr_c();
/** unscaled c(x) (at current point) */
SmartPtr<const Vector> unscaled_curr_c();
/** c(x) (at trial point) */
SmartPtr<const Vector> trial_c();
/** unscaled c(x) (at trial point) */
SmartPtr<const Vector> unscaled_trial_c();
/** d(x) (at current point) */
SmartPtr<const Vector> curr_d();
/** unscaled d(x) (at current point) */
SmartPtr<const Vector> unscaled_curr_d();
/** d(x) (at trial point) */
SmartPtr<const Vector> trial_d();
/** d(x) - s (at current point) */
SmartPtr<const Vector> curr_d_minus_s();
/** d(x) - s (at trial point) */
SmartPtr<const Vector> trial_d_minus_s();
/** Jacobian of c (at current point) */
SmartPtr<const Matrix> curr_jac_c();
/** Jacobian of c (at trial point) */
SmartPtr<const Matrix> trial_jac_c();
/** Jacobian of d (at current point) */
SmartPtr<const Matrix> curr_jac_d();
/** Jacobian of d (at trial point) */
SmartPtr<const Matrix> trial_jac_d();
/** Product of Jacobian (evaluated at current point) of C
* transpose with general vector */
SmartPtr<const Vector> curr_jac_cT_times_vec(const Vector& vec);
/** Product of Jacobian (evaluated at trial point) of C
* transpose with general vector */
SmartPtr<const Vector> trial_jac_cT_times_vec(const Vector& vec);
/** Product of Jacobian (evaluated at current point) of D
* transpose with general vector */
SmartPtr<const Vector> curr_jac_dT_times_vec(const Vector& vec);
/** Product of Jacobian (evaluated at trial point) of D
* transpose with general vector */
SmartPtr<const Vector> trial_jac_dT_times_vec(const Vector& vec);
/** Product of Jacobian (evaluated at current point) of C
* transpose with current y_c */
SmartPtr<const Vector> curr_jac_cT_times_curr_y_c();
/** Product of Jacobian (evaluated at trial point) of C
* transpose with trial y_c */
SmartPtr<const Vector> trial_jac_cT_times_trial_y_c();
/** Product of Jacobian (evaluated at current point) of D
* transpose with current y_d */
SmartPtr<const Vector> curr_jac_dT_times_curr_y_d();
/** Product of Jacobian (evaluated at trial point) of D
* transpose with trial y_d */
SmartPtr<const Vector> trial_jac_dT_times_trial_y_d();
/** Product of Jacobian (evaluated at current point) of C
* with general vector */
SmartPtr<const Vector> curr_jac_c_times_vec(const Vector& vec);
/** Product of Jacobian (evaluated at current point) of D
* with general vector */
SmartPtr<const Vector> curr_jac_d_times_vec(const Vector& vec);
/** Constraint Violation (at current iterate). This value should
* be used in the line search, and not curr_primal_infeasibility().
* What type of norm is used depends on constr_viol_normtype */
virtual Number curr_constraint_violation();
/** Constraint Violation (at trial point). This value should
* be used in the line search, and not curr_primal_infeasibility().
* What type of norm is used depends on constr_viol_normtype */
virtual Number trial_constraint_violation();
/** Real constraint violation in a given norm (at current
* iterate). This considers the inequality constraints without
* slacks. */
virtual Number curr_nlp_constraint_violation(ENormType NormType);
/** Unscaled real constraint violation in a given norm (at current
* iterate). This considers the inequality constraints without
* slacks. */
virtual Number unscaled_curr_nlp_constraint_violation(ENormType NormType);
/** Unscaled real constraint violation in a given norm (at trial
* iterate). This considers the inequality constraints without
* slacks. */
virtual Number unscaled_trial_nlp_constraint_violation(ENormType NormType);
//@}
/** @name Hessian matrices */
//@{
/** exact Hessian at current iterate (uncached) */
SmartPtr<const SymMatrix> curr_exact_hessian();
//@}
/** @name primal-dual error and its components */
//@{
/** x-part of gradient of Lagrangian function (at current point) */
SmartPtr<const Vector> curr_grad_lag_x();
/** x-part of gradient of Lagrangian function (at trial point) */
SmartPtr<const Vector> trial_grad_lag_x();
/** s-part of gradient of Lagrangian function (at current point) */
SmartPtr<const Vector> curr_grad_lag_s();
/** s-part of gradient of Lagrangian function (at trial point) */
SmartPtr<const Vector> trial_grad_lag_s();
/** x-part of gradient of Lagrangian function (at current point)
including linear damping term */
SmartPtr<const Vector> curr_grad_lag_with_damping_x();
/** s-part of gradient of Lagrangian function (at current point)
including linear damping term */
SmartPtr<const Vector> curr_grad_lag_with_damping_s();
/** Complementarity for x_L (for current iterate) */
SmartPtr<const Vector> curr_compl_x_L();
/** Complementarity for x_U (for current iterate) */
SmartPtr<const Vector> curr_compl_x_U();
/** Complementarity for s_L (for current iterate) */
SmartPtr<const Vector> curr_compl_s_L();
/** Complementarity for s_U (for current iterate) */
SmartPtr<const Vector> curr_compl_s_U();
/** Complementarity for x_L (for trial iterate) */
SmartPtr<const Vector> trial_compl_x_L();
/** Complementarity for x_U (for trial iterate) */
SmartPtr<const Vector> trial_compl_x_U();
/** Complementarity for s_L (for trial iterate) */
SmartPtr<const Vector> trial_compl_s_L();
/** Complementarity for s_U (for trial iterate) */
SmartPtr<const Vector> trial_compl_s_U();
/** Relaxed complementarity for x_L (for current iterate and current mu) */
SmartPtr<const Vector> curr_relaxed_compl_x_L();
/** Relaxed complementarity for x_U (for current iterate and current mu) */
SmartPtr<const Vector> curr_relaxed_compl_x_U();
/** Relaxed complementarity for s_L (for current iterate and current mu) */
SmartPtr<const Vector> curr_relaxed_compl_s_L();
/** Relaxed complementarity for s_U (for current iterate and current mu) */
SmartPtr<const Vector> curr_relaxed_compl_s_U();
/** Primal infeasibility in a given norm (at current iterate). */
virtual Number curr_primal_infeasibility(ENormType NormType);
/** Primal infeasibility in a given norm (at trial point) */
virtual Number trial_primal_infeasibility(ENormType NormType);
/** Dual infeasibility in a given norm (at current iterate) */
virtual Number curr_dual_infeasibility(ENormType NormType);
/** Dual infeasibility in a given norm (at trial iterate) */
virtual Number trial_dual_infeasibility(ENormType NormType);
/** Unscaled dual infeasibility in a given norm (at current iterate) */
virtual Number unscaled_curr_dual_infeasibility(ENormType NormType);
/** Complementarity (for all complementarity conditions together)
* in a given norm (at current iterate) */
virtual Number curr_complementarity(Number mu, ENormType NormType);
/** Complementarity (for all complementarity conditions together)
* in a given norm (at trial iterate) */
virtual Number trial_complementarity(Number mu, ENormType NormType);
/** Complementarity (for all complementarity conditions together)
* in a given norm (at current iterate) without NLP scaling. */
virtual Number unscaled_curr_complementarity(Number mu, ENormType NormType);
/** Centrality measure (in spirit of the -infinity-neighborhood. */
Number CalcCentralityMeasure(const Vector& compl_x_L,
const Vector& compl_x_U,
const Vector& compl_s_L,
const Vector& compl_s_U);
/** Centrality measure at current point */
virtual Number curr_centrality_measure();
/** Total optimality error for the original NLP at the current
* iterate, using scaling factors based on multipliers. Note
* that here the constraint violation is measured without slacks
* (nlp_constraint_violation) */
virtual Number curr_nlp_error();
/** Total optimality error for the original NLP at the current
* iterate, but using no scaling based on multipliers, and no
* scaling for the NLP. Note that here the constraint violation
* is measured without slacks (nlp_constraint_violation) */
virtual Number unscaled_curr_nlp_error();
/** Total optimality error for the barrier problem at the
* current iterate, using scaling factors based on multipliers. */
virtual Number curr_barrier_error();
/** Norm of the primal-dual system for a given mu (at current
* iterate). The norm is defined as the sum of the 1-norms of
* dual infeasibiliy, primal infeasibility, and complementarity,
* all divided by the number of elements of the vectors of which
* the norm is taken.
*/
virtual Number curr_primal_dual_system_error(Number mu);
/** Norm of the primal-dual system for a given mu (at trial
* iterate). The norm is defined as the sum of the 1-norms of
* dual infeasibiliy, primal infeasibility, and complementarity,
* all divided by the number of elements of the vectors of which
* the norm is taken.
*/
virtual Number trial_primal_dual_system_error(Number mu);
//@}
/** @name Computing fraction-to-the-boundary step sizes */
//@{
/** Fraction to the boundary from (current) primal variables x and s
* for a given step */
Number primal_frac_to_the_bound(Number tau,
const Vector& delta_x,
const Vector& delta_s);
/** Fraction to the boundary from (current) primal variables x and s
* for internal (current) step */
Number curr_primal_frac_to_the_bound(Number tau);
/** Fraction to the boundary from (current) dual variables z and v
* for a given step */
Number dual_frac_to_the_bound(Number tau,
const Vector& delta_z_L,
const Vector& delta_z_U,
const Vector& delta_v_L,
const Vector& delta_v_U);
/** Fraction to the boundary from (current) dual variables z and v
* for a given step, without caching */
Number uncached_dual_frac_to_the_bound(Number tau,
const Vector& delta_z_L,
const Vector& delta_z_U,
const Vector& delta_v_L,
const Vector& delta_v_U);
/** Fraction to the boundary from (current) dual variables z and v
* for internal (current) step */
Number curr_dual_frac_to_the_bound(Number tau);
/** Fraction to the boundary from (current) slacks for a given
* step in the slacks. Usually, one will use the
* primal_frac_to_the_bound method to compute the primal fraction
* to the boundary step size, but if it is cheaper to provide the
* steps in the slacks directly (e.g. when the primal step sizes
* are only temporary), the this method is more efficient. This
* method does not cache computations. */
Number uncached_slack_frac_to_the_bound(Number tau,
const Vector& delta_x_L,
const Vector& delta_x_U,
const Vector& delta_s_L,
const Vector& delta_s_U);
//@}
/** @name Sigma matrices */
//@{
SmartPtr<const Vector> curr_sigma_x();
SmartPtr<const Vector> curr_sigma_s();
//@}
/** average of current values of the complementarities */
Number curr_avrg_compl();
/** average of trial values of the complementarities */
Number trial_avrg_compl();
/** inner_product of current barrier obj. fn. gradient with
* current search direction */
Number curr_gradBarrTDelta();
/** Compute the norm of a specific type of a set of vectors (uncached) */
Number
CalcNormOfType(ENormType NormType,
std::vector<SmartPtr<const Vector> > vecs);
/** Compute the norm of a specific type of two vectors (uncached) */
Number
CalcNormOfType(ENormType NormType,
const Vector& vec1, const Vector& vec2);
/** Norm type used for calculating constraint violation */
ENormType constr_viol_normtype() const
{
return constr_viol_normtype_;
}
/** Method returning true if this is a square problem */
bool IsSquareProblem() const;
/** Method returning the IpoptNLP object. This should only be
* used with care! */
SmartPtr<IpoptNLP>& GetIpoptNLP()
{
return ip_nlp_;
}
IpoptAdditionalCq& AdditionalCq()
{
DBG_ASSERT(IsValid(add_cq_));
return *add_cq_;
}
/** Methods for IpoptType */
//@{
/** Called by IpoptType to register the options */
static void RegisterOptions(SmartPtr<RegisteredOptions> roptions);
//@}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
IpoptCalculatedQuantities();
/** Copy Constructor */
IpoptCalculatedQuantities(const IpoptCalculatedQuantities&);
/** Overloaded Equals Operator */
void operator=(const IpoptCalculatedQuantities&);
//@}
/** @name Pointers for easy access to data and NLP information */
//@{
/** Ipopt NLP object */
SmartPtr<IpoptNLP> ip_nlp_;
/** Ipopt Data object */
SmartPtr<IpoptData> ip_data_;
/** Chen-Goldfarb specific calculated quantities */
SmartPtr<IpoptAdditionalCq> add_cq_;
//@}
/** @name Algorithmic Parameters that can be set throught the
* options list. Those parameters are initialize by calling the
* Initialize method.*/
//@{
/** Parameter in formula for computing overall primal-dual
* optimality error */
Number s_max_;
/** Weighting factor for the linear damping term added to the
* barrier objective funciton. */
Number kappa_d_;
/** fractional movement allowed in bounds */
Number slack_move_;
/** Norm type to be used when calculating the constraint violation */
ENormType constr_viol_normtype_;
/** Flag indicating whether the TNLP with identical structure has
* already been solved before. */
bool warm_start_same_structure_;
/** Desired value of the barrier parameter */
Number mu_target_;
//@}
/** @name Caches for slacks */
//@{
CachedResults< SmartPtr<Vector> > curr_slack_x_L_cache_;
CachedResults< SmartPtr<Vector> > curr_slack_x_U_cache_;
CachedResults< SmartPtr<Vector> > curr_slack_s_L_cache_;
CachedResults< SmartPtr<Vector> > curr_slack_s_U_cache_;
CachedResults< SmartPtr<Vector> > trial_slack_x_L_cache_;
CachedResults< SmartPtr<Vector> > trial_slack_x_U_cache_;
CachedResults< SmartPtr<Vector> > trial_slack_s_L_cache_;
CachedResults< SmartPtr<Vector> > trial_slack_s_U_cache_;
Index num_adjusted_slack_x_L_;
Index num_adjusted_slack_x_U_;
Index num_adjusted_slack_s_L_;
Index num_adjusted_slack_s_U_;
//@}
/** @name Cached for objective function stuff */
//@{
CachedResults<Number> curr_f_cache_;
CachedResults<Number> trial_f_cache_;
CachedResults< SmartPtr<const Vector> > curr_grad_f_cache_;
CachedResults< SmartPtr<const Vector> > trial_grad_f_cache_;
//@}
/** @name Caches for barrier function stuff */
//@{
CachedResults<Number> curr_barrier_obj_cache_;
CachedResults<Number> trial_barrier_obj_cache_;
CachedResults< SmartPtr<const Vector> > curr_grad_barrier_obj_x_cache_;
CachedResults< SmartPtr<const Vector> > curr_grad_barrier_obj_s_cache_;
CachedResults< SmartPtr<const Vector> > grad_kappa_times_damping_x_cache_;
CachedResults< SmartPtr<const Vector> > grad_kappa_times_damping_s_cache_;
//@}
/** @name Caches for constraint stuff */
//@{
CachedResults< SmartPtr<const Vector> > curr_c_cache_;
CachedResults< SmartPtr<const Vector> > trial_c_cache_;
CachedResults< SmartPtr<const Vector> > curr_d_cache_;
CachedResults< SmartPtr<const Vector> > trial_d_cache_;
CachedResults< SmartPtr<const Vector> > curr_d_minus_s_cache_;
CachedResults< SmartPtr<const Vector> > trial_d_minus_s_cache_;
CachedResults< SmartPtr<const Matrix> > curr_jac_c_cache_;
CachedResults< SmartPtr<const Matrix> > trial_jac_c_cache_;
CachedResults< SmartPtr<const Matrix> > curr_jac_d_cache_;
CachedResults< SmartPtr<const Matrix> > trial_jac_d_cache_;
CachedResults< SmartPtr<const Vector> > curr_jac_cT_times_vec_cache_;
CachedResults< SmartPtr<const Vector> > trial_jac_cT_times_vec_cache_;
CachedResults< SmartPtr<const Vector> > curr_jac_dT_times_vec_cache_;
CachedResults< SmartPtr<const Vector> > trial_jac_dT_times_vec_cache_;
CachedResults< SmartPtr<const Vector> > curr_jac_c_times_vec_cache_;
CachedResults< SmartPtr<const Vector> > curr_jac_d_times_vec_cache_;
CachedResults<Number> curr_constraint_violation_cache_;
CachedResults<Number> trial_constraint_violation_cache_;
CachedResults<Number> curr_nlp_constraint_violation_cache_;
CachedResults<Number> unscaled_curr_nlp_constraint_violation_cache_;
CachedResults<Number> unscaled_trial_nlp_constraint_violation_cache_;
//@}
/** Cache for the exact Hessian */
CachedResults< SmartPtr<const SymMatrix> > curr_exact_hessian_cache_;
/** @name Components of primal-dual error */
//@{
CachedResults< SmartPtr<const Vector> > curr_grad_lag_x_cache_;
CachedResults< SmartPtr<const Vector> > trial_grad_lag_x_cache_;
CachedResults< SmartPtr<const Vector> > curr_grad_lag_s_cache_;
CachedResults< SmartPtr<const Vector> > trial_grad_lag_s_cache_;
CachedResults< SmartPtr<const Vector> > curr_grad_lag_with_damping_x_cache_;
CachedResults< SmartPtr<const Vector> > curr_grad_lag_with_damping_s_cache_;
CachedResults< SmartPtr<const Vector> > curr_compl_x_L_cache_;
CachedResults< SmartPtr<const Vector> > curr_compl_x_U_cache_;
CachedResults< SmartPtr<const Vector> > curr_compl_s_L_cache_;
CachedResults< SmartPtr<const Vector> > curr_compl_s_U_cache_;
CachedResults< SmartPtr<const Vector> > trial_compl_x_L_cache_;
CachedResults< SmartPtr<const Vector> > trial_compl_x_U_cache_;
CachedResults< SmartPtr<const Vector> > trial_compl_s_L_cache_;
CachedResults< SmartPtr<const Vector> > trial_compl_s_U_cache_;
CachedResults< SmartPtr<const Vector> > curr_relaxed_compl_x_L_cache_;
CachedResults< SmartPtr<const Vector> > curr_relaxed_compl_x_U_cache_;
CachedResults< SmartPtr<const Vector> > curr_relaxed_compl_s_L_cache_;
CachedResults< SmartPtr<const Vector> > curr_relaxed_compl_s_U_cache_;
CachedResults<Number> curr_primal_infeasibility_cache_;
CachedResults<Number> trial_primal_infeasibility_cache_;
CachedResults<Number> curr_dual_infeasibility_cache_;
CachedResults<Number> trial_dual_infeasibility_cache_;
CachedResults<Number> unscaled_curr_dual_infeasibility_cache_;
CachedResults<Number> curr_complementarity_cache_;
CachedResults<Number> trial_complementarity_cache_;
CachedResults<Number> curr_centrality_measure_cache_;
CachedResults<Number> curr_nlp_error_cache_;
CachedResults<Number> unscaled_curr_nlp_error_cache_;
CachedResults<Number> curr_barrier_error_cache_;
CachedResults<Number> curr_primal_dual_system_error_cache_;
CachedResults<Number> trial_primal_dual_system_error_cache_;
//@}
/** @name Caches for fraction to the boundary step sizes */
//@{
CachedResults<Number> primal_frac_to_the_bound_cache_;
CachedResults<Number> dual_frac_to_the_bound_cache_;
//@}
/** @name Caches for sigma matrices */
//@{
CachedResults< SmartPtr<const Vector> > curr_sigma_x_cache_;
CachedResults< SmartPtr<const Vector> > curr_sigma_s_cache_;
//@}
/** Cache for average of current complementarity */
CachedResults<Number> curr_avrg_compl_cache_;
/** Cache for average of trial complementarity */
CachedResults<Number> trial_avrg_compl_cache_;
/** Cache for grad barrier obj. fn inner product with step */
CachedResults<Number> curr_gradBarrTDelta_cache_;
/** @name Indicator vectors required for the linear damping terms
* to handle unbounded solution sets. */
//@{
/** Indicator vector for selecting the elements in x that have
* only lower bounds. */
SmartPtr<Vector> dampind_x_L_;
/** Indicator vector for selecting the elements in x that have
* only upper bounds. */
SmartPtr<Vector> dampind_x_U_;
/** Indicator vector for selecting the elements in s that have
* only lower bounds. */
SmartPtr<Vector> dampind_s_L_;
/** Indicator vector for selecting the elements in s that have
* only upper bounds. */
SmartPtr<Vector> dampind_s_U_;
//@}
/** @name Temporary vectors for intermediate calcuations. We keep
* these around to avoid unnecessarily many new allocations of
* Vectors. */
//@{
SmartPtr<Vector> tmp_x_;
SmartPtr<Vector> tmp_s_;
SmartPtr<Vector> tmp_c_;
SmartPtr<Vector> tmp_d_;
SmartPtr<Vector> tmp_x_L_;
SmartPtr<Vector> tmp_x_U_;
SmartPtr<Vector> tmp_s_L_;
SmartPtr<Vector> tmp_s_U_;
/** Accessor methods for the temporary vectors */
Vector& Tmp_x();
Vector& Tmp_s();
Vector& Tmp_c();
Vector& Tmp_d();
Vector& Tmp_x_L();
Vector& Tmp_x_U();
Vector& Tmp_s_L();
Vector& Tmp_s_U();
//@}
/** flag indicating if Initialize method has been called (for
* debugging) */
bool initialize_called_;
/** @name Auxiliary functions */
//@{
/** Compute new vector containing the slack to a lower bound
* (uncached)
*/
SmartPtr<Vector> CalcSlack_L(const Matrix& P,
const Vector& x,
const Vector& x_bound);
/** Compute new vector containing the slack to a upper bound
* (uncached)
*/
SmartPtr<Vector> CalcSlack_U(const Matrix& P,
const Vector& x,
const Vector& x_bound);
/** Compute barrier term at given point
* (uncached)
*/
Number CalcBarrierTerm(Number mu,
const Vector& slack_x_L,
const Vector& slack_x_U,
const Vector& slack_s_L,
const Vector& slack_s_U);
/** Compute complementarity for slack / multiplier pair */
SmartPtr<const Vector> CalcCompl(const Vector& slack,
const Vector& mult);
/** Compute fraction to the boundary parameter for lower and upper bounds */
Number CalcFracToBound(const Vector& slack_L,
Vector& tmp_L,
const Matrix& P_L,
const Vector& slack_U,
Vector& tmp_U,
const Matrix& P_U,
const Vector& delta,
Number tau);
/** Compute the scaling factors for the optimality error. */
void ComputeOptimalityErrorScaling(const Vector& y_c, const Vector& y_d,
const Vector& z_L, const Vector& z_U,
const Vector& v_L, const Vector& v_U,
Number s_max,
Number& s_d, Number& s_c);
/** Check if slacks are becoming too small. If slacks are
* becoming too small, they are change. The return value is the
* number of corrected slacks. */
Index CalculateSafeSlack(SmartPtr<Vector>& slack,
const SmartPtr<const Vector>& bound,
const SmartPtr<const Vector>& curr_point,
const SmartPtr<const Vector>& multiplier);
/** Computes the indicator vectors that can be used to filter out
* those entries in the slack_... variables, that correspond to
* variables with only lower and upper bounds. This is required
* for the linear damping term in the barrier objective function
* to handle unbounded solution sets. */
void ComputeDampingIndicators(SmartPtr<const Vector>& dampind_x_L,
SmartPtr<const Vector>& dampind_x_U,
SmartPtr<const Vector>& dampind_s_L,
SmartPtr<const Vector>& dampind_s_U);
/** Check if we are in the restoration phase. Returns true, if the
* ip_nlp is of the type RestoIpoptNLP. ToDo: We probably want to
* handle this more elegant and don't have an explicit dependency
* here. Now I added this because otherwise the caching doesn't
* work properly since the restoration phase objective function
* depends on the current barrier parameter. */
bool in_restoration_phase();
//@}
};
} // namespace Ipopt
#endif
+819
View File
@@ -0,0 +1,819 @@
// Copyright (C) 2004, 2009 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpIpoptData.hpp 2472 2014-04-05 17:47:20Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPIPOPTDATA_HPP__
#define __IPIPOPTDATA_HPP__
#include "IpSymMatrix.hpp"
#include "IpOptionsList.hpp"
#include "IpIteratesVector.hpp"
#include "IpRegOptions.hpp"
#include "IpTimingStatistics.hpp"
namespace Ipopt
{
/* Forward declaration */
class IpoptNLP;
/** Base class for additional data that is special to a particular
* type of algorithm, such as the CG penalty function, or using
* iterative linear solvers. The regular IpoptData object should
* be given a derivation of this base class when it is created. */
class IpoptAdditionalData : public ReferencedObject
{
public:
/**@name Constructors/Destructors */
//@{
/** Default Constructor */
IpoptAdditionalData()
{}
/** Default destructor */
virtual ~IpoptAdditionalData()
{}
//@}
/** This method is called to initialize the global algorithmic
* parameters. The parameters are taken from the OptionsList
* object. */
virtual bool Initialize(const Journalist& jnlst,
const OptionsList& options,
const std::string& prefix) = 0;
/** Initialize Data Structures at the beginning. */
virtual bool InitializeDataStructures() = 0;
/** Do whatever is necessary to accept a trial point as current
* iterate. This is also used to finish an iteration, i.e., to
* release memory, and to reset any flags for a new iteration. */
virtual void AcceptTrialPoint() = 0;
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Copy Constructor */
IpoptAdditionalData(const IpoptAdditionalData&);
/** Overloaded Equals Operator */
void operator=(const IpoptAdditionalData&);
//@}
};
/** Class to organize all the data required by the algorithm.
* Internally, once this Data object has been initialized, all
* internal curr_ vectors must always be set (so that prototyes are
* available). The current values can only be set from the trial
* values. The trial values can be set by copying from a vector or
* by adding some fraction of a step to the current values. This
* object also stores steps, which allows to easily communicate the
* step from the step computation object to the line search object.
*/
class IpoptData : public ReferencedObject
{
public:
/**@name Constructors/Destructors */
//@{
/** Constructor */
IpoptData(SmartPtr<IpoptAdditionalData> add_data = NULL,
Number cpu_time_start = -1.);
/** Default destructor */
virtual ~IpoptData();
//@}
/** Initialize Data Structures */
bool InitializeDataStructures(IpoptNLP& ip_nlp,
bool want_x,
bool want_y_c,
bool want_y_d,
bool want_z_L,
bool want_z_U);
/** This method must be called to initialize the global
* algorithmic parameters. The parameters are taken from the
* OptionsList object. */
bool Initialize(const Journalist& jnlst,
const OptionsList& options,
const std::string& prefix);
/** @name Get Methods for Iterates */
//@{
/** Current point */
inline
SmartPtr<const IteratesVector> curr() const;
/** Get the current point in a copied container that is non-const.
The entries in the container cannot be modified, but
the container can be modified to point to new entries.
*/
// SmartPtr<IteratesVector> curr_container() const;
/** Get Trial point */
inline
SmartPtr<const IteratesVector> trial() const;
/** Get Trial point in a copied container that is non-const.
* The entries in the container can not be modified, but
* the container can be modified to point to new entries.
*/
//SmartPtr<IteratesVector> trial_container() const;
/** Set the trial point - this method copies the pointer for
* efficiency (no copy and to keep cache tags the same) so
* after you call set you cannot modify the data again
*/
inline
void set_trial(SmartPtr<IteratesVector>& trial);
/** Set the values of the primal trial variables (x and s) from
* provided Step with step length alpha.
*/
void SetTrialPrimalVariablesFromStep(Number alpha,
const Vector& delta_x,
const Vector& delta_s);
/** Set the values of the trial values for the equality constraint
* multipliers (y_c and y_d) from provided step with step length
* alpha.
*/
void SetTrialEqMultipliersFromStep(Number alpha,
const Vector& delta_y_c,
const Vector& delta_y_d);
/** Set the value of the trial values for the bound multipliers
* (z_L, z_U, v_L, v_U) from provided step with step length
* alpha.
*/
void SetTrialBoundMultipliersFromStep(Number alpha,
const Vector& delta_z_L,
const Vector& delta_z_U,
const Vector& delta_v_L,
const Vector& delta_v_U);
/** ToDo: I may need to add versions of set_trial like the
* following, but I am not sure
*/
// void set_trial(const SmartPtr<IteratesVector>& trial_iterates);
// void set_trial(SmartPtr<const IteratesVector>& trial_iterates);
/** get the current delta */
inline
SmartPtr<const IteratesVector> delta() const;
/** Set the current delta - like the trial point, this method copies
* the pointer for efficiency (no copy and to keep cache tags the
* same) so after you call set, you cannot modify the data
*/
inline
void set_delta(SmartPtr<IteratesVector>& delta);
/** Set the current delta - like the trial point, this method
* copies the pointer for efficiency (no copy and to keep cache
* tags the same) so after you call set, you cannot modify the
* data. This is the version that is happy with a pointer to
* const IteratesVector.
*/
inline
void set_delta(SmartPtr<const IteratesVector>& delta);
/** Affine Delta */
inline
SmartPtr<const IteratesVector> delta_aff() const;
/** Set the affine delta - like the trial point, this method copies
* the pointer for efficiency (no copy and to keep cache tags the
* same) so after you call set, you cannot modify the data
*/
inline
void set_delta_aff(SmartPtr<IteratesVector>& delta_aff);
/** Hessian or Hessian approximation (do not hold on to it, it might be changed) */
SmartPtr<const SymMatrix> W()
{
DBG_ASSERT(IsValid(W_));
return W_;
}
/** Set Hessian approximation */
void Set_W(SmartPtr<const SymMatrix> W)
{
W_ = W;
}
/** @name ("Main") Primal-dual search direction. Those fields are
* used to store the search directions computed from solving the
* primal-dual system, and can be used in the line search. They
* are overwritten in every iteration, so do not hold on to the
* pointers (make copies instead) */
//@{
/** Returns true, if the primal-dual step have been already
* computed for the current iteration. This flag is reset after
* every call of AcceptTrialPoint(). If the search direction is
* computed during the computation of the barrier parameter, the
* method computing the barrier parameter should call
* SetHaveDeltas(true) to tell the IpoptAlgorithm object that it
* doesn't need to recompute the primal-dual step. */
bool HaveDeltas() const
{
return have_deltas_;
}
/** Method for setting the HaveDeltas flag. This method should be
* called if some method computes the primal-dual step (and
* stores it in the delta_ fields of IpoptData) at an early part
* of the iteration. If that flag is set to true, the
* IpoptAlgorithm object will not recompute the step. */
void SetHaveDeltas(bool have_deltas)
{
have_deltas_ = have_deltas;
}
//@}
/** @name Affine-scaling step. Those fields can be used to store
* the affine scaling step. For example, if the method for
* computing the current barrier parameter computes the affine
* scaling steps, then the corrector step in the line search does
* not have to recompute those solutions of the linear system. */
//@{
/** Returns true, if the affine-scaling step have been already
* computed for the current iteration. This flag is reset after
* every call of AcceptTrialPoint(). If the search direction is
* computed during the computation of the barrier parameter, the
* method computing the barrier parameter should call
* SetHaveDeltas(true) to tell the line search does not have to
* recompute them in case it wants to do a corrector step. */
bool HaveAffineDeltas() const
{
return have_affine_deltas_;
}
/** Method for setting the HaveDeltas flag. This method should be
* called if some method computes the primal-dual step (and
* stores it in the delta_ fields of IpoptData) at an early part
* of the iteration. If that flag is set to true, the
* IpoptAlgorithm object will not recompute the step. */
void SetHaveAffineDeltas(bool have_affine_deltas)
{
have_affine_deltas_ = have_affine_deltas;
}
//@}
/** @name Public Methods for updating iterates */
//@{
/** Copy the trial values to the current values */
inline
void CopyTrialToCurrent();
/** Set the current iterate values from the
* trial values. */
void AcceptTrialPoint();
//@}
/** @name General algorithmic data */
//@{
Index iter_count() const
{
return iter_count_;
}
void Set_iter_count(Index iter_count)
{
iter_count_ = iter_count;
}
Number curr_mu() const
{
DBG_ASSERT(mu_initialized_);
return curr_mu_;
}
void Set_mu(Number mu)
{
curr_mu_ = mu;
mu_initialized_ = true;
}
bool MuInitialized() const
{
return mu_initialized_;
}
Number curr_tau() const
{
DBG_ASSERT(tau_initialized_);
return curr_tau_;
}
void Set_tau(Number tau)
{
curr_tau_ = tau;
tau_initialized_ = true;
}
bool TauInitialized() const
{
return tau_initialized_;
}
void SetFreeMuMode(bool free_mu_mode)
{
free_mu_mode_ = free_mu_mode;
}
bool FreeMuMode() const
{
return free_mu_mode_;
}
/** Setting the flag that indicates if a tiny step (below machine
* precision) has been detected */
void Set_tiny_step_flag(bool flag)
{
tiny_step_flag_ = flag;
}
bool tiny_step_flag()
{
return tiny_step_flag_;
}
//@}
/** Overall convergence tolerance. It is used in the convergence
* test, but also in some other parts of the algorithm that
* depend on the specified tolerance, such as the minimum value
* for the barrier parameter. */
//@{
/** Obtain the tolerance. */
Number tol() const
{
DBG_ASSERT(initialize_called_);
return tol_;
}
/** Set a new value for the tolerance. One should be very careful
* when using this, since changing the predefined tolerance might
* have unexpected consequences. This method is for example used
* in the restoration convergence checker to tighten the
* restoration phase convergence tolerance, if the restoration
* phase converged to a point that has not a large value for the
* constraint violation. */
void Set_tol(Number tol)
{
tol_ = tol;
}
//@}
/** Cpu time counter at the beginning of the optimization. This
* is useful to see how much CPU time has been spent in this
* optimization run. */
Number cpu_time_start() const
{
return cpu_time_start_;
}
/** @name Information gathered for iteration output */
//@{
Number info_regu_x() const
{
return info_regu_x_;
}
void Set_info_regu_x(Number regu_x)
{
info_regu_x_ = regu_x;
}
Number info_alpha_primal() const
{
return info_alpha_primal_;
}
void Set_info_alpha_primal(Number alpha_primal)
{
info_alpha_primal_ = alpha_primal;
}
char info_alpha_primal_char() const
{
return info_alpha_primal_char_;
}
void Set_info_alpha_primal_char(char info_alpha_primal_char)
{
info_alpha_primal_char_ = info_alpha_primal_char;
}
Number info_alpha_dual() const
{
return info_alpha_dual_;
}
void Set_info_alpha_dual(Number alpha_dual)
{
info_alpha_dual_ = alpha_dual;
}
Index info_ls_count() const
{
return info_ls_count_;
}
void Set_info_ls_count(Index ls_count)
{
info_ls_count_ = ls_count;
}
bool info_skip_output() const
{
return info_skip_output_;
}
void Append_info_string(const std::string& add_str)
{
info_string_ += add_str;
}
const std::string& info_string() const
{
return info_string_;
}
/** Set this to true, if the next time when output is written, the
* summary line should not be printed. */
void Set_info_skip_output(bool info_skip_output)
{
info_skip_output_ = info_skip_output;
}
/** gives time when the last summary output line was printed */
Number info_last_output()
{
return info_last_output_;
}
/** sets time when the last summary output line was printed */
void Set_info_last_output(Number info_last_output)
{
info_last_output_ = info_last_output;
}
/** gives number of iteration summaries actually printed
* since last summary header was printed */
int info_iters_since_header()
{
return info_iters_since_header_;
}
/** increases number of iteration summaries actually printed
* since last summary header was printed */
void Inc_info_iters_since_header()
{
info_iters_since_header_++;
}
/** sets number of iteration summaries actually printed
* since last summary header was printed */
void Set_info_iters_since_header(int info_iters_since_header)
{
info_iters_since_header_ = info_iters_since_header;
}
/** Reset all info fields */
void ResetInfo()
{
info_regu_x_ = 0;
info_alpha_primal_ = 0;
info_alpha_dual_ = 0.;
info_alpha_primal_char_ = ' ';
info_skip_output_ = false;
info_string_.erase();
}
//@}
/** Return Timing Statistics Object */
TimingStatistics& TimingStats()
{
return timing_statistics_;
}
/** Check if additional data has been set */
bool HaveAddData()
{
return IsValid(add_data_);
}
/** Get access to additional data object */
IpoptAdditionalData& AdditionalData()
{
return *add_data_;
}
/** Set a new pointer for additional Ipopt data */
void SetAddData(SmartPtr<IpoptAdditionalData> add_data)
{
DBG_ASSERT(!HaveAddData());
add_data_ = add_data;
}
/** Set the perturbation of the primal-dual system */
void setPDPert(Number pd_pert_x, Number pd_pert_s,
Number pd_pert_c, Number pd_pert_d)
{
pd_pert_x_ = pd_pert_x;
pd_pert_s_ = pd_pert_s;
pd_pert_c_ = pd_pert_c;
pd_pert_d_ = pd_pert_d;
}
/** Get the current perturbation of the primal-dual system */
void getPDPert(Number& pd_pert_x, Number& pd_pert_s,
Number& pd_pert_c, Number& pd_pert_d)
{
pd_pert_x = pd_pert_x_;
pd_pert_s = pd_pert_s_;
pd_pert_c = pd_pert_c_;
pd_pert_d = pd_pert_d_;
}
/** Methods for IpoptType */
//@{
static void RegisterOptions(const SmartPtr<RegisteredOptions>& roptions);
//@}
private:
/** @name Iterates */
//@{
/** Main iteration variables
* (current iteration) */
SmartPtr<const IteratesVector> curr_;
/** Main iteration variables
* (trial calculations) */
SmartPtr<const IteratesVector> trial_;
/** Hessian (approximation) - might be changed elsewhere! */
SmartPtr<const SymMatrix> W_;
/** @name Primal-dual Step */
//@{
SmartPtr<const IteratesVector> delta_;
/** The following flag is set to true, if some other part of the
* algorithm (like the method for computing the barrier
* parameter) has already computed the primal-dual search
* direction. This flag is reset when the AcceptTrialPoint
* method is called.
* ToDo: we could cue off of a null delta_;
*/
bool have_deltas_;
//@}
/** @name Affine-scaling step. This used to transfer the
* information about the affine-scaling step from the computation
* of the barrier parameter to the corrector (in the line
* search). */
//@{
SmartPtr<const IteratesVector> delta_aff_;
/** The following flag is set to true, if some other part of the
* algorithm (like the method for computing the barrier
* parameter) has already computed the affine-scaling step. This
* flag is reset when the AcceptTrialPoint method is called.
* ToDo: we could cue off of a null delta_aff_;
*/
bool have_affine_deltas_;
//@}
/** iteration count */
Index iter_count_;
/** current barrier parameter */
Number curr_mu_;
bool mu_initialized_;
/** current fraction to the boundary parameter */
Number curr_tau_;
bool tau_initialized_;
/** flag indicating if Initialize method has been called (for
* debugging) */
bool initialize_called_;
/** flag for debugging whether we have already curr_ values
* available (from which new Vectors can be generated */
bool have_prototypes_;
/** @name Global algorithm parameters. Those are options that can
* be modified by the user and appear at different places in the
* algorithm. They are set using an OptionsList object in the
* Initialize method. */
//@{
/** Overall convergence tolerance */
Number tol_;
//@}
/** @name Status data **/
//@{
/** flag indicating whether the algorithm is in the free mu mode */
bool free_mu_mode_;
/** flag indicating if a tiny step has been detected */
bool tiny_step_flag_;
//@}
/** @name Gathered information for iteration output */
//@{
/** Size of regularization for the Hessian */
Number info_regu_x_;
/** Primal step size */
Number info_alpha_primal_;
/** Info character for primal step size */
char info_alpha_primal_char_;
/** Dual step size */
Number info_alpha_dual_;
/** Number of backtracking trial steps */
Index info_ls_count_;
/** true, if next summary output line should not be printed (eg
* after restoration phase. */
bool info_skip_output_;
/** any string of characters for the end of the output line */
std::string info_string_;
/** time when the last summary output line was printed */
Number info_last_output_;
/** number of iteration summaries actually printed since last
* summary header was printed */
int info_iters_since_header_;
//@}
/** VectorSpace for all the iterates */
SmartPtr<IteratesVectorSpace> iterates_space_;
/** TimingStatistics object collecting all Ipopt timing
* statistics */
TimingStatistics timing_statistics_;
/** CPU time counter at initialization. */
Number cpu_time_start_;
/** Object for the data specific for the Chen-Goldfarb penalty
* method algorithm */
SmartPtr<IpoptAdditionalData> add_data_;
/** @name Information about the perturbation of the primal-dual
* system */
//@{
Number pd_pert_x_;
Number pd_pert_s_;
Number pd_pert_c_;
Number pd_pert_d_;
//@}
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Copy Constructor */
IpoptData(const IpoptData&);
/** Overloaded Equals Operator */
void operator=(const IpoptData&);
//@}
#if COIN_IPOPT_CHECKLEVEL > 0
/** Some debug flags to make sure vectors are not changed
* behind the IpoptData's back
*/
//@{
TaggedObject::Tag debug_curr_tag_;
TaggedObject::Tag debug_trial_tag_;
TaggedObject::Tag debug_delta_tag_;
TaggedObject::Tag debug_delta_aff_tag_;
TaggedObject::Tag debug_curr_tag_sum_;
TaggedObject::Tag debug_trial_tag_sum_;
TaggedObject::Tag debug_delta_tag_sum_;
TaggedObject::Tag debug_delta_aff_tag_sum_;
//@}
#endif
};
inline
SmartPtr<const IteratesVector> IpoptData::curr() const
{
DBG_ASSERT(IsNull(curr_) || (curr_->GetTag() == debug_curr_tag_ && curr_->GetTagSum() == debug_curr_tag_sum_) );
return curr_;
}
inline
SmartPtr<const IteratesVector> IpoptData::trial() const
{
DBG_ASSERT(IsNull(trial_) || (trial_->GetTag() == debug_trial_tag_ && trial_->GetTagSum() == debug_trial_tag_sum_) );
return trial_;
}
inline
SmartPtr<const IteratesVector> IpoptData::delta() const
{
DBG_ASSERT(IsNull(delta_) || (delta_->GetTag() == debug_delta_tag_ && delta_->GetTagSum() == debug_delta_tag_sum_) );
return delta_;
}
inline
SmartPtr<const IteratesVector> IpoptData::delta_aff() const
{
DBG_ASSERT(IsNull(delta_aff_) || (delta_aff_->GetTag() == debug_delta_aff_tag_ && delta_aff_->GetTagSum() == debug_delta_aff_tag_sum_) );
return delta_aff_;
}
inline
void IpoptData::CopyTrialToCurrent()
{
curr_ = trial_;
#if COIN_IPOPT_CHECKLEVEL > 0
if (IsValid(curr_)) {
debug_curr_tag_ = curr_->GetTag();
debug_curr_tag_sum_ = curr_->GetTagSum();
}
else {
debug_curr_tag_ = 0;
debug_curr_tag_sum_ = 0;
}
#endif
}
inline
void IpoptData::set_trial(SmartPtr<IteratesVector>& trial)
{
trial_ = ConstPtr(trial);
#if COIN_IPOPT_CHECKLEVEL > 0
// verify the correct space
DBG_ASSERT(trial_->OwnerSpace() == (VectorSpace*)GetRawPtr(iterates_space_));
if (IsValid(trial)) {
debug_trial_tag_ = trial->GetTag();
debug_trial_tag_sum_ = trial->GetTagSum();
}
else {
debug_trial_tag_ = 0;
debug_trial_tag_sum_ = 0;
}
#endif
trial = NULL;
}
inline
void IpoptData::set_delta(SmartPtr<IteratesVector>& delta)
{
delta_ = ConstPtr(delta);
#if COIN_IPOPT_CHECKLEVEL > 0
if (IsValid(delta)) {
debug_delta_tag_ = delta->GetTag();
debug_delta_tag_sum_ = delta->GetTagSum();
}
else {
debug_delta_tag_ = 0;
debug_delta_tag_sum_ = 0;
}
#endif
delta = NULL;
}
inline
void IpoptData::set_delta(SmartPtr<const IteratesVector>& delta)
{
delta_ = delta;
#if COIN_IPOPT_CHECKLEVEL > 0
if (IsValid(delta)) {
debug_delta_tag_ = delta->GetTag();
debug_delta_tag_sum_ = delta->GetTagSum();
}
else {
debug_delta_tag_ = 0;
debug_delta_tag_sum_ = 0;
}
#endif
delta = NULL;
}
inline
void IpoptData::set_delta_aff(SmartPtr<IteratesVector>& delta_aff)
{
delta_aff_ = ConstPtr(delta_aff);
#if COIN_IPOPT_CHECKLEVEL > 0
if (IsValid(delta_aff)) {
debug_delta_aff_tag_ = delta_aff->GetTag();
debug_delta_aff_tag_sum_ = delta_aff->GetTagSum();
}
else {
debug_delta_aff_tag_ = 0;
debug_delta_aff_tag_sum_ = delta_aff->GetTagSum();
}
#endif
delta_aff = NULL;
}
} // namespace Ipopt
#endif
+261
View File
@@ -0,0 +1,261 @@
// Copyright (C) 2004, 2006 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpIpoptNLP.hpp 2594 2015-08-09 14:31:05Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPIPOPTNLP_HPP__
#define __IPIPOPTNLP_HPP__
#include "IpNLP.hpp"
#include "IpJournalist.hpp"
#include "IpNLPScaling.hpp"
namespace Ipopt
{
// forward declarations
class IteratesVector;
/** This is the abstract base class for classes that map
* the traditional NLP into
* something that is more useful by Ipopt.
* This class takes care of storing the
* calculated model results, handles cacheing,
* and (some day) takes care of addition of slacks.
*/
class IpoptNLP : public ReferencedObject
{
public:
/**@name Constructors/Destructors */
//@{
IpoptNLP(const SmartPtr<NLPScalingObject> nlp_scaling)
:
nlp_scaling_(nlp_scaling)
{}
/** Default destructor */
virtual ~IpoptNLP()
{}
//@}
/** Initialization method. Set the internal options and
* initialize internal data structures. */
virtual bool Initialize(const Journalist& jnlst,
const OptionsList& options,
const std::string& prefix)
{
bool ret = true;
if (IsValid(nlp_scaling_)) {
ret = nlp_scaling_->Initialize(jnlst, options, prefix);
}
return ret;
}
/**@name Possible Exceptions */
//@{
/** thrown if there is any error evaluating values from the nlp */
DECLARE_STD_EXCEPTION(Eval_Error);
//@}
/** Initialize (create) structures for
* the iteration data */
virtual bool InitializeStructures(SmartPtr<Vector>& x,
bool init_x,
SmartPtr<Vector>& y_c,
bool init_y_c,
SmartPtr<Vector>& y_d,
bool init_y_d,
SmartPtr<Vector>& z_L,
bool init_z_L,
SmartPtr<Vector>& z_U,
bool init_z_U,
SmartPtr<Vector>& v_L,
SmartPtr<Vector>& v_U
) = 0;
/** Method accessing the GetWarmStartIterate of the NLP */
virtual bool GetWarmStartIterate(IteratesVector& warm_start_iterate)=0;
/** Accessor methods for model data */
//@{
/** Objective value */
virtual Number f(const Vector& x) = 0;
/** Gradient of the objective */
virtual SmartPtr<const Vector> grad_f(const Vector& x) = 0;
/** Equality constraint residual */
virtual SmartPtr<const Vector> c(const Vector& x) = 0;
/** Jacobian Matrix for equality constraints */
virtual SmartPtr<const Matrix> jac_c(const Vector& x) = 0;
/** Inequality constraint residual (reformulated
* as equalities with slacks */
virtual SmartPtr<const Vector> d(const Vector& x) = 0;
/** Jacobian Matrix for inequality constraints */
virtual SmartPtr<const Matrix> jac_d(const Vector& x) = 0;
/** Hessian of the Lagrangian */
virtual SmartPtr<const SymMatrix> h(const Vector& x,
Number obj_factor,
const Vector& yc,
const Vector& yd
) = 0;
/** Lower bounds on x */
virtual SmartPtr<const Vector> x_L() const = 0;
/** Permutation matrix (x_L_ -> x) */
virtual SmartPtr<const Matrix> Px_L() const = 0;
/** Upper bounds on x */
virtual SmartPtr<const Vector> x_U() const = 0;
/** Permutation matrix (x_U_ -> x */
virtual SmartPtr<const Matrix> Px_U() const = 0;
/** Lower bounds on d */
virtual SmartPtr<const Vector> d_L() const = 0;
/** Permutation matrix (d_L_ -> d) */
virtual SmartPtr<const Matrix> Pd_L() const = 0;
/** Upper bounds on d */
virtual SmartPtr<const Vector> d_U() const = 0;
/** Permutation matrix (d_U_ -> d */
virtual SmartPtr<const Matrix> Pd_U() const = 0;
/** x_space */
virtual SmartPtr<const VectorSpace> x_space() const = 0;
/** Accessor method to obtain the MatrixSpace for the Hessian
* matrix (or it's approximation) */
virtual SmartPtr<const SymMatrixSpace> HessianMatrixSpace() const = 0;
//@}
/** Accessor method for vector/matrix spaces pointers. */
virtual void GetSpaces(SmartPtr<const VectorSpace>& x_space,
SmartPtr<const VectorSpace>& c_space,
SmartPtr<const VectorSpace>& d_space,
SmartPtr<const VectorSpace>& x_l_space,
SmartPtr<const MatrixSpace>& px_l_space,
SmartPtr<const VectorSpace>& x_u_space,
SmartPtr<const MatrixSpace>& px_u_space,
SmartPtr<const VectorSpace>& d_l_space,
SmartPtr<const MatrixSpace>& pd_l_space,
SmartPtr<const VectorSpace>& d_u_space,
SmartPtr<const MatrixSpace>& pd_u_space,
SmartPtr<const MatrixSpace>& Jac_c_space,
SmartPtr<const MatrixSpace>& Jac_d_space,
SmartPtr<const SymMatrixSpace>& Hess_lagrangian_space) = 0;
/** Method for adapting the variable bounds. This is called if
* slacks are becoming too small */
virtual void AdjustVariableBounds(const Vector& new_x_L,
const Vector& new_x_U,
const Vector& new_d_L,
const Vector& new_d_U)=0;
/** @name Counters for the number of function evaluations. */
//@{
virtual Index f_evals() const = 0;
virtual Index grad_f_evals() const = 0;
virtual Index c_evals() const = 0;
virtual Index jac_c_evals() const = 0;
virtual Index d_evals() const = 0;
virtual Index jac_d_evals() const = 0;
virtual Index h_evals() const = 0;
//@}
/** @name Special method for dealing with the fact that the
* restoration phase objective function depends on the barrier
* parameter */
//@{
/** Method for telling the IpoptCalculatedQuantities class whether
* the objective function depends on the barrier function. This
* is only used for the restoration phase NLP
* formulation. Probably only RestoIpoptNLP should overwrite
* this. */
virtual bool objective_depends_on_mu() const
{
return false;
}
/** Replacement for the default objective function method which
* knows about the barrier parameter */
virtual Number f(const Vector& x, Number mu) = 0;
/** Replacement for the default objective gradient method which
* knows about the barrier parameter */
virtual SmartPtr<const Vector> grad_f(const Vector& x, Number mu) = 0;
/** Replacement for the default Lagrangian Hessian method which
* knows about the barrier parameter */
virtual SmartPtr<const SymMatrix> h(const Vector& x,
Number obj_factor,
const Vector& yc,
const Vector& yd,
Number mu) = 0;
/** Provides a Hessian matrix from the correct matrix space with
* uninitialized values. This can be used in LeastSquareMults to
* obtain a "zero Hessian". */
virtual SmartPtr<const SymMatrix> uninitialized_h() = 0;
//@}
/**@name solution routines */
//@{
virtual void FinalizeSolution(SolverReturn status,
const Vector& x, const Vector& z_L, const Vector& z_U,
const Vector& c, const Vector& d,
const Vector& y_c, const Vector& y_d,
Number obj_value,
const IpoptData* ip_data,
IpoptCalculatedQuantities* ip_cq)=0;
virtual bool IntermediateCallBack(AlgorithmMode mode,
Index iter, Number obj_value,
Number inf_pr, Number inf_du,
Number mu, Number d_norm,
Number regularization_size,
Number alpha_du, Number alpha_pr,
Index ls_trials,
SmartPtr<const IpoptData> ip_data,
SmartPtr<IpoptCalculatedQuantities> ip_cq)=0;
//@}
/** Returns the scaling strategy object */
SmartPtr<NLPScalingObject> NLP_scaling() const
{
DBG_ASSERT(IsValid(nlp_scaling_));
return nlp_scaling_;
}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Copy Constructor */
IpoptNLP(const IpoptNLP&);
/** Overloaded Equals Operator */
void operator=(const IpoptNLP&);
//@}
SmartPtr<NLPScalingObject> nlp_scaling_;
};
} // namespace Ipopt
#endif
+64
View File
@@ -0,0 +1,64 @@
// Copyright (C) 2004, 2006 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpIterateInitializer.hpp 1861 2010-12-21 21:34:47Z andreasw $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-09-24
#ifndef __IPITERATEINITIALIZER_HPP__
#define __IPITERATEINITIALIZER_HPP__
#include "IpAlgStrategy.hpp"
#include "IpIpoptNLP.hpp"
#include "IpIpoptData.hpp"
#include "IpIpoptCalculatedQuantities.hpp"
namespace Ipopt
{
/** Base class for all methods for initializing the iterates.
*/
class IterateInitializer: public AlgorithmStrategyObject
{
public:
/**@name Constructors/Destructors */
//@{
/** Default Constructor */
IterateInitializer()
{}
/** Default destructor */
virtual ~IterateInitializer()
{}
//@}
/** overloaded from AlgorithmStrategyObject */
virtual bool InitializeImpl(const OptionsList& options,
const std::string& prefix) = 0;
/** Compute the initial iterates and set the into the curr field
* of the ip_data object. */
virtual bool SetInitialIterates() = 0;
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Copy Constructor */
IterateInitializer(const IterateInitializer&);
/** Overloaded Equals Operator */
void operator=(const IterateInitializer&);
//@}
};
} // namespace Ipopt
#endif
+689
View File
@@ -0,0 +1,689 @@
// Copyright (C) 2004, 2006 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpIteratesVector.hpp 2472 2014-04-05 17:47:20Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-06-06
#ifndef __IPITERATESVECTOR_HPP__
#define __IPITERATESVECTOR_HPP__
#include "IpCompoundVector.hpp"
namespace Ipopt
{
/* forward declarations */
class IteratesVectorSpace;
/** Specialized CompoundVector class specifically for the algorithm
* iterates. This class inherits from CompoundVector and is a
* specialized class for handling the iterates of the Ipopt
* Algorithm, that is, x, s, y_c, y_d, z_L, z_U, v_L, and v_U. It
* inherits from CompoundVector so it can behave like a CV in most
* calculations, but it has fixed dimensions and cannot be
* customized
*/
class IteratesVector : public CompoundVector
{
public:
/** Constructors / Destructors */
//@{
IteratesVector(const IteratesVectorSpace* owner_space, bool create_new);
virtual ~IteratesVector();
//@}
/** Make New methods */
//@{
/** Use this method to create a new iterates vector. The MakeNew
* method on the Vector class also works, but it does not give
* the create_new option.
*/
SmartPtr<IteratesVector> MakeNewIteratesVector(bool create_new = true) const;
/** Use this method to create a new iterates vector with a copy of
* all the data.
*/
SmartPtr<IteratesVector> MakeNewIteratesVectorCopy() const
{
SmartPtr<IteratesVector> ret = MakeNewIteratesVector(true);
ret->Copy(*this);
return ret;
}
/** Use this method to create a new iterates vector
* container. This creates a new NonConst container, but the
* elements inside the iterates vector may be const. Therefore,
* the container can be modified to point to new entries, but the
* existing entries may or may not be modifiable.
*/
SmartPtr<IteratesVector> MakeNewContainer() const;
//@}
/** Iterates Set/Get Methods */
//@{
/** Get the x iterate (const) */
SmartPtr<const Vector> x() const
{
return GetIterateFromComp(0);
}
/** Get the x iterate (non-const) - this can only be called if the
* vector was created intenally, or the Set_x_NonConst method was
* used. */
SmartPtr<Vector> x_NonConst()
{
return GetNonConstIterateFromComp(0);
}
/** Create a new vector in the x entry */
inline
SmartPtr<Vector> create_new_x();
/** Create a new vector in the x entry and copy the current values
* into it. */
SmartPtr<Vector> create_new_x_copy()
{
SmartPtr<const Vector> curr_x = GetComp(0);
Set_x_NonConst(*curr_x->MakeNew());
x_NonConst()->Copy(*curr_x);
return x_NonConst();
}
/** Set the x iterate (const). Sets the pointer, does NOT copy
* data. */
void Set_x(const Vector& vec)
{
SetComp(0, vec);
}
/** Set the x iterate (non-const). Sets the pointer, does NOT copy
* data. */
void Set_x_NonConst(Vector& vec)
{
SetCompNonConst(0, vec);
}
/** Get the s iterate (const) */
SmartPtr<const Vector> s() const
{
return GetIterateFromComp(1);
}
/** Get the s iterate (non-const) - this can only be called if the
* vector was created intenally, or the Set_s_NonConst method was
* used. */
SmartPtr<Vector> s_NonConst()
{
return GetNonConstIterateFromComp(1);
}
/** Create a new vector in the s entry */
inline
SmartPtr<Vector> create_new_s();
/** Create a new vector in the s entry and copy the current values
* into it. */
SmartPtr<Vector> create_new_s_copy()
{
SmartPtr<const Vector> curr_s = GetComp(1);
Set_s_NonConst(*curr_s->MakeNew());
s_NonConst()->Copy(*curr_s);
return s_NonConst();
}
/** Set the s iterate (const). Sets the pointer, does NOT copy
* data. */
void Set_s(const Vector& vec)
{
SetComp(1, vec);
}
/** Set the s iterate (non-const). Sets the pointer, does NOT copy
* data. */
void Set_s_NonConst(Vector& vec)
{
SetCompNonConst(1, vec);
}
/** Get the y_c iterate (const) */
SmartPtr<const Vector> y_c() const
{
return GetIterateFromComp(2);
}
/** Get the y_c iterate (non-const) - this can only be called if
* the vector was created intenally, or the Set_y_c_NonConst
* method was used. */
SmartPtr<Vector> y_c_NonConst()
{
return GetNonConstIterateFromComp(2);
}
/** Create a new vector in the y_c entry */
inline
SmartPtr<Vector> create_new_y_c();
/** Create a new vector in the y_c entry and copy the current
* values into it. */
SmartPtr<Vector> create_new_y_c_copy()
{
SmartPtr<const Vector> curr_y_c = GetComp(2);
Set_y_c_NonConst(*curr_y_c->MakeNew());
y_c_NonConst()->Copy(*curr_y_c);
return y_c_NonConst();
}
/** Set the y_c iterate (const). Sets the pointer, does NOT copy
* data. */
void Set_y_c(const Vector& vec)
{
SetComp(2, vec);
}
/** Set the y_c iterate (non-const). Sets the pointer, does NOT
* copy data. */
void Set_y_c_NonConst(Vector& vec)
{
SetCompNonConst(2, vec);
}
/** Get the y_d iterate (const) */
SmartPtr<const Vector> y_d() const
{
return GetIterateFromComp(3);
}
/** Get the y_d iterate (non-const) - this can only be called if
* the vector was created intenally, or the Set_y_d_NonConst
* method was used. */
SmartPtr<Vector> y_d_NonConst()
{
return GetNonConstIterateFromComp(3);
}
/** Create a new vector in the y_d entry */
inline
SmartPtr<Vector> create_new_y_d();
/** Create a new vector in the y_d entry and copy the current
* values into it. */
SmartPtr<Vector> create_new_y_d_copy()
{
SmartPtr<const Vector> curr_y_d = GetComp(3);
Set_y_d_NonConst(*curr_y_d->MakeNew());
y_d_NonConst()->Copy(*curr_y_d);
return y_d_NonConst();
}
/** Set the y_d iterate (const). Sets the pointer, does NOT copy
* data. */
void Set_y_d(const Vector& vec)
{
SetComp(3, vec);
}
/** Set the y_d iterate (non-const). Sets the pointer, does NOT
* copy data. */
void Set_y_d_NonConst(Vector& vec)
{
SetCompNonConst(3, vec);
}
/** Get the z_L iterate (const) */
SmartPtr<const Vector> z_L() const
{
return GetIterateFromComp(4);
}
/** Get the z_L iterate (non-const) - this can only be called if
* the vector was created intenally, or the Set_z_L_NonConst
* method was used. */
SmartPtr<Vector> z_L_NonConst()
{
return GetNonConstIterateFromComp(4);
}
/** Create a new vector in the z_L entry */
inline
SmartPtr<Vector> create_new_z_L();
/** Create a new vector in the z_L entry and copy the current
* values into it. */
SmartPtr<Vector> create_new_z_L_copy()
{
SmartPtr<const Vector> curr_z_L = GetComp(4);
Set_z_L_NonConst(*curr_z_L->MakeNew());
z_L_NonConst()->Copy(*curr_z_L);
return z_L_NonConst();
}
/** Set the z_L iterate (const). Sets the pointer, does NOT copy
* data. */
void Set_z_L(const Vector& vec)
{
SetComp(4, vec);
}
/** Set the z_L iterate (non-const). Sets the pointer, does NOT
* copy data. */
void Set_z_L_NonConst(Vector& vec)
{
SetCompNonConst(4, vec);
}
/** Get the z_U iterate (const) */
SmartPtr<const Vector> z_U() const
{
return GetIterateFromComp(5);
}
/** Get the z_U iterate (non-const) - this can only be called if
* the vector was created intenally, or the Set_z_U_NonConst
* method was used. */
SmartPtr<Vector> z_U_NonConst()
{
return GetNonConstIterateFromComp(5);
}
/** Create a new vector in the z_U entry */
inline
SmartPtr<Vector> create_new_z_U();
/** Create a new vector in the z_U entry and copy the current
* values into it. */
SmartPtr<Vector> create_new_z_U_copy()
{
SmartPtr<const Vector> curr_z_U = GetComp(5);
Set_z_U_NonConst(*curr_z_U->MakeNew());
z_U_NonConst()->Copy(*curr_z_U);
return z_U_NonConst();
}
/** Set the z_U iterate (const). Sets the pointer, does NOT copy
* data. */
void Set_z_U(const Vector& vec)
{
SetComp(5, vec);
}
/** Set the z_U iterate (non-const). Sets the pointer, does NOT
* copy data. */
void Set_z_U_NonConst(Vector& vec)
{
SetCompNonConst(5, vec);
}
/** Get the v_L iterate (const) */
SmartPtr<const Vector> v_L() const
{
return GetIterateFromComp(6);
}
/** Get the v_L iterate (non-const) - this can only be called if
* the vector was created intenally, or the Set_v_L_NonConst
* method was used. */
SmartPtr<Vector> v_L_NonConst()
{
return GetNonConstIterateFromComp(6);
}
/** Create a new vector in the v_L entry */
inline
SmartPtr<Vector> create_new_v_L();
/** Create a new vector in the v_L entry and copy the current
* values into it. */
SmartPtr<Vector> create_new_v_L_copy()
{
SmartPtr<const Vector> curr_v_L = GetComp(6);
Set_v_L_NonConst(*curr_v_L->MakeNew());
v_L_NonConst()->Copy(*curr_v_L);
return v_L_NonConst();
}
/** Set the v_L iterate (const). Sets the pointer, does NOT copy
* data. */
void Set_v_L(const Vector& vec)
{
SetComp(6, vec);
}
/** Set the v_L iterate (non-const). Sets the pointer, does NOT
* copy data. */
void Set_v_L_NonConst(Vector& vec)
{
SetCompNonConst(6, vec);
}
/** Get the v_U iterate (const) */
SmartPtr<const Vector> v_U() const
{
return GetIterateFromComp(7);
}
/** Get the v_U iterate (non-const) - this can only be called if
* the vector was created intenally, or the Set_v_U_NonConst
* method was used. */
SmartPtr<Vector> v_U_NonConst()
{
return GetNonConstIterateFromComp(7);
}
/** Create a new vector in the v_U entry */
inline
SmartPtr<Vector> create_new_v_U();
/** Create a new vector in the v_U entry and copy the current
* values into it. */
SmartPtr<Vector> create_new_v_U_copy()
{
SmartPtr<const Vector> curr_v_U = GetComp(7);
Set_v_U_NonConst(*curr_v_U->MakeNew());
v_U_NonConst()->Copy(*curr_v_U);
return v_U_NonConst();
}
/** Set the v_U iterate (const). Sets the pointer, does NOT copy
* data. */
void Set_v_U(const Vector& vec)
{
SetComp(7, vec);
}
/** Set the v_U iterate (non-const). Sets the pointer, does NOT
* copy data. */
void Set_v_U_NonConst(Vector& vec)
{
SetCompNonConst(7, vec);
}
/** Set the primal variables all in one shot. Sets the pointers,
* does NOT copy data */
void Set_primal(const Vector& x, const Vector& s)
{
SetComp(0, x);
SetComp(1, s);
}
void Set_primal_NonConst(Vector& x, Vector& s)
{
SetCompNonConst(0, x);
SetCompNonConst(1, s);
}
/** Set the eq multipliers all in one shot. Sets the pointers,
* does not copy data. */
void Set_eq_mult(const Vector& y_c, const Vector& y_d)
{
SetComp(2, y_c);
SetComp(3, y_d);
}
void Set_eq_mult_NonConst(Vector& y_c, Vector& y_d)
{
SetCompNonConst(2, y_c);
SetCompNonConst(3, y_d);
}
/** Set the bound multipliers all in one shot. Sets the pointers,
* does not copy data. */
void Set_bound_mult(const Vector& z_L, const Vector& z_U, const Vector& v_L, const Vector& v_U)
{
SetComp(4, z_L);
SetComp(5, z_U);
SetComp(6, v_L);
SetComp(7, v_U);
}
void Set_bound_mult_NonConst(Vector& z_L, Vector& z_U, Vector& v_L, Vector& v_U)
{
SetCompNonConst(4, z_L);
SetCompNonConst(5, z_U);
SetCompNonConst(6, v_L);
SetCompNonConst(7, v_U);
}
/** Get a sum of the tags of the contained items. There is no
* guarantee that this is unique, but there is a high chance it
* is unique and it can be used for debug checks relatively
* reliably.
*/
TaggedObject::Tag GetTagSum() const
{
TaggedObject::Tag tag = 0;
if (IsValid(x())) {
tag += x()->GetTag();
}
if (IsValid(s())) {
tag += s()->GetTag();
}
if (IsValid(y_c())) {
tag += y_c()->GetTag();
}
if (IsValid(y_d())) {
tag += y_d()->GetTag();
}
if (IsValid(z_L())) {
tag += z_L()->GetTag();
}
if (IsValid(z_U())) {
tag += z_U()->GetTag();
}
if (IsValid(v_L())) {
tag += v_L()->GetTag();
}
if (IsValid(v_U())) {
tag += v_U()->GetTag();
}
return tag;
}
//@}
private:
/**@name Default Compiler Generated Methods (Hidden to avoid
* implicit creation/calling). These methods are not implemented
* and we do not want the compiler to implement them for us, so we
* declare them private and do not define them. This ensures that
* they will not be implicitly created/called.
*/
//@{
/** Default Constructor */
IteratesVector();
/** Copy Constructor */
IteratesVector(const IteratesVector&);
/** Overloaded Equals Operator */
void operator=(const IteratesVector&);
//@}
const IteratesVectorSpace* owner_space_;
/** private method to return the const element from the compound
* vector. This method will return NULL if none is currently
* set.
*/
SmartPtr<const Vector> GetIterateFromComp(Index i) const
{
if (IsCompNull(i)) {
return NULL;
}
return GetComp(i);
}
/** private method to return the non-const element from the
* compound vector. This method will return NULL if none is
* currently set.
*/
SmartPtr<Vector> GetNonConstIterateFromComp(Index i)
{
if (IsCompNull(i)) {
return NULL;
}
return GetCompNonConst(i);
}
};
/** Vector Space for the IteratesVector class. This is a
* specialized vector space for the IteratesVector class.
*/
class IteratesVectorSpace : public CompoundVectorSpace
{
public:
/** @name Constructors/Destructors. */
//@{
/** Constructor that takes the spaces for each of the iterates.
* Warning! None of these can be NULL !
*/
IteratesVectorSpace(const VectorSpace& x_space, const VectorSpace& s_space,
const VectorSpace& y_c_space, const VectorSpace& y_d_space,
const VectorSpace& z_L_space, const VectorSpace& z_U_space,
const VectorSpace& v_L_space, const VectorSpace& v_U_space
);
virtual ~IteratesVectorSpace();
//@}
/** Method for creating vectors . */
//@{
/** Use this to create a new IteratesVector. You can pass-in
* create_new = false if you only want a container and do not
* want vectors allocated.
*/
virtual IteratesVector* MakeNewIteratesVector(bool create_new = true) const
{
return new IteratesVector(this, create_new);
}
/** Use this method to create a new const IteratesVector. You must pass in
* valid pointers for all of the entries.
*/
const SmartPtr<const IteratesVector> MakeNewIteratesVector(const Vector& x, const Vector& s,
const Vector& y_c, const Vector& y_d,
const Vector& z_L, const Vector& z_U,
const Vector& v_L, const Vector& v_U)
{
SmartPtr<IteratesVector> newvec = MakeNewIteratesVector(false);
newvec->Set_x(x);
newvec->Set_s(s);
newvec->Set_y_c(y_c);
newvec->Set_y_d(y_d);
newvec->Set_z_L(z_L);
newvec->Set_z_U(z_U);
newvec->Set_v_L(v_L);
newvec->Set_v_U(v_U);
return ConstPtr(newvec);
}
/** This method overloads
* ComooundVectorSpace::MakeNewCompoundVector to make sure that
* we get a vector of the correct type
*/
virtual CompoundVector* MakeNewCompoundVector(bool create_new = true) const
{
return MakeNewIteratesVector(create_new);
}
/** This method creates a new vector (and allocates space in all
* the contained vectors. This is really only used for code that
* does not know what type of vector it is dealing with - for
* example, this method is called from Vector::MakeNew()
*/
virtual Vector* MakeNew() const
{
return MakeNewIteratesVector();
}
//@}
/** This method hides the CompoundVectorSpace::SetCompSpace method
* since the components of the Iterates are fixed at
* construction.
*/
virtual void SetCompSpace(Index icomp, const VectorSpace& vec_space)
{
DBG_ASSERT(false && "This is an IteratesVectorSpace - a special compound vector for Ipopt iterates. The contained spaces should not be modified.");
}
private:
/**@name Default Compiler Generated Methods (Hidden to avoid
* implicit creation/calling). These methods are not implemented
* and we do not want the compiler to implement them for us, so we
* declare them private and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default constructor */
IteratesVectorSpace();
/** Copy Constructor */
IteratesVectorSpace(const IteratesVectorSpace&);
/** Overloaded Equals Operator */
IteratesVectorSpace& operator=(const IteratesVectorSpace&);
//@}
/** Contained Spaces */
SmartPtr<const VectorSpace> x_space_;
SmartPtr<const VectorSpace> s_space_;
SmartPtr<const VectorSpace> y_c_space_;
SmartPtr<const VectorSpace> y_d_space_;
SmartPtr<const VectorSpace> z_L_space_;
SmartPtr<const VectorSpace> z_U_space_;
SmartPtr<const VectorSpace> v_L_space_;
SmartPtr<const VectorSpace> v_U_space_;
};
inline
SmartPtr<Vector> IteratesVector::create_new_x()
{
Set_x_NonConst(*owner_space_->GetCompSpace(0)->MakeNew());
return x_NonConst();
}
inline
SmartPtr<Vector> IteratesVector::create_new_s()
{
Set_s_NonConst(*owner_space_->GetCompSpace(1)->MakeNew());
return s_NonConst();
}
inline
SmartPtr<Vector> IteratesVector::create_new_y_c()
{
Set_y_c_NonConst(*owner_space_->GetCompSpace(2)->MakeNew());
return y_c_NonConst();
}
inline
SmartPtr<Vector> IteratesVector::create_new_y_d()
{
Set_y_d_NonConst(*owner_space_->GetCompSpace(3)->MakeNew());
return y_d_NonConst();
}
inline
SmartPtr<Vector> IteratesVector::create_new_z_L()
{
Set_z_L_NonConst(*owner_space_->GetCompSpace(4)->MakeNew());
return z_L_NonConst();
}
inline
SmartPtr<Vector> IteratesVector::create_new_z_U()
{
Set_z_U_NonConst(*owner_space_->GetCompSpace(5)->MakeNew());
return z_U_NonConst();
}
inline
SmartPtr<Vector> IteratesVector::create_new_v_L()
{
Set_v_L_NonConst(*owner_space_->GetCompSpace(6)->MakeNew());
return v_L_NonConst();
}
inline
SmartPtr<Vector> IteratesVector::create_new_v_U()
{
Set_v_U_NonConst(*owner_space_->GetCompSpace(7)->MakeNew());
return v_U_NonConst();
}
} // namespace Ipopt
#endif
+71
View File
@@ -0,0 +1,71 @@
// Copyright (C) 2004, 2011 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpIterationOutput.hpp 2020 2011-06-16 20:46:16Z andreasw $
//
// Authors: Andreas Waechter, Carl Laird IBM 2004-09-27
#ifndef __IPITERATIONOUTPUT_HPP__
#define __IPITERATIONOUTPUT_HPP__
#include "IpAlgStrategy.hpp"
#include "IpIpoptNLP.hpp"
#include "IpIpoptData.hpp"
#include "IpIpoptCalculatedQuantities.hpp"
namespace Ipopt
{
/** Base class for objects that do the output summary per iteration.
*/
class IterationOutput: public AlgorithmStrategyObject
{
public:
/**@name Constructors/Destructors */
//@{
/** Default Constructor */
IterationOutput()
{}
/** Default destructor */
virtual ~IterationOutput()
{}
//@}
/** overloaded from AlgorithmStrategyObject */
virtual bool InitializeImpl(const OptionsList& options,
const std::string& prefix) = 0;
/** Method to do all the summary output per iteration. This
* include the one-line summary output as well as writing the
* details about the iterates if desired */
virtual void WriteOutput() = 0;
protected:
/** enumeration for different inf_pr output options */
enum InfPrOutput
{
INTERNAL=0,
ORIGINAL
};
private:
/**@name Default Compiler Generated Methods (Hidden to avoid
* implicit creation/calling). These methods are not implemented
* and we do not want the compiler to implement them for us, so we
* declare them private and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Copy Constructor */
IterationOutput(const IterationOutput&);
/** Overloaded Equals Operator */
void operator=(const IterationOutput&);
//@}
};
} // namespace Ipopt
#endif
+497
View File
@@ -0,0 +1,497 @@
// Copyright (C) 2004, 2009 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpJournalist.hpp 2204 2013-04-13 13:49:26Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPJOURNALIST_HPP__
#define __IPJOURNALIST_HPP__
#include "IpoptConfig.h"
#include "IpTypes.hpp"
#include "IpReferenced.hpp"
#include "IpSmartPtr.hpp"
#ifdef HAVE_CSTDARG
# include <cstdarg>
#else
# ifdef HAVE_STDARG_H
# include <stdarg.h>
# else
# include <cstdarg> // if this header is included by someone who does not define HAVE_CSTDARG or HAVE_STDARG, let's hope that cstdarg is available
# endif
#endif
#ifdef HAVE_CSTDIO
# include <cstdio>
#else
# ifdef HAVE_STDIO_H
# include <stdio.h>
# else
# include <cstdio> // if this header is included by someone who does not define HAVE_CSTDIO or HAVE_STDIO, let's hope that cstdio is available
# endif
#endif
#include <string>
#include <vector>
#include <ostream>
namespace Ipopt
{
// forward declarations
class Journal;
class FileJournal;
/**@name Journalist Enumerations. */
//@{
/** Print Level Enum. */
enum EJournalLevel {
J_INSUPPRESSIBLE=-1,
J_NONE=0,
J_ERROR,
J_STRONGWARNING,
J_SUMMARY,
J_WARNING,
J_ITERSUMMARY,
J_DETAILED,
J_MOREDETAILED,
J_VECTOR,
J_MOREVECTOR,
J_MATRIX,
J_MOREMATRIX,
J_ALL,
J_LAST_LEVEL
};
/** Category Selection Enum. */
enum EJournalCategory {
J_DBG=0,
J_STATISTICS,
J_MAIN,
J_INITIALIZATION,
J_BARRIER_UPDATE,
J_SOLVE_PD_SYSTEM,
J_FRAC_TO_BOUND,
J_LINEAR_ALGEBRA,
J_LINE_SEARCH,
J_HESSIAN_APPROXIMATION,
J_SOLUTION,
J_DOCUMENTATION,
J_NLP,
J_TIMING_STATISTICS,
J_USER_APPLICATION /** This can be used by the user's application*/ ,
J_USER1 /** This can be used by the user's application*/ ,
J_USER2 /** This can be used by the user's application*/ ,
J_USER3 /** This can be used by the user's application*/ ,
J_USER4 /** This can be used by the user's application*/ ,
J_USER5 /** This can be used by the user's application*/ ,
J_USER6 /** This can be used by the user's application*/ ,
J_USER7 /** This can be used by the user's application*/ ,
J_USER8 /** This can be used by the user's application*/ ,
J_USER9 /** This can be used by the user's application*/ ,
J_USER10 /** This can be used by the user's application*/ ,
J_USER11 /** This can be used by the user's application*/ ,
J_USER12 /** This can be used by the user's application*/ ,
J_USER13 /** This can be used by the user's application*/ ,
J_USER14 /** This can be used by the user's application*/ ,
J_USER15 /** This can be used by the user's application*/ ,
J_USER16 /** This can be used by the user's application*/ ,
J_USER17 /** This can be used by the user's application*/ ,
J_LAST_CATEGORY
};
//@}
/** Class responsible for all message output.
* This class is responsible for all messaging and output.
* The "printing" code or "author" should send ALL messages to the
* Journalist, indicating an appropriate category and print level.
* The journalist then decides, based on reader specified
* acceptance criteria, which message is actually printed in which
* journals.
* This allows the printing code to send everything, while the
* "reader" can decide what they really want to see.
*
* Authors:
* Authors use the
* Journals: You can add as many Journals as you like to the
* Journalist with the AddJournal or the AddFileJournal methods.
* Each one represents a different printing location (or file).
* Then, you can call the "print" methods of the Journalist to output
* information to each of the journals.
*
* Acceptance Criteria: Each print message should be flagged
* appropriately with an EJournalCategory and EJournalLevel.
*
* The AddFileJournal
* method returns a pointer to the newly created Journal object
* (if successful) so you can set Acceptance criteria for that
* particular location.
*
*/
class Journalist : public ReferencedObject
{
public:
/**@name Constructor / Desructor. */
//@{
/** Constructor. */
Journalist();
/** Destructor... */
virtual ~Journalist();
//@}
/**@name Author Methods.
* These methods are used by authoring code, or code that wants
* to report some information.
*/
//@{
/** Method to print a formatted string */
virtual void Printf(EJournalLevel level, EJournalCategory category,
const char* format, ...) const;
/** Method to print a long string including indentation. The
* string is printed starting at the current position. If the
* position (counting started at the current position) exceeds
* max_length, a new line is inserted, and indent_spaces many
* spaces are printed before the string is continued. This is
* for example used during the printing of the option
* documentation. */
virtual void PrintStringOverLines(EJournalLevel level, EJournalCategory category,
Index indent_spaces, Index max_length,
const std::string& line) const;
/** Method to print a formatted string with indentation */
virtual void PrintfIndented(EJournalLevel level,
EJournalCategory category,
Index indent_level,
const char* format, ...) const;
/** Method to print a formatted string
* using the va_list argument. */
virtual void VPrintf(EJournalLevel level,
EJournalCategory category,
const char* pformat,
va_list ap) const;
/** Method to print a formatted string with indentation,
* using the va_list argument. */
virtual void VPrintfIndented(EJournalLevel level,
EJournalCategory category,
Index indent_level,
const char* pformat,
va_list ap) const;
/** Method that returns true if there is a Journal that would
* write output for the given JournalLevel and JournalCategory.
* This is useful if expensive computation would be required for
* a particular output. The author code can check with this
* method if the computations are indeed required.
*/
virtual bool ProduceOutput(EJournalLevel level,
EJournalCategory category) const;
/** Method that flushes the current buffer for all Journalists.
Calling this method after one optimization run helps to avoid
cluttering output with that produced by other parts of the
program (e.g. written in Fortran) */
virtual void FlushBuffer() const;
//@}
/**@name Reader Methods.
* These methods are used by the reader. The reader will setup the
* journalist with each output file and the acceptance
* criteria for that file.
*
* Use these methods to setup the journals (files or other output).
* These are the internal objects that keep track of the print levels
* for each category. Then use the internal Journal objects to
* set specific print levels for each category (or keep defaults).
*
*/
//@{
/** Add a new journal. The location_name is a string identifier,
* which can be used to obtain the pointer to the new Journal at
* a later point using the GetJournal method.
* The default_level is
* used to initialize the * printing level for all categories.
*/
virtual bool AddJournal(const SmartPtr<Journal> jrnl);
/** Add a new FileJournal. fname is the name
* of the * file to which this Journal corresponds. Use
* fname="stdout" * for stdout, and use fname="stderr" for
* stderr. This method * returns the Journal pointer so you can
* set specific acceptance criteria. It returns NULL if there
* was a problem creating a new Journal.
*/
virtual SmartPtr<Journal> AddFileJournal(
const std::string& location_name, /**< journal identifier */
const std::string& fname, /**< file name */
EJournalLevel default_level = J_WARNING /**< default journal level */
);
/** Get an existing journal. You can use this method to change
* the acceptance criteria at runtime.
*/
virtual SmartPtr<Journal> GetJournal(const std::string& location_name);
/** Delete all journals curently known by the journalist. */
virtual void DeleteAllJournals();
//@}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Copy Constructor */
Journalist(const Journalist&);
/** Overloaded Equals Operator */
void operator=(const Journalist&);
//@}
//** Private Data Members. */
//@{
std::vector< SmartPtr<Journal> > journals_;
//@}
};
/** Journal class (part of the Journalist implementation.). This
* class is the base class for all Journals. It controls the
* acceptance criteria for print statements etc. Derived classes
* like the FileJournal - output those messages to specific locations
*/
class Journal : public ReferencedObject
{
public:
/** Constructor. */
Journal(const std::string& name, EJournalLevel default_level);
/** Destructor. */
virtual ~Journal();
/** Get the name of the Journal */
virtual std::string Name();
/** Set the print level for a particular category. */
virtual void SetPrintLevel(
EJournalCategory category, EJournalLevel level
);
/** Set the print level for all category. */
virtual void SetAllPrintLevels(
EJournalLevel level
);
/**@name Journal Output Methods. These methods are called by the
* Journalist who first checks if the output print level and category
* are acceptable.
* Calling the Print methods explicitly (instead of through the
* Journalist will output the message regardless of print level
* and category. You should use the Journalist to print & flush instead
*/
//@{
/** Ask if a particular print level/category is accepted by the
* journal.
*/
virtual bool IsAccepted(
EJournalCategory category, EJournalLevel level
) const;
/** Print to the designated output location */
virtual void Print(EJournalCategory category, EJournalLevel level,
const char* str)
{
PrintImpl(category, level, str);
}
/** Printf to the designated output location */
virtual void Printf(EJournalCategory category, EJournalLevel level,
const char* pformat, va_list ap)
{
PrintfImpl(category, level, pformat, ap);
}
/** Flush output buffer.*/
virtual void FlushBuffer()
{
FlushBufferImpl();
}
//@}
protected:
/**@name Implementation version of Print methods. Derived classes
* should overload the Impl methods.
*/
//@{
/** Print to the designated output location */
virtual void PrintImpl(EJournalCategory category, EJournalLevel level,
const char* str)=0;
/** Printf to the designated output location */
virtual void PrintfImpl(EJournalCategory category, EJournalLevel level,
const char* pformat, va_list ap)=0;
/** Flush output buffer.*/
virtual void FlushBufferImpl()=0;
//@}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
Journal();
/** Copy Constructor */
Journal(const Journal&);
/** Overloaded Equals Operator */
void operator=(const Journal&);
//@}
/** Name of the output location */
std::string name_;
/** vector of integers indicating the level for each category */
Index print_levels_[J_LAST_CATEGORY];
};
/** FileJournal class. This is a particular Journal implementation that
* writes to a file for output. It can write to (stdout, stderr, or disk)
* by using "stdout" and "stderr" as filenames.
*/
class FileJournal : public Journal
{
public:
/** Constructor. */
FileJournal(const std::string& name, EJournalLevel default_level);
/** Destructor. */
virtual ~FileJournal();
/** Open a new file for the output location.
* Special Names: stdout means stdout,
* : stderr means stderr.
*
* Return code is false only if the file with the given name
* could not be opened.
*/
virtual bool Open(const char* fname);
protected:
/**@name Implementation version of Print methods - Overloaded from
* Journal base class.
*/
//@{
/** Print to the designated output location */
virtual void PrintImpl(EJournalCategory category, EJournalLevel level,
const char* str);
/** Printf to the designated output location */
virtual void PrintfImpl(EJournalCategory category, EJournalLevel level,
const char* pformat, va_list ap);
/** Flush output buffer.*/
virtual void FlushBufferImpl();
//@}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
FileJournal();
/** Copy Constructor */
FileJournal(const FileJournal&);
/** Overloaded Equals Operator */
void operator=(const FileJournal&);
//@}
/** FILE pointer for the output destination */
FILE* file_;
};
/** StreamJournal class. This is a particular Journal implementation that
* writes to a stream for output.
*/
class StreamJournal : public Journal
{
public:
/** Constructor. */
StreamJournal(const std::string& name, EJournalLevel default_level);
/** Destructor. */
virtual ~StreamJournal()
{}
/** Setting the output stream pointer */
void SetOutputStream(std::ostream* os);
protected:
/**@name Implementation version of Print methods - Overloaded from
* Journal base class.
*/
//@{
/** Print to the designated output location */
virtual void PrintImpl(EJournalCategory category, EJournalLevel level,
const char* str);
/** Printf to the designated output location */
virtual void PrintfImpl(EJournalCategory category, EJournalLevel level,
const char* pformat, va_list ap);
/** Flush output buffer.*/
virtual void FlushBufferImpl();
//@}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
StreamJournal();
/** Copy Constructor */
StreamJournal(const StreamJournal&);
/** Overloaded Equals Operator */
void operator=(const StreamJournal&);
//@}
/** pointer to output stream for the output destination */
std::ostream* os_;
/** buffer for sprintf. Being generous in size here... */
char buffer_[32768];
};
}
#endif
+55
View File
@@ -0,0 +1,55 @@
// Copyright (C) 2005, 2009 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpLapack.hpp 2449 2013-12-16 00:25:42Z ghackebeil $
//
// Authors: Andreas Waechter IBM 2005-12-25
#ifndef __IPLAPACK_HPP__
#define __IPLAPACK_HPP__
#include "IpUtils.hpp"
#include "IpException.hpp"
namespace Ipopt
{
DECLARE_STD_EXCEPTION(LAPACK_NOT_INCLUDED);
/** Wrapper for LAPACK subroutine DPOTRS. Solving a linear system
* given a Cholesky factorization. We assume that the Cholesky
* factor is lower traiangular. */
void IpLapackDpotrs(Index ndim, Index nrhs, const Number *a, Index lda,
Number *b, Index ldb);
/** Wrapper for LAPACK subroutine DPOTRF. Compute Cholesky
* factorization (lower triangular factor). info is the return
* value from the LAPACK routine. */
void IpLapackDpotrf(Index ndim, Number *a, Index lda, Index& info);
/** Wrapper for LAPACK subroutine DSYEV. Compute the Eigenvalue
* decomposition for a given matrix. If compute_eigenvectors is
* true, a will contain the eigenvectors in its columns on
* return. */
void IpLapackDsyev(bool compute_eigenvectors, Index ndim, Number *a,
Index lda, Number *w, Index& info);
/** Wrapper for LAPACK subroutine DGETRF. Compute LU factorization.
* info is the return value from the LAPACK routine. */
void IpLapackDgetrf(Index ndim, Number *a, Index* pivot, Index lda,
Index& info);
/** Wrapper for LAPACK subroutine DGETRS. Solving a linear system
* given a LU factorization. */
void IpLapackDgetrs(Index ndim, Index nrhs, const Number *a, Index lda,
Index* ipiv, Number *b, Index ldb);
/** Wrapper for LAPACK subroutine DPPSV. Solves a symmetric positive
* definite linear system in packed storage format (upper triangular).
* info is the return value from the LAPACK routine. */
void IpLapackDppsv(Index ndim, Index nrhs, const Number *a,
Number *b, Index ldb, Index& info);
} // namespace Ipopt
#endif
+96
View File
@@ -0,0 +1,96 @@
// Copyright (C) 2004, 2006 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpLineSearch.hpp 1861 2010-12-21 21:34:47Z andreasw $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPLINESEARCH_HPP__
#define __IPLINESEARCH_HPP__
#include "IpAlgStrategy.hpp"
#include "IpIpoptCalculatedQuantities.hpp"
namespace Ipopt
{
/** Base class for line search objects.
*/
class LineSearch : public AlgorithmStrategyObject
{
public:
/**@name Constructors/Destructors */
//@{
/** Default Constructor */
LineSearch()
{}
/** Default destructor */
virtual ~LineSearch()
{}
//@}
/** Perform the line search. As search direction the delta
* in the data object is used
*/
virtual void FindAcceptableTrialPoint() = 0;
/** Reset the line search.
* This function should be called if all previous information
* should be discarded when the line search is performed the
* next time. For example, this method should be called after
* the barrier parameter is changed.
*/
virtual void Reset() = 0;
/** Set flag indicating whether a very rigorous line search should
* be performed. If this flag is set to true, the line search
* algorithm might decide to abort the line search and not to
* accept a new iterate. If the line search decided not to
* accept a new iterate, the return value of
* CheckSkippedLineSearch() is true at the next call. For
* example, in the non-monotone barrier parameter update
* procedure, the filter algorithm should not switch to the
* restoration phase in the free mode; instead, the algorithm
* should swtich to the fixed mode.
*/
virtual void SetRigorousLineSearch(bool rigorous) = 0;
/** Check if the line search procedure didn't accept a new iterate
* during the last call of FindAcceptableTrialPoint().
*
*/
virtual bool CheckSkippedLineSearch() = 0;
/** This method should be called if the optimization process
* requires the line search object to switch to some fallback
* mechanism (like the restoration phase), when the regular
* optimization procedure cannot be continued (for example,
* because the search direction could not be computed). This
* will cause the line search object to immediately proceed with
* this mechanism when FindAcceptableTrialPoint() is call. This
* method returns false if no fallback mechanism is available. */
virtual bool ActivateFallbackMechanism() = 0;
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Copy Constructor */
LineSearch(const LineSearch&);
/** Overloaded Equals Operator */
void operator=(const LineSearch&);
//@}
};
} // namespace Ipopt
#endif
+345
View File
@@ -0,0 +1,345 @@
// Copyright (C) 2004, 2008 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpMatrix.hpp 2472 2014-04-05 17:47:20Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPMATRIX_HPP__
#define __IPMATRIX_HPP__
#include "IpVector.hpp"
namespace Ipopt
{
/* forward declarations */
class MatrixSpace;
/** Matrix Base Class. This is the base class for all derived matrix
* types. All Matrices, such as Jacobian and Hessian matrices, as
* well as possibly the iteration matrices needed for the step
* computation, are of this type.
*
* Deriving from Matrix: Overload the protected XXX_Impl method.
*/
class Matrix : public TaggedObject
{
public:
/** @name Constructor/Destructor */
//@{
/** Constructor. It has to be given a pointer to the
* corresponding MatrixSpace.
*/
Matrix(const MatrixSpace* owner_space)
:
TaggedObject(),
owner_space_(owner_space),
valid_cache_tag_(0)
{}
/** Destructor */
virtual ~Matrix()
{}
//@}
/**@name Operations of the Matrix on a Vector */
//@{
/** Matrix-vector multiply. Computes y = alpha * Matrix * x +
* beta * y. Do not overload. Overload MultVectorImpl instead.
*/
void MultVector(Number alpha, const Vector& x, Number beta,
Vector& y) const
{
MultVectorImpl(alpha, x, beta, y);
}
/** Matrix(transpose) vector multiply. Computes y = alpha *
* Matrix^T * x + beta * y. Do not overload. Overload
* TransMultVectorImpl instead.
*/
void TransMultVector(Number alpha, const Vector& x, Number beta,
Vector& y) const
{
TransMultVectorImpl(alpha, x, beta, y);
}
//@}
/** @name Methods for specialized operations. A prototype
* implementation is provided, but for efficient implementation
* those should be specially implemented.
*/
//@{
/** X = X + alpha*(Matrix S^{-1} Z). Should be implemented
* efficiently for the ExansionMatrix
*/
void AddMSinvZ(Number alpha, const Vector& S, const Vector& Z,
Vector& X) const;
/** X = S^{-1} (r + alpha*Z*M^Td). Should be implemented
* efficiently for the ExansionMatrix
*/
void SinvBlrmZMTdBr(Number alpha, const Vector& S,
const Vector& R, const Vector& Z,
const Vector& D, Vector& X) const;
//@}
/** Method for determining if all stored numbers are valid (i.e.,
* no Inf or Nan). */
bool HasValidNumbers() const;
/** @name Information about the size of the matrix */
//@{
/** Number of rows */
inline
Index NRows() const;
/** Number of columns */
inline
Index NCols() const;
//@}
/** @name Norms of the individual rows and columns */
//@{
/** Compute the max-norm of the rows in the matrix. The result is
* stored in rows_norms. The vector is assumed to be initialized
* of init is false. */
void ComputeRowAMax(Vector& rows_norms, bool init=true) const
{
DBG_ASSERT(NRows() == rows_norms.Dim());
if (init) rows_norms.Set(0.);
ComputeRowAMaxImpl(rows_norms, init);
}
/** Compute the max-norm of the columns in the matrix. The result
* is stored in cols_norms The vector is assumed to be initialized
* of init is false. */
void ComputeColAMax(Vector& cols_norms, bool init=true) const
{
DBG_ASSERT(NCols() == cols_norms.Dim());
if (init) cols_norms.Set(0.);
ComputeColAMaxImpl(cols_norms, init);
}
//@}
/** Print detailed information about the matrix. Do not overload.
* Overload PrintImpl instead.
*/
//@{
virtual void Print(SmartPtr<const Journalist> jnlst,
EJournalLevel level,
EJournalCategory category,
const std::string& name,
Index indent=0,
const std::string& prefix="") const;
virtual void Print(const Journalist& jnlst,
EJournalLevel level,
EJournalCategory category,
const std::string& name,
Index indent=0,
const std::string& prefix="") const;
//@}
/** Return the owner MatrixSpace*/
inline
SmartPtr<const MatrixSpace> OwnerSpace() const;
protected:
/** @name implementation methods (derived classes MUST
* overload these pure virtual protected methods.
*/
//@{
/** Matrix-vector multiply. Computes y = alpha * Matrix * x +
* beta * y
*/
virtual void MultVectorImpl(Number alpha, const Vector& x, Number beta, Vector& y) const =0;
/** Matrix(transpose) vector multiply.
* Computes y = alpha * Matrix^T * x + beta * y
*/
virtual void TransMultVectorImpl(Number alpha, const Vector& x, Number beta, Vector& y) const =0;
/** X = X + alpha*(Matrix S^{-1} Z). Prototype for this
* specialize method is provided, but for efficient
* implementation it should be overloaded for the expansion matrix.
*/
virtual void AddMSinvZImpl(Number alpha, const Vector& S, const Vector& Z,
Vector& X) const;
/** X = S^{-1} (r + alpha*Z*M^Td). Should be implemented
* efficiently for the ExpansionMatrix.
*/
virtual void SinvBlrmZMTdBrImpl(Number alpha, const Vector& S,
const Vector& R, const Vector& Z,
const Vector& D, Vector& X) const;
/** Method for determining if all stored numbers are valid (i.e.,
* no Inf or Nan). A default implementation always returning true
* is provided, but if possible it should be implemented. */
virtual bool HasValidNumbersImpl() const
{
return true;
}
/** Compute the max-norm of the rows in the matrix. The result is
* stored in rows_norms. The vector is assumed to be
* initialized. */
virtual void ComputeRowAMaxImpl(Vector& rows_norms, bool init) const = 0;
/** Compute the max-norm of the columns in the matrix. The result
* is stored in cols_norms. The vector is assumed to be
* initialized. */
virtual void ComputeColAMaxImpl(Vector& cols_norms, bool init) const = 0;
/** Print detailed information about the matrix. */
virtual void PrintImpl(const Journalist& jnlst,
EJournalLevel level,
EJournalCategory category,
const std::string& name,
Index indent,
const std::string& prefix) const =0;
//@}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** default constructor */
Matrix();
/** Copy constructor */
Matrix(const Matrix&);
/** Overloaded Equals Operator */
Matrix& operator=(const Matrix&);
//@}
const SmartPtr<const MatrixSpace> owner_space_;
/**@name CachedResults data members */
//@{
mutable TaggedObject::Tag valid_cache_tag_;
mutable bool cached_valid_;
//@}
};
/** MatrixSpace base class, corresponding to the Matrix base class.
* For each Matrix implementation, a corresponding MatrixSpace has
* to be implemented. A MatrixSpace is able to create new Matrices
* of a specific type. The MatrixSpace should also store
* information that is common to all Matrices of that type. For
* example, the dimensions of a Matrix is stored in the MatrixSpace
* base class.
*/
class MatrixSpace : public ReferencedObject
{
public:
/** @name Constructors/Destructors */
//@{
/** Constructor, given the number rows and columns of all matrices
* generated by this MatrixSpace.
*/
MatrixSpace(Index nRows, Index nCols)
:
nRows_(nRows),
nCols_(nCols)
{}
/** Destructor */
virtual ~MatrixSpace()
{}
//@}
/** Pure virtual method for creating a new Matrix of the
* corresponding type.
*/
virtual Matrix* MakeNew() const=0;
/** Accessor function for the number of rows. */
Index NRows() const
{
return nRows_;
}
/** Accessor function for the number of columns. */
Index NCols() const
{
return nCols_;
}
/** Method to test if a given matrix belongs to a particular
* matrix space.
*/
bool IsMatrixFromSpace(const Matrix& matrix) const
{
return (matrix.OwnerSpace() == this);
}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** default constructor */
MatrixSpace();
/** Copy constructor */
MatrixSpace(const MatrixSpace&);
/** Overloaded Equals Operator */
MatrixSpace& operator=(const MatrixSpace&);
//@}
/** Number of rows for all matrices of this type. */
const Index nRows_;
/** Number of columns for all matrices of this type. */
const Index nCols_;
};
/* Inline Methods */
inline
Index Matrix::NRows() const
{
return owner_space_->NRows();
}
inline
Index Matrix::NCols() const
{
return owner_space_->NCols();
}
inline
SmartPtr<const MatrixSpace> Matrix::OwnerSpace() const
{
return owner_space_;
}
} // namespace Ipopt
// Macro definitions for debugging matrices
#if COIN_IPOPT_VERBOSITY == 0
# define DBG_PRINT_MATRIX(__verbose_level, __mat_name, __mat)
#else
# define DBG_PRINT_MATRIX(__verbose_level, __mat_name, __mat) \
if (dbg_jrnl.Verbosity() >= (__verbose_level)) { \
if (dbg_jrnl.Jnlst()!=NULL) { \
(__mat).Print(dbg_jrnl.Jnlst(), \
J_ERROR, J_DBG, \
__mat_name, \
dbg_jrnl.IndentationLevel()*2, \
"# "); \
} \
}
#endif // #if COIN_IPOPT_VERBOSITY == 0
#endif
+69
View File
@@ -0,0 +1,69 @@
// Copyright (C) 2004, 2006 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpMuUpdate.hpp 1861 2010-12-21 21:34:47Z andreasw $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPMUUPDATE_HPP__
#define __IPMUUPDATE_HPP__
#include "IpAlgStrategy.hpp"
namespace Ipopt
{
/** Abstract Base Class for classes that implement methods for computing
* the barrier and fraction-to-the-boundary rule parameter for the
* current iteration.
*/
class MuUpdate : public AlgorithmStrategyObject
{
public:
/**@name Constructors/Destructors */
//@{
/** Default Constructor */
MuUpdate()
{}
/** Default destructor */
virtual ~MuUpdate()
{}
//@}
/** Initialize method - overloaded from AlgorithmStrategyObject */
virtual bool InitializeImpl(const OptionsList& options,
const std::string& prefix) = 0;
/** Method for determining the barrier parameter for the next
* iteration. A LineSearch object is passed, so that this method
* can call the Reset method in the LineSearch object, for
* example when then barrier parameter is changed. This method is
* also responsible for setting the fraction-to-the-boundary
* parameter tau. This method returns false if the update could
* not be performed and the algorithm should revert to an
* emergency fallback mechanism. */
virtual bool UpdateBarrierParameter() = 0;
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Copy Constructor */
MuUpdate(const MuUpdate&);
/** Overloaded Equals Operator */
void operator=(const MuUpdate&);
//@}
};
} // namespace Ipopt
#endif
+243
View File
@@ -0,0 +1,243 @@
// Copyright (C) 2004, 2006 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpNLP.hpp 2269 2013-05-05 11:32:40Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPNLP_HPP__
#define __IPNLP_HPP__
#include "IpUtils.hpp"
#include "IpVector.hpp"
#include "IpSmartPtr.hpp"
#include "IpMatrix.hpp"
#include "IpSymMatrix.hpp"
#include "IpOptionsList.hpp"
#include "IpAlgTypes.hpp"
#include "IpReturnCodes.hpp"
namespace Ipopt
{
// forward declarations
class IpoptData;
class IpoptCalculatedQuantities;
class IteratesVector;
/** Brief Class Description.
* Detailed Class Description.
*/
class NLP : public ReferencedObject
{
public:
/**@name Constructors/Destructors */
//@{
/** Default constructor */
NLP()
{}
/** Default destructor */
virtual ~NLP()
{}
//@}
/** Exceptions */
//@{
DECLARE_STD_EXCEPTION(USER_SCALING_NOT_IMPLEMENTED);
DECLARE_STD_EXCEPTION(INVALID_NLP);
//@}
/** @name NLP Initialization (overload in
* derived classes).*/
//@{
/** Overload if you want the chance to process options or parameters that
* may be specific to the NLP */
virtual bool ProcessOptions(const OptionsList& options,
const std::string& prefix)
{
return true;
}
/** Method for creating the derived vector / matrix types. The
* Hess_lagrangian_space pointer can be NULL if a quasi-Newton
* options is chosen. */
virtual bool GetSpaces(SmartPtr<const VectorSpace>& x_space,
SmartPtr<const VectorSpace>& c_space,
SmartPtr<const VectorSpace>& d_space,
SmartPtr<const VectorSpace>& x_l_space,
SmartPtr<const MatrixSpace>& px_l_space,
SmartPtr<const VectorSpace>& x_u_space,
SmartPtr<const MatrixSpace>& px_u_space,
SmartPtr<const VectorSpace>& d_l_space,
SmartPtr<const MatrixSpace>& pd_l_space,
SmartPtr<const VectorSpace>& d_u_space,
SmartPtr<const MatrixSpace>& pd_u_space,
SmartPtr<const MatrixSpace>& Jac_c_space,
SmartPtr<const MatrixSpace>& Jac_d_space,
SmartPtr<const SymMatrixSpace>& Hess_lagrangian_space)=0;
/** Method for obtaining the bounds information */
virtual bool GetBoundsInformation(const Matrix& Px_L,
Vector& x_L,
const Matrix& Px_U,
Vector& x_U,
const Matrix& Pd_L,
Vector& d_L,
const Matrix& Pd_U,
Vector& d_U)=0;
/** Method for obtaining the starting point for all the
* iterates. ToDo it might not make sense to ask for initial
* values for v_L and v_U? */
virtual bool GetStartingPoint(
SmartPtr<Vector> x,
bool need_x,
SmartPtr<Vector> y_c,
bool need_y_c,
SmartPtr<Vector> y_d,
bool need_y_d,
SmartPtr<Vector> z_L,
bool need_z_L,
SmartPtr<Vector> z_U,
bool need_z_U
)=0;
/** Method for obtaining an entire iterate as a warmstart point.
* The incoming IteratesVector has to be filled. The default
* dummy implementation returns false. */
virtual bool GetWarmStartIterate(IteratesVector& warm_start_iterate)
{
return false;
}
//@}
/** @name NLP evaluation routines (overload
* in derived classes. */
//@{
virtual bool Eval_f(const Vector& x, Number& f) = 0;
virtual bool Eval_grad_f(const Vector& x, Vector& g_f) = 0;
virtual bool Eval_c(const Vector& x, Vector& c) = 0;
virtual bool Eval_jac_c(const Vector& x, Matrix& jac_c) = 0;
virtual bool Eval_d(const Vector& x, Vector& d) = 0;
virtual bool Eval_jac_d(const Vector& x, Matrix& jac_d) = 0;
virtual bool Eval_h(const Vector& x,
Number obj_factor,
const Vector& yc,
const Vector& yd,
SymMatrix& h) = 0;
//@}
/** @name NLP solution routines. Have default dummy
* implementations that can be overloaded. */
//@{
/** This method is called at the very end of the optimization. It
* provides the final iterate to the user, so that it can be
* stored as the solution. The status flag indicates the outcome
* of the optimization, where SolverReturn is defined in
* IpAlgTypes.hpp. */
virtual void FinalizeSolution(SolverReturn status,
const Vector& x, const Vector& z_L,
const Vector& z_U,
const Vector& c, const Vector& d,
const Vector& y_c, const Vector& y_d,
Number obj_value,
const IpoptData* ip_data,
IpoptCalculatedQuantities* ip_cq)
{}
/** This method is called once per iteration, after the iteration
* summary output has been printed. It provides the current
* information to the user to do with it anything she wants. It
* also allows the user to ask for a premature termination of the
* optimization by returning false, in which case Ipopt will
* terminate with a corresponding return status. The basic
* information provided in the argument list has the quantities
* values printed in the iteration summary line. If more
* information is required, a user can obtain it from the IpData
* and IpCalculatedQuantities objects. However, note that the
* provided quantities are all for the problem that Ipopt sees,
* i.e., the quantities might be scaled, fixed variables might be
* sorted out, etc. The status indicates things like whether the
* algorithm is in the restoration phase... In the restoration
* phase, the dual variables are probably not not changing. */
virtual bool IntermediateCallBack(AlgorithmMode mode,
Index iter, Number obj_value,
Number inf_pr, Number inf_du,
Number mu, Number d_norm,
Number regularization_size,
Number alpha_du, Number alpha_pr,
Index ls_trials,
const IpoptData* ip_data,
IpoptCalculatedQuantities* ip_cq)
{
return true;
}
//@}
/** Routines to get the scaling parameters. These do not need to
* be overloaded unless the options are set for User scaling
*/
//@{
virtual void GetScalingParameters(
const SmartPtr<const VectorSpace> x_space,
const SmartPtr<const VectorSpace> c_space,
const SmartPtr<const VectorSpace> d_space,
Number& obj_scaling,
SmartPtr<Vector>& x_scaling,
SmartPtr<Vector>& c_scaling,
SmartPtr<Vector>& d_scaling) const
{
THROW_EXCEPTION(USER_SCALING_NOT_IMPLEMENTED,
"You have set options for user provided scaling, but have"
" not implemented GetScalingParameters in the NLP interface");
}
//@}
/** Method for obtaining the subspace in which the limited-memory
* Hessian approximation should be done. This is only called if
* the limited-memory Hessian approximation is chosen. Since the
* Hessian is zero in the space of all variables that appear in
* the problem functions only linearly, this allows the user to
* provide a VectorSpace for all nonlinear variables, and an
* ExpansionMatrix to lift from this VectorSpace to the
* VectorSpace of the primal variables x. If the returned values
* are NULL, it is assumed that the Hessian is to be approximated
* in the space of all x variables. The default instantiation of
* this method returns NULL, and a user only has to overwrite
* this method if the approximation is to be done only in a
* subspace. */
virtual void
GetQuasiNewtonApproximationSpaces(SmartPtr<VectorSpace>& approx_space,
SmartPtr<Matrix>& P_approx)
{
approx_space = NULL;
P_approx = NULL;
}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Copy Constructor */
NLP(const NLP&);
/** Overloaded Equals Operator */
void operator=(const NLP&);
//@}
};
} // namespace Ipopt
#endif
+451
View File
@@ -0,0 +1,451 @@
// Copyright (C) 2004, 2007 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpNLPScaling.hpp 2269 2013-05-05 11:32:40Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPNLPSCALING_HPP__
#define __IPNLPSCALING_HPP__
#include "IpOptionsList.hpp"
#include "IpRegOptions.hpp"
namespace Ipopt
{
// forward declarations
class Vector;
class VectorSpace;
class Matrix;
class MatrixSpace;
class SymMatrix;
class SymMatrixSpace;
class ScaledMatrixSpace;
class SymScaledMatrixSpace;
/** This is the abstract base class for problem scaling.
* It is repsonsible for determining the scaling factors
* and mapping quantities in and out of scaled and unscaled
* versions
*/
class NLPScalingObject : public ReferencedObject
{
public:
/**@name Constructors/Destructors */
//@{
NLPScalingObject();
/** Default destructor */
virtual ~NLPScalingObject();
//@}
/** Method to initialize the options */
bool Initialize(const Journalist& jnlst,
const OptionsList& options,
const std::string& prefix)
{
jnlst_ = &jnlst;
return InitializeImpl(options, prefix);
}
/** Methods to map scaled and unscaled matrices */
//@{
/** Returns an obj-scaled version of the given scalar */
virtual Number apply_obj_scaling(const Number& f)=0;
/** Returns an obj-unscaled version of the given scalar */
virtual Number unapply_obj_scaling(const Number& f)=0;
/** Returns an x-scaled version of the given vector */
virtual SmartPtr<Vector>
apply_vector_scaling_x_NonConst(const SmartPtr<const Vector>& v)=0;
/** Returns an x-scaled version of the given vector */
virtual SmartPtr<const Vector>
apply_vector_scaling_x(const SmartPtr<const Vector>& v)=0;
/** Returns an x-unscaled version of the given vector */
virtual SmartPtr<Vector>
unapply_vector_scaling_x_NonConst(const SmartPtr<const Vector>& v)=0;
/** Returns an x-unscaled version of the given vector */
virtual SmartPtr<const Vector>
unapply_vector_scaling_x(const SmartPtr<const Vector>& v)=0;
/** Returns an c-scaled version of the given vector */
virtual SmartPtr<const Vector>
apply_vector_scaling_c(const SmartPtr<const Vector>& v)=0;
/** Returns an c-unscaled version of the given vector */
virtual SmartPtr<const Vector>
unapply_vector_scaling_c(const SmartPtr<const Vector>& v)=0;
/** Returns an c-scaled version of the given vector */
virtual SmartPtr<Vector>
apply_vector_scaling_c_NonConst(const SmartPtr<const Vector>& v)=0;
/** Returns an c-unscaled version of the given vector */
virtual SmartPtr<Vector>
unapply_vector_scaling_c_NonConst(const SmartPtr<const Vector>& v)=0;
/** Returns an d-scaled version of the given vector */
virtual SmartPtr<const Vector>
apply_vector_scaling_d(const SmartPtr<const Vector>& v)=0;
/** Returns an d-unscaled version of the given vector */
virtual SmartPtr<const Vector>
unapply_vector_scaling_d(const SmartPtr<const Vector>& v)=0;
/** Returns an d-scaled version of the given vector */
virtual SmartPtr<Vector>
apply_vector_scaling_d_NonConst(const SmartPtr<const Vector>& v)=0;
/** Returns an d-unscaled version of the given vector */
virtual SmartPtr<Vector>
unapply_vector_scaling_d_NonConst(const SmartPtr<const Vector>& v)=0;
/** Returns a scaled version of the jacobian for c. If the
* overloaded method does not make a new matrix, make sure to set
* the matrix ptr passed in to NULL.
*/
virtual SmartPtr<const Matrix>
apply_jac_c_scaling(SmartPtr<const Matrix> matrix)=0;
/** Returns a scaled version of the jacobian for d If the
* overloaded method does not create a new matrix, make sure to
* set the matrix ptr passed in to NULL.
*/
virtual SmartPtr<const Matrix>
apply_jac_d_scaling(SmartPtr<const Matrix> matrix)=0;
/** Returns a scaled version of the hessian of the lagrangian If
* the overloaded method does not create a new matrix, make sure
* to set the matrix ptr passed in to NULL.
*/
virtual SmartPtr<const SymMatrix>
apply_hessian_scaling(SmartPtr<const SymMatrix> matrix)=0;
//@}
/** Methods for scaling bounds - these wrap those above */
//@{
/** Returns an x-scaled vector in the x_L or x_U space */
SmartPtr<Vector> apply_vector_scaling_x_LU_NonConst(
const Matrix& Px_LU,
const SmartPtr<const Vector>& lu,
const VectorSpace& x_space);
/** Returns an x-scaled vector in the x_L or x_U space */
SmartPtr<const Vector> apply_vector_scaling_x_LU(
const Matrix& Px_LU,
const SmartPtr<const Vector>& lu,
const VectorSpace& x_space);
/** Returns an d-scaled vector in the d_L or d_U space */
SmartPtr<Vector> apply_vector_scaling_d_LU_NonConst(
const Matrix& Pd_LU,
const SmartPtr<const Vector>& lu,
const VectorSpace& d_space);
/** Returns an d-scaled vector in the d_L or d_U space */
SmartPtr<const Vector> apply_vector_scaling_d_LU(
const Matrix& Pd_LU,
const SmartPtr<const Vector>& lu,
const VectorSpace& d_space);
/** Returns an d-unscaled vector in the d_L or d_U space */
SmartPtr<Vector> unapply_vector_scaling_d_LU_NonConst(
const Matrix& Pd_LU,
const SmartPtr<const Vector>& lu,
const VectorSpace& d_space);
/** Returns an d-unscaled vector in the d_L or d_U space */
SmartPtr<const Vector> unapply_vector_scaling_d_LU(
const Matrix& Pd_LU,
const SmartPtr<const Vector>& lu,
const VectorSpace& d_space);
//@}
/** Methods for scaling the gradient of the objective - wraps the
* virtual methods above
*/
//@{
/** Returns a grad_f scaled version (d_f * D_x^{-1}) of the given vector */
virtual SmartPtr<Vector>
apply_grad_obj_scaling_NonConst(const SmartPtr<const Vector>& v);
/** Returns a grad_f scaled version (d_f * D_x^{-1}) of the given vector */
virtual SmartPtr<const Vector>
apply_grad_obj_scaling(const SmartPtr<const Vector>& v);
/** Returns a grad_f unscaled version (d_f * D_x^{-1}) of the
* given vector */
virtual SmartPtr<Vector>
unapply_grad_obj_scaling_NonConst(const SmartPtr<const Vector>& v);
/** Returns a grad_f unscaled version (d_f * D_x^{-1}) of the
* given vector */
virtual SmartPtr<const Vector>
unapply_grad_obj_scaling(const SmartPtr<const Vector>& v);
//@}
/** @name Methods for determining whether scaling for entities is
* done */
//@{
/** Returns true if the primal x variables are scaled. */
virtual bool have_x_scaling()=0;
/** Returns true if the equality constraints are scaled. */
virtual bool have_c_scaling()=0;
/** Returns true if the inequality constraints are scaled. */
virtual bool have_d_scaling()=0;
//@}
/** This method is called by the IpoptNLP's at a convenient time to
* compute and/or read scaling factors
*/
virtual void DetermineScaling(const SmartPtr<const VectorSpace> x_space,
const SmartPtr<const VectorSpace> c_space,
const SmartPtr<const VectorSpace> d_space,
const SmartPtr<const MatrixSpace> jac_c_space,
const SmartPtr<const MatrixSpace> jac_d_space,
const SmartPtr<const SymMatrixSpace> h_space,
SmartPtr<const MatrixSpace>& new_jac_c_space,
SmartPtr<const MatrixSpace>& new_jac_d_space,
SmartPtr<const SymMatrixSpace>& new_h_space,
const Matrix& Px_L, const Vector& x_L,
const Matrix& Px_U, const Vector& x_U)=0;
protected:
/** Implementation of the initialization method that has to be
* overloaded by for each derived class. */
virtual bool InitializeImpl(const OptionsList& options,
const std::string& prefix)=0;
/** Accessor method for the journalist */
const Journalist& Jnlst() const
{
return *jnlst_;
}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Copy Constructor */
NLPScalingObject(const NLPScalingObject&);
/** Overloaded Equals Operator */
void operator=(const NLPScalingObject&);
//@}
SmartPtr<const Journalist> jnlst_;
};
/** This is a base class for many standard scaling
* techniques. The overloaded classes only need to
* provide the scaling parameters
*/
class StandardScalingBase : public NLPScalingObject
{
public:
/**@name Constructors/Destructors */
//@{
StandardScalingBase();
/** Default destructor */
virtual ~StandardScalingBase();
//@}
/** Methods to map scaled and unscaled matrices */
//@{
/** Returns an obj-scaled version of the given scalar */
virtual Number apply_obj_scaling(const Number& f);
/** Returns an obj-unscaled version of the given scalar */
virtual Number unapply_obj_scaling(const Number& f);
/** Returns an x-scaled version of the given vector */
virtual SmartPtr<Vector>
apply_vector_scaling_x_NonConst(const SmartPtr<const Vector>& v);
/** Returns an x-scaled version of the given vector */
virtual SmartPtr<const Vector>
apply_vector_scaling_x(const SmartPtr<const Vector>& v);
/** Returns an x-unscaled version of the given vector */
virtual SmartPtr<Vector>
unapply_vector_scaling_x_NonConst(const SmartPtr<const Vector>& v);
/** Returns an x-unscaled version of the given vector */
virtual SmartPtr<const Vector>
unapply_vector_scaling_x(const SmartPtr<const Vector>& v);
/** Returns an c-scaled version of the given vector */
virtual SmartPtr<const Vector>
apply_vector_scaling_c(const SmartPtr<const Vector>& v);
/** Returns an c-unscaled version of the given vector */
virtual SmartPtr<const Vector>
unapply_vector_scaling_c(const SmartPtr<const Vector>& v);
/** Returns an c-scaled version of the given vector */
virtual SmartPtr<Vector>
apply_vector_scaling_c_NonConst(const SmartPtr<const Vector>& v);
/** Returns an c-unscaled version of the given vector */
virtual SmartPtr<Vector>
unapply_vector_scaling_c_NonConst(const SmartPtr<const Vector>& v);
/** Returns an d-scaled version of the given vector */
virtual SmartPtr<const Vector>
apply_vector_scaling_d(const SmartPtr<const Vector>& v);
/** Returns an d-unscaled version of the given vector */
virtual SmartPtr<const Vector>
unapply_vector_scaling_d(const SmartPtr<const Vector>& v);
/** Returns an d-scaled version of the given vector */
virtual SmartPtr<Vector>
apply_vector_scaling_d_NonConst(const SmartPtr<const Vector>& v);
/** Returns an d-unscaled version of the given vector */
virtual SmartPtr<Vector>
unapply_vector_scaling_d_NonConst(const SmartPtr<const Vector>& v);
/** Returns a scaled version of the jacobian for c. If the
* overloaded method does not make a new matrix, make sure to set
* the matrix ptr passed in to NULL.
*/
virtual SmartPtr<const Matrix>
apply_jac_c_scaling(SmartPtr<const Matrix> matrix);
/** Returns a scaled version of the jacobian for d If the
* overloaded method does not create a new matrix, make sure to
* set the matrix ptr passed in to NULL.
*/
virtual SmartPtr<const Matrix>
apply_jac_d_scaling(SmartPtr<const Matrix> matrix);
/** Returns a scaled version of the hessian of the lagrangian If
* the overloaded method does not create a new matrix, make sure
* to set the matrix ptr passed in to NULL.
*/
virtual SmartPtr<const SymMatrix>
apply_hessian_scaling(SmartPtr<const SymMatrix> matrix);
//@}
/** @name Methods for determining whether scaling for entities is
* done */
//@{
virtual bool have_x_scaling();
virtual bool have_c_scaling();
virtual bool have_d_scaling();
//@}
/** This method is called by the IpoptNLP's at a convenient time to
* compute and/or read scaling factors
*/
virtual void DetermineScaling(const SmartPtr<const VectorSpace> x_space,
const SmartPtr<const VectorSpace> c_space,
const SmartPtr<const VectorSpace> d_space,
const SmartPtr<const MatrixSpace> jac_c_space,
const SmartPtr<const MatrixSpace> jac_d_space,
const SmartPtr<const SymMatrixSpace> h_space,
SmartPtr<const MatrixSpace>& new_jac_c_space,
SmartPtr<const MatrixSpace>& new_jac_d_space,
SmartPtr<const SymMatrixSpace>& new_h_space,
const Matrix& Px_L, const Vector& x_L,
const Matrix& Px_U, const Vector& x_U);
/** Methods for IpoptType */
//@{
static void RegisterOptions(SmartPtr<RegisteredOptions> roptions);
//@}
protected:
/** Overloaded initialization method */
virtual bool InitializeImpl(const OptionsList& options,
const std::string& prefix);
/** This is the method that has to be overloaded by a particular
* scaling method that somehow computes the scaling vectors dx,
* dc, and dd. The pointers to those vectors can be NULL, in
* which case no scaling for that item will be done later. */
virtual void DetermineScalingParametersImpl(
const SmartPtr<const VectorSpace> x_space,
const SmartPtr<const VectorSpace> c_space,
const SmartPtr<const VectorSpace> d_space,
const SmartPtr<const MatrixSpace> jac_c_space,
const SmartPtr<const MatrixSpace> jac_d_space,
const SmartPtr<const SymMatrixSpace> h_space,
const Matrix& Px_L, const Vector& x_L,
const Matrix& Px_U, const Vector& x_U,
Number& df,
SmartPtr<Vector>& dx,
SmartPtr<Vector>& dc,
SmartPtr<Vector>& dd)=0;
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Copy Constructor */
StandardScalingBase(const StandardScalingBase&);
/** Overloaded Equals Operator */
void operator=(const StandardScalingBase&);
//@}
/** Scaling parameters - we only need to keep copies of
* the objective scaling and the x scaling - the others we can
* get from the scaled matrix spaces.
*/
//@{
/** objective scaling parameter */
Number df_;
/** x scaling */
SmartPtr<Vector> dx_;
//@}
/** Scaled Matrix Spaces */
//@{
/** Scaled jacobian of c space */
SmartPtr<ScaledMatrixSpace> scaled_jac_c_space_;
/** Scaled jacobian of d space */
SmartPtr<ScaledMatrixSpace> scaled_jac_d_space_;
/** Scaled hessian of lagrangian spacea */
SmartPtr<SymScaledMatrixSpace> scaled_h_space_;
//@}
/** @name Algorithmic parameters */
//@{
/** Additional scaling value for the objective function */
Number obj_scaling_factor_;
//@}
};
/** Class implementing the scaling object that doesn't to any scaling */
class NoNLPScalingObject : public StandardScalingBase
{
public:
/**@name Constructors/Destructors */
//@{
NoNLPScalingObject()
{}
/** Default destructor */
virtual ~NoNLPScalingObject()
{}
//@}
protected:
/** Overloaded from StandardScalingBase */
virtual void DetermineScalingParametersImpl(
const SmartPtr<const VectorSpace> x_space,
const SmartPtr<const VectorSpace> c_space,
const SmartPtr<const VectorSpace> d_space,
const SmartPtr<const MatrixSpace> jac_c_space,
const SmartPtr<const MatrixSpace> jac_d_space,
const SmartPtr<const SymMatrixSpace> h_space,
const Matrix& Px_L, const Vector& x_L,
const Matrix& Px_U, const Vector& x_U,
Number& df,
SmartPtr<Vector>& dx,
SmartPtr<Vector>& dc,
SmartPtr<Vector>& dd);
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Copy Constructor */
NoNLPScalingObject(const NoNLPScalingObject&);
/** Overloaded Equals Operator */
void operator=(const NoNLPScalingObject&);
//@}
};
} // namespace Ipopt
#endif
+366
View File
@@ -0,0 +1,366 @@
// Copyright (C) 2004, 2006 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpObserver.hpp 2161 2013-01-01 20:39:05Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPOBSERVER_HPP__
#define __IPOBSERVER_HPP__
#include "IpUtils.hpp"
#include <vector>
#include <algorithm>
//#define IP_DEBUG_OBSERVER
#if COIN_IPOPT_CHECKLEVEL > 2
# define IP_DEBUG_OBSERVER
#endif
#ifdef IP_DEBUG_OBSERVER
# include "IpDebug.hpp"
#endif
namespace Ipopt
{
/** Forward declarations */
class Subject;
/** Slight Variation of the Observer Design Pattern.
* This class implements the Observer class of the
* Observer Design Pattern. An Observer "Attach"es
* to a Subject, indicating that it would like to
* be notified of changes in the Subject.
* Any derived class wishing to recieve notifications
* from a Subject should inherit off of
* Observer and overload the protected method,
* RecieveNotification_(...).
*/
class Observer
{
public:
#ifdef IP_DEBUG_OBSERVER
static const Index dbg_verbosity;
#endif
/**@name Constructors/Destructors */
//@{
/** Default Constructor */
Observer()
{}
/** Default destructor */
inline
virtual ~Observer();
//@}
/** Enumeration specifying the type of notification */
enum NotifyType
{
NT_All,
NT_BeingDestroyed,
NT_Changed
};
protected:
/** Derived classes should call this method
* to request an "Attach" to a Subject. Do
* not call "Attach" explicitly on the Subject
* since further processing is done here
*/
inline
void RequestAttach(NotifyType notify_type, const Subject* subject);
/** Derived classes should call this method
* to request a "Detach" to a Subject. Do
* not call "Detach" explicitly on the Subject
* since further processing is done here
*/
inline
void RequestDetach(NotifyType notify_type, const Subject* subject);
/** Derived classes should overload this method to
* recieve the requested notification from
* attached Subjects
*/
virtual void RecieveNotification(NotifyType notify_type, const Subject* subject)=0;
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Copy Constructor */
Observer(const Observer&);
/** Overloaded Equals Operator */
void operator=(const Observer&);
//@}
/** A list of the subjects currently being
* observed. */
std::vector<const Subject*> subjects_;
/** Private Method for Recieving Notification
* should only be called by the friend class
* Subject. This method will, in turn, call
* the overloaded RecieveNotification method
* for the derived class to process.
*/
inline
void ProcessNotification(NotifyType notify_type, const Subject* subject);
friend class Subject;
};
/** Slight Variation of the Observer Design Pattern (Subject part).
* This class implements the Subject class of the Observer Design
* Pattern. An Observer "Attach"es to a Subject, indicating that it
* would like to be notified of changes in the Subject. Any
* derived class that is to be observed has to inherit off the
* Subject base class. If the subject needs to notify the
* Observer, it calls the Notify method.
*/
class Subject
{
public:
#ifdef IP_DEBUG_OBSERVER
static const Index dbg_verbosity;
#endif
/**@name Constructors/Destructors */
//@{
/** Default Constructor */
Subject()
{}
/** Default destructor */
inline
virtual ~Subject();
//@}
/**@name Methods to Add and Remove Observers.
* Currently, the notify_type flags are not used,
* and Observers are attached in general and will
* recieve all notifications (of the type requested
* and possibly of types not requested). It is
* up to the observer to ignore the types they
* are not interested in. The NotifyType in the
* parameter list is so a more efficient mechanism
* depending on type could be implemented later if
* necessary.*/
//@{
/** Attach the specified observer
* (i.e., begin recieving notifications). */
inline
void AttachObserver(Observer::NotifyType notify_type, Observer* observer) const;
/** Detach the specified observer
* (i.e., no longer recieve notifications). */
inline
void DetachObserver(Observer::NotifyType notify_type, Observer* observer) const;
//@}
protected:
inline
void Notify(Observer::NotifyType notify_type) const;
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Copy Constructor */
Subject(const Subject&);
/** Overloaded Equals Operator */
void operator=(const Subject&);
//@}
mutable std::vector<Observer*> observers_;
};
/* inline methods */
inline
Observer::~Observer()
{
#ifdef IP_DEBUG_OBSERVER
DBG_START_METH("Observer::~Observer", dbg_verbosity);
if (DBG_VERBOSITY()>=1) {
for (Index i=0; i<(Index)subjects_.size(); i++) {
DBG_PRINT((1,"subjects_[%d] = 0x%x\n", i, subjects_[i]));
}
}
#endif
// Detach all subjects
for (Int i=(Int)(subjects_.size()-1); i>=0; i--) {
#ifdef IP_DEBUG_OBSERVER
DBG_PRINT((1,"About to detach subjects_[%d] = 0x%x\n", i, subjects_[i]));
#endif
RequestDetach(NT_All, subjects_[i]);
}
}
inline
void Observer::RequestAttach(NotifyType notify_type, const Subject* subject)
{
#ifdef IP_DEBUG_OBSERVER
DBG_START_METH("Observer::RequestAttach", dbg_verbosity);
// Add the subject to the list if it does not already exist
std::vector<const Subject*>::iterator attached_subject;
attached_subject = std::find(subjects_.begin(), subjects_.end(), subject);
DBG_ASSERT(attached_subject == subjects_.end());
DBG_ASSERT(subject);
#endif
// add the subject to the list
subjects_.push_back(subject);
// Attach the observer to the subject
subject->AttachObserver(notify_type, this);
}
inline
void Observer::RequestDetach(NotifyType notify_type, const Subject* subject)
{
#ifdef IP_DEBUG_OBSERVER
DBG_START_METH("Observer::RequestDetach", dbg_verbosity);
DBG_PRINT((1, "Requesting detach of subject: 0x%x\n", subject));
DBG_ASSERT(subject);
#endif
if (subject) {
std::vector<const Subject*>::iterator attached_subject;
attached_subject = std::find(subjects_.begin(), subjects_.end(), subject);
#ifdef IP_DEBUG_OBSERVER
DBG_ASSERT(attached_subject != subjects_.end());
#endif
if (attached_subject != subjects_.end()) {
#ifdef IP_DEBUG_OBSERVER
DBG_PRINT((1, "Removing subject: 0x%x from the list\n", subject));
#endif
subjects_.erase(attached_subject);
}
// Detach the observer from the subject
subject->DetachObserver(notify_type, this);
}
}
inline
void Observer::ProcessNotification(NotifyType notify_type, const Subject* subject)
{
#ifdef IP_DEBUG_OBSERVER
DBG_START_METH("Observer::ProcessNotification", dbg_verbosity);
DBG_ASSERT(subject);
#endif
if (subject) {
std::vector<const Subject*>::iterator attached_subject;
attached_subject = std::find(subjects_.begin(), subjects_.end(), subject);
// We must be processing a notification for a
// subject that was previously attached.
#ifdef IP_DEBUG_OBSERVER
DBG_ASSERT(attached_subject != subjects_.end());
#endif
this->RecieveNotification(notify_type, subject);
if (notify_type == NT_BeingDestroyed) {
// the subject is going away, remove it from our list
subjects_.erase(attached_subject);
}
}
}
inline
Subject::~Subject()
{
#ifdef IP_DEBUG_OBSERVER
DBG_START_METH("Subject::~Subject", dbg_verbosity);
#endif
std::vector<Observer*>::iterator iter;
for (iter = observers_.begin(); iter != observers_.end(); iter++) {
(*iter)->ProcessNotification(Observer::NT_BeingDestroyed, this);
}
}
inline
void Subject::AttachObserver(Observer::NotifyType notify_type, Observer* observer) const
{
#ifdef IP_DEBUG_OBSERVER
DBG_START_METH("Subject::AttachObserver", dbg_verbosity);
// current implementation notifies all observers of everything
// they must filter the notifications that they are not interested
// in (i.e. a hub, not a router)
DBG_ASSERT(observer);
std::vector<Observer*>::iterator attached_observer;
attached_observer = std::find(observers_.begin(), observers_.end(), observer);
DBG_ASSERT(attached_observer == observers_.end());
DBG_ASSERT(observer);
#endif
observers_.push_back(observer);
}
inline
void Subject::DetachObserver(Observer::NotifyType notify_type, Observer* observer) const
{
#ifdef IP_DEBUG_OBSERVER
DBG_START_METH("Subject::DetachObserver", dbg_verbosity);
DBG_ASSERT(observer);
#endif
if (observer) {
std::vector<Observer*>::iterator attached_observer;
attached_observer = std::find(observers_.begin(), observers_.end(), observer);
#ifdef IP_DEBUG_OBSERVER
DBG_ASSERT(attached_observer != observers_.end());
#endif
if (attached_observer != observers_.end()) {
observers_.erase(attached_observer);
}
}
}
inline
void Subject::Notify(Observer::NotifyType notify_type) const
{
#ifdef IP_DEBUG_OBSERVER
DBG_START_METH("Subject::Notify", dbg_verbosity);
#endif
std::vector<Observer*>::iterator iter;
for (iter = observers_.begin(); iter != observers_.end(); iter++) {
(*iter)->ProcessNotification(notify_type, this);
}
}
} // namespace Ipopt
#endif
+289
View File
@@ -0,0 +1,289 @@
// Copyright (C) 2004, 2006 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpOptionsList.hpp 2613 2015-11-04 14:42:02Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPOPTLIST_HPP__
#define __IPOPTLIST_HPP__
#include "IpUtils.hpp"
#include "IpReferenced.hpp"
#include "IpException.hpp"
#include "IpRegOptions.hpp"
#include <iostream>
#include <map>
namespace Ipopt
{
/** Exception that can be used to indicate errors with options */
DECLARE_STD_EXCEPTION(OPTION_INVALID);
/** This class stores a list of user set options. Each options is
* identified by a case-insensitive keyword (tag). Its value is
* stored internally as a string (always lower case), but for
* convenience set and get methods are provided to obtain Index and
* Number type values. For each keyword we also keep track of how
* often the value of an option has been requested by a get method.
*/
class OptionsList : public ReferencedObject
{
/** Class for storing the value and counter for each option in
* OptionsList. */
class OptionValue
{
public:
/**@name Constructors/Destructors */
//@{
/** Default constructor (needed for the map) */
OptionValue()
:
initialized_(false)
{}
/** Constructor given the value */
OptionValue(std::string value, bool allow_clobber, bool dont_print)
:
value_(value),
counter_(0),
initialized_(true),
allow_clobber_(allow_clobber),
dont_print_(dont_print)
{}
/** Copy Constructor */
OptionValue(const OptionValue& copy)
:
value_(copy.value_),
counter_(copy.counter_),
initialized_(copy.initialized_),
allow_clobber_(copy.allow_clobber_),
dont_print_(copy.dont_print_)
{}
/** Equals operator */
void operator=(const OptionValue& copy)
{
value_=copy.value_;
counter_=copy.counter_;
initialized_=copy.initialized_;
allow_clobber_=copy.allow_clobber_;
dont_print_=copy.dont_print_;
}
/** Default Destructor */
~OptionValue()
{}
//@}
/** Method for retrieving the value of an option. Calling this
* method will increase the counter by one. */
std::string GetValue() const
{
DBG_ASSERT(initialized_);
counter_++;
return value_;
}
/** Method for retrieving the value without increasing the
* counter */
std::string Value() const
{
DBG_ASSERT(initialized_);
return value_;
}
/** Method for accessing current value of the request counter */
Index Counter() const
{
DBG_ASSERT(initialized_);
return counter_;
}
/** True if the option can be overwritten */
bool AllowClobber() const
{
DBG_ASSERT(initialized_);
return allow_clobber_;
}
/** True if this option is not to show up in the
* print_user_options output */
bool DontPrint() const
{
DBG_ASSERT(initialized_);
return dont_print_;
}
private:
/** Value for this option */
std::string value_;
/** Counter for requests */
mutable Index counter_;
/** for debugging */
bool initialized_;
/** True if the option can be overwritten */
bool allow_clobber_;
/** True if this option is not to show up in the
* print_user_options output */
bool dont_print_;
};
public:
/**@name Constructors/Destructors */
//@{
OptionsList(SmartPtr<RegisteredOptions> reg_options, SmartPtr<Journalist> jnlst)
: reg_options_(reg_options), jnlst_(jnlst)
{}
OptionsList()
{}
/** Copy Constructor */
OptionsList(const OptionsList& copy)
{
// copy all the option strings and values
options_ = copy.options_;
// copy the registered options pointer
reg_options_ = copy.reg_options_;
}
/** Default destructor */
virtual ~OptionsList()
{}
/** Overloaded Equals Operator */
virtual void operator=(const OptionsList& source)
{
options_ = source.options_;
reg_options_ = source.reg_options_;
jnlst_ = source.jnlst_;
}
//@}
/** Method for clearing all previously set options */
virtual void clear()
{
options_.clear();
}
/** @name Get / Set Methods */
//@{
virtual void SetRegisteredOptions(const SmartPtr<RegisteredOptions> reg_options)
{
reg_options_ = reg_options;
}
virtual void SetJournalist(const SmartPtr<Journalist> jnlst)
{
jnlst_ = jnlst;
}
//@}
/** @name Methods for setting options */
//@{
virtual bool SetStringValue(const std::string& tag, const std::string& value,
bool allow_clobber = true, bool dont_print = false);
virtual bool SetNumericValue(const std::string& tag, Number value,
bool allow_clobber = true, bool dont_print = false);
virtual bool SetIntegerValue(const std::string& tag, Index value,
bool allow_clobber = true, bool dont_print = false);
//@}
/** @name Methods for setting options only if they have not been
* set before*/
//@{
virtual bool SetStringValueIfUnset(const std::string& tag, const std::string& value,
bool allow_clobber = true, bool dont_print = false);
virtual bool SetNumericValueIfUnset(const std::string& tag, Number value,
bool allow_clobber = true, bool dont_print = false);
virtual bool SetIntegerValueIfUnset(const std::string& tag, Index value,
bool allow_clobber = true, bool dont_print = false);
//@}
/** @name Methods for retrieving values from the options list. If
* a tag is not found, the methods return false, and value is set
* to the default value defined in the registered options. */
//@{
virtual bool GetStringValue(const std::string& tag, std::string& value,
const std::string& prefix) const;
virtual bool GetEnumValue(const std::string& tag, Index& value,
const std::string& prefix) const;
virtual bool GetBoolValue(const std::string& tag, bool& value,
const std::string& prefix) const;
virtual bool GetNumericValue(const std::string& tag, Number& value,
const std::string& prefix) const;
virtual bool GetIntegerValue(const std::string& tag, Index& value,
const std::string& prefix) const;
//@}
/** Get a string with the list of all options (tag, value, counter) */
virtual void PrintList(std::string& list) const;
/** Get a string with the list of all options set by the user
* (tag, value, use/notused). Here, options with dont_print flag
* set to true are not printed. */
virtual void PrintUserOptions(std::string& list) const;
/** Read options from the stream is. Returns false if
* an error was encountered. */
virtual bool ReadFromStream(const Journalist& jnlst, std::istream& is, bool allow_clobber = false);
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
// OptionsList();
//@}
/** map for storing the options */
std::map< std::string, OptionValue > options_;
/** list of all the registered options to validate against */
SmartPtr<RegisteredOptions> reg_options_;
/** Journalist for writing error messages, etc. */
SmartPtr<Journalist> jnlst_;
/** auxilliary method for converting sting to all lower-case
* letters */
const std::string& lowercase(const std::string tag) const;
/** auxilliary method for finding the value for a tag in the
* options list. This method first looks for the concatenated
* string prefix+tag (if prefix is not ""), and if this is not
* found, it looks for tag. The return value is true iff
* prefix+tag or tag is found. In that case, the corresponding
* string value is copied into value. */
bool find_tag(const std::string& tag, const std::string& prefix,
std::string& value) const;
/** tells whether or not we can clobber a particular option.
* returns true if the option does not already exist, or if
* the option exists but is set to allow_clobber
*/
bool will_allow_clobber(const std::string& tag) const;
/** read the next token from stream is. Returns false, if EOF was
* reached before a tokens was ecountered. */
bool readnexttoken(std::istream& is, std::string& token);
/** auxilliary string set by lowercase method */
mutable std::string lowercase_buffer_;
};
} // namespace Ipopt
#endif
+488
View File
@@ -0,0 +1,488 @@
// Copyright (C) 2004, 2010 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpOrigIpoptNLP.hpp 2594 2015-08-09 14:31:05Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPORIGIPOPTNLP_HPP__
#define __IPORIGIPOPTNLP_HPP__
#include "IpIpoptNLP.hpp"
#include "IpException.hpp"
#include "IpTimingStatistics.hpp"
namespace Ipopt
{
/** enumeration for the Hessian information type. */
enum HessianApproximationType {
EXACT=0,
LIMITED_MEMORY
};
/** enumeration for the Hessian approximation space. */
enum HessianApproximationSpace {
NONLINEAR_VARS=0,
ALL_VARS
};
/** This class maps the traditional NLP into
* something that is more useful by Ipopt.
* This class takes care of storing the
* calculated model results, handles caching,
* and (some day) takes care of addition of slacks.
*/
class OrigIpoptNLP : public IpoptNLP
{
public:
/**@name Constructors/Destructors */
//@{
OrigIpoptNLP(const SmartPtr<const Journalist>& jnlst,
const SmartPtr<NLP>& nlp,
const SmartPtr<NLPScalingObject>& nlp_scaling);
/** Default destructor */
virtual ~OrigIpoptNLP();
//@}
/** Initialize - overloaded from IpoptNLP */
virtual bool Initialize(const Journalist& jnlst,
const OptionsList& options,
const std::string& prefix);
/** Initialize (create) structures for
* the iteration data */
virtual bool InitializeStructures(SmartPtr<Vector>& x,
bool init_x,
SmartPtr<Vector>& y_c,
bool init_y_c,
SmartPtr<Vector>& y_d,
bool init_y_d,
SmartPtr<Vector>& z_L,
bool init_z_L,
SmartPtr<Vector>& z_U,
bool init_z_U,
SmartPtr<Vector>& v_L,
SmartPtr<Vector>& v_U
);
/** Method accessing the GetWarmStartIterate of the NLP */
virtual bool GetWarmStartIterate(IteratesVector& warm_start_iterate)
{
return nlp_->GetWarmStartIterate(warm_start_iterate);
}
/** Accessor methods for model data */
//@{
/** Objective value */
virtual Number f(const Vector& x);
/** Objective value (depending in mu) - incorrect version for
* OrigIpoptNLP */
virtual Number f(const Vector& x, Number mu);
/** Gradient of the objective */
virtual SmartPtr<const Vector> grad_f(const Vector& x);
/** Gradient of the objective (depending in mu) - incorrect
* version for OrigIpoptNLP */
virtual SmartPtr<const Vector> grad_f(const Vector& x, Number mu);
/** Equality constraint residual */
virtual SmartPtr<const Vector> c(const Vector& x);
/** Jacobian Matrix for equality constraints */
virtual SmartPtr<const Matrix> jac_c(const Vector& x);
/** Inequality constraint residual (reformulated
* as equalities with slacks */
virtual SmartPtr<const Vector> d(const Vector& x);
/** Jacobian Matrix for inequality constraints*/
virtual SmartPtr<const Matrix> jac_d(const Vector& x);
/** Hessian of the Lagrangian */
virtual SmartPtr<const SymMatrix> h(const Vector& x,
Number obj_factor,
const Vector& yc,
const Vector& yd
);
/** Hessian of the Lagrangian (depending in mu) - incorrect
* version for OrigIpoptNLP */
virtual SmartPtr<const SymMatrix> h(const Vector& x,
Number obj_factor,
const Vector& yc,
const Vector& yd,
Number mu);
/** Provides a Hessian matrix from the correct matrix space with
* uninitialized values. This can be used in LeastSquareMults to
* obtain a "zero Hessian". */
virtual SmartPtr<const SymMatrix> uninitialized_h();
/** Lower bounds on x */
virtual SmartPtr<const Vector> x_L() const
{
return x_L_;
}
/** Permutation matrix (x_L_ -> x) */
virtual SmartPtr<const Matrix> Px_L() const
{
return Px_L_;
}
/** Upper bounds on x */
virtual SmartPtr<const Vector> x_U() const
{
return x_U_;
}
/** Permutation matrix (x_U_ -> x */
virtual SmartPtr<const Matrix> Px_U() const
{
return Px_U_;
}
/** Lower bounds on d */
virtual SmartPtr<const Vector> d_L() const
{
return d_L_;
}
/** Permutation matrix (d_L_ -> d) */
virtual SmartPtr<const Matrix> Pd_L() const
{
return Pd_L_;
}
/** Upper bounds on d */
virtual SmartPtr<const Vector> d_U() const
{
return d_U_;
}
/** Permutation matrix (d_U_ -> d */
virtual SmartPtr<const Matrix> Pd_U() const
{
return Pd_U_;
}
virtual SmartPtr<const SymMatrixSpace> HessianMatrixSpace() const
{
return h_space_;
}
virtual SmartPtr<const VectorSpace> x_space() const
{
return x_space_;
}
//@}
/** Accessor method for vector/matrix spaces pointers */
virtual void GetSpaces(SmartPtr<const VectorSpace>& x_space,
SmartPtr<const VectorSpace>& c_space,
SmartPtr<const VectorSpace>& d_space,
SmartPtr<const VectorSpace>& x_l_space,
SmartPtr<const MatrixSpace>& px_l_space,
SmartPtr<const VectorSpace>& x_u_space,
SmartPtr<const MatrixSpace>& px_u_space,
SmartPtr<const VectorSpace>& d_l_space,
SmartPtr<const MatrixSpace>& pd_l_space,
SmartPtr<const VectorSpace>& d_u_space,
SmartPtr<const MatrixSpace>& pd_u_space,
SmartPtr<const MatrixSpace>& Jac_c_space,
SmartPtr<const MatrixSpace>& Jac_d_space,
SmartPtr<const SymMatrixSpace>& Hess_lagrangian_space);
/** Method for adapting the variable bounds. This is called if
* slacks are becoming too small */
virtual void AdjustVariableBounds(const Vector& new_x_L,
const Vector& new_x_U,
const Vector& new_d_L,
const Vector& new_d_U);
/** @name Counters for the number of function evaluations. */
//@{
virtual Index f_evals() const
{
return f_evals_;
}
virtual Index grad_f_evals() const
{
return grad_f_evals_;
}
virtual Index c_evals() const
{
return c_evals_;
}
virtual Index jac_c_evals() const
{
return jac_c_evals_;
}
virtual Index d_evals() const
{
return d_evals_;
}
virtual Index jac_d_evals() const
{
return jac_d_evals_;
}
virtual Index h_evals() const
{
return h_evals_;
}
//@}
/** Solution Routines - overloaded from IpoptNLP*/
//@{
void FinalizeSolution(SolverReturn status,
const Vector& x, const Vector& z_L, const Vector& z_U,
const Vector& c, const Vector& d,
const Vector& y_c, const Vector& y_d,
Number obj_value,
const IpoptData* ip_data,
IpoptCalculatedQuantities* ip_cq);
bool IntermediateCallBack(AlgorithmMode mode,
Index iter, Number obj_value,
Number inf_pr, Number inf_du,
Number mu, Number d_norm,
Number regularization_size,
Number alpha_du, Number alpha_pr,
Index ls_trials,
SmartPtr<const IpoptData> ip_data,
SmartPtr<IpoptCalculatedQuantities> ip_cq);
//@}
/** @name Methods for IpoptType */
//@{
/** Called by IpoptType to register the options */
static void RegisterOptions(SmartPtr<RegisteredOptions> roptions);
//@}
/** Accessor method to the underlying NLP */
SmartPtr<NLP> nlp()
{
return nlp_;
}
/**@name Methods related to function evaluation timing. */
//@{
/** Reset the timing statistics */
void ResetTimes();
void PrintTimingStatistics(Journalist& jnlst,
EJournalLevel level,
EJournalCategory category) const;
const TimedTask& f_eval_time() const
{
return f_eval_time_;
}
const TimedTask& grad_f_eval_time() const
{
return grad_f_eval_time_;
}
const TimedTask& c_eval_time() const
{
return c_eval_time_;
}
const TimedTask& jac_c_eval_time() const
{
return jac_c_eval_time_;
}
const TimedTask& d_eval_time() const
{
return d_eval_time_;
}
const TimedTask& jac_d_eval_time() const
{
return jac_d_eval_time_;
}
const TimedTask& h_eval_time() const
{
return h_eval_time_;
}
Number TotalFunctionEvaluationCpuTime() const;
Number TotalFunctionEvaluationSysTime() const;
Number TotalFunctionEvaluationWallclockTime() const;
//@}
private:
/** journalist */
SmartPtr<const Journalist> jnlst_;
/** Pointer to the NLP */
SmartPtr<NLP> nlp_;
/** Necessary Vector/Matrix spaces */
//@{
SmartPtr<const VectorSpace> x_space_;
SmartPtr<const VectorSpace> c_space_;
SmartPtr<const VectorSpace> d_space_;
SmartPtr<const VectorSpace> x_l_space_;
SmartPtr<const MatrixSpace> px_l_space_;
SmartPtr<const VectorSpace> x_u_space_;
SmartPtr<const MatrixSpace> px_u_space_;
SmartPtr<const VectorSpace> d_l_space_;
SmartPtr<const MatrixSpace> pd_l_space_;
SmartPtr<const VectorSpace> d_u_space_;
SmartPtr<const MatrixSpace> pd_u_space_;
SmartPtr<const MatrixSpace> jac_c_space_;
SmartPtr<const MatrixSpace> jac_d_space_;
SmartPtr<const SymMatrixSpace> h_space_;
SmartPtr<const MatrixSpace> scaled_jac_c_space_;
SmartPtr<const MatrixSpace> scaled_jac_d_space_;
SmartPtr<const SymMatrixSpace> scaled_h_space_;
//@}
/**@name Storage for Model Quantities */
//@{
/** Objective function */
CachedResults<Number> f_cache_;
/** Gradient of the objective function */
CachedResults<SmartPtr<const Vector> > grad_f_cache_;
/** Equality constraint residuals */
CachedResults<SmartPtr<const Vector> > c_cache_;
/** Jacobian Matrix for equality constraints
* (current iteration) */
CachedResults<SmartPtr<const Matrix> > jac_c_cache_;
/** Inequality constraint residual (reformulated
* as equalities with slacks */
CachedResults<SmartPtr<const Vector> > d_cache_;
/** Jacobian Matrix for inequality constraints
* (current iteration) */
CachedResults<SmartPtr<const Matrix> > jac_d_cache_;
/** Hessian of the lagrangian
* (current iteration) */
CachedResults<SmartPtr<const SymMatrix> > h_cache_;
/** Unscaled version of x vector */
CachedResults<SmartPtr<const Vector> > unscaled_x_cache_;
/** Lower bounds on x */
SmartPtr<const Vector> x_L_;
/** Permutation matrix (x_L_ -> x) */
SmartPtr<const Matrix> Px_L_;
/** Upper bounds on x */
SmartPtr<const Vector> x_U_;
/** Permutation matrix (x_U_ -> x */
SmartPtr<const Matrix> Px_U_;
/** Lower bounds on d */
SmartPtr<const Vector> d_L_;
/** Permutation matrix (d_L_ -> d) */
SmartPtr<const Matrix> Pd_L_;
/** Upper bounds on d */
SmartPtr<const Vector> d_U_;
/** Permutation matrix (d_U_ -> d */
SmartPtr<const Matrix> Pd_U_;
/** Original unmodified lower bounds on x */
SmartPtr<const Vector> orig_x_L_;
/** Original unmodified upper bounds on x */
SmartPtr<const Vector> orig_x_U_;
//@}
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
OrigIpoptNLP();
/** Copy Constructor */
OrigIpoptNLP(const OrigIpoptNLP&);
/** Overloaded Equals Operator */
void operator=(const OrigIpoptNLP&);
//@}
/** @name auxilliary functions */
//@{
/** relax the bounds by a relative move of relax_bound_factor.
* Here, relax_bound_factor should be negative (or zero) for
* lower bounds, and positive (or zero) for upper bounds.
*/
void relax_bounds(Number bound_relax_factor, Vector& bounds);
/** Method for getting the unscaled version of the x vector */
SmartPtr<const Vector> get_unscaled_x(const Vector& x);
//@}
/** @name Algorithmic parameters */
//@{
/** relaxation factor for the bounds */
Number bound_relax_factor_;
/** Flag indicating whether the primal variables should be
* projected back into original bounds are optimization. */
bool honor_original_bounds_;
/** Flag indicating whether the TNLP with identical structure has
* already been solved before. */
bool warm_start_same_structure_;
/** Flag indicating what Hessian information is to be used. */
HessianApproximationType hessian_approximation_;
/** Flag indicating in which space Hessian is to be approximated. */
HessianApproximationSpace hessian_approximation_space_;
/** Flag indicating whether it is desired to check if there are
* Nan or Inf entries in first and second derivative matrices. */
bool check_derivatives_for_naninf_;
/** Flag indicating if we need to ask for equality constraint
* Jacobians only once */
bool jac_c_constant_;
/** Flag indicating if we need to ask for inequality constraint
* Jacobians only once */
bool jac_d_constant_;
/** Flag indicating if we need to ask for Hessian only once */
bool hessian_constant_;
//@}
/** @name Counters for the function evaluations */
//@{
Index f_evals_;
Index grad_f_evals_;
Index c_evals_;
Index jac_c_evals_;
Index d_evals_;
Index jac_d_evals_;
Index h_evals_;
//@}
/** Flag indicating if initialization method has been called */
bool initialized_;
/**@name Timing statistics for the function evaluations. */
//@{
TimedTask f_eval_time_;
TimedTask grad_f_eval_time_;
TimedTask c_eval_time_;
TimedTask jac_c_eval_time_;
TimedTask d_eval_time_;
TimedTask jac_d_eval_time_;
TimedTask h_eval_time_;
//@}
};
} // namespace Ipopt
#endif
+130
View File
@@ -0,0 +1,130 @@
// Copyright (C) 2004, 2006 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpPDSystemSolver.hpp 1861 2010-12-21 21:34:47Z andreasw $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPPDSYSTEMSOLVER_HPP__
#define __IPPDSYSTEMSOLVER_HPP__
#include "IpUtils.hpp"
#include "IpSymMatrix.hpp"
#include "IpAlgStrategy.hpp"
#include "IpIteratesVector.hpp"
namespace Ipopt
{
/** Pure Primal Dual System Solver Base Class.
* This is the base class for all derived Primal-Dual System Solver Types.
*
* Here, we understand the primal-dual system as the following linear
* system:
*
* \f$
* \left[\begin{array}{cccccccc}
* W & 0 & J_c^T & J_d^T & -P^x_L & P^x_U & 0 & 0 \\
* 0 & 0 & 0 & -I & 0 & 0 & -P_L^d & P_U^d \\
* J_c & 0 & 0 & 0 & 0 & 0 & 0 & 0\\
* J_d & -I & 0 & 0 & 0 & 0 & 0 & 0\\
* Z_L(P_L^x)^T & 0 & 0 & 0 & Sl^x_L & 0 & 0 & 0\\
* -Z_U(P_U^x)^T & 0 & 0 & 0 & 0 & Sl^x_U & 0 & 0\\
* 0 & V_L(P_L^d)^T & 0 & 0 & 0 & 0 & Sl^s_L & 0 \\
* 0 & -V_U(P_U^d)^T & 0 & 0 & 0 & 0 & 0 & Sl^s_U \\
* \end{array}\right]
* \left(\begin{array}{c}
* sol_x\\ sol_s\\ sol_c\\ sol_d\\ sol^z_L\\ sol^z_U\\ sol^v_L\\
* sol^v_U
* \end{array}\right) =
* \left(\begin{array}{c}
* rhs_x\\ rhs_s\\ rhs_c\\ rhs_d\\ rhs^z_L\\ rhs^z_U\\ rhs^v_L\\
* rhs^v_U
* \end{array}\right)
* \f$
*
* Here, \f$Sl^x_L = (P^x_L)^T x - x_L\f$,
* \f$Sl^x_U = x_U - (P^x_U)^T x\f$, \f$Sl^d_L = (P^d_L)^T d(x) - d_L\f$,
* \f$Sl^d_U = d_U - (P^d_U)^T d(x)\f$. The results returned to the
* caller is \f$res = \alpha * sol + \beta * res\f$.
*
* The solution of this linear system (in order to compute the search
* direction of the algorthim) usually requires a considerable amount of
* computation time. Therefore, it is important to tailor the solution
* of this system to the characteristics of the problem. The purpose of
* this base class is to provide a generic interface to the algorithm
* that it can use whenever it requires a solution of the above system.
* Particular implementation can then be written to provide the methods
* defined here.
*
* It is implicitly assumed here, that the upper left 2 by 2 block
* is possibly modified (implicitly or explicitly) so that its
* projection onto the null space of the overall constraint
* Jacobian \f$\left[\begin{array}{cc}J_c & 0\\J_d &
* -I\end{array}\right]\f$ is positive definite. This is necessary
* to guarantee certain descent properties of the resulting search
* direction. For example, in the full space implementation, a
* multiple of the identity might be added to the upper left 2 by 2
* block.
*
* Note that the Solve method might be called several times for different
* right hand sides, but with identical data. Therefore, if possible,
* an implemetation of PDSystem should check whether the incoming data has
* changed, and not redo factorization etc. unless necessary.
*/
class PDSystemSolver: public AlgorithmStrategyObject
{
public:
/** @name /Destructor */
//@{
/** Default Constructor */
PDSystemSolver()
{}
/** Default destructor */
virtual ~PDSystemSolver()
{}
//@}
/** overloaded from AlgorithmStrategyObject */
virtual bool InitializeImpl(const OptionsList& options,
const std::string& prefix) = 0;
/** Solve the primal dual system, given one right hand side. If
* the flag allow_inexact is set to true, it is not necessary to
* solve the system to best accuracy; for example, we don't want
* iterative refinement during the computation of the second
* order correction. On the other hand, if improve_solution is
* true, the solution given in res should be improved (here beta
* has to be zero, and res is assume to be the solution for the
* system using rhs, without the factor alpha...). THe return
* value is false, if a solution could not be computed (for
* example, when the Hessian regularization parameter becomes too
* large.)
*/
virtual bool Solve(Number alpha,
Number beta,
const IteratesVector& rhs,
IteratesVector& res,
bool allow_inexact=false,
bool improve_solution=false) =0;
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Overloaded Equals Operator */
PDSystemSolver& operator=(const PDSystemSolver&);
//@}
};
} // namespace Ipopt
#endif
+258
View File
@@ -0,0 +1,258 @@
// Copyright (C) 2004, 2006 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpReferenced.hpp 2182 2013-03-30 20:02:18Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPREFERENCED_HPP__
#define __IPREFERENCED_HPP__
#include "IpTypes.hpp"
#include "IpDebug.hpp"
#include <list>
#if COIN_IPOPT_CHECKLEVEL > 3
#define IP_DEBUG_REFERENCED
#endif
namespace Ipopt
{
/** Psydo-class, from which everything has to inherit that wants to
* use be registered as a Referencer for a ReferencedObject.
*/
class Referencer
{}
;
/** ReferencedObject class.
* This is part of the implementation of an intrusive smart pointer
* design. This class stores the reference count of all the smart
* pointers that currently reference it. See the documentation for
* the SmartPtr class for more details.
*
* A SmartPtr behaves much like a raw pointer, but manages the lifetime
* of an object, deleting the object automatically. This class implements
* a reference-counting, intrusive smart pointer design, where all
* objects pointed to must inherit off of ReferencedObject, which
* stores the reference count. Although this is intrusive (native types
* and externally authored classes require wrappers to be referenced
* by smart pointers), it is a safer design. A more detailed discussion of
* these issues follows after the usage information.
*
* Usage Example:
* Note: to use the SmartPtr, all objects to which you point MUST
* inherit off of ReferencedObject.
*
* \verbatim
*
* In MyClass.hpp...
*
* #include "IpReferenced.hpp"
* namespace Ipopt {
*
* class MyClass : public ReferencedObject // must derive from ReferencedObject
* {
* ...
* }
* } // namespace Ipopt
*
*
* In my_usage.cpp...
*
* #include "IpSmartPtr.hpp"
* #include "MyClass.hpp"
*
* void func(AnyObject& obj)
* {
* SmartPtr<MyClass> ptr_to_myclass = new MyClass(...);
* // ptr_to_myclass now points to a new MyClass,
* // and the reference count is 1
*
* ...
*
* obj.SetMyClass(ptr_to_myclass);
* // Here, let's assume that AnyObject uses a
* // SmartPtr<MyClass> internally here.
* // Now, both ptr_to_myclass and the internal
* // SmartPtr in obj point to the same MyClass object
* // and its reference count is 2.
*
* ...
*
* // No need to delete ptr_to_myclass, this
* // will be done automatically when the
* // reference count drops to zero.
*
* }
*
* \endverbatim
*
* Other Notes:
* The SmartPtr implements both dereference operators -> & *.
* The SmartPtr does NOT implement a conversion operator to
* the raw pointer. Use the GetRawPtr() method when this
* is necessary. Make sure that the raw pointer is NOT
* deleted.
* The SmartPtr implements the comparison operators == & !=
* for a variety of types. Use these instead of
* \verbatim
* if (GetRawPtr(smrt_ptr) == ptr) // Don't use this
* \endverbatim
* SmartPtr's, as currently implemented, do NOT handle circular references.
* For example: consider a higher level object using SmartPtrs to point to
* A and B, but A and B also point to each other (i.e. A has a SmartPtr
* to B and B has a SmartPtr to A). In this scenario, when the higher
* level object is finished with A and B, their reference counts will
* never drop to zero (since they reference each other) and they
* will not be deleted. This can be detected by memory leak tools like
* valgrind. If the circular reference is necessary, the problem can be
* overcome by a number of techniques:
*
* 1) A and B can have a method that "releases" each other, that is
* they set their internal SmartPtrs to NULL.
* \verbatim
* void AClass::ReleaseCircularReferences()
* {
* smart_ptr_to_B = NULL;
* }
* \endverbatim
* Then, the higher level class can call these methods before
* it is done using A & B.
*
* 2) Raw pointers can be used in A and B to reference each other.
* Here, an implicit assumption is made that the lifetime is
* controlled by the higher level object and that A and B will
* both exist in a controlled manner. Although this seems
* dangerous, in many situations, this type of referencing
* is very controlled and this is reasonably safe.
*
* 3) This SmartPtr class could be redesigned with the Weak/Strong
* design concept. Here, the SmartPtr is identified as being
* Strong (controls lifetime of the object) or Weak (merely
* referencing the object). The Strong SmartPtr increments
* (and decrements) the reference count in ReferencedObject
* but the Weak SmartPtr does not. In the example above,
* the higher level object would have Strong SmartPtrs to
* A and B, but A and B would have Weak SmartPtrs to each
* other. Then, when the higher level object was done with
* A and B, they would be deleted. The Weak SmartPtrs in A
* and B would not decrement the reference count and would,
* of course, not delete the object. This idea is very similar
* to item (2), where it is implied that the sequence of events
* is controlled such that A and B will not call anything using
* their pointers following the higher level delete (i.e. in
* their destructors!). This is somehow safer, however, because
* code can be written (however expensive) to perform run-time
* detection of this situation. For example, the ReferencedObject
* could store pointers to all Weak SmartPtrs that are referencing
* it and, in its destructor, tell these pointers that it is
* dying. They could then set themselves to NULL, or set an
* internal flag to detect usage past this point.
*
* For every most derived object only one ReferencedObject may exist,
* that is multiple inheritance requires virtual inheritance, see also
* the 2nd point in ticket #162.
*
* Comments on Non-Intrusive Design:
* In a non-intrusive design, the reference count is stored somewhere other
* than the object being referenced. This means, unless the reference
* counting pointer is the first referencer, it must get a pointer to the
* referenced object from another smart pointer (so it has access to the
* reference count location). In this non-intrusive design, if we are
* pointing to an object with a smart pointer (or a number of smart
* pointers), and we then give another smart pointer the address through
* a RAW pointer, we will have two independent, AND INCORRECT, reference
* counts. To avoid this pitfall, we use an intrusive reference counting
* technique where the reference count is stored in the object being
* referenced.
*/
class ReferencedObject
{
public:
ReferencedObject()
:
reference_count_(0)
{}
virtual ~ReferencedObject()
{
DBG_ASSERT(reference_count_ == 0);
}
inline
Index ReferenceCount() const;
inline
void AddRef(const Referencer* referencer) const;
inline
void ReleaseRef(const Referencer* referencer) const;
private:
mutable Index reference_count_;
# ifdef IP_DEBUG_REFERENCED
mutable std::list<const Referencer*> referencers_;
# endif
};
/* inline methods */
inline
Index ReferencedObject::ReferenceCount() const
{
// DBG_START_METH("ReferencedObject::ReferenceCount()", 0);
// DBG_PRINT((1,"Returning reference_count_ = %d\n", reference_count_));
return reference_count_;
}
inline
void ReferencedObject::AddRef(const Referencer* referencer) const
{
// DBG_START_METH("ReferencedObject::AddRef(const Referencer* referencer)", 0);
reference_count_++;
// DBG_PRINT((1, "New reference_count_ = %d\n", reference_count_));
# ifdef IP_DEBUG_REFERENCED
referencers_.push_back(referencer);
# endif
}
inline
void ReferencedObject::ReleaseRef(const Referencer* referencer) const
{
// DBG_START_METH("ReferencedObject::ReleaseRef(const Referencer* referencer)",
// 0);
reference_count_--;
// DBG_PRINT((1, "New reference_count_ = %d\n", reference_count_));
# ifdef IP_DEBUG_REFERENCED
bool found = false;
std::list<const Referencer*>::iterator iter;
for (iter = referencers_.begin(); iter != referencers_.end(); iter++) {
if ((*iter) == referencer) {
found = true;
break;
}
}
// cannot call release on a reference that was never added...
DBG_ASSERT(found);
if (found) {
referencers_.erase(iter);
}
# endif
}
} // namespace Ipopt
#endif
+658
View File
@@ -0,0 +1,658 @@
// Copyright (C) 2004, 2007 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpRegOptions.hpp 2189 2013-03-31 15:06:11Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2005-06-18
#ifndef __IPREGOPTIONS_HPP__
#define __IPREGOPTIONS_HPP__
#include "IpUtils.hpp"
#include "IpReferenced.hpp"
#include "IpException.hpp"
#include "IpSmartPtr.hpp"
#include <map>
namespace Ipopt
{
enum RegisteredOptionType
{
OT_Number,
OT_Integer,
OT_String,
OT_Unknown
};
/** Base class for registered options. The derived types are more
* specific to a string option or a Number (real) option, etc.
*/
class RegisteredOption : public ReferencedObject
{
public:
/** class to hold the valid string settings for a string option */
class string_entry
{
public:
string_entry(const std::string& value, const std::string& description)
: value_(value), description_(description)
{}
std::string value_;
std::string description_;
};
/** Constructors / Destructors */
//@{
RegisteredOption(Index counter)
:
type_(OT_Unknown),
has_lower_(false),
has_upper_(false),
counter_(counter)
{}
RegisteredOption(const std::string& name,
const std::string& short_description,
const std::string& long_description,
const std::string& registering_category,
Index counter)
:
name_(name),
short_description_(short_description),
long_description_(long_description),
registering_category_(registering_category),
type_(OT_Unknown),
has_lower_(false),
has_upper_(false),
counter_(counter)
{}
RegisteredOption(const RegisteredOption& copy)
:
name_(copy.name_),
short_description_(copy.short_description_),
long_description_(copy.long_description_),
registering_category_(copy.registering_category_),
type_(copy.type_),
has_lower_(copy.has_lower_),
lower_(copy.lower_),
has_upper_(copy.has_upper_),
upper_(copy.upper_),
valid_strings_(copy.valid_strings_),
counter_(copy.counter_)
{}
virtual ~RegisteredOption()
{}
//@}
DECLARE_STD_EXCEPTION(ERROR_CONVERTING_STRING_TO_ENUM);
/** Standard Get / Set Methods */
//@{
/** Get the option's name (tag in the input file) */
virtual const std::string& Name() const
{
return name_;
}
/** Set the option's name (tag in the input file) */
virtual void SetName(const std::string& name)
{
name_ = name;
}
/** Get the short description */
virtual const std::string& ShortDescription() const
{
return short_description_;
}
/** Get the long description */
virtual const std::string& LongDescription() const
{
return long_description_;
}
/** Set the short description */
virtual void SetShortDescription(const std::string& short_description)
{
short_description_ = short_description;
}
/** Set the long description */
virtual void SetLongDescription(const std::string& long_description)
{
long_description_ = long_description;
}
/** Get the registering class */
virtual const std::string& RegisteringCategory() const
{
return registering_category_;
}
/** Set the registering class */
virtual void SetRegisteringCategory(const std::string& registering_category)
{
registering_category_ = registering_category;
}
/** Get the Option's type */
virtual const RegisteredOptionType& Type() const
{
return type_;
}
/** Get the Option's type */
virtual void SetType(const RegisteredOptionType& type)
{
type_ = type;
}
/** Counter */
virtual Index Counter() const
{
return counter_;
}
//@}
/** @name Get / Set methods valid for specific types - NOTE: the Type
* must be set before calling these methods.
*/
//@{
/** check if the option has a lower bound - can be called for
* OT_Number & OT_Integer*/
virtual const bool& HasLower() const
{
DBG_ASSERT(type_ == OT_Number || type_ == OT_Integer);
return has_lower_;
}
/** check if the lower bound is strict - can be called for
OT_Number */
virtual const bool& LowerStrict() const
{
DBG_ASSERT(type_ == OT_Number && has_lower_ == true);
return lower_strict_;
}
/** get the Number version of the lower bound - can be called for
* OT_Number */
virtual Number LowerNumber() const
{
DBG_ASSERT(has_lower_ == true && type_ == OT_Number);
return lower_;
}
/** set the Number version of the lower bound - can be called for
* OT_Number */
virtual void SetLowerNumber(const Number& lower, const bool& strict)
{
DBG_ASSERT(type_ == OT_Number);
lower_ = lower;
lower_strict_ = strict, has_lower_ = true;
}
/** get the Integer version of the lower bound can be called for
* OT_Integer*/
virtual Index LowerInteger() const
{
DBG_ASSERT(has_lower_ == true && type_ == OT_Integer);
return (Index)lower_;
}
/** set the Integer version of the lower bound - can be called for
* OT_Integer */
virtual void SetLowerInteger(const Index& lower)
{
DBG_ASSERT(type_ == OT_Integer);
lower_ = (Number)lower;
has_lower_ = true;
}
/** check if the option has an upper bound - can be called for
* OT_Number & OT_Integer*/
virtual const bool& HasUpper() const
{
DBG_ASSERT(type_ == OT_Number || type_ == OT_Integer);
return has_upper_;
}
/** check if the upper bound is strict - can be called for
* OT_Number */
virtual const bool& UpperStrict() const
{
DBG_ASSERT(type_ == OT_Number && has_upper_ == true);
return upper_strict_;
}
/** get the Number version of the upper bound - can be called for
* OT_Number */
virtual Number UpperNumber() const
{
DBG_ASSERT(has_upper_ == true && type_ == OT_Number);
return upper_;
}
/** set the Number version of the upper bound - can be called for
* OT_Number */
virtual void SetUpperNumber(const Number& upper, const bool& strict)
{
DBG_ASSERT(type_ == OT_Number);
upper_ = upper;
upper_strict_ = strict;
has_upper_ = true;
}
/** get the Integer version of the upper bound - can be called for
* OT_Integer*/
virtual Index UpperInteger() const
{
DBG_ASSERT(has_upper_ == true && type_ == OT_Integer);
return (Index)upper_;
}
/** set the Integer version of the upper bound - can be called for
* OT_Integer */
virtual void SetUpperInteger(const Index& upper)
{
DBG_ASSERT(type_ == OT_Integer);
upper_ = (Number)upper;
has_upper_ = true;
}
/** method to add valid string entries - can be called for
* OT_String */
virtual void AddValidStringSetting(const std::string value,
const std::string description)
{
DBG_ASSERT(type_ == OT_String);
valid_strings_.push_back(string_entry(value, description));
}
/** get the default as a Number - can be called for OT_Number */
virtual Number DefaultNumber() const
{
DBG_ASSERT(type_ == OT_Number);
return default_number_;
}
/** Set the default as a Number - can be called for OT_Number */
virtual void SetDefaultNumber(const Number& default_value)
{
DBG_ASSERT(type_ == OT_Number);
default_number_ = default_value;
}
/** get the default as an Integer - can be called for OT_Integer*/
virtual Index DefaultInteger() const
{
DBG_ASSERT(type_ == OT_Integer);
return (Index)default_number_;
}
/** Set the default as an Integer - can be called for
OT_Integer */
virtual void SetDefaultInteger(const Index& default_value)
{
DBG_ASSERT(type_ == OT_Integer);
default_number_ = (Number)default_value;
}
/** get the default as a string - can be called for OT_String */
virtual std::string DefaultString() const
{
DBG_ASSERT(type_ == OT_String);
return default_string_;
}
/** get the default as a string, but as the index of the string in
* the list - helps map from a string to an enum- can be called
* for OT_String */
virtual Index DefaultStringAsEnum() const
{
DBG_ASSERT(type_ == OT_String);
return MapStringSettingToEnum(default_string_);
}
/** Set the default as a string - can be called for OT_String */
virtual void SetDefaultString(const std::string& default_value)
{
DBG_ASSERT(type_ == OT_String);
default_string_ = default_value;
}
/** get the valid string settings - can be called for OT_String */
virtual std::vector<string_entry> GetValidStrings() const
{
DBG_ASSERT(type_ == OT_String);
return valid_strings_;
}
/** Check if the Number value is a valid setting - can be called
* for OT_Number */
virtual bool IsValidNumberSetting(const Number& value) const
{
DBG_ASSERT(type_ == OT_Number);
if (has_lower_ && ((lower_strict_ == true && value <= lower_) ||
(lower_strict_ == false && value < lower_))) {
return false;
}
if (has_upper_ && ((upper_strict_ == true && value >= upper_) ||
(upper_strict_ == false && value > upper_))) {
return false;
}
return true;
}
/** Check if the Integer value is a valid setting - can be called
* for OT_Integer */
virtual bool IsValidIntegerSetting(const Index& value) const
{
DBG_ASSERT(type_ == OT_Integer);
if (has_lower_ && value < lower_) {
return false;
}
if (has_upper_ && value > upper_) {
return false;
}
return true;
}
/** Check if the String value is a valid setting - can be called
* for OT_String */
virtual bool IsValidStringSetting(const std::string& value) const;
/** Map a user setting (allowing any case) to the case used when
* the setting was registered.
*/
virtual std::string MapStringSetting(const std::string& value) const;
/** Map a user setting (allowing any case) to the index of the
* matched setting in the list of string settings. Helps map a
* string setting to an enumeration.
*/
virtual Index MapStringSettingToEnum(const std::string& value) const;
//@}
/** output a description of the option */
virtual void OutputDescription(const Journalist& jnlst) const;
/** output a more concise version */
virtual void OutputShortDescription(const Journalist& jnlst) const;
/** output a latex version */
virtual void OutputLatexDescription(const Journalist& jnlst) const;
private:
std::string name_;
std::string short_description_;
std::string long_description_;
std::string registering_category_;
RegisteredOptionType type_;
bool has_lower_;
bool lower_strict_;
Number lower_;
bool has_upper_;
bool upper_strict_;
Number upper_;
Number default_number_;
void MakeValidLatexString(std::string source, std::string& dest) const;
std::string MakeValidLatexNumber(Number value) const;
/** Compare two strings and return true if they are equal (case
insensitive comparison) */
bool string_equal_insensitive(const std::string& s1,
const std::string& s2) const;
std::vector<string_entry> valid_strings_;
std::string default_string_;
/** Has the information as how many-th option this one was
* registered. */
const Index counter_;
};
/** Class for storing registered options. Used for validation and
* documentation.
*/
class RegisteredOptions : public ReferencedObject
{
public:
/** Constructors / Destructors */
//@{
/** Standard Constructor */
RegisteredOptions()
:
next_counter_(0),
current_registering_category_("Uncategorized")
{}
/** Standard Destructor */
virtual ~RegisteredOptions()
{}
//@}
DECLARE_STD_EXCEPTION(OPTION_ALREADY_REGISTERED);
/** Methods to interact with registered options */
//@{
/** set the registering class. All subsequent options will be
* added with the registered class */
virtual void SetRegisteringCategory(const std::string& registering_category)
{
current_registering_category_ = registering_category;
}
/** retrieve the value of the current registering category */
virtual std::string RegisteringCategory()
{
return current_registering_category_;
}
/** Add a Number option (with no restrictions) */
virtual void AddNumberOption(const std::string& name,
const std::string& short_description,
Number default_value,
const std::string& long_description="");
/** Add a Number option (with a lower bound) */
virtual void AddLowerBoundedNumberOption(const std::string& name,
const std::string& short_description,
Number lower, bool strict,
Number default_value,
const std::string& long_description="");
/** Add a Number option (with a upper bound) */
virtual void AddUpperBoundedNumberOption(const std::string& name,
const std::string& short_description,
Number upper, bool strict,
Number default_value,
const std::string& long_description="");
/** Add a Number option (with a both bounds) */
virtual void AddBoundedNumberOption(const std::string& name,
const std::string& short_description,
Number lower, bool lower_strict,
Number upper, bool upper_strict,
Number default_value,
const std::string& long_description="");
/** Add a Integer option (with no restrictions) */
virtual void AddIntegerOption(const std::string& name,
const std::string& short_description,
Index default_value,
const std::string& long_description="");
/** Add a Integer option (with a lower bound) */
virtual void AddLowerBoundedIntegerOption(const std::string& name,
const std::string& short_description,
Index lower, Index default_value,
const std::string& long_description="");
/** Add a Integer option (with a upper bound) */
virtual void AddUpperBoundedIntegerOption(const std::string& name,
const std::string& short_description,
Index upper, Index default_value,
const std::string& long_description="");
/** Add a Integer option (with a both bounds) */
virtual void AddBoundedIntegerOption(const std::string& name,
const std::string& short_description,
Index lower, Index upper,
Index default_value,
const std::string& long_description="");
/** Add a String option (with no restrictions) */
virtual void AddStringOption(const std::string& name,
const std::string& short_description,
const std::string& default_value,
const std::vector<std::string>& settings,
const std::vector<std::string>& descriptions,
const std::string& long_description="");
/** Methods that make adding string options with only a few
* entries easier */
virtual void AddStringOption1(const std::string& name,
const std::string& short_description,
const std::string& default_value,
const std::string& setting1,
const std::string& description1,
const std::string& long_description="");
virtual void AddStringOption2(const std::string& name,
const std::string& short_description,
const std::string& default_value,
const std::string& setting1,
const std::string& description1,
const std::string& setting2,
const std::string& description2,
const std::string& long_description="");
virtual void AddStringOption3(const std::string& name,
const std::string& short_description,
const std::string& default_value,
const std::string& setting1,
const std::string& description1,
const std::string& setting2,
const std::string& description2,
const std::string& setting3,
const std::string& description3,
const std::string& long_description="");
virtual void AddStringOption4(const std::string& name,
const std::string& short_description,
const std::string& default_value,
const std::string& setting1,
const std::string& description1,
const std::string& setting2,
const std::string& description2,
const std::string& setting3,
const std::string& description3,
const std::string& setting4,
const std::string& description4,
const std::string& long_description="");
virtual void AddStringOption5(const std::string& name,
const std::string& short_description,
const std::string& default_value,
const std::string& setting1,
const std::string& description1,
const std::string& setting2,
const std::string& description2,
const std::string& setting3,
const std::string& description3,
const std::string& setting4,
const std::string& description4,
const std::string& setting5,
const std::string& description5,
const std::string& long_description="");
virtual void AddStringOption6(const std::string& name,
const std::string& short_description,
const std::string& default_value,
const std::string& setting1,
const std::string& description1,
const std::string& setting2,
const std::string& description2,
const std::string& setting3,
const std::string& description3,
const std::string& setting4,
const std::string& description4,
const std::string& setting5,
const std::string& description5,
const std::string& setting6,
const std::string& description6,
const std::string& long_description="");
virtual void AddStringOption7(const std::string& name,
const std::string& short_description,
const std::string& default_value,
const std::string& setting1,
const std::string& description1,
const std::string& setting2,
const std::string& description2,
const std::string& setting3,
const std::string& description3,
const std::string& setting4,
const std::string& description4,
const std::string& setting5,
const std::string& description5,
const std::string& setting6,
const std::string& description6,
const std::string& setting7,
const std::string& description7,
const std::string& long_description="");
virtual void AddStringOption8(const std::string& name,
const std::string& short_description,
const std::string& default_value,
const std::string& setting1,
const std::string& description1,
const std::string& setting2,
const std::string& description2,
const std::string& setting3,
const std::string& description3,
const std::string& setting4,
const std::string& description4,
const std::string& setting5,
const std::string& description5,
const std::string& setting6,
const std::string& description6,
const std::string& setting7,
const std::string& description7,
const std::string& setting8,
const std::string& description8,
const std::string& long_description="");
virtual void AddStringOption9(const std::string& name,
const std::string& short_description,
const std::string& default_value,
const std::string& setting1,
const std::string& description1,
const std::string& setting2,
const std::string& description2,
const std::string& setting3,
const std::string& description3,
const std::string& setting4,
const std::string& description4,
const std::string& setting5,
const std::string& description5,
const std::string& setting6,
const std::string& description6,
const std::string& setting7,
const std::string& description7,
const std::string& setting8,
const std::string& description8,
const std::string& setting9,
const std::string& description9,
const std::string& long_description="");
virtual void AddStringOption10(const std::string& name,
const std::string& short_description,
const std::string& default_value,
const std::string& setting1,
const std::string& description1,
const std::string& setting2,
const std::string& description2,
const std::string& setting3,
const std::string& description3,
const std::string& setting4,
const std::string& description4,
const std::string& setting5,
const std::string& description5,
const std::string& setting6,
const std::string& description6,
const std::string& setting7,
const std::string& description7,
const std::string& setting8,
const std::string& description8,
const std::string& setting9,
const std::string& description9,
const std::string& setting10,
const std::string& description10,
const std::string& long_description="");
/** Get a registered option - this will return NULL if the option
* does not exist */
virtual SmartPtr<const RegisteredOption> GetOption(const std::string& name);
/** Output documentation for the options - gives a description,
* etc. */
virtual void OutputOptionDocumentation(const Journalist& jnlst, std::list<std::string>& categories);
/** Output documentation in Latex format to include in a latex file */
virtual void OutputLatexOptionDocumentation(const Journalist& jnlst, std::list<std::string>& categories);
//@}
typedef std::map<std::string, SmartPtr<RegisteredOption> > RegOptionsList;
/** Giving access to iteratable representation of the registered
* options */
virtual const RegOptionsList& RegisteredOptionsList () const
{
return registered_options_;
}
private:
Index next_counter_;
std::string current_registering_category_;
std::map<std::string, SmartPtr<RegisteredOption> > registered_options_;
};
} // namespace Ipopt
#endif
+18
View File
@@ -0,0 +1,18 @@
/***********************************************************************
// Copyright (C) 2004, 2006 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpReturnCodes.h 1861 2010-12-21 21:34:47Z andreasw $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
************************************************************************/
#ifndef __IPRETURNCODES_H__
#define __IPRETURNCODES_H__
/* include from a common include file */
#include "IpReturnCodes_inc.h"
#endif
+21
View File
@@ -0,0 +1,21 @@
/***********************************************************************
// Copyright (C) 2006 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpReturnCodes.hpp 1861 2010-12-21 21:34:47Z andreasw $
//
// Authors: Andreas Waechter IBM 2006-03-01
************************************************************************/
#ifndef __IPRETURNCODES_HPP__
#define __IPRETURNCODES_HPP__
/* include from a common include file */
namespace Ipopt
{
#include "IpReturnCodes_inc.h"
}
#endif
+70
View File
@@ -0,0 +1,70 @@
C Copyright (C) 2005, 2009 International Business Machines and others.
C All Rights Reserved.
C This code is published under the Eclipse Public License.
C
C $Id: IpReturnCodes.inc 1861 2010-12-21 21:34:47Z andreasw $
C
C Author: Andreas Waechter IBM 2005-08-11
C
INTEGER IP_SOLVE_SUCCEEDED
PARAMETER( IP_SOLVE_SUCCEEDED = 0 )
INTEGER IP_ACCEPTABLE_LEVEL
PARAMETER( IP_ACCEPTABLE_LEVEL = 1 )
INTEGER IP_INFEASIBLE_PROBLEM
PARAMETER( IP_INFEASIBLE_PROBLEM = 2 )
INTEGER IP_SEARCH_DIRECTION_TOO_SMALL
PARAMETER( IP_SEARCH_DIRECTION_TOO_SMALL = 3 )
INTEGER IP_DIVERGING_ITERATES
PARAMETER( IP_DIVERGING_ITERATES = 4 )
INTEGER IP_USER_REQUESTED_STOP
PARAMETER( IP_USER_REQUESTED_STOP = 5 )
INTEGER IP_FEASIBLE_POINT_FOUND
PARAMETER( IP_FEASIBLE_POINT_FOUND = 6 )
INTEGER IP_ITERATION_EXCEEDED
PARAMETER( IP_ITERATION_EXCEEDED = -1 )
INTEGER IP_RESTORATION_FAILED
PARAMETER( IP_RESTORATION_FAILED = -2 )
INTEGER IP_ERROR_IN_STEP_COMPUTATION
PARAMETER( IP_ERROR_IN_STEP_COMPUTATION = -3 )
INTEGER IP_CPUTIME_EXCEEDED
PARAMETER( IP_CPUTIME_EXCEEDED = -4 )
INTEGER IP_NOT_ENOUGH_DEGREES_OF_FRE
PARAMETER( IP_NOT_ENOUGH_DEGREES_OF_FRE = -10 )
INTEGER IP_INVALID_PROBLEM_DEFINITION
PARAMETER( IP_INVALID_PROBLEM_DEFINITION = -11)
INTEGER IP_INVALID_OPTION
PARAMETER( IP_INVALID_OPTION = -12 )
INTEGER IP_INVALID_NUMBER_DETECTED
PARAMETER( IP_INVALID_NUMBER_DETECTED = -13 )
INTEGER IP_UNRECOVERABLE_EXCEPTION
PARAMETER( IP_UNRECOVERABLE_EXCEPTION = -100 )
INTEGER IP_NON_IPOPT_EXCEPTION
PARAMETER( IP_NON_IPOPT_EXCEPTION = -101 )
INTEGER IP_INSUFFICIENT_MEMORY
PARAMETER( IP_INSUFFICIENT_MEMORY = -102 )
INTEGER IP_INTERNAL_ERROR
PARAMETER( IP_INTERNAL_ERROR = -199 )
INTEGER IP_REGULAR_MODE
PARAMETER( IP_REGULAR_MODE = 0 )
INTEGER IP_RESTORATION_PHASE_MODE
PARAMETER( IP_RESTORATION_PHASE_MODE = 1 )
+46
View File
@@ -0,0 +1,46 @@
/***********************************************************************
// Copyright (C) 2004, 2009 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpReturnCodes_inc.h 2216 2013-04-14 17:06:00Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
************************************************************************/
/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
/* !!!!!!!!! REMEMBER TO UPDATE IpReturnCodes.inc and Ipopt.java !!!!!!!! */
/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
/** Return codes for the Optimize call for an application */
enum ApplicationReturnStatus
{
Solve_Succeeded=0,
Solved_To_Acceptable_Level=1,
Infeasible_Problem_Detected=2,
Search_Direction_Becomes_Too_Small=3,
Diverging_Iterates=4,
User_Requested_Stop=5,
Feasible_Point_Found=6,
Maximum_Iterations_Exceeded=-1,
Restoration_Failed=-2,
Error_In_Step_Computation=-3,
Maximum_CpuTime_Exceeded=-4,
Not_Enough_Degrees_Of_Freedom=-10,
Invalid_Problem_Definition=-11,
Invalid_Option=-12,
Invalid_Number_Detected=-13,
Unrecoverable_Exception=-100,
NonIpopt_Exception_Thrown=-101,
Insufficient_Memory=-102,
Internal_Error=-199
};
/** enum to indicate the mode in which the algorithm is */
enum AlgorithmMode
{
RegularMode=0,
RestorationPhaseMode=1
};
+254
View File
@@ -0,0 +1,254 @@
// Copyright (C) 2004, 2008 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpScaledMatrix.hpp 2269 2013-05-05 11:32:40Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPSCALEDMATRIX_HPP__
#define __IPSCALEDMATRIX_HPP__
#include "IpUtils.hpp"
#include "IpMatrix.hpp"
namespace Ipopt
{
/* forward declarations */
class ScaledMatrixSpace;
/** Class for a Matrix in conjunction with its scaling factors for
* row and column scaling. Operations on the matrix are performed using
* the scaled matrix. You can pull out the pointer to the
* unscaled matrix for unscaled calculations.
*/
class ScaledMatrix : public Matrix
{
public:
/**@name Constructors / Destructors */
//@{
/** Constructor, taking the owner_space.
*/
ScaledMatrix(const ScaledMatrixSpace* owner_space);
/** Destructor */
~ScaledMatrix();
//@}
/** Set the unscaled matrix */
void SetUnscaledMatrix(const SmartPtr<const Matrix> unscaled_matrix);
/** Set the unscaled matrix in a non-const version */
void SetUnscaledMatrixNonConst(const SmartPtr<Matrix>& unscaled_matrix);
/** Return the unscaled matrix in const form */
SmartPtr<const Matrix> GetUnscaledMatrix() const;
/** Return the unscaled matrix in non-const form */
SmartPtr<Matrix> GetUnscaledMatrixNonConst();
/** return the vector for the row scaling */
SmartPtr<const Vector> RowScaling() const;
/** return the vector for the column scaling */
SmartPtr<const Vector> ColumnScaling() const;
protected:
/**@name Methods overloaded from Matrix */
//@{
virtual void MultVectorImpl(Number alpha, const Vector& x,
Number beta, Vector& y) const;
virtual void TransMultVectorImpl(Number alpha, const Vector& x,
Number beta, Vector& y) const;
/** Method for determining if all stored numbers are valid (i.e.,
* no Inf or Nan). It is assumed that the scaling factors are
* valid. */
virtual bool HasValidNumbersImpl() const;
virtual void ComputeRowAMaxImpl(Vector& rows_norms, bool init) const;
virtual void ComputeColAMaxImpl(Vector& cols_norms, bool init) const;
virtual void PrintImpl(const Journalist& jnlst,
EJournalLevel level,
EJournalCategory category,
const std::string& name,
Index indent,
const std::string& prefix) const;
/** X = beta*X + alpha*(Matrix S^{-1} Z). Specialized
* implementation missing so far!
*/
virtual void AddMSinvZImpl(Number alpha, const Vector& S, const Vector& Z,
Vector& X) const;
/** X = S^{-1} (r + alpha*Z*M^Td). Specialized implementation
* missing so far!
*/
virtual void SinvBlrmZMTdBrImpl(Number alpha, const Vector& S,
const Vector& R, const Vector& Z,
const Vector& D, Vector& X) const;
//@}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
ScaledMatrix();
/** Copy Constructor */
ScaledMatrix(const ScaledMatrix&);
/** Overloaded Equals Operator */
void operator=(const ScaledMatrix&);
//@}
/** const version of the unscaled matrix */
SmartPtr<const Matrix> matrix_;
/** non-const version of the unscaled matrix */
SmartPtr<Matrix> nonconst_matrix_;
/** Matrix space stored as a ScaledMatrixSpace */
SmartPtr<const ScaledMatrixSpace> owner_space_;
};
/** This is the matrix space for ScaledMatrix.
*/
class ScaledMatrixSpace : public MatrixSpace
{
public:
/** @name Constructors / Destructors */
//@{
/** Constructor, given the number of row and columns blocks, as
* well as the totel number of rows and columns.
*/
ScaledMatrixSpace(const SmartPtr<const Vector>& row_scaling,
bool row_scaling_reciprocal,
const SmartPtr<const MatrixSpace>& unscaled_matrix_space,
const SmartPtr<const Vector>& column_scaling,
bool column_scaling_reciprocal);
/** Destructor */
~ScaledMatrixSpace()
{}
//@}
/** Method for creating a new matrix of this specific type. */
ScaledMatrix* MakeNewScaledMatrix(bool allocate_unscaled_matrix = false) const
{
ScaledMatrix* ret = new ScaledMatrix(this);
if (allocate_unscaled_matrix) {
SmartPtr<Matrix> unscaled_matrix = unscaled_matrix_space_->MakeNew();
ret->SetUnscaledMatrixNonConst(unscaled_matrix);
}
return ret;
}
/** Overloaded MakeNew method for the MatrixSpace base class.
*/
virtual Matrix* MakeNew() const
{
return MakeNewScaledMatrix();
}
/** return the vector for the row scaling */
SmartPtr<const Vector> RowScaling() const
{
return ConstPtr(row_scaling_);
}
/** return the matrix space for the unscaled matrix */
SmartPtr<const MatrixSpace> UnscaledMatrixSpace() const
{
return unscaled_matrix_space_;
}
/** return the vector for the column scaling */
SmartPtr<const Vector> ColumnScaling() const
{
return ConstPtr(column_scaling_);
}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default constructor */
ScaledMatrixSpace();
/** Copy Constructor */
ScaledMatrixSpace(const ScaledMatrixSpace&);
/** Overloaded Equals Operator */
ScaledMatrixSpace& operator=(const ScaledMatrixSpace&);
//@}
/** Row scaling vector */
SmartPtr<Vector> row_scaling_;
/** unscaled matrix space */
SmartPtr<const MatrixSpace> unscaled_matrix_space_;
/** column scaling vector */
SmartPtr<Vector> column_scaling_;
};
inline
void ScaledMatrix::SetUnscaledMatrix(const SmartPtr<const Matrix> unscaled_matrix)
{
matrix_ = unscaled_matrix;
nonconst_matrix_ = NULL;
ObjectChanged();
}
inline
void ScaledMatrix::SetUnscaledMatrixNonConst(const SmartPtr<Matrix>& unscaled_matrix)
{
nonconst_matrix_ = unscaled_matrix;
matrix_ = GetRawPtr(unscaled_matrix);
ObjectChanged();
}
inline
SmartPtr<const Matrix> ScaledMatrix::GetUnscaledMatrix() const
{
return matrix_;
}
inline
SmartPtr<Matrix> ScaledMatrix::GetUnscaledMatrixNonConst()
{
DBG_ASSERT(IsValid(nonconst_matrix_));
ObjectChanged();
return nonconst_matrix_;
}
inline
SmartPtr<const Vector> ScaledMatrix::RowScaling() const
{
return ConstPtr(owner_space_->RowScaling());
}
inline
SmartPtr<const Vector> ScaledMatrix::ColumnScaling() const
{
return ConstPtr(owner_space_->ColumnScaling());
}
} // namespace Ipopt
#endif
+65
View File
@@ -0,0 +1,65 @@
// Copyright (C) 2005, 2007 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpSearchDirCalculator.hpp 1861 2010-12-21 21:34:47Z andreasw $
//
// Authors: Andreas Waechter IBM 2005-10-13
#ifndef __IPSEARCHDIRCALCULATOR_HPP__
#define __IPSEARCHDIRCALCULATOR_HPP__
#include "IpAlgStrategy.hpp"
namespace Ipopt
{
/** Base class for computing the search direction for the line
* search.
*/
class SearchDirectionCalculator : public AlgorithmStrategyObject
{
public:
/**@name Constructors/Destructors */
//@{
/** Constructor */
SearchDirectionCalculator()
{}
/** Default destructor */
virtual ~SearchDirectionCalculator()
{}
//@}
/** overloaded from AlgorithmStrategyObject */
virtual bool InitializeImpl(const OptionsList& options,
const std::string& prefix) = 0;
/** Pure virtual method for computing the search direction. The
* computed direction is stored in IpData().delta().*/
virtual bool ComputeSearchDirection()=0;
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
// SearchDirectionCalculator();
/** Copy Constructor */
SearchDirectionCalculator(const SearchDirectionCalculator&);
/** Overloaded Equals Operator */
void operator=(const SearchDirectionCalculator&);
//@}
};
} // namespace Ipopt
#endif
+734
View File
@@ -0,0 +1,734 @@
// Copyright (C) 2004, 2011 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpSmartPtr.hpp 2182 2013-03-30 20:02:18Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPSMARTPTR_HPP__
#define __IPSMARTPTR_HPP__
#include "IpReferenced.hpp"
#include "IpDebug.hpp"
#if COIN_IPOPT_CHECKLEVEL > 2
# define IP_DEBUG_SMARTPTR
#endif
#ifndef IPOPT_UNUSED
# if defined(__GNUC__)
# define IPOPT_UNUSED __attribute__((unused))
# else
# define IPOPT_UNUSED
# endif
#endif
namespace Ipopt
{
/** Template class for Smart Pointers.
* A SmartPtr behaves much like a raw pointer, but manages the lifetime
* of an object, deleting the object automatically. This class implements
* a reference-counting, intrusive smart pointer design, where all
* objects pointed to must inherit off of ReferencedObject, which
* stores the reference count. Although this is intrusive (native types
* and externally authored classes require wrappers to be referenced
* by smart pointers), it is a safer design. A more detailed discussion of
* these issues follows after the usage information.
*
* Usage Example:
* Note: to use the SmartPtr, all objects to which you point MUST
* inherit off of ReferencedObject.
*
* \verbatim
*
* In MyClass.hpp...
*
* #include "IpReferenced.hpp"
* namespace Ipopt {
*
* class MyClass : public ReferencedObject // must derive from ReferencedObject
* {
* ...
* }
* } // namespace Ipopt
*
*
* In my_usage.cpp...
*
* #include "IpSmartPtr.hpp"
* #include "MyClass.hpp"
*
* void func(AnyObject& obj)
* {
* SmartPtr<MyClass> ptr_to_myclass = new MyClass(...);
* // ptr_to_myclass now points to a new MyClass,
* // and the reference count is 1
*
* ...
*
* obj.SetMyClass(ptr_to_myclass);
* // Here, let's assume that AnyObject uses a
* // SmartPtr<MyClass> internally here.
* // Now, both ptr_to_myclass and the internal
* // SmartPtr in obj point to the same MyClass object
* // and its reference count is 2.
*
* ...
*
* // No need to delete ptr_to_myclass, this
* // will be done automatically when the
* // reference count drops to zero.
*
* }
*
* \endverbatim
*
* It is not necessary to use SmartPtr's in all cases where an
* object is used that has been allocated "into" a SmartPtr. It is
* possible to just pass objects by reference or regular pointers,
* even if lower down in the stack a SmartPtr is to be held on to.
* Everything should work fine as long as a pointer created by "new"
* is immediately passed into a SmartPtr, and if SmartPtr's are used
* to hold on to objects.
*
* Other Notes:
* The SmartPtr implements both dereference operators -> & *.
* The SmartPtr does NOT implement a conversion operator to
* the raw pointer. Use the GetRawPtr() method when this
* is necessary. Make sure that the raw pointer is NOT
* deleted.
* The SmartPtr implements the comparison operators == & !=
* for a variety of types. Use these instead of
* \verbatim
* if (GetRawPtr(smrt_ptr) == ptr) // Don't use this
* \endverbatim
* SmartPtr's, as currently implemented, do NOT handle circular references.
* For example: consider a higher level object using SmartPtrs to point to
* A and B, but A and B also point to each other (i.e. A has a SmartPtr
* to B and B has a SmartPtr to A). In this scenario, when the higher
* level object is finished with A and B, their reference counts will
* never drop to zero (since they reference each other) and they
* will not be deleted. This can be detected by memory leak tools like
* valgrind. If the circular reference is necessary, the problem can be
* overcome by a number of techniques:
*
* 1) A and B can have a method that "releases" each other, that is
* they set their internal SmartPtrs to NULL.
* \verbatim
* void AClass::ReleaseCircularReferences()
* {
* smart_ptr_to_B = NULL;
* }
* \endverbatim
* Then, the higher level class can call these methods before
* it is done using A & B.
*
* 2) Raw pointers can be used in A and B to reference each other.
* Here, an implicit assumption is made that the lifetime is
* controlled by the higher level object and that A and B will
* both exist in a controlled manner. Although this seems
* dangerous, in many situations, this type of referencing
* is very controlled and this is reasonably safe.
*
* 3) This SmartPtr class could be redesigned with the Weak/Strong
* design concept. Here, the SmartPtr is identified as being
* Strong (controls lifetime of the object) or Weak (merely
* referencing the object). The Strong SmartPtr increments
* (and decrements) the reference count in ReferencedObject
* but the Weak SmartPtr does not. In the example above,
* the higher level object would have Strong SmartPtrs to
* A and B, but A and B would have Weak SmartPtrs to each
* other. Then, when the higher level object was done with
* A and B, they would be deleted. The Weak SmartPtrs in A
* and B would not decrement the reference count and would,
* of course, not delete the object. This idea is very similar
* to item (2), where it is implied that the sequence of events
* is controlled such that A and B will not call anything using
* their pointers following the higher level delete (i.e. in
* their destructors!). This is somehow safer, however, because
* code can be written (however expensive) to perform run-time
* detection of this situation. For example, the ReferencedObject
* could store pointers to all Weak SmartPtrs that are referencing
* it and, in its destructor, tell these pointers that it is
* dying. They could then set themselves to NULL, or set an
* internal flag to detect usage past this point.
*
* Comments on Non-Intrusive Design:
* In a non-intrusive design, the reference count is stored somewhere other
* than the object being referenced. This means, unless the reference
* counting pointer is the first referencer, it must get a pointer to the
* referenced object from another smart pointer (so it has access to the
* reference count location). In this non-intrusive design, if we are
* pointing to an object with a smart pointer (or a number of smart
* pointers), and we then give another smart pointer the address through
* a RAW pointer, we will have two independent, AND INCORRECT, reference
* counts. To avoid this pitfall, we use an intrusive reference counting
* technique where the reference count is stored in the object being
* referenced.
*/
template<class T>
class SmartPtr : public Referencer
{
public:
#define ipopt_dbg_smartptr_verbosity 0
/**@name Constructors/Destructors */
//@{
/** Default constructor, initialized to NULL */
SmartPtr();
/** Copy constructor, initialized from copy of type T */
SmartPtr(const SmartPtr<T>& copy);
/** Copy constructor, initialized from copy of type U */
template <class U>
SmartPtr(const SmartPtr<U>& copy);
/** Constructor, initialized from T* ptr */
SmartPtr(T* ptr);
/** Destructor, automatically decrements the
* reference count, deletes the object if
* necessary.*/
~SmartPtr();
//@}
/**@name Overloaded operators. */
//@{
/** Overloaded arrow operator, allows the user to call
* methods using the contained pointer. */
T* operator->() const;
/** Overloaded dereference operator, allows the user
* to dereference the contained pointer. */
T& operator*() const;
/** Overloaded equals operator, allows the user to
* set the value of the SmartPtr from a raw pointer */
SmartPtr<T>& operator=(T* rhs);
/** Overloaded equals operator, allows the user to
* set the value of the SmartPtr from another
* SmartPtr */
SmartPtr<T>& operator=(const SmartPtr<T>& rhs);
/** Overloaded equals operator, allows the user to
* set the value of the SmartPtr from another
* SmartPtr of a different type */
template <class U>
SmartPtr<T>& operator=(const SmartPtr<U>& rhs);
/** Overloaded equality comparison operator, allows the
* user to compare the value of two SmartPtrs */
template <class U1, class U2>
friend
bool operator==(const SmartPtr<U1>& lhs, const SmartPtr<U2>& rhs);
/** Overloaded equality comparison operator, allows the
* user to compare the value of a SmartPtr with a raw pointer. */
template <class U1, class U2>
friend
bool operator==(const SmartPtr<U1>& lhs, U2* raw_rhs);
/** Overloaded equality comparison operator, allows the
* user to compare the value of a raw pointer with a SmartPtr. */
template <class U1, class U2>
friend
bool operator==(U1* lhs, const SmartPtr<U2>& raw_rhs);
/** Overloaded in-equality comparison operator, allows the
* user to compare the value of two SmartPtrs */
template <class U1, class U2>
friend
bool operator!=(const SmartPtr<U1>& lhs, const SmartPtr<U2>& rhs);
/** Overloaded in-equality comparison operator, allows the
* user to compare the value of a SmartPtr with a raw pointer. */
template <class U1, class U2>
friend
bool operator!=(const SmartPtr<U1>& lhs, U2* raw_rhs);
/** Overloaded in-equality comparison operator, allows the
* user to compare the value of a SmartPtr with a raw pointer. */
template <class U1, class U2>
friend
bool operator!=(U1* lhs, const SmartPtr<U2>& raw_rhs);
/** Overloaded less-than comparison operator, allows the
* user to compare the value of two SmartPtrs */
template <class U>
friend
bool operator<(const SmartPtr<U>& lhs, const SmartPtr<U>& rhs);
//@}
/**@name friend method declarations. */
//@{
/** Returns the raw pointer contained.
* Use to get the value of
* the raw ptr (i.e. to pass to other
* methods/functions, etc.)
* Note: This method does NOT copy,
* therefore, modifications using this
* value modify the underlying object
* contained by the SmartPtr,
* NEVER delete this returned value.
*/
template <class U>
friend
U* GetRawPtr(const SmartPtr<U>& smart_ptr);
/** Returns a const pointer */
template <class U>
friend
SmartPtr<const U> ConstPtr(const SmartPtr<U>& smart_ptr);
/** Returns true if the SmartPtr is NOT NULL.
* Use this to check if the SmartPtr is not null
* This is preferred to if(GetRawPtr(sp) != NULL)
*/
template <class U>
friend
bool IsValid(const SmartPtr<U>& smart_ptr);
/** Returns true if the SmartPtr is NULL.
* Use this to check if the SmartPtr IsNull.
* This is preferred to if(GetRawPtr(sp) == NULL)
*/
template <class U>
friend
bool IsNull(const SmartPtr<U>& smart_ptr);
//@}
private:
/**@name Private Data/Methods */
//@{
/** Actual raw pointer to the object. */
T* ptr_;
/** Set the value of the internal raw pointer
* from another raw pointer, releasing the
* previously referenced object if necessary. */
SmartPtr<T>& SetFromRawPtr_(T* rhs);
/** Set the value of the internal raw pointer
* from a SmartPtr, releasing the previously referenced
* object if necessary. */
SmartPtr<T>& SetFromSmartPtr_(const SmartPtr<T>& rhs);
/** Release the currently referenced object. */
void ReleasePointer_();
//@}
};
/**@name SmartPtr friend function declarations.*/
//@{
template <class U>
U* GetRawPtr(const SmartPtr<U>& smart_ptr);
template <class U>
SmartPtr<const U> ConstPtr(const SmartPtr<U>& smart_ptr);
template <class U>
bool IsNull(const SmartPtr<U>& smart_ptr);
template <class U>
bool IsValid(const SmartPtr<U>& smart_ptr);
template <class U1, class U2>
bool operator==(const SmartPtr<U1>& lhs, const SmartPtr<U2>& rhs);
template <class U1, class U2>
bool operator==(const SmartPtr<U1>& lhs, U2* raw_rhs);
template <class U1, class U2>
bool operator==(U1* lhs, const SmartPtr<U2>& raw_rhs);
template <class U1, class U2>
bool operator!=(const SmartPtr<U1>& lhs, const SmartPtr<U2>& rhs);
template <class U1, class U2>
bool operator!=(const SmartPtr<U1>& lhs, U2* raw_rhs);
template <class U1, class U2>
bool operator!=(U1* lhs, const SmartPtr<U2>& raw_rhs);
//@}
template <class T>
SmartPtr<T>::SmartPtr()
:
ptr_(0)
{
#ifdef IP_DEBUG_SMARTPTR
DBG_START_METH("SmartPtr<T>::SmartPtr()", ipopt_dbg_smartptr_verbosity);
#endif
#ifndef NDEBUG
const ReferencedObject* IPOPT_UNUSED trying_to_use_SmartPtr_with_an_object_that_does_not_inherit_from_ReferencedObject_ = ptr_;
#endif
}
template <class T>
SmartPtr<T>::SmartPtr(const SmartPtr<T>& copy)
:
ptr_(0)
{
#ifdef IP_DEBUG_SMARTPTR
DBG_START_METH("SmartPtr<T>::SmartPtr(const SmartPtr<T>& copy)", ipopt_dbg_smartptr_verbosity);
#endif
#ifndef NDEBUG
const ReferencedObject* IPOPT_UNUSED trying_to_use_SmartPtr_with_an_object_that_does_not_inherit_from_ReferencedObject_ = ptr_;
#endif
(void) SetFromSmartPtr_(copy);
}
template <class T>
template <class U>
SmartPtr<T>::SmartPtr(const SmartPtr<U>& copy)
:
ptr_(0)
{
#ifdef IP_DEBUG_SMARTPTR
DBG_START_METH("SmartPtr<T>::SmartPtr(const SmartPtr<U>& copy)", ipopt_dbg_smartptr_verbosity);
#endif
#ifndef NDEBUG
const ReferencedObject* IPOPT_UNUSED trying_to_use_SmartPtr_with_an_object_that_does_not_inherit_from_ReferencedObject_ = ptr_;
#endif
(void) SetFromSmartPtr_(GetRawPtr(copy));
}
template <class T>
SmartPtr<T>::SmartPtr(T* ptr)
:
ptr_(0)
{
#ifdef IP_DEBUG_SMARTPTR
DBG_START_METH("SmartPtr<T>::SmartPtr(T* ptr)", ipopt_dbg_smartptr_verbosity);
#endif
#ifndef NDEBUG
const ReferencedObject* IPOPT_UNUSED trying_to_use_SmartPtr_with_an_object_that_does_not_inherit_from_ReferencedObject_ = ptr_;
#endif
(void) SetFromRawPtr_(ptr);
}
template <class T>
SmartPtr<T>::~SmartPtr()
{
#ifdef IP_DEBUG_SMARTPTR
DBG_START_METH("SmartPtr<T>::~SmartPtr(T* ptr)", ipopt_dbg_smartptr_verbosity);
#endif
ReleasePointer_();
}
template <class T>
T* SmartPtr<T>::operator->() const
{
#ifdef IP_DEBUG_SMARTPTR
DBG_START_METH("T* SmartPtr<T>::operator->()", ipopt_dbg_smartptr_verbosity);
#endif
// cannot deref a null pointer
#if COIN_IPOPT_CHECKLEVEL > 0
assert(ptr_);
#endif
return ptr_;
}
template <class T>
T& SmartPtr<T>::operator*() const
{
#ifdef IP_DEBUG_SMARTPTR
DBG_START_METH("T& SmartPtr<T>::operator*()", ipopt_dbg_smartptr_verbosity);
#endif
// cannot dereference a null pointer
#if COIN_IPOPT_CHECKLEVEL > 0
assert(ptr_);
#endif
return *ptr_;
}
template <class T>
SmartPtr<T>& SmartPtr<T>::operator=(T* rhs)
{
#ifdef IP_DEBUG_SMARTPTR
DBG_START_METH("SmartPtr<T>& SmartPtr<T>::operator=(T* rhs)", ipopt_dbg_smartptr_verbosity);
#endif
return SetFromRawPtr_(rhs);
}
template <class T>
SmartPtr<T>& SmartPtr<T>::operator=(const SmartPtr<T>& rhs)
{
#ifdef IP_DEBUG_SMARTPTR
DBG_START_METH(
"SmartPtr<T>& SmartPtr<T>::operator=(const SmartPtr<T>& rhs)",
ipopt_dbg_smartptr_verbosity);
#endif
return SetFromSmartPtr_(rhs);
}
template <class T>
template <class U>
SmartPtr<T>& SmartPtr<T>::operator=(const SmartPtr<U>& rhs)
{
#ifdef IP_DEBUG_SMARTPTR
DBG_START_METH(
"SmartPtr<T>& SmartPtr<T>::operator=(const SmartPtr<U>& rhs)",
ipopt_dbg_smartptr_verbosity);
#endif
return SetFromSmartPtr_(GetRawPtr(rhs));
}
template <class T>
SmartPtr<T>& SmartPtr<T>::SetFromRawPtr_(T* rhs)
{
#ifdef IP_DEBUG_SMARTPTR
DBG_START_METH(
"SmartPtr<T>& SmartPtr<T>::SetFromRawPtr_(T* rhs)", ipopt_dbg_smartptr_verbosity);
#endif
if (rhs != 0)
rhs->AddRef(this);
// Release any old pointer
ReleasePointer_();
ptr_ = rhs;
return *this;
}
template <class T>
SmartPtr<T>& SmartPtr<T>::SetFromSmartPtr_(const SmartPtr<T>& rhs)
{
#ifdef IP_DEBUG_SMARTPTR
DBG_START_METH(
"SmartPtr<T>& SmartPtr<T>::SetFromSmartPtr_(const SmartPtr<T>& rhs)",
ipopt_dbg_smartptr_verbosity);
#endif
SetFromRawPtr_(GetRawPtr(rhs));
return (*this);
}
template <class T>
void SmartPtr<T>::ReleasePointer_()
{
#ifdef IP_DEBUG_SMARTPTR
DBG_START_METH(
"void SmartPtr<T>::ReleasePointer()",
ipopt_dbg_smartptr_verbosity);
#endif
if (ptr_) {
ptr_->ReleaseRef(this);
if (ptr_->ReferenceCount() == 0)
delete ptr_;
}
}
template <class U>
U* GetRawPtr(const SmartPtr<U>& smart_ptr)
{
#ifdef IP_DEBUG_SMARTPTR
DBG_START_FUN(
"T* GetRawPtr(const SmartPtr<T>& smart_ptr)",
0);
#endif
return smart_ptr.ptr_;
}
template <class U>
SmartPtr<const U> ConstPtr(const SmartPtr<U>& smart_ptr)
{
// compiler should implicitly cast
return GetRawPtr(smart_ptr);
}
template <class U>
bool IsValid(const SmartPtr<U>& smart_ptr)
{
return !IsNull(smart_ptr);
}
template <class U>
bool IsNull(const SmartPtr<U>& smart_ptr)
{
#ifdef IP_DEBUG_SMARTPTR
DBG_START_FUN(
"bool IsNull(const SmartPtr<T>& smart_ptr)",
0);
#endif
return (smart_ptr.ptr_ == 0);
}
template <class U1, class U2>
bool ComparePointers(const U1* lhs, const U2* rhs)
{
#ifdef IP_DEBUG_SMARTPTR
DBG_START_FUN(
"bool ComparePtrs(const U1* lhs, const U2* rhs)",
ipopt_dbg_smartptr_verbosity);
#endif
// Even if lhs and rhs point to the same object
// with different interfaces U1 and U2, we cannot guarantee that
// the value of the pointers will be equivalent. We can
// guarantee this if we convert to ReferencedObject* (see also #162)
const ReferencedObject* v_lhs = lhs;
const ReferencedObject* v_rhs = rhs;
return v_lhs == v_rhs;
}
template <class U1, class U2>
bool operator==(const SmartPtr<U1>& lhs, const SmartPtr<U2>& rhs)
{
#ifdef IP_DEBUG_SMARTPTR
DBG_START_FUN(
"bool operator==(const SmartPtr<U1>& lhs, const SmartPtr<U2>& rhs)",
ipopt_dbg_smartptr_verbosity);
#endif
U1* raw_lhs = GetRawPtr(lhs);
U2* raw_rhs = GetRawPtr(rhs);
return ComparePointers(raw_lhs, raw_rhs);
}
template <class U1, class U2>
bool operator==(const SmartPtr<U1>& lhs, U2* raw_rhs)
{
#ifdef IP_DEBUG_SMARTPTR
DBG_START_FUN(
"bool operator==(SmartPtr<U1>& lhs, U2* rhs)",
ipopt_dbg_smartptr_verbosity);
#endif
U1* raw_lhs = GetRawPtr(lhs);
return ComparePointers(raw_lhs, raw_rhs);
}
template <class U1, class U2>
bool operator==(U1* raw_lhs, const SmartPtr<U2>& rhs)
{
#ifdef IP_DEBUG_SMARTPTR
DBG_START_FUN(
"bool operator==(U1* raw_lhs, SmartPtr<U2>& rhs)",
ipopt_dbg_smartptr_verbosity);
#endif
const U2* raw_rhs = GetRawPtr(rhs);
return ComparePointers(raw_lhs, raw_rhs);
}
template <class U1, class U2>
bool operator!=(const SmartPtr<U1>& lhs, const SmartPtr<U2>& rhs)
{
#ifdef IP_DEBUG_SMARTPTR
DBG_START_FUN(
"bool operator!=(const SmartPtr<U1>& lhs, const SmartPtr<U2>& rhs)",
ipopt_dbg_smartptr_verbosity);
#endif
bool retValue = operator==(lhs, rhs);
return !retValue;
}
template <class U1, class U2>
bool operator!=(const SmartPtr<U1>& lhs, U2* raw_rhs)
{
#ifdef IP_DEBUG_SMARTPTR
DBG_START_FUN(
"bool operator!=(SmartPtr<U1>& lhs, U2* rhs)",
ipopt_dbg_smartptr_verbosity);
#endif
bool retValue = operator==(lhs, raw_rhs);
return !retValue;
}
template <class U1, class U2>
bool operator!=(U1* raw_lhs, const SmartPtr<U2>& rhs)
{
#ifdef IP_DEBUG_SMARTPTR
DBG_START_FUN(
"bool operator!=(U1* raw_lhs, SmartPtr<U2>& rhs)",
ipopt_dbg_smartptr_verbosity);
#endif
bool retValue = operator==(raw_lhs, rhs);
return !retValue;
}
template <class T>
void swap(SmartPtr<T>& a, SmartPtr<T>& b)
{
#ifdef IP_DEBUG_REFERENCED
SmartPtr<T> tmp(a);
a = b;
b = tmp;
#else
std::swap(a.prt_, b.ptr_);
#endif
}
template <class T>
bool operator<(const SmartPtr<T>& lhs, const SmartPtr<T>& rhs)
{
return lhs.ptr_ < rhs.ptr_;
}
template <class T>
bool operator> (const SmartPtr<T>& lhs, const SmartPtr<T>& rhs)
{
return rhs < lhs;
}
template <class T> bool
operator<=(const SmartPtr<T>& lhs, const SmartPtr<T>& rhs)
{
return !( rhs < lhs );
}
template <class T> bool
operator>=(const SmartPtr<T>& lhs, const SmartPtr<T>& rhs)
{
return !( lhs < rhs );
}
} // namespace Ipopt
#undef ipopt_dbg_smartptr_verbosity
#endif
+150
View File
@@ -0,0 +1,150 @@
// Copyright (C) 2005, 2009 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpSolveStatistics.hpp 1861 2010-12-21 21:34:47Z andreasw $
//
// Authors: Carl Laird, Andreas Waechter IBM 2005-08-15
#ifndef __IPSOLVESTATISTICS_HPP__
#define __IPSOLVESTATISTICS_HPP__
#include "IpReferenced.hpp"
#include "IpSmartPtr.hpp"
namespace Ipopt
{
// forward declaration (to avoid inclusion of too many header files)
class IpoptNLP;
class IpoptData;
class IpoptCalculatedQuantities;
/** This class collects statistics about an optimziation run, such
* as iteration count, final infeasibilities etc. It is meant to
* provide such information to a user of Ipopt during the
* finalize_solution call.
*/
class SolveStatistics : public ReferencedObject
{
public:
/**@name Constructors/Destructors */
//@{
/** Default constructor. It takes in those collecting Ipopt
* objects that can provide the statistics information. Those
* statistics are retrieved at the time of the constructor
* call. */
SolveStatistics(const SmartPtr<IpoptNLP>& ip_nlp,
const SmartPtr<IpoptData>& ip_data,
const SmartPtr<IpoptCalculatedQuantities>& ip_cq);
/** Default destructor */
virtual ~SolveStatistics()
{}
//@}
/** @name Accessor methods for retrieving different kind of solver
* statistics information */
//@{
/** Iteration counts. */
virtual Index IterationCount() const;
/** Total CPU time, including function evaluations. */
virtual Number TotalCpuTime() const;
/** Total CPU time, including function evaluations. Included for
* backward compatibility. */
Number TotalCPUTime() const
{
return TotalCpuTime();
}
/** Total System time, including function evaluations. */
virtual Number TotalSysTime() const;
/** Total wall clock time, including function evaluations. */
virtual Number TotalWallclockTime() const;
/** Number of NLP function evaluations. */
virtual void NumberOfEvaluations(Index& num_obj_evals,
Index& num_constr_evals,
Index& num_obj_grad_evals,
Index& num_constr_jac_evals,
Index& num_hess_evals) const;
/** Unscaled solution infeasibilities */
virtual void Infeasibilities(Number& dual_inf,
Number& constr_viol,
Number& complementarity,
Number& kkt_error) const;
/** Scaled solution infeasibilities */
virtual void ScaledInfeasibilities(Number& scaled_dual_inf,
Number& scaled_constr_viol,
Number& scaled_complementarity,
Number& scaled_kkt_error) const;
/** Final value of objective function */
virtual Number FinalObjective() const;
/** Final scaled value of objective function */
virtual Number FinalScaledObjective() const;
//@}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
SolveStatistics();
/** Copy Constructor */
SolveStatistics(const SolveStatistics&);
/** Overloaded Equals Operator */
void operator=(const SolveStatistics&);
//@}
/** @name Fields for storing the statistics data */
//@{
/** Number of iterations. */
Index num_iters_;
/* Total CPU time */
Number total_cpu_time_;
/* Total system time */
Number total_sys_time_;
/* Total wall clock time */
Number total_wallclock_time_;
/** Number of objective function evaluations. */
Index num_obj_evals_;
/** Number of constraints evaluations (max of equality and
* inequality) */
Index num_constr_evals_;
/** Number of objective gradient evaluations. */
Index num_obj_grad_evals_;
/** Number of constraint Jacobian evaluations. */
Index num_constr_jac_evals_;
/** Number of Lagrangian Hessian evaluations. */
Index num_hess_evals_;
/** Final scaled value of objective function */
Number scaled_obj_val_;
/** Final unscaled value of objective function */
Number obj_val_;
/** Final scaled dual infeasibility (max-norm) */
Number scaled_dual_inf_;
/** Final unscaled dual infeasibility (max-norm) */
Number dual_inf_;
/** Final scaled constraint violation (max-norm) */
Number scaled_constr_viol_;
/** Final unscaled constraint violation (max-norm) */
Number constr_viol_;
/** Final scaled complementarity error (max-norm) */
Number scaled_compl_;
/** Final unscaled complementarity error (max-norm) */
Number compl_;
/** Final overall scaled KKT error (max-norm) */
Number scaled_kkt_error_;
/** Final overall unscaled KKT error (max-norm) */
Number kkt_error_;
//@}
};
} // namespace Ipopt
#endif
+271
View File
@@ -0,0 +1,271 @@
/*************************************************************************
Copyright (C) 2004, 2010 International Business Machines and others.
All Rights Reserved.
This code is published under the Eclipse Public License.
$Id: IpStdCInterface.h 2082 2012-02-16 03:00:34Z andreasw $
Authors: Carl Laird, Andreas Waechter IBM 2004-09-02
*************************************************************************/
#ifndef __IPSTDCINTERFACE_H__
#define __IPSTDCINTERFACE_H__
#ifndef IPOPT_EXPORT
#ifdef _MSC_VER
#ifdef IPOPT_DLL
#define IPOPT_EXPORT(type) __declspec(dllexport) type __cdecl
#else
#define IPOPT_EXPORT(type) type __cdecl
#endif
#else
#define IPOPT_EXPORT(type) type
#endif
#endif
#ifdef __cplusplus
extern "C"
{
#endif
/** Type for all number. We need to make sure that this is
identical with what is defined in Common/IpTypes.hpp */
typedef double Number;
/** Type for all incides. We need to make sure that this is
identical with what is defined in Common/IpTypes.hpp */
typedef int Index;
/** Type for all integers. We need to make sure that this is
identical with what is defined in Common/IpTypes.hpp */
typedef int Int;
/* This includes the SolverReturn enum type */
#include "IpReturnCodes.h"
/** Structure collecting all information about the problem
* definition and solve statistics etc. This is defined in the
* source file. */
struct IpoptProblemInfo;
/** Pointer to a Ipopt Problem. */
typedef struct IpoptProblemInfo* IpoptProblem;
/** define a boolean type for C */
typedef int Bool;
#ifndef TRUE
# define TRUE (1)
#endif
#ifndef FALSE
# define FALSE (0)
#endif
/** A pointer for anything that is to be passed between the called
* and individual callback function */
typedef void * UserDataPtr;
/** Type defining the callback function for evaluating the value of
* the objective function. Return value should be set to false if
* there was a problem doing the evaluation. */
typedef Bool (*Eval_F_CB)(Index n, Number* x, Bool new_x,
Number* obj_value, UserDataPtr user_data);
/** Type defining the callback function for evaluating the gradient of
* the objective function. Return value should be set to false if
* there was a problem doing the evaluation. */
typedef Bool (*Eval_Grad_F_CB)(Index n, Number* x, Bool new_x,
Number* grad_f, UserDataPtr user_data);
/** Type defining the callback function for evaluating the value of
* the constraint functions. Return value should be set to false if
* there was a problem doing the evaluation. */
typedef Bool (*Eval_G_CB)(Index n, Number* x, Bool new_x,
Index m, Number* g, UserDataPtr user_data);
/** Type defining the callback function for evaluating the Jacobian of
* the constrant functions. Return value should be set to false if
* there was a problem doing the evaluation. */
typedef Bool (*Eval_Jac_G_CB)(Index n, Number *x, Bool new_x,
Index m, Index nele_jac,
Index *iRow, Index *jCol, Number *values,
UserDataPtr user_data);
/** Type defining the callback function for evaluating the Hessian of
* the Lagrangian function. Return value should be set to false if
* there was a problem doing the evaluation. */
typedef Bool (*Eval_H_CB)(Index n, Number *x, Bool new_x, Number obj_factor,
Index m, Number *lambda, Bool new_lambda,
Index nele_hess, Index *iRow, Index *jCol,
Number *values, UserDataPtr user_data);
/** Type defining the callback function for giving intermediate
* execution control to the user. If set, it is called once per
* iteration, providing the user with some information on the state
* of the optimization. This can be used to print some
* user-defined output. It also gives the user a way to terminate
* the optimization prematurely. If this method returns false,
* Ipopt will terminate the optimization. */
typedef Bool (*Intermediate_CB)(Index alg_mod, /* 0 is regular, 1 is resto */
Index iter_count, Number obj_value,
Number inf_pr, Number inf_du,
Number mu, Number d_norm,
Number regularization_size,
Number alpha_du, Number alpha_pr,
Index ls_trials, UserDataPtr user_data);
/** Function for creating a new Ipopt Problem object. This function
* returns an object that can be passed to the IpoptSolve call. It
* contains the basic definition of the optimization problem, such
* as number of variables and constraints, bounds on variables and
* constraints, information about the derivatives, and the callback
* function for the computation of the optimization problem
* functions and derivatives. During this call, the options file
* PARAMS.DAT is read as well.
*
* If NULL is returned, there was a problem with one of the inputs
* or reading the options file. */
IPOPT_EXPORT(IpoptProblem) CreateIpoptProblem(
Index n /** Number of optimization variables */
, Number* x_L /** Lower bounds on variables. This array of
size n is copied internally, so that the
caller can change the incoming data after
return without that IpoptProblem is
modified. Any value less or equal than
the number specified by option
'nlp_lower_bound_inf' is interpreted to
be minus infinity. */
, Number* x_U /** Upper bounds on variables. This array of
size n is copied internally, so that the
caller can change the incoming data after
return without that IpoptProblem is
modified. Any value greater or equal
than the number specified by option
'nlp_upper_bound_inf' is interpreted to
be plus infinity. */
, Index m /** Number of constraints. */
, Number* g_L /** Lower bounds on constraints. This array of
size m is copied internally, so that the
caller can change the incoming data after
return without that IpoptProblem is
modified. Any value less or equal than
the number specified by option
'nlp_lower_bound_inf' is interpreted to
be minus infinity. */
, Number* g_U /** Upper bounds on constraints. This array of
size m is copied internally, so that the
caller can change the incoming data after
return without that IpoptProblem is
modified. Any value greater or equal
than the number specified by option
'nlp_upper_bound_inf' is interpreted to
be plus infinity. */
, Index nele_jac /** Number of non-zero elements in constraint
Jacobian. */
, Index nele_hess /** Number of non-zero elements in Hessian of
Lagrangian. */
, Index index_style /** indexing style for iRow & jCol,
0 for C style, 1 for Fortran style */
, Eval_F_CB eval_f /** Callback function for evaluating
objective function */
, Eval_G_CB eval_g /** Callback function for evaluating
constraint functions */
, Eval_Grad_F_CB eval_grad_f
/** Callback function for evaluating gradient
of objective function */
, Eval_Jac_G_CB eval_jac_g
/** Callback function for evaluating Jacobian
of constraint functions */
, Eval_H_CB eval_h /** Callback function for evaluating Hessian
of Lagrangian function */
);
/** Method for freeing a previously created IpoptProblem. After
freeing an IpoptProblem, it cannot be used anymore. */
IPOPT_EXPORT(void) FreeIpoptProblem(IpoptProblem ipopt_problem);
/** Function for adding a string option. Returns FALSE the option
* could not be set (e.g., if keyword is unknown) */
IPOPT_EXPORT(Bool) AddIpoptStrOption(IpoptProblem ipopt_problem, char* keyword, char* val);
/** Function for adding a Number option. Returns FALSE the option
* could not be set (e.g., if keyword is unknown) */
IPOPT_EXPORT(Bool) AddIpoptNumOption(IpoptProblem ipopt_problem, char* keyword, Number val);
/** Function for adding an Int option. Returns FALSE the option
* could not be set (e.g., if keyword is unknown) */
IPOPT_EXPORT(Bool) AddIpoptIntOption(IpoptProblem ipopt_problem, char* keyword, Int val);
/** Function for opening an output file for a given name with given
* printlevel. Returns false, if there was a problem opening the
* file. */
IPOPT_EXPORT(Bool) OpenIpoptOutputFile(IpoptProblem ipopt_problem, char* file_name,
Int print_level);
/** Optional function for setting scaling parameter for the NLP.
* This corresponds to the get_scaling_parameters method in TNLP.
* If the pointers x_scaling or g_scaling are NULL, then no scaling
* for x resp. g is done. */
IPOPT_EXPORT(Bool) SetIpoptProblemScaling(IpoptProblem ipopt_problem,
Number obj_scaling,
Number* x_scaling,
Number* g_scaling);
/** Setting a callback function for the "intermediate callback"
* method in the TNLP. This gives control back to the user once
* per iteration. If set, it provides the user with some
* information on the state of the optimization. This can be used
* to print some user-defined output. It also gives the user a way
* to terminate the optimization prematurely. If the callback
* method returns false, Ipopt will terminate the optimization.
* Calling this set method to set the CB pointer to NULL disables
* the intermediate callback functionality. */
IPOPT_EXPORT(Bool) SetIntermediateCallback(IpoptProblem ipopt_problem,
Intermediate_CB intermediate_cb);
/** Function calling the Ipopt optimization algorithm for a problem
previously defined with CreateIpoptProblem. The return
specified outcome of the optimization procedure (e.g., success,
failure etc).
*/
IPOPT_EXPORT(enum ApplicationReturnStatus) IpoptSolve(
IpoptProblem ipopt_problem
/** Problem that is to be optimized. Ipopt
will use the options previously specified with
AddIpoptOption (etc) for this problem. */
, Number* x /** Input: Starting point
Output: Optimal solution */
, Number* g /** Values of constraint at final point
(output only - ignored if set to NULL) */
, Number* obj_val /** Final value of objective function
(output only - ignored if set to NULL) */
, Number* mult_g /** Input: Initial values for the constraint
multipliers (only if warm start option
is chosen)
Output: Final multipliers for constraints
(ignored if set to NULL) */
, Number* mult_x_L /** Input: Initial values for the multipliers for
lower variable bounds (only if warm start
option is chosen)
Output: Final multipliers for lower variable
bounds (ignored if set to NULL) */
, Number* mult_x_U /** Input: Initial values for the multipliers for
upper variable bounds (only if warm start
option is chosen)
Output: Final multipliers for upper variable
bounds (ignored if set to NULL) */
, UserDataPtr user_data
/** Pointer to user data. This will be
passed unmodified to the callback
functions. */
);
/**
void IpoptStatisticsCounts;
void IpoptStatisticsInfeasibilities; */
#ifdef __cplusplus
} /* extern "C" { */
#endif
#endif
+152
View File
@@ -0,0 +1,152 @@
// Copyright (C) 2004, 2008 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpSumSymMatrix.hpp 2269 2013-05-05 11:32:40Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPSUMSYMMATRIX_HPP__
#define __IPSUMSYMMATRIX_HPP__
#include "IpUtils.hpp"
#include "IpSymMatrix.hpp"
namespace Ipopt
{
/* forward declarations */
class SumSymMatrixSpace;
/** Class for Matrices which are sum of symmetric matrices.
* For each term in the we store the matrix and a factor.
*/
class SumSymMatrix : public SymMatrix
{
public:
/**@name Constructors / Destructors */
//@{
/** Constructor, initializing with dimensions of the matrix and
* the number of terms in the sum.
*/
SumSymMatrix(const SumSymMatrixSpace* owner_space);
/** Destructor */
~SumSymMatrix();
//@}
/** Method for setting term iterm for the sum. Note that counting
* of terms starts at 0. */
void SetTerm(Index iterm, Number factor, const SymMatrix& matrix);
/** Method for getting term iterm for the sum. Note that counting
* of terms starts at 0. */
void GetTerm(Index iterm, Number& factor, SmartPtr<const SymMatrix>& matrix) const;
/** Return the number of terms */
Index NTerms() const;
protected:
/**@name Methods overloaded from matrix */
//@{
virtual void MultVectorImpl(Number alpha, const Vector& x,
Number beta, Vector& y) const;
/** Method for determining if all stored numbers are valid (i.e.,
* no Inf or Nan). */
virtual bool HasValidNumbersImpl() const;
virtual void ComputeRowAMaxImpl(Vector& rows_norms, bool init) const;
virtual void ComputeColAMaxImpl(Vector& cols_norms, bool init) const;
virtual void PrintImpl(const Journalist& jnlst,
EJournalLevel level,
EJournalCategory category,
const std::string& name,
Index indent,
const std::string& prefix) const;
//@}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
SumSymMatrix();
/** Copy Constructor */
SumSymMatrix(const SumSymMatrix&);
/** Overloaded Equals Operator */
void operator=(const SumSymMatrix&);
//@}
/** std::vector storing the factors for each term. */
std::vector<Number> factors_;
/** std::vector storing the matrices for each term. */
std::vector<SmartPtr<const SymMatrix> > matrices_;
/** Copy of the owner_space as a SumSymMatrixSpace */
const SumSymMatrixSpace* owner_space_;
};
/** Class for matrix space for SumSymMatrix */
class SumSymMatrixSpace : public SymMatrixSpace
{
public:
/** @name Constructors / Destructors */
//@{
/** Constructor, given the dimension of the matrix and the number
* of terms in the sum. */
SumSymMatrixSpace(Index ndim, Index nterms)
:
SymMatrixSpace(ndim),
nterms_(nterms)
{}
/** Destructor */
~SumSymMatrixSpace()
{}
//@}
/** @name Accessor functions */
//@{
/** Number of terms in the sum. */
Index NTerms() const
{
return nterms_;
}
//@}
/** Use this method to set the matrix spaces for the various terms.
* You will not be able to create a matrix until all these spaces
* are set. */
void SetTermSpace(Index term_idx, const SymMatrixSpace& space);
/** Get the matix space for a particular term */
SmartPtr<const SymMatrixSpace> GetTermSpace(Index term_idx) const;
/** Method for creating a new matrix of this specific type. */
SumSymMatrix* MakeNewSumSymMatrix() const;
/** Overloaded MakeNew method for the SymMatrixSpace base class.
*/
virtual SymMatrix* MakeNewSymMatrix() const;
private:
Index nterms_;
std::vector< SmartPtr<const SymMatrixSpace> > term_spaces_;
};
} // namespace Ipopt
#endif
+130
View File
@@ -0,0 +1,130 @@
// Copyright (C) 2004, 2006 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpSymLinearSolver.hpp 2322 2013-06-12 17:45:57Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPSYMLINEARSOLVER_HPP__
#define __IPSYMLINEARSOLVER_HPP__
#include "IpUtils.hpp"
#include "IpSymMatrix.hpp"
#include "IpAlgStrategy.hpp"
#include <vector>
namespace Ipopt
{
/** Enum to report outcome of a linear solve */
enum ESymSolverStatus {
/** Successful solve */
SYMSOLVER_SUCCESS,
/** Matrix seems to be singular; solve was aborted */
SYMSOLVER_SINGULAR,
/** The number of negative eigenvalues is not correct */
SYMSOLVER_WRONG_INERTIA,
/** Call the solver interface again after the matrix values have
* been restored */
SYMSOLVER_CALL_AGAIN,
/** Unrecoverable error in linear solver occurred. The
* optimization will be aborted. */
SYMSOLVER_FATAL_ERROR
};
/** Base class for all derived symmetric linear
* solvers. In the full space version of Ipopt a large linear
* system has to be solved for the augmented system. This case is
* meant to be the base class for all derived linear solvers for
* symmetric matrices (of type SymMatrix).
*
* A linear solver can be used repeatedly for matrices with
* identical structure of nonzero elements. The nonzero structure
* of those matrices must not be changed between calls.
*
* The called might ask the solver to only solve the linear system
* if the system is nonsingular, and if the number of negative
* eigenvalues matches a given number.
*/
class SymLinearSolver: public AlgorithmStrategyObject
{
public:
/** @name Constructor/Destructor */
//@{
SymLinearSolver()
{}
virtual ~SymLinearSolver()
{}
//@}
/** overloaded from AlgorithmStrategyObject */
virtual bool InitializeImpl(const OptionsList& options,
const std::string& prefix) = 0;
/** @name Methods for requesting solution of the linear system. */
//@{
/** Solve operation for multiple right hand sides. Solves the
* linear system A * Sol = Rhs with multiple right hand sides. If
* necessary, A is factorized. Correct solutions are only
* guaranteed if the return values is SYMSOLVER_SUCCESS. The
* solver will return SYMSOLVER_SINGULAR if the linear system is
* singular, and it will return SYMSOLVER_WRONG_INERTIA if
* check_NegEVals is true and the number of negative eigenvalues
* in the matrix does not match numberOfNegEVals.
*
* check_NegEVals cannot be chosen true, if ProvidesInertia()
* returns false.
*/
virtual ESymSolverStatus MultiSolve(const SymMatrix &A,
std::vector<SmartPtr<const Vector> >& rhsV,
std::vector<SmartPtr<Vector> >& solV,
bool check_NegEVals,
Index numberOfNegEVals)=0;
/** Solve operation for a single right hand side. Solves the
* linear system A * Sol = Rhs. See MultiSolve for more
* details. */
ESymSolverStatus Solve(const SymMatrix &A,
const Vector& rhs, Vector& sol,
bool check_NegEVals,
Index numberOfNegEVals)
{
std::vector<SmartPtr<const Vector> > rhsV(1);
rhsV[0] = &rhs;
std::vector<SmartPtr<Vector> > solV(1);
solV[0] = &sol;
return MultiSolve(A, rhsV, solV, check_NegEVals,
numberOfNegEVals);
}
/** Number of negative eigenvalues detected during last
* factorization. Returns the number of negative eigenvalues of
* the most recent factorized matrix. This must not be called if
* the linear solver does not compute this quantities (see
* ProvidesInertia).
*/
virtual Index NumberOfNegEVals() const =0;
//@}
//* @name Options of Linear solver */
//@{
/** Request to increase quality of solution for next solve.
* Ask linear solver to increase quality of solution for the next
* solve (e.g. increase pivot tolerance). Returns false, if this
* is not possible (e.g. maximal pivot tolerance already used.)
*/
virtual bool IncreaseQuality() =0;
/** Query whether inertia is computed by linear solver.
* Returns true, if linear solver provides inertia.
*/
virtual bool ProvidesInertia() const =0;
//@}
};
} // namespace Ipopt
#endif
+162
View File
@@ -0,0 +1,162 @@
// Copyright (C) 2004, 2008 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpSymMatrix.hpp 2269 2013-05-05 11:32:40Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPSYMMATRIX_HPP__
#define __IPSYMMATRIX_HPP__
#include "IpUtils.hpp"
#include "IpMatrix.hpp"
namespace Ipopt
{
/* forward declarations */
class SymMatrixSpace;
/** This is the base class for all derived symmetric matrix types.
*/
class SymMatrix : public Matrix
{
public:
/** @name Constructor/Destructor */
//@{
/** Constructor, taking the owner_space.
*/
inline
SymMatrix(const SymMatrixSpace* owner_space);
/** Destructor */
virtual ~SymMatrix()
{}
//@}
/** @name Information about the size of the matrix */
//@{
/** Dimension of the matrix (number of rows and columns) */
inline
Index Dim() const;
//@}
inline
SmartPtr<const SymMatrixSpace> OwnerSymMatrixSpace() const;
protected:
/** @name Overloaded methods from Matrix. */
//@{
/** Since the matrix is
* symmetric, it is only necessary to implement the
* MultVectorImpl method in a class that inherits from this base
* class. If the TransMultVectorImpl is called, this base class
* automatically calls MultVectorImpl instead. */
virtual void TransMultVectorImpl(Number alpha, const Vector& x, Number beta,
Vector& y) const
{
// Since this matrix is symetric, this is the same operation as
// MultVector
MultVector(alpha, x, beta, y);
}
/** Since the matrix is symmetric, the row and column max norms
* are identical */
virtual void ComputeColAMaxImpl(Vector& cols_norms, bool init) const
{
ComputeRowAMaxImpl(cols_norms, init);
}
//@}
private:
/** Copy of the owner space ptr as a SymMatrixSpace instead
* of a MatrixSpace
*/
const SymMatrixSpace* owner_space_;
};
/** SymMatrixSpace base class, corresponding to the SymMatrix base
* class. */
class SymMatrixSpace : public MatrixSpace
{
public:
/** @name Constructors/Destructors */
//@{
/** Constructor, given the dimension (identical to the number of
* rows and columns).
*/
SymMatrixSpace(Index dim)
:
MatrixSpace(dim,dim)
{}
/** Destructor */
virtual ~SymMatrixSpace()
{}
//@}
/** Pure virtual method for creating a new matrix of this specific
* type. */
virtual SymMatrix* MakeNewSymMatrix() const=0;
/** Overloaded MakeNew method for the MatrixSpace base class.
*/
virtual Matrix* MakeNew() const
{
return MakeNewSymMatrix();
}
/** Accessor method for the dimension of the matrices in this
* matrix space.
*/
Index Dim() const
{
DBG_ASSERT(NRows() == NCols());
return NRows();
}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** default constructor */
SymMatrixSpace();
/* Copy constructor */
SymMatrixSpace(const SymMatrixSpace&);
/** Overloaded Equals Operator */
SymMatrixSpace& operator=(const SymMatrixSpace&);
//@}
};
/* inline methods */
inline
SymMatrix::SymMatrix(const SymMatrixSpace* owner_space)
:
Matrix(owner_space),
owner_space_(owner_space)
{}
inline
Index SymMatrix::Dim() const
{
return owner_space_->Dim();
}
inline
SmartPtr<const SymMatrixSpace> SymMatrix::OwnerSymMatrixSpace() const
{
return owner_space_;
}
} // namespace Ipopt
#endif
+230
View File
@@ -0,0 +1,230 @@
// Copyright (C) 2004, 2008 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpSymScaledMatrix.hpp 2269 2013-05-05 11:32:40Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPSYMSCALEDMATRIX_HPP__
#define __IPSYMSCALEDMATRIX_HPP__
#include "IpUtils.hpp"
#include "IpSymMatrix.hpp"
namespace Ipopt
{
/* forward declarations */
class SymScaledMatrixSpace;
/** Class for a Matrix in conjunction with its scaling factors for
* row and column scaling. Operations on the matrix are performed using
* the scaled matrix. You can pull out the pointer to the
* unscaled matrix for unscaled calculations.
*/
class SymScaledMatrix : public SymMatrix
{
public:
/**@name Constructors / Destructors */
//@{
/** Constructor, taking the owner_space.
*/
SymScaledMatrix(const SymScaledMatrixSpace* owner_space);
/** Destructor */
~SymScaledMatrix();
//@}
/** Set the unscaled matrix */
void SetUnscaledMatrix(const SmartPtr<const SymMatrix> unscaled_matrix);
/** Set the unscaled matrix in a non-const version */
void SetUnscaledMatrixNonConst(const SmartPtr<SymMatrix>& unscaled_matrix);
/** Return the unscaled matrix in const form */
SmartPtr<const SymMatrix> GetUnscaledMatrix() const;
/** Return the unscaled matrix in non-const form */
SmartPtr<SymMatrix> GetUnscaledMatrixNonConst();
/** return the vector for the row and column scaling */
SmartPtr<const Vector> RowColScaling() const;
protected:
/**@name Methods overloaded from Matrix */
//@{
virtual void MultVectorImpl(Number alpha, const Vector& x,
Number beta, Vector& y) const;
/** Method for determining if all stored numbers are valid (i.e.,
* no Inf or Nan). It is assumed here that the scaling factors
* are always valid numbers. */
virtual bool HasValidNumbersImpl() const;
virtual void ComputeRowAMaxImpl(Vector& rows_norms, bool init) const;
virtual void PrintImpl(const Journalist& jnlst,
EJournalLevel level,
EJournalCategory category,
const std::string& name,
Index indent,
const std::string& prefix) const;
//@}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
SymScaledMatrix();
/** Copy Constructor */
SymScaledMatrix(const SymScaledMatrix&);
/** Overloaded Equals Operator */
void operator=(const SymScaledMatrix&);
//@}
/** const version of the unscaled matrix */
SmartPtr<const SymMatrix> matrix_;
/** non-const version of the unscaled matrix */
SmartPtr<SymMatrix> nonconst_matrix_;
/** Matrix space stored as a SymScaledMatrixSpace */
SmartPtr<const SymScaledMatrixSpace> owner_space_;
};
/** This is the matrix space for SymScaledMatrix.
*/
class SymScaledMatrixSpace : public SymMatrixSpace
{
public:
/** @name Constructors / Destructors */
//@{
/** Constructor, given the number of row and columns blocks, as
* well as the totel number of rows and columns.
*/
SymScaledMatrixSpace(const SmartPtr<const Vector>& row_col_scaling,
bool row_col_scaling_reciprocal,
const SmartPtr<const SymMatrixSpace>& unscaled_matrix_space)
:
SymMatrixSpace(unscaled_matrix_space->Dim()),
unscaled_matrix_space_(unscaled_matrix_space)
{
scaling_ = row_col_scaling->MakeNewCopy();
if (row_col_scaling_reciprocal) {
scaling_->ElementWiseReciprocal();
}
}
/** Destructor */
~SymScaledMatrixSpace()
{}
//@}
/** Method for creating a new matrix of this specific type. */
SymScaledMatrix* MakeNewSymScaledMatrix(bool allocate_unscaled_matrix = false) const
{
SymScaledMatrix* ret = new SymScaledMatrix(this);
if (allocate_unscaled_matrix) {
SmartPtr<SymMatrix> unscaled_matrix = unscaled_matrix_space_->MakeNewSymMatrix();
ret->SetUnscaledMatrixNonConst(unscaled_matrix);
}
return ret;
}
/** Overloaded method from SymMatrixSpace */
virtual SymMatrix* MakeNewSymMatrix() const
{
return MakeNewSymScaledMatrix();
}
/** Overloaded MakeNew method for the MatrixSpace base class.
*/
virtual Matrix* MakeNew() const
{
return MakeNewSymScaledMatrix();
}
/** return the vector for the row and column scaling */
SmartPtr<const Vector> RowColScaling() const
{
return ConstPtr(scaling_);
}
/** return the matrix space for the unscaled matrix */
SmartPtr<const SymMatrixSpace> UnscaledMatrixSpace() const
{
return unscaled_matrix_space_;
}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default constructor */
SymScaledMatrixSpace();
/** Copy Constructor */
SymScaledMatrixSpace(const SymScaledMatrixSpace&);
/** Overloaded Equals Operator */
SymScaledMatrixSpace& operator=(const SymScaledMatrixSpace&);
//@}
/** Row scaling vector */
SmartPtr<Vector> scaling_;
/** unscaled matrix space */
SmartPtr<const SymMatrixSpace> unscaled_matrix_space_;
};
inline
void SymScaledMatrix::SetUnscaledMatrix(const SmartPtr<const SymMatrix> unscaled_matrix)
{
matrix_ = unscaled_matrix;
nonconst_matrix_ = NULL;
ObjectChanged();
}
inline
void SymScaledMatrix::SetUnscaledMatrixNonConst(const SmartPtr<SymMatrix>& unscaled_matrix)
{
nonconst_matrix_ = unscaled_matrix;
matrix_ = GetRawPtr(unscaled_matrix);
ObjectChanged();
}
inline
SmartPtr<const SymMatrix> SymScaledMatrix::GetUnscaledMatrix() const
{
return matrix_;
}
inline
SmartPtr<SymMatrix> SymScaledMatrix::GetUnscaledMatrixNonConst()
{
DBG_ASSERT(IsValid(nonconst_matrix_));
ObjectChanged();
return nonconst_matrix_;
}
inline SmartPtr<const Vector> SymScaledMatrix::RowColScaling() const
{
return ConstPtr(owner_space_->RowColScaling());
}
} // namespace Ipopt
#endif
+253
View File
@@ -0,0 +1,253 @@
// Copyright (C) 2004, 2006 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpSymTMatrix.hpp 2269 2013-05-05 11:32:40Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPSYMTMATRIX_HPP__
#define __IPSYMTMATRIX_HPP__
#include "IpUtils.hpp"
#include "IpSymMatrix.hpp"
namespace Ipopt
{
/* forward declarations */
class SymTMatrixSpace;
/** Class for symmetric matrices stored in triplet format. In the
* triplet format, the nonzeros elements of a symmetric matrix is
* stored in three arrays, Irn, Jcn, and Values, all of length
* Nonzeros. The first two arrays indicate the location of a
* non-zero element (as the row and column indices), and the last
* array stores the value at that location. Off-diagonal elements
* need to be stored only once since the matrix is symmetric. For
* example, the element \f$a_{1,2}=a_{2,1}\f$ would be stored only
* once, either with Irn[i]=1 and Jcn[i]=2, or with Irn[i]=2 and
* Jcn[i]=1. Both representations are identical. If nonzero
* elements (or their symmetric counter part) are listed more than
* once, their values are added.
*
* The structure of the nonzeros (i.e. the arrays Irn and Jcn)
* cannot be changed after the matrix can been initialized. Only
* the values of the nonzero elements can be modified.
*
* Note that the first row and column of a matrix has index 1, not
* 0.
*
*/
class SymTMatrix : public SymMatrix
{
public:
/**@name Constructors / Destructors */
//@{
/** Constructor, taking the corresponding matrix space.
*/
SymTMatrix(const SymTMatrixSpace* owner_space);
/** Destructor */
~SymTMatrix();
//@}
/**@name Changing the Values.*/
//@{
/** Set values of nonzero elements. The values of the nonzero
* elements is copied from the incoming Number array. Important:
* It is assume that the order of the values in Values
* corresponds to the one of Irn and Jcn given to the matrix
* space. */
void SetValues(const Number* Values);
//@}
/** @name Accessor Methods */
//@{
/** Number of nonzero entries */
Index Nonzeros() const;
/** Obtain pointer to the internal Index array irn_ without the
* intention to change the matrix data (USE WITH CARE!). This
* does not produce a copy, and lifetime is not guaranteed!
*/
const Index* Irows() const;
/** Obtain pointer to the internal Index array jcn_ without the
* intention to change the matrix data (USE WITH CARE!). This
* does not produce a copy, and lifetime is not guaranteed!
*/
const Index* Jcols() const;
/** Obtain pointer to the internal Number array values_ with the
* intention to change the matrix data (USE WITH CARE!). This
* does not produce a copy, and lifetime is not guaranteed!
*/
Number* Values();
/** Obtain pointer to the internal Number array values_ without the
* intention to change the matrix data (USE WITH CARE!). This
* does not produce a copy, and lifetime is not guaranteed!
*/
const Number* Values() const;
//@}
/**@name Methods for providing copy of the matrix data */
//@{
/** Copy the nonzero structure into provided space */
void FillStruct(ipfint* Irn, ipfint* Jcn) const;
/** Copy the value data into provided space */
void FillValues(Number* Values) const;
//@}
protected:
/**@name Methods overloaded from matrix */
//@{
virtual void MultVectorImpl(Number alpha, const Vector& x, Number beta,
Vector& y) const;
/** Method for determining if all stored numbers are valid (i.e.,
* no Inf or Nan). */
virtual bool HasValidNumbersImpl() const;
virtual void ComputeRowAMaxImpl(Vector& rows_norms, bool init) const;
virtual void PrintImpl(const Journalist& jnlst,
EJournalLevel level,
EJournalCategory category,
const std::string& name,
Index indent,
const std::string& prefix) const;
//@}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
SymTMatrix();
/** Copy Constructor */
SymTMatrix(const SymTMatrix&);
/** Overloaded Equals Operator */
void operator=(const SymTMatrix&);
//@}
/** Copy of the owner_space ptr as a SymTMatrixSpace insteaqd
* of a MatrixSpace
*/
const SymTMatrixSpace* owner_space_;
/** Values of nonzeros */
Number* values_;
/** Flag for Initialization */
bool initialized_;
};
/** This is the matrix space for a SymTMatrix with fixed sparsity
* structure. The sparsity structure is stored here in the matrix
* space.
*/
class SymTMatrixSpace : public SymMatrixSpace
{
public:
/** @name Constructors / Destructors */
//@{
/** Constructor, given the number of rows and columns (both as
* dim), as well as the number of nonzeros and the position of
* the nonzero elements. Note that the counting of the nonzeros
* starts a 1, i.e., iRows[i]==1 and jCols[i]==1 refers to the
* first element in the first row. This is in accordance with
* the HSL data structure. Off-diagonal elements are stored only
* once.
*/
SymTMatrixSpace(Index dim, Index nonZeros, const Index* iRows,
const Index* jCols);
/** Destructor */
~SymTMatrixSpace();
//@}
/** Overloaded MakeNew method for the sYMMatrixSpace base class.
*/
virtual SymMatrix* MakeNewSymMatrix() const
{
return MakeNewSymTMatrix();
}
/** Method for creating a new matrix of this specific type. */
SymTMatrix* MakeNewSymTMatrix() const
{
return new SymTMatrix(this);
}
/**@name Methods describing Matrix structure */
//@{
/** Number of non-zeros in the sparse matrix */
Index Nonzeros() const
{
return nonZeros_;
}
/** Row index of each non-zero element */
const Index* Irows() const
{
return iRows_;
}
/** Column index of each non-zero element */
const Index* Jcols() const
{
return jCols_;
}
//@}
private:
/**@name Methods called by SymTMatrix for memory management */
//@{
/** Allocate internal storage for the SymTMatrix values */
Number* AllocateInternalStorage() const;
/** Deallocate internal storage for the SymTMatrix values */
void FreeInternalStorage(Number* values) const;
//@}
const Index nonZeros_;
Index* iRows_;
Index* jCols_;
friend class SymTMatrix;
};
/* Inline Methods */
inline
Index SymTMatrix::Nonzeros() const
{
return owner_space_->Nonzeros();
}
inline
const Index* SymTMatrix::Irows() const
{
return owner_space_->Irows();
}
inline
const Index* SymTMatrix::Jcols() const
{
return owner_space_->Jcols();
}
} // namespace Ipopt
#endif
+301
View File
@@ -0,0 +1,301 @@
// Copyright (C) 2004, 2009 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpTNLP.hpp 2212 2013-04-14 14:51:52Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPTNLP_HPP__
#define __IPTNLP_HPP__
#include "IpUtils.hpp"
#include "IpReferenced.hpp"
#include "IpException.hpp"
#include "IpAlgTypes.hpp"
#include "IpReturnCodes.hpp"
#include <map>
namespace Ipopt
{
// forward declarations
class IpoptData;
class IpoptCalculatedQuantities;
class IteratesVector;
/** Base class for all NLP's that use standard triplet matrix form
* and dense vectors. This is the standard base class for all
* NLP's that use the standard triplet matrix form (as for Harwell
* routines) and dense vectors. The class TNLPAdapter then converts
* this interface to an interface that can be used directly by
* ipopt.
*
* This interface presents the problem form:
*
* min f(x)
*
* s.t. gL <= g(x) <= gU
*
* xL <= x <= xU
*
* In order to specify an equality constraint, set gL_i = gU_i =
* rhs. The value that indicates "infinity" for the bounds
* (i.e. the variable or constraint has no lower bound (-infinity)
* or upper bound (+infinity)) is set through the option
* nlp_lower_bound_inf and nlp_upper_bound_inf. To indicate that a
* variable has no upper or lower bound, set the bound to
* -ipopt_inf or +ipopt_inf respectively
*/
class TNLP : public ReferencedObject
{
public:
/** Type of the constraints*/
enum LinearityType
{
LINEAR/** Constraint/Variable is linear.*/,
NON_LINEAR/**Constraint/Varaible is non-linear.*/
};
/**@name Constructors/Destructors */
//@{
TNLP()
{}
/** Default destructor */
virtual ~TNLP()
{}
//@}
DECLARE_STD_EXCEPTION(INVALID_TNLP);
/**@name methods to gather information about the NLP */
//@{
/** overload this method to return the number of variables
* and constraints, and the number of non-zeros in the jacobian and
* the hessian. The index_style parameter lets you specify C or Fortran
* style indexing for the sparse matrix iRow and jCol parameters.
* C_STYLE is 0-based, and FORTRAN_STYLE is 1-based.
*/
enum IndexStyleEnum { C_STYLE=0, FORTRAN_STYLE=1 };
virtual bool get_nlp_info(Index& n, Index& m, Index& nnz_jac_g,
Index& nnz_h_lag, IndexStyleEnum& index_style)=0;
typedef std::map<std::string, std::vector<std::string> > StringMetaDataMapType;
typedef std::map<std::string, std::vector<Index> > IntegerMetaDataMapType;
typedef std::map<std::string, std::vector<Number> > NumericMetaDataMapType;
/** overload this method to return any meta data for
* the variables and the constraints */
virtual bool get_var_con_metadata(Index n,
StringMetaDataMapType& var_string_md,
IntegerMetaDataMapType& var_integer_md,
NumericMetaDataMapType& var_numeric_md,
Index m,
StringMetaDataMapType& con_string_md,
IntegerMetaDataMapType& con_integer_md,
NumericMetaDataMapType& con_numeric_md)
{
return false;
}
/** overload this method to return the information about the bound
* on the variables and constraints. The value that indicates
* that a bound does not exist is specified in the parameters
* nlp_lower_bound_inf and nlp_upper_bound_inf. By default,
* nlp_lower_bound_inf is -1e19 and nlp_upper_bound_inf is
* 1e19. (see TNLPAdapter) */
virtual bool get_bounds_info(Index n, Number* x_l, Number* x_u,
Index m, Number* g_l, Number* g_u)=0;
/** overload this method to return scaling parameters. This is
* only called if the options are set to retrieve user scaling.
* There, use_x_scaling (or use_g_scaling) should get set to true
* only if the variables (or constraints) are to be scaled. This
* method should return true only if the scaling parameters could
* be provided.
*/
virtual bool get_scaling_parameters(Number& obj_scaling,
bool& use_x_scaling, Index n,
Number* x_scaling,
bool& use_g_scaling, Index m,
Number* g_scaling)
{
return false;
}
/** overload this method to return the variables linearity
* (TNLP::LINEAR or TNLP::NON_LINEAR). The var_types
* array has been allocated with length at least n. (default implementation
* just return false and does not fill the array).*/
virtual bool get_variables_linearity(Index n, LinearityType* var_types)
{
return false;
}
/** overload this method to return the constraint linearity.
* array has been allocated with length at least n. (default implementation
* just return false and does not fill the array).*/
virtual bool get_constraints_linearity(Index m, LinearityType* const_types)
{
return false;
}
/** overload this method to return the starting point. The bool
* variables indicate whether the algorithm wants you to
* initialize x, z_L/z_u, and lambda, respectively. If, for some
* reason, the algorithm wants you to initialize these and you
* cannot, return false, which will cause Ipopt to stop. You
* will have to run Ipopt with different options then.
*/
virtual bool get_starting_point(Index n, bool init_x, Number* x,
bool init_z, Number* z_L, Number* z_U,
Index m, bool init_lambda,
Number* lambda)=0;
/** overload this method to provide an Ipopt iterate (already in
* the form Ipopt requires it internally) for a warm start.
* Since this is only for expert users, a default dummy
* implementation is provided and returns false. */
virtual bool get_warm_start_iterate(IteratesVector& warm_start_iterate)
{
return false;
}
/** overload this method to return the value of the objective function */
virtual bool eval_f(Index n, const Number* x, bool new_x,
Number& obj_value)=0;
/** overload this method to return the vector of the gradient of
* the objective w.r.t. x */
virtual bool eval_grad_f(Index n, const Number* x, bool new_x,
Number* grad_f)=0;
/** overload this method to return the vector of constraint values */
virtual bool eval_g(Index n, const Number* x, bool new_x,
Index m, Number* g)=0;
/** overload this method to return the jacobian of the
* constraints. The vectors iRow and jCol only need to be set
* once. The first call is used to set the structure only (iRow
* and jCol will be non-NULL, and values will be NULL) For
* subsequent calls, iRow and jCol will be NULL. */
virtual bool eval_jac_g(Index n, const Number* x, bool new_x,
Index m, Index nele_jac, Index* iRow,
Index *jCol, Number* values)=0;
/** overload this method to return the hessian of the
* lagrangian. The vectors iRow and jCol only need to be set once
* (during the first call). The first call is used to set the
* structure only (iRow and jCol will be non-NULL, and values
* will be NULL) For subsequent calls, iRow and jCol will be
* NULL. This matrix is symmetric - specify the lower diagonal
* only. A default implementation is provided, in case the user
* wants to se quasi-Newton approximations to estimate the second
* derivatives and doesn't not neet to implement this method. */
virtual bool eval_h(Index n, const Number* x, bool new_x,
Number obj_factor, Index m, const Number* lambda,
bool new_lambda, Index nele_hess,
Index* iRow, Index* jCol, Number* values)
{
return false;
}
//@}
/** @name Solution Methods */
//@{
/** This method is called when the algorithm is complete so the TNLP can store/write the solution */
virtual void finalize_solution(SolverReturn status,
Index n, const Number* x, const Number* z_L, const Number* z_U,
Index m, const Number* g, const Number* lambda,
Number obj_value,
const IpoptData* ip_data,
IpoptCalculatedQuantities* ip_cq)=0;
/** This method is called just before finalize_solution. With
* this method, the algorithm returns any metadata collected
* during its run, including the metadata provided by the user
* with the above get_var_con_metadata. Each metadata can be of
* type string, integer, and numeric. It can be associated to
* either the variables or the constraints. The metadata that
* was associated with the primal variable vector is stored in
* var_..._md. The metadata associated with the constraint
* multipliers is stored in con_..._md. The metadata associated
* with the bound multipliers is stored in var_..._md, with the
* suffixes "_z_L", and "_z_U", denoting lower and upper
* bounds. */
virtual void finalize_metadata(Index n,
const StringMetaDataMapType& var_string_md,
const IntegerMetaDataMapType& var_integer_md,
const NumericMetaDataMapType& var_numeric_md,
Index m,
const StringMetaDataMapType& con_string_md,
const IntegerMetaDataMapType& con_integer_md,
const NumericMetaDataMapType& con_numeric_md)
{}
/** Intermediate Callback method for the user. Providing dummy
* default implementation. For details see IntermediateCallBack
* in IpNLP.hpp. */
virtual bool intermediate_callback(AlgorithmMode mode,
Index iter, Number obj_value,
Number inf_pr, Number inf_du,
Number mu, Number d_norm,
Number regularization_size,
Number alpha_du, Number alpha_pr,
Index ls_trials,
const IpoptData* ip_data,
IpoptCalculatedQuantities* ip_cq)
{
return true;
}
//@}
/** @name Methods for quasi-Newton approximation. If the second
* derivatives are approximated by Ipopt, it is better to do this
* only in the space of nonlinear variables. The following
* methods are call by Ipopt if the quasi-Newton approximation is
* selected. If -1 is returned as number of nonlinear variables,
* Ipopt assumes that all variables are nonlinear. Otherwise, it
* calls get_list_of_nonlinear_variables with an array into which
* the indices of the nonlinear variables should be written - the
* array has the lengths num_nonlin_vars, which is identical with
* the return value of get_number_of_nonlinear_variables(). It
* is assumed that the indices are counted starting with 1 in the
* FORTRAN_STYLE, and 0 for the C_STYLE. */
//@{
virtual Index get_number_of_nonlinear_variables()
{
return -1;
}
virtual bool get_list_of_nonlinear_variables(Index num_nonlin_vars,
Index* pos_nonlin_vars)
{
return false;
}
//@}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
//TNLP();
/** Copy Constructor */
TNLP(const TNLP&);
/** Overloaded Equals Operator */
void operator=(const TNLP&);
//@}
};
} // namespace Ipopt
#endif
+427
View File
@@ -0,0 +1,427 @@
// Copyright (C) 2004, 2008 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpTNLPAdapter.hpp 2269 2013-05-05 11:32:40Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPTNLPADAPTER_HPP__
#define __IPTNLPADAPTER_HPP__
#include "IpNLP.hpp"
#include "IpTNLP.hpp"
#include "IpOrigIpoptNLP.hpp"
#include <list>
namespace Ipopt
{
// forward declarations
class ExpansionMatrix;
class ExpansionMatrixSpace;
class IteratesVector;
class TDependencyDetector;
/** This class Adapts the TNLP interface so it looks like an NLP interface.
* This is an Adapter class (Design Patterns) that converts a TNLP to an
* NLP. This allows users to write to the "more convenient" TNLP interface.
*/
class TNLPAdapter : public NLP
{
public:
/**@name Constructors/Destructors */
//@{
/** Default constructor */
TNLPAdapter(const SmartPtr<TNLP> tnlp,
const SmartPtr<const Journalist> jnlst = NULL);
/** Default destructor */
virtual ~TNLPAdapter();
//@}
/**@name Exceptions */
//@{
DECLARE_STD_EXCEPTION(INVALID_TNLP);
DECLARE_STD_EXCEPTION(ERROR_IN_TNLP_DERIVATIVE_TEST);
//@}
/** @name TNLPAdapter Initialization. */
//@{
virtual bool ProcessOptions(const OptionsList& options,
const std::string& prefix);
/** Method for creating the derived vector / matrix types
* (Do not delete these, the ). */
virtual bool GetSpaces(SmartPtr<const VectorSpace>& x_space,
SmartPtr<const VectorSpace>& c_space,
SmartPtr<const VectorSpace>& d_space,
SmartPtr<const VectorSpace>& x_l_space,
SmartPtr<const MatrixSpace>& px_l_space,
SmartPtr<const VectorSpace>& x_u_space,
SmartPtr<const MatrixSpace>& px_u_space,
SmartPtr<const VectorSpace>& d_l_space,
SmartPtr<const MatrixSpace>& pd_l_space,
SmartPtr<const VectorSpace>& d_u_space,
SmartPtr<const MatrixSpace>& pd_u_space,
SmartPtr<const MatrixSpace>& Jac_c_space,
SmartPtr<const MatrixSpace>& Jac_d_space,
SmartPtr<const SymMatrixSpace>& Hess_lagrangian_space);
/** Method for obtaining the bounds information */
virtual bool GetBoundsInformation(const Matrix& Px_L,
Vector& x_L,
const Matrix& Px_U,
Vector& x_U,
const Matrix& Pd_L,
Vector& d_L,
const Matrix& Pd_U,
Vector& d_U);
/** Method for obtaining the starting point
* for all the iterates. */
virtual bool GetStartingPoint(
SmartPtr<Vector> x,
bool need_x,
SmartPtr<Vector> y_c,
bool need_y_c,
SmartPtr<Vector> y_d,
bool need_y_d,
SmartPtr<Vector> z_L,
bool need_z_L,
SmartPtr<Vector> z_U,
bool need_z_U
);
/** Method for obtaining an entire iterate as a warmstart point.
* The incoming IteratesVector has to be filled. */
virtual bool GetWarmStartIterate(IteratesVector& warm_start_iterate);
//@}
/** @name TNLPAdapter evaluation routines. */
//@{
virtual bool Eval_f(const Vector& x, Number& f);
virtual bool Eval_grad_f(const Vector& x, Vector& g_f);
virtual bool Eval_c(const Vector& x, Vector& c);
virtual bool Eval_jac_c(const Vector& x, Matrix& jac_c);
virtual bool Eval_d(const Vector& x, Vector& d);
virtual bool Eval_jac_d(const Vector& x, Matrix& jac_d);
virtual bool Eval_h(const Vector& x,
Number obj_factor,
const Vector& yc,
const Vector& yd,
SymMatrix& h);
virtual void GetScalingParameters(
const SmartPtr<const VectorSpace> x_space,
const SmartPtr<const VectorSpace> c_space,
const SmartPtr<const VectorSpace> d_space,
Number& obj_scaling,
SmartPtr<Vector>& x_scaling,
SmartPtr<Vector>& c_scaling,
SmartPtr<Vector>& d_scaling) const;
//@}
/** @name Solution Reporting Methods */
//@{
virtual void FinalizeSolution(SolverReturn status,
const Vector& x,
const Vector& z_L, const Vector& z_U,
const Vector& c, const Vector& d,
const Vector& y_c, const Vector& y_d,
Number obj_value,
const IpoptData* ip_data,
IpoptCalculatedQuantities* ip_cq);
virtual bool IntermediateCallBack(AlgorithmMode mode,
Index iter, Number obj_value,
Number inf_pr, Number inf_du,
Number mu, Number d_norm,
Number regularization_size,
Number alpha_du, Number alpha_pr,
Index ls_trials,
const IpoptData* ip_data,
IpoptCalculatedQuantities* ip_cq);
//@}
/** Method returning information on quasi-Newton approximation. */
virtual void
GetQuasiNewtonApproximationSpaces(SmartPtr<VectorSpace>& approx_space,
SmartPtr<Matrix>& P_approx);
/** Enum for treatment of fixed variables option */
enum FixedVariableTreatmentEnum
{
MAKE_PARAMETER=0,
MAKE_CONSTRAINT,
RELAX_BOUNDS
};
/** Enum for specifying which derivative test is to be performed. */
enum DerivativeTestEnum
{
NO_TEST=0,
FIRST_ORDER_TEST,
SECOND_ORDER_TEST,
ONLY_SECOND_ORDER_TEST
};
/** Enum for specifying technique for computing Jacobian */
enum JacobianApproxEnum
{
JAC_EXACT=0,
JAC_FINDIFF_VALUES
};
/** Method for performing the derivative test */
bool CheckDerivatives(DerivativeTestEnum deriv_test,
Index deriv_test_start_index);
/** @name Methods for IpoptType */
//@{
static void RegisterOptions(SmartPtr<RegisteredOptions> roptions);
//@}
/** Accessor method for the underlying TNLP. */
SmartPtr<TNLP> tnlp() const
{
return tnlp_;
}
/** @name Methods for translating data for IpoptNLP into the TNLP
* data. These methods are used to obtain the current (or
* final) data for the TNLP formulation from the IpoptNLP
* structure. */
//@{
/** Sort the primal variables, and add the fixed values in x */
void ResortX(const Vector& x, Number* x_orig);
void ResortG(const Vector& c, const Vector& d, Number *g_orig);
void ResortBnds(const Vector& x_L, Number* x_L_orig,
const Vector& x_U, Number* x_U_orig);
//@}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Copy Constructor */
TNLPAdapter(const TNLPAdapter&);
/** Overloaded Equals Operator */
void operator=(const TNLPAdapter&);
//@}
/** @name Method implementing the detection of linearly dependent
equality constraints */
bool DetermineDependentConstraints(Index n_x_var,
const Index* x_not_fixed_map,
const Number* x_l, const Number* x_u,
const Number* g_l, const Number* g_u,
Index n_c, const Index* c_map,
std::list<Index>& c_deps);
/** Pointer to the TNLP class (class specific to Number* vectors and
* harwell triplet matrices) */
SmartPtr<TNLP> tnlp_;
/** Journalist */
SmartPtr<const Journalist> jnlst_;
/** Object that can be used to detect linearly dependent rows in
* the equality constraint Jacobian */
SmartPtr<TDependencyDetector> dependency_detector_;
/**@name Algorithmic parameters */
//@{
/** Value for a lower bound that denotes -infinity */
Number nlp_lower_bound_inf_;
/** Value for a upper bound that denotes infinity */
Number nlp_upper_bound_inf_;
/** Flag indicating how fixed variables should be handled */
FixedVariableTreatmentEnum fixed_variable_treatment_;
/* Determines relaxation of fixing bound for RELAX_BOUNDS. */
Number bound_relax_factor_;
/* Maximal slack for one-sidedly bounded variables. If a
* variable has only one bound, say a lower bound xL, then an
* upper bound xL + max_onesided_bound_slack_. If this value is
* zero, no upper bound is added. */
/* Took this out: Number max_onesided_bound_slack_; */
/** Enum indicating whether and which derivative test should be
* performed at starting point. */
DerivativeTestEnum derivative_test_;
/** Size of the perturbation for the derivative test */
Number derivative_test_perturbation_;
/** Relative threshold for marking deviation from finite
* difference test */
Number derivative_test_tol_;
/** Flag indicating if all test values should be printed, or only
* those violating the threshold. */
bool derivative_test_print_all_;
/** Index of first quantity to be checked. */
Index derivative_test_first_index_;
/** Flag indicating whether the TNLP with identical structure has
* already been solved before. */
bool warm_start_same_structure_;
/** Flag indicating what Hessian information is to be used. */
HessianApproximationType hessian_approximation_;
/** Number of linear variables. */
Index num_linear_variables_;
/** Flag indicating how Jacobian is computed. */
JacobianApproxEnum jacobian_approximation_;
/** Size of the perturbation for the derivative approximation */
Number findiff_perturbation_;
/** Maximal perturbation of the initial point */
Number point_perturbation_radius_;
/** Flag indicating if rhs should be considered during dependency
* detection */
bool dependency_detection_with_rhs_;
/** Overall convergence tolerance */
Number tol_;
//@}
/**@name Problem Size Data */
//@{
/** full dimension of x (fixed + non-fixed) */
Index n_full_x_;
/** full dimension of g (c + d) */
Index n_full_g_;
/** non-zeros of the jacobian of c */
Index nz_jac_c_;
/** non-zeros of the jacobian of c without added constraints for
* fixed variables. */
Index nz_jac_c_no_extra_;
/** non-zeros of the jacobian of d */
Index nz_jac_d_;
/** number of non-zeros in full-size Jacobian of g */
Index nz_full_jac_g_;
/** number of non-zeros in full-size Hessian */
Index nz_full_h_;
/** number of non-zeros in the non-fixed-size Hessian */
Index nz_h_;
/** Number of fixed variables */
Index n_x_fixed_;
//@}
/** Numbering style of variables and constraints */
TNLP::IndexStyleEnum index_style_;
/** @name Local copy of spaces (for warm start) */
//@{
SmartPtr<const VectorSpace> x_space_;
SmartPtr<const VectorSpace> c_space_;
SmartPtr<const VectorSpace> d_space_;
SmartPtr<const VectorSpace> x_l_space_;
SmartPtr<const MatrixSpace> px_l_space_;
SmartPtr<const VectorSpace> x_u_space_;
SmartPtr<const MatrixSpace> px_u_space_;
SmartPtr<const VectorSpace> d_l_space_;
SmartPtr<const MatrixSpace> pd_l_space_;
SmartPtr<const VectorSpace> d_u_space_;
SmartPtr<const MatrixSpace> pd_u_space_;
SmartPtr<const MatrixSpace> Jac_c_space_;
SmartPtr<const MatrixSpace> Jac_d_space_;
SmartPtr<const SymMatrixSpace> Hess_lagrangian_space_;
//@}
/**@name Local Copy of the Data */
//@{
Number* full_x_; /** copy of the full x vector (fixed & non-fixed) */
Number* full_lambda_; /** copy of lambda (yc & yd) */
Number* full_g_; /** copy of g (c & d) */
Number* jac_g_; /** the values for the full jacobian of g */
Number* c_rhs_; /** the rhs values of c */
//@}
/**@name Tags for deciding when to update internal copies of vectors */
//@{
TaggedObject::Tag x_tag_for_iterates_;
TaggedObject::Tag y_c_tag_for_iterates_;
TaggedObject::Tag y_d_tag_for_iterates_;
TaggedObject::Tag x_tag_for_g_;
TaggedObject::Tag x_tag_for_jac_g_;
//@}
/**@name Methods to update the values in the local copies of vectors */
//@{
bool update_local_x(const Vector& x);
bool update_local_lambda(const Vector& y_c, const Vector& y_d);
//@}
/**@name Internal routines for evaluating g and jac_g (values stored since
* they are used in both c and d routines */
//@{
bool internal_eval_g(bool new_x);
bool internal_eval_jac_g(bool new_x);
//@}
/** @name Internal methods for dealing with finite difference
approxation */
//@{
/** Initialize sparsity structure for finite difference Jacobian */
void initialize_findiff_jac(const Index* iRow, const Index* jCol);
//@}
/**@name Internal Permutation Spaces and matrices
*/
//@{
/** Expansion from fixed x (ipopt) to full x */
SmartPtr<ExpansionMatrix> P_x_full_x_;
SmartPtr<ExpansionMatrixSpace> P_x_full_x_space_;
/** Expansion from fixed x_L (ipopt) to full x */
SmartPtr<ExpansionMatrix> P_x_x_L_;
SmartPtr<ExpansionMatrixSpace> P_x_x_L_space_;
/** Expansion from fixed x_U (ipopt) to full x */
SmartPtr<ExpansionMatrix> P_x_x_U_;
SmartPtr<ExpansionMatrixSpace> P_x_x_U_space_;
/** Expansion from c only (ipopt) to full ampl c */
SmartPtr<ExpansionMatrixSpace> P_c_g_space_;
SmartPtr<ExpansionMatrix> P_c_g_;
/** Expansion from d only (ipopt) to full ampl d */
SmartPtr<ExpansionMatrixSpace> P_d_g_space_;
SmartPtr<ExpansionMatrix> P_d_g_;
Index* jac_idx_map_;
Index* h_idx_map_;
/** Position of fixed variables. This is required for a warm start */
Index* x_fixed_map_;
//@}
/** @name Data for finite difference approximations of derivatives */
//@{
/** Number of unique nonzeros in constraint Jacobian */
Index findiff_jac_nnz_;
/** Start position for nonzero indices in ja for each column of
Jacobian */
Index* findiff_jac_ia_;
/** Ordered by columns, for each column the row indices in
Jacobian */
Index* findiff_jac_ja_;
/** Position of entry in original triplet matrix */
Index* findiff_jac_postriplet_;
/** Copy of the lower bounds */
Number* findiff_x_l_;
/** Copy of the upper bounds */
Number* findiff_x_u_;
//@}
};
} // namespace Ipopt
#endif
+180
View File
@@ -0,0 +1,180 @@
// Copyright (C) 2008 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpTNLPReducer.hpp 1861 2010-12-21 21:34:47Z andreasw $
//
// Authors: Andreas Waechter IBM 2008-08-10
#ifndef __IPTNLPREDUCER_HPP__
#define __IPTNLPREDUCER_HPP__
#include "IpTNLP.hpp"
namespace Ipopt
{
/** This is a wrapper around a given TNLP class that takes out a
* list of constraints that are given to the constructor. It is
* provided for convenience, if one wants to experiment with
* problems that consist of only a subset of the constraints. But
* keep in mind that this is not efficient, since behind the scenes
* we are still evaluation all functions and derivatives, and are
* making copies of the original data. */
class TNLPReducer : public TNLP
{
public:
/**@name Constructors/Destructors */
//@{
/** Constructor is given the indices of the constraints that
* should be taken out of the problem statement, as well as the
* original TNLP. */
TNLPReducer(TNLP& tnlp, Index n_g_skip, const Index* index_g_skip,
Index n_xL_skip, const Index* index_xL_skip,
Index n_xU_skip, const Index* index_xU_skip,
Index n_x_fix, const Index* index_f_fix);
/** Default destructor */
virtual ~TNLPReducer();
//@}
/** @name Overloaded methods from TNLP */
virtual bool get_nlp_info(Index& n, Index& m, Index& nnz_jac_g,
Index& nnz_h_lag, IndexStyleEnum& index_style);
virtual bool get_bounds_info(Index n, Number* x_l, Number* x_u,
Index m, Number* g_l, Number* g_u);
virtual bool get_scaling_parameters(Number& obj_scaling,
bool& use_x_scaling, Index n,
Number* x_scaling,
bool& use_g_scaling, Index m,
Number* g_scaling);
virtual bool get_variables_linearity(Index n, LinearityType* var_types);
virtual bool get_constraints_linearity(Index m, LinearityType* const_types);
virtual bool get_starting_point(Index n, bool init_x, Number* x,
bool init_z, Number* z_L, Number* z_U,
Index m, bool init_lambda,
Number* lambda);
virtual bool get_warm_start_iterate(IteratesVector& warm_start_iterate);
virtual bool eval_f(Index n, const Number* x, bool new_x,
Number& obj_value);
virtual bool eval_grad_f(Index n, const Number* x, bool new_x,
Number* grad_f);
virtual bool eval_g(Index n, const Number* x, bool new_x,
Index m, Number* g);
virtual bool eval_jac_g(Index n, const Number* x, bool new_x,
Index m, Index nele_jac, Index* iRow,
Index *jCol, Number* values);
virtual bool eval_h(Index n, const Number* x, bool new_x,
Number obj_factor, Index m, const Number* lambda,
bool new_lambda, Index nele_hess,
Index* iRow, Index* jCol, Number* values);
virtual void finalize_solution(SolverReturn status,
Index n, const Number* x, const Number* z_L, const Number* z_U,
Index m, const Number* g, const Number* lambda,
Number obj_value,
const IpoptData* ip_data,
IpoptCalculatedQuantities* ip_cq);
virtual bool intermediate_callback(AlgorithmMode mode,
Index iter, Number obj_value,
Number inf_pr, Number inf_du,
Number mu, Number d_norm,
Number regularization_size,
Number alpha_du, Number alpha_pr,
Index ls_trials,
const IpoptData* ip_data,
IpoptCalculatedQuantities* ip_cq);
virtual Index get_number_of_nonlinear_variables();
virtual bool get_list_of_nonlinear_variables(Index num_nonlin_vars,
Index* pos_nonlin_vars);
//@}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
TNLPReducer();
/** Copy Constructor */
TNLPReducer(const TNLPReducer&);
/** Overloaded Equals Operator */
void operator=(const TNLPReducer&);
//@}
/** @name original TNLP */
//@{
SmartPtr<TNLP> tnlp_;
Index m_orig_;
Index nnz_jac_g_orig_;
//@}
/** Number of constraints to be skipped */
Index n_g_skip_;
/** Array of indices of the constraints that are to be skipped.
* This is provided at the beginning in the constructor. */
Index* index_g_skip_;
/** Index style for original problem. Internally, we use C-Style
* now. */
IndexStyleEnum index_style_orig_;
/** Map from original constraints to new constraints. A -1 means
* that a constraint is skipped. */
Index* g_keep_map_;
/** Number of constraints in reduced NLP */
Index m_reduced_;
/** Number of Jacobian nonzeros in the reduced NLP */
Index nnz_jac_g_reduced_;
/** Number of Jacobian nonzeros that are skipped */
Index nnz_jac_g_skipped_;
/** Array of Jacobian elements that are to be skipped. This is in
* increasing order. */
Index* jac_g_skipped_;
/** Number of lower variable bounds to be skipped. */
Index n_xL_skip_;
/** Array of indices of the lower variable bounds to be skipped. */
Index* index_xL_skip_;
/** Number of upper variable bounds to be skipped. */
Index n_xU_skip_;
/** Array of indices of the upper variable bounds to be skipped. */
Index* index_xU_skip_;
/** Number of variables that are to be fixed to initial value. */
Index n_x_fix_;
/** Array of indices of the variables that are to be fixed. */
Index* index_x_fix_;
};
} // namespace Ipopt
#endif
+162
View File
@@ -0,0 +1,162 @@
// Copyright (C) 2004, 2006 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpTaggedObject.hpp 2613 2015-11-04 14:42:02Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPTAGGEDOBJECT_HPP__
#define __IPTAGGEDOBJECT_HPP__
#include "IpUtils.hpp"
#include "IpDebug.hpp"
#include "IpReferenced.hpp"
#include "IpObserver.hpp"
#include <limits>
/* keyword to declare a thread-local variable according to http://en.wikipedia.org/wiki/Thread-local_storage
* GCC < 4.5 on MacOS X does not support TLS
* With Intel compiler on MacOS X, problems with TLS were reported.
*/
#ifndef IPOPT_THREAD_LOCAL
#if defined(_MSC_VER)
#define IPOPT_THREAD_LOCAL __declspec(thread)
#elif defined(__APPLE__) && ((defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ < 405)) || defined(__INTEL_COMPILER))
#define IPOPT_THREAD_LOCAL
#else
#define IPOPT_THREAD_LOCAL __thread
#endif
#endif
namespace Ipopt
{
/** TaggedObject class.
* Often, certain calculations or operations are expensive,
* and it can be very inefficient to perform these calculations
* again if the input to the calculation has not changed
* since the result was last stored.
* This base class provides an efficient mechanism to update
* a tag, indicating that the object has changed.
* Users of a TaggedObject class, need their own Tag data
* member to keep track of the state of the TaggedObject, the
* last time they performed a calculation. A basic use case for
* users of a class inheriting from TaggedObject follows like
* this:
*
* 1. Initialize your own Tag to zero in constructor.
*
* 2. Before an expensive calculation,
* check if the TaggedObject has changed, passing in
* your own Tag, indicating the last time you used
* the object for the calculation. If it has changed,
* perform the calculation again, and store the result.
* If it has not changed, simply return the stored result.
*
* Here is a simple example:
\verbatim
if (vector.HasChanged(my_vector_tag_)) {
my_vector_tag_ = vector.GetTag();
result = PerformExpensiveCalculation(vector);
return result;
}
else {
return result;
}
\endverbatim
*
* Objects derived from TaggedObject must indicate that they have changed to
* the base class using the protected member function ObjectChanged(). For
* example, a Vector class, inside its own set method, MUST call
* ObjectChanged() to update the internally stored tag for comparison.
*/
class TaggedObject : public ReferencedObject, public Subject
{
public:
/** Type for the Tag values */
typedef unsigned int Tag;
/** Constructor. */
TaggedObject()
:
Subject()
{
ObjectChanged();
}
/** Destructor. */
virtual ~TaggedObject()
{}
/** Users of TaggedObjects call this to
* update their own internal tags every time
* they perform the expensive operation.
*/
Tag GetTag() const
{
return tag_;
}
/** Users of TaggedObjects call this to
* check if the object HasChanged since
* they last updated their own internal
* tag.
*/
bool HasChanged(const Tag comparison_tag) const
{
return (comparison_tag == tag_) ? false : true;
}
protected:
/** Objects derived from TaggedObject MUST call this
* method every time their internal state changes to
* update the internal tag for comparison
*/
void ObjectChanged()
{
DBG_START_METH("TaggedObject::ObjectChanged()", 0);
tag_ = unique_tag_;
unique_tag_++;
DBG_ASSERT(unique_tag_ < std::numeric_limits<Tag>::max());
// The Notify method from the Subject base class notifies all
// registered Observers that this subject has changed.
Notify(Observer::NT_Changed);
}
private:
/**@name Default Compiler Generated Methods (Hidden to avoid
* implicit creation/calling). These methods are not implemented
* and we do not want the compiler to implement them for us, so we
* declare them private and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Copy Constructor */
TaggedObject(const TaggedObject&);
/** Overloaded Equals Operator */
void operator=(const TaggedObject&);
//@}
/** static data member that is incremented every
* time ANY TaggedObject changes. This allows us
* to obtain a unique Tag when the object changes
*/
static IPOPT_THREAD_LOCAL Tag unique_tag_;
/** The tag indicating the current state of the object.
* We use this to compare against the comparison_tag
* in the HasChanged method. This member is updated
* from the unique_tag_ every time the object changes.
*/
Tag tag_;
/** The index indicating the cache priority for this
* TaggedObject. If a result that depended on this
* TaggedObject is cached, it will be cached with this
* priority
*/
Index cache_priority_;
};
} // namespace Ipopt
#endif
+146
View File
@@ -0,0 +1,146 @@
// Copyright (C) 2006, 2009 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpTimedTask.hpp 1861 2010-12-21 21:34:47Z andreasw $
//
// Authors: Andreas Waechter IBM 2005-09-19
#ifndef __IPTIMEDTASK_HPP__
#define __IPTIMEDTASK_HPP__
#include "IpUtils.hpp"
namespace Ipopt
{
/** This class is used to collect timing information for a
* particular task. */
class TimedTask
{
public:
/**@name Constructors/Destructors */
//@{
/** Default constructor. */
TimedTask()
:
total_cputime_(0.),
total_systime_(0.),
total_walltime_(0.),
start_called_(false),
end_called_(true)
{}
/** Default destructor */
~TimedTask()
{}
//@}
/** Method for resetting time to zero. */
void Reset()
{
total_cputime_ = 0.;
total_systime_ = 0.;
total_walltime_ = 0.;
start_called_ = false;
end_called_ = true;
}
/** Method that is called before execution of the task. */
void Start()
{
DBG_ASSERT(end_called_);
DBG_ASSERT(!start_called_);
end_called_ = false;
start_called_ = true;
start_cputime_ = CpuTime();
start_systime_ = SysTime();
start_walltime_ = WallclockTime();
}
/** Method that is called after execution of the task. */
void End()
{
DBG_ASSERT(!end_called_);
DBG_ASSERT(start_called_);
end_called_ = true;
start_called_ = false;
total_cputime_ += CpuTime() - start_cputime_;
total_systime_ += SysTime() - start_systime_;
total_walltime_ += WallclockTime() - start_walltime_;
}
/** Method that is called after execution of the task for which
* timing might have been started. This only updates the timing
* if the timing has indeed been conducted. This is useful to
* stop timing after catching exceptions. */
void EndIfStarted()
{
if (start_called_) {
end_called_ = true;
start_called_ = false;
total_cputime_ += CpuTime() - start_cputime_;
total_systime_ += SysTime() - start_systime_;
total_walltime_ += WallclockTime() - start_walltime_;
}
DBG_ASSERT(end_called_);
}
/** Method returning total CPU time spend for task so far. */
Number TotalCpuTime() const
{
DBG_ASSERT(end_called_);
return total_cputime_;
}
/** Method returning total system time spend for task so far. */
Number TotalSysTime() const
{
DBG_ASSERT(end_called_);
return total_systime_;
}
/** Method returning total wall clock time spend for task so far. */
Number TotalWallclockTime() const
{
DBG_ASSERT(end_called_);
return total_walltime_;
}
private:
/**@name Default Compiler Generated Methods (Hidden to avoid
* implicit creation/calling). These methods are not
* implemented and we do not want the compiler to implement them
* for us, so we declare them private and do not define
* them. This ensures that they will not be implicitly
* created/called. */
//@{
/** Copy Constructor */
TimedTask(const TimedTask&);
/** Overloaded Equals Operator */
void operator=(const TimedTask&);
//@}
/** CPU time at beginning of task. */
Number start_cputime_;
/** Total CPU time for task measured so far. */
Number total_cputime_;
/** System time at beginning of task. */
Number start_systime_;
/** Total system time for task measured so far. */
Number total_systime_;
/** Wall clock time at beginning of task. */
Number start_walltime_;
/** Total wall clock time for task measured so far. */
Number total_walltime_;
/** @name fields for debugging */
//@{
bool start_called_;
bool end_called_;
//@}
};
} // namespace Ipopt
#endif
+213
View File
@@ -0,0 +1,213 @@
// Copyright (C) 2005, 2008 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpTimingStatistics.hpp 2005 2011-06-06 12:55:16Z stefan $
//
// Authors: Andreas Waechter IBM 2005-09-19
#ifndef __IPTIMINGSTATISTICS_HPP__
#define __IPTIMINGSTATISTICS_HPP__
#include "IpReferenced.hpp"
#include "IpJournalist.hpp"
#include "IpTimedTask.hpp"
namespace Ipopt
{
/** This class collects all timing statistics for Ipopt.
*/
class TimingStatistics : public ReferencedObject
{
public:
/**@name Constructors/Destructors */
//@{
/** Default constructor. */
TimingStatistics()
{}
/** Default destructor */
virtual ~TimingStatistics()
{}
//@}
/** Method for resetting all times. */
void ResetTimes();
/** Method for printing all timing information */
void PrintAllTimingStatistics(Journalist& jnlst,
EJournalLevel level,
EJournalCategory category) const;
/**@name Accessor methods to all timed tasks. */
//@{
TimedTask& OverallAlgorithm()
{
return OverallAlgorithm_;
}
TimedTask& PrintProblemStatistics()
{
return PrintProblemStatistics_;
}
TimedTask& InitializeIterates()
{
return InitializeIterates_;
}
TimedTask& UpdateHessian()
{
return UpdateHessian_;
}
TimedTask& OutputIteration()
{
return OutputIteration_;
}
TimedTask& UpdateBarrierParameter()
{
return UpdateBarrierParameter_;
}
TimedTask& ComputeSearchDirection()
{
return ComputeSearchDirection_;
}
TimedTask& ComputeAcceptableTrialPoint()
{
return ComputeAcceptableTrialPoint_;
}
TimedTask& AcceptTrialPoint()
{
return AcceptTrialPoint_;
}
TimedTask& CheckConvergence()
{
return CheckConvergence_;
}
TimedTask& PDSystemSolverTotal()
{
return PDSystemSolverTotal_;
}
TimedTask& PDSystemSolverSolveOnce()
{
return PDSystemSolverSolveOnce_;
}
TimedTask& ComputeResiduals()
{
return ComputeResiduals_;
}
TimedTask& StdAugSystemSolverMultiSolve()
{
return StdAugSystemSolverMultiSolve_;
}
TimedTask& LinearSystemScaling()
{
return LinearSystemScaling_;
}
TimedTask& LinearSystemSymbolicFactorization()
{
return LinearSystemSymbolicFactorization_;
}
TimedTask& LinearSystemFactorization()
{
return LinearSystemFactorization_;
}
TimedTask& LinearSystemBackSolve()
{
return LinearSystemBackSolve_;
}
TimedTask& LinearSystemStructureConverter()
{
return LinearSystemStructureConverter_;
}
TimedTask& LinearSystemStructureConverterInit()
{
return LinearSystemStructureConverterInit_;
}
TimedTask& QualityFunctionSearch()
{
return QualityFunctionSearch_;
}
TimedTask& TryCorrector()
{
return TryCorrector_;
}
TimedTask& Task1()
{
return Task1_;
}
TimedTask& Task2()
{
return Task2_;
}
TimedTask& Task3()
{
return Task3_;
}
TimedTask& Task4()
{
return Task4_;
}
TimedTask& Task5()
{
return Task5_;
}
TimedTask& Task6()
{
return Task6_;
}
//@}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Copy Constructor */
TimingStatistics(const TimingStatistics&);
/** Overloaded Equals Operator */
void operator=(const TimingStatistics&);
//@}
/**@name All timed tasks. */
//@{
TimedTask OverallAlgorithm_;
TimedTask PrintProblemStatistics_;
TimedTask InitializeIterates_;
TimedTask UpdateHessian_;
TimedTask OutputIteration_;
TimedTask UpdateBarrierParameter_;
TimedTask ComputeSearchDirection_;
TimedTask ComputeAcceptableTrialPoint_;
TimedTask AcceptTrialPoint_;
TimedTask CheckConvergence_;
TimedTask PDSystemSolverTotal_;
TimedTask PDSystemSolverSolveOnce_;
TimedTask ComputeResiduals_;
TimedTask StdAugSystemSolverMultiSolve_;
TimedTask LinearSystemScaling_;
TimedTask LinearSystemSymbolicFactorization_;
TimedTask LinearSystemFactorization_;
TimedTask LinearSystemBackSolve_;
TimedTask LinearSystemStructureConverter_;
TimedTask LinearSystemStructureConverterInit_;
TimedTask QualityFunctionSearch_;
TimedTask TryCorrector_;
TimedTask Task1_;
TimedTask Task2_;
TimedTask Task3_;
TimedTask Task4_;
TimedTask Task5_;
TimedTask Task6_;
//@}
};
} // namespace Ipopt
#endif
+135
View File
@@ -0,0 +1,135 @@
// Copyright (C) 2004, 2009 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpTripletHelper.hpp 2380 2013-09-06 22:57:49Z ghackebeil $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPTRIPLETHELPER_HPP__
#define __IPTRIPLETHELPER_HPP__
#include "IpTypes.hpp"
#include "IpException.hpp"
namespace Ipopt
{
DECLARE_STD_EXCEPTION(UNKNOWN_MATRIX_TYPE);
DECLARE_STD_EXCEPTION(UNKNOWN_VECTOR_TYPE);
/** forward declarations */
class Matrix;
class GenTMatrix;
class SymTMatrix;
class DiagMatrix;
class IdentityMatrix;
class ExpansionMatrix;
class ScaledMatrix;
class SymScaledMatrix;
class SumMatrix;
class SumSymMatrix;
class ZeroMatrix;
class ZeroSymMatrix;
class CompoundMatrix;
class CompoundSymMatrix;
class TransposeMatrix;
class ExpandedMultiVectorMatrix;
class Vector;
class TripletHelper
{
public:
/**@name A set of recursive routines that help with the Triplet format. */
//@{
/** find the total number of triplet entries of a Matrix */
static Index GetNumberEntries(const Matrix& matrix);
/** fill the irows, jcols structure for the triplet format from the matrix */
static void FillRowCol(Index n_entries, const Matrix& matrix, Index* iRow, Index* jCol, Index row_offset=0, Index col_offset=0);
/** fill the values for the triplet format from the matrix */
static void FillValues(Index n_entries, const Matrix& matrix, Number* values);
/** fill the values from the vector into a dense double* structure */
static void FillValuesFromVector(Index dim, const Vector& vector, Number* values);
/** put the values from the double* back into the vector */
static void PutValuesInVector(Index dim, const double* values, Vector& vector);
//@}
private:
/** find the total number of triplet entries for the SumMatrix */
static Index GetNumberEntries_(const SumMatrix& matrix);
/** find the total number of triplet entries for the SumSymMatrix */
static Index GetNumberEntries_(const SumSymMatrix& matrix);
/** find the total number of triplet entries for the CompoundMatrix */
static Index GetNumberEntries_(const CompoundMatrix& matrix);
/** find the total number of triplet entries for the CompoundSymMatrix */
static Index GetNumberEntries_(const CompoundSymMatrix& matrix);
/** find the total number of triplet entries for the TransposeMatrix */
static Index GetNumberEntries_(const TransposeMatrix& matrix);
/** find the total number of triplet entries for the TransposeMatrix */
static Index GetNumberEntries_(const ExpandedMultiVectorMatrix& matrix);
static void FillRowCol_(Index n_entries, const GenTMatrix& matrix, Index row_offset, Index col_offset, Index* iRow, Index* jCol);
static void FillValues_(Index n_entries, const GenTMatrix& matrix, Number* values);
static void FillRowCol_(Index n_entries, const SymTMatrix& matrix, Index row_offset, Index col_offset, Index* iRow, Index* jCol);
static void FillValues_(Index n_entries, const SymTMatrix& matrix, Number* values);
static void FillRowCol_(Index n_entries, const DiagMatrix& matrix, Index row_offset, Index col_offset, Index* iRow, Index* jCol);
static void FillValues_(Index n_entries, const DiagMatrix& matrix, Number* values);
static void FillRowCol_(Index n_entries, const IdentityMatrix& matrix, Index row_offset, Index col_offset, Index* iRow, Index* jCol);
static void FillValues_(Index n_entries, const IdentityMatrix& matrix, Number* values);
static void FillRowCol_(Index n_entries, const ExpansionMatrix& matrix, Index row_offset, Index col_offset, Index* iRow, Index* jCol);
static void FillValues_(Index n_entries, const ExpansionMatrix& matrix, Number* values);
static void FillRowCol_(Index n_entries, const SumMatrix& matrix, Index row_offset, Index col_offset, Index* iRow, Index* jCol);
static void FillValues_(Index n_entries, const SumMatrix& matrix, Number* values);
static void FillRowCol_(Index n_entries, const SumSymMatrix& matrix, Index row_offset, Index col_offset, Index* iRow, Index* jCol);
static void FillValues_(Index n_entries, const SumSymMatrix& matrix, Number* values);
static void FillRowCol_(Index n_entries, const CompoundMatrix& matrix, Index row_offset, Index col_offset, Index* iRow, Index* jCol);
static void FillValues_(Index n_entries, const CompoundMatrix& matrix, Number* values);
static void FillRowCol_(Index n_entries, const CompoundSymMatrix& matrix, Index row_offset, Index col_offset, Index* iRow, Index* jCol);
static void FillValues_(Index n_entries, const CompoundSymMatrix& matrix, Number* values);
static void FillRowCol_(Index n_entries, const ScaledMatrix& matrix, Index row_offset, Index col_offset, Index* iRow, Index* jCol);
static void FillValues_(Index n_entries, const ScaledMatrix& matrix, Number* values);
static void FillRowCol_(Index n_entries, const SymScaledMatrix& matrix, Index row_offset, Index col_offset, Index* iRow, Index* jCol);
static void FillValues_(Index n_entries, const SymScaledMatrix& matrix, Number* values);
static void FillRowCol_(Index n_entries, const TransposeMatrix& matrix, Index row_offset, Index col_offset, Index* iRow, Index* jCol);
static void FillValues_(Index n_entries, const TransposeMatrix& matrix, Number* values);
static void FillRowCol_(Index n_entries, const ExpandedMultiVectorMatrix& matrix, Index row_offset, Index col_offset, Index* iRow, Index* jCol);
static void FillValues_(Index n_entries, const ExpandedMultiVectorMatrix& matrix, Number* values);
};
} // namespace Ipopt
#endif
+28
View File
@@ -0,0 +1,28 @@
// Copyright (C) 2004, 2006 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpTypes.hpp 2005 2011-06-06 12:55:16Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPTYPES_HPP__
#define __IPTYPES_HPP__
#include "IpoptConfig.h"
namespace Ipopt
{
/** Type of all numbers */
typedef double Number;
/** Type of all indices of vectors, matrices etc */
typedef int Index;
/** Type of default integer */
typedef int Int;
} // namespace Ipopt
/* Type of Fortran integer translated into C */
typedef FORTRAN_INTEGER_TYPE ipfint;
#endif
+128
View File
@@ -0,0 +1,128 @@
// Copyright (C) 2004, 2009 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpUtils.hpp 2167 2013-03-08 11:15:38Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPUTILS_HPP__
#define __IPUTILS_HPP__
// Standard Ip Include Files
#include "IpTypes.hpp"
#include "IpDebug.hpp"
namespace Ipopt
{
inline Index Max(Index a, Index b)
{
return ((a) > (b) ? (a) : (b));
}
inline Index Max(Index a, Index b, Index c)
{
Index max = Max(a,b);
max = Max(max, c);
return max;
}
inline Index Max(Index a, Index b, Index c, Index d)
{
Index max = Max(a, b, c);
max = Max(max, d);
return max;
}
inline Index Min(Index a, Index b)
{
return ((a) < (b) ? (a) : (b));
}
inline Index Min(Index a, Index b, Index c)
{
Index min = Min(a,b);
min = Min(min, c);
return min;
}
inline Index Min(Index a, Index b, Index c, Index d)
{
Index min = Min(a, b, c);
min = Min(min, d);
return min;
}
///////////////////////////////////////////
inline Number Max(Number a, Number b)
{
return ((a) > (b) ? (a) : (b));
}
inline Number Max(Number a, Number b, Number c)
{
Number max = Max(a,b);
max = Max(max, c);
return max;
}
inline Number Max(Number a, Number b, Number c, Number d)
{
Number max = Max(a, b, c);
max = Max(max, d);
return max;
}
inline Number Min(Number a, Number b)
{
return ((a) < (b) ? (a) : (b));
}
inline Number Min(Number a, Number b, Number c)
{
Number min = Min(a,b);
min = Min(min, c);
return min;
}
inline Number Min(Number a, Number b, Number c, Number d)
{
Number min = Min(a, b, c);
min = Min(min, d);
return min;
}
/** Function returning true iff the argument is a valid double number
* (not NaN or Inf). */
bool IsFiniteNumber(Number val);
/** Function returning a random number between 0 and 1 */
Number IpRandom01();
/** Function resetting the random number generator */
void IpResetRandom01();
/** method determining CPU time */
Number CpuTime();
/** method determining system time */
Number SysTime();
/** method determining wallclock time since first call */
Number WallclockTime();
/** Method for comparing two numbers within machine precision. The
* return value is true if lhs is less or equal the rhs, relaxing
* this inequality by something a little larger than machine
* precision relative to the absolute value of BasVal. */
bool Compare_le(Number lhs, Number rhs, Number BasVal);
/** Method for printing a formatted output to a string with given size.
*/
int Snprintf(char* str, long size, const char* format, ...);
} //namespace Ipopt
#endif
+774
View File
@@ -0,0 +1,774 @@
// Copyright (C) 2004, 2008 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpVector.hpp 2472 2014-04-05 17:47:20Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPVECTOR_HPP__
#define __IPVECTOR_HPP__
#include "IpTypes.hpp"
#include "IpTaggedObject.hpp"
#include "IpCachedResults.hpp"
#include "IpSmartPtr.hpp"
#include "IpJournalist.hpp"
#include "IpException.hpp"
#include <vector>
namespace Ipopt
{
/** Exception that can be used to flag unimplemented linear algebra
* methods */
DECLARE_STD_EXCEPTION(UNIMPLEMENTED_LINALG_METHOD_CALLED);
/* forward declarations */
class VectorSpace;
/** Vector Base Class.
* This is the base class for all derived vector types. Those vectors
* are meant to store entities like iterates, Lagrangian multipliers,
* constraint values etc. The implementation of a vector type depends
* on the computational environment (e.g. just a double array on a shared
* memory machine, or distributed double arrays for a distributed
* memory machine.)
*
* Deriving from Vector: This class inherits from tagged object to
* implement an advanced caching scheme. Because of this, the
* TaggedObject method ObjectChanged() must be called each time the
* Vector changes. If you overload the XXXX_Impl protected methods,
* this taken care of (along with caching if possible) for you. If
* you have additional methods in your derived class that change the
* underlying data (vector values), you MUST remember to call
* ObjectChanged() AFTER making the change!
*/
class Vector : public TaggedObject
{
public:
/** @name Constructor/Destructor */
//@{
/** Constructor. It has to be given a pointer to the
* corresponding VectorSpace.
*/
inline
Vector(const VectorSpace* owner_space);
/** Destructor */
inline
virtual ~Vector();
//@}
/** Create new Vector of the same type with uninitialized data */
inline
Vector* MakeNew() const;
/** Create new Vector of the same type and copy the data over */
inline
Vector* MakeNewCopy() const;
/**@name Standard BLAS-1 Operations
* (derived classes do NOT overload these
* methods, instead, overload the
* protected versions of these methods). */
//@{
/** Copy the data of the vector x into this vector (DCOPY). */
inline
void Copy(const Vector& x);
/** Scales the vector by scalar alpha (DSCAL) */
void Scal(Number alpha);
/** Add the multiple alpha of vector x to this vector (DAXPY) */
inline
void Axpy(Number alpha, const Vector &x);
/** Computes inner product of vector x with this (DDOT) */
inline
Number Dot(const Vector &x) const;
/** Computes the 2-norm of this vector (DNRM2) */
inline
Number Nrm2() const;
/** Computes the 1-norm of this vector (DASUM) */
inline
Number Asum() const;
/** Computes the max-norm of this vector (based on IDAMAX) */
inline
Number Amax() const;
//@}
/** @name Additional (Non-BLAS) Vector Methods
* (derived classes do NOT overload these
* methods, instead, overload the
* protected versions of these methods). */
//@{
/** Set each element in the vector to the scalar alpha. */
inline
void Set(Number alpha);
/** Element-wise division \f$y_i \gets y_i/x_i\f$*/
inline
void ElementWiseDivide(const Vector& x);
/** Element-wise multiplication \f$y_i \gets y_i*x_i\f$ */
inline
void ElementWiseMultiply(const Vector& x);
/** Element-wise max against entries in x */
inline
void ElementWiseMax(const Vector& x);
/** Element-wise min against entries in x */
inline
void ElementWiseMin(const Vector& x);
/** Reciprocates the entries in the vector */
inline
void ElementWiseReciprocal();
/** Absolute values of the entries in the vector */
inline
void ElementWiseAbs();
/** Element-wise square root of the entries in the vector */
inline
void ElementWiseSqrt();
/** Replaces the vector values with their sgn values
( -1 if x_i < 0, 0 if x_i == 0, and 1 if x_i > 0)
*/
inline
void ElementWiseSgn();
/** Add scalar to every vector component */
inline
void AddScalar(Number scalar);
/** Returns the maximum value in the vector */
inline
Number Max() const;
/** Returns the minimum value in the vector */
inline
Number Min() const;
/** Returns the sum of the vector entries */
inline
Number Sum() const;
/** Returns the sum of the logs of each vector entry */
inline
Number SumLogs() const;
//@}
/** @name Methods for specialized operations. A prototype
* implementation is provided, but for efficient implementation
* those should be specially implemented.
*/
//@{
/** Add one vector, y = a * v1 + c * y. This is automatically
* reduced to call AddTwoVectors. */
inline
void AddOneVector(Number a, const Vector& v1, Number c);
/** Add two vectors, y = a * v1 + b * v2 + c * y. Here, this
* vector is y */
inline void AddTwoVectors(Number a, const Vector& v1,
Number b, const Vector& v2, Number c);
/** Fraction to the boundary parameter. Computes \f$\alpha =
* \max\{\bar\alpha\in(0,1] : x + \bar\alpha \Delta \geq (1-\tau)x\}\f$
*/
inline
Number FracToBound(const Vector& delta, Number tau) const;
/** Add the quotient of two vectors, y = a * z/s + c * y. */
inline
void AddVectorQuotient(Number a, const Vector& z, const Vector& s,
Number c);
//@}
/** Method for determining if all stored numbers are valid (i.e.,
* no Inf or Nan). */
inline
bool HasValidNumbers() const;
/** @name Accessor methods */
//@{
/** Dimension of the Vector */
inline
Index Dim() const;
/** Return the owner VectorSpace*/
inline
SmartPtr<const VectorSpace> OwnerSpace() const;
//@}
/** @name Output methods
* (derived classes do NOT overload these
* methods, instead, overload the
* protected versions of these methods). */
//@{
/** Print the entire vector */
void Print(SmartPtr<const Journalist> jnlst,
EJournalLevel level,
EJournalCategory category,
const std::string& name,
Index indent=0,
const std::string& prefix="") const;
void Print(const Journalist& jnlst,
EJournalLevel level,
EJournalCategory category,
const std::string& name,
Index indent=0,
const std::string& prefix="") const;
//@}
protected:
/** @name implementation methods (derived classes MUST
* overload these pure virtual protected methods.)
*/
//@{
/** Copy the data of the vector x into this vector (DCOPY). */
virtual void CopyImpl(const Vector& x)=0;
/** Scales the vector by scalar alpha (DSCAL) */
virtual void ScalImpl(Number alpha)=0;
/** Add the multiple alpha of vector x to this vector (DAXPY) */
virtual void AxpyImpl(Number alpha, const Vector &x)=0;
/** Computes inner product of vector x with this (DDOT) */
virtual Number DotImpl(const Vector &x) const =0;
/** Computes the 2-norm of this vector (DNRM2) */
virtual Number Nrm2Impl() const =0;
/** Computes the 1-norm of this vector (DASUM) */
virtual Number AsumImpl() const =0;
/** Computes the max-norm of this vector (based on IDAMAX) */
virtual Number AmaxImpl() const =0;
/** Set each element in the vector to the scalar alpha. */
virtual void SetImpl(Number alpha)=0;
/** Element-wise division \f$y_i \gets y_i/x_i\f$*/
virtual void ElementWiseDivideImpl(const Vector& x)=0;
/** Element-wise multiplication \f$y_i \gets y_i*x_i\f$ */
virtual void ElementWiseMultiplyImpl(const Vector& x)=0;
/** Element-wise max against entries in x */
virtual void ElementWiseMaxImpl(const Vector& x)=0;
/** Element-wise min against entries in x */
virtual void ElementWiseMinImpl(const Vector& x)=0;
/** Reciprocates the elements of the vector */
virtual void ElementWiseReciprocalImpl()=0;
/** Take elementwise absolute values of the elements of the vector */
virtual void ElementWiseAbsImpl()=0;
/** Take elementwise square-root of the elements of the vector */
virtual void ElementWiseSqrtImpl()=0;
/** Replaces entries with sgn of the entry */
virtual void ElementWiseSgnImpl()=0;
/** Add scalar to every component of vector */
virtual void AddScalarImpl(Number scalar)=0;
/** Max value in the vector */
virtual Number MaxImpl() const=0;
/** Min number in the vector */
virtual Number MinImpl() const=0;
/** Sum of entries in the vector */
virtual Number SumImpl() const=0;
/** Sum of logs of entries in the vector */
virtual Number SumLogsImpl() const=0;
/** Add two vectors (a * v1 + b * v2). Result is stored in this
vector. */
virtual void AddTwoVectorsImpl(Number a, const Vector& v1,
Number b, const Vector& v2, Number c);
/** Fraction to boundary parameter. */
virtual Number FracToBoundImpl(const Vector& delta, Number tau) const;
/** Add the quotient of two vectors */
virtual void AddVectorQuotientImpl(Number a, const Vector& z,
const Vector& s, Number c);
/** Method for determining if all stored numbers are valid (i.e.,
* no Inf or Nan). A default implementation using Asum is
* provided. */
virtual bool HasValidNumbersImpl() const;
/** Print the entire vector */
virtual void PrintImpl(const Journalist& jnlst,
EJournalLevel level,
EJournalCategory category,
const std::string& name,
Index indent,
const std::string& prefix) const =0;
//@}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default constructor */
Vector();
/** Copy constructor */
Vector(const Vector&);
/** Overloaded Equals Operator */
Vector& operator=(const Vector&);
//@}
/** Vector Space */
const SmartPtr<const VectorSpace> owner_space_;
/**@name CachedResults data members */
//@{
/** Cache for dot products */
mutable CachedResults<Number> dot_cache_;
mutable TaggedObject::Tag nrm2_cache_tag_;
mutable Number cached_nrm2_;
mutable TaggedObject::Tag asum_cache_tag_;
mutable Number cached_asum_;
mutable TaggedObject::Tag amax_cache_tag_;
mutable Number cached_amax_;
mutable TaggedObject::Tag max_cache_tag_;
mutable Number cached_max_;
mutable TaggedObject::Tag min_cache_tag_;
mutable Number cached_min_;
mutable TaggedObject::Tag sum_cache_tag_;
mutable Number cached_sum_;
mutable TaggedObject::Tag sumlogs_cache_tag_;
mutable Number cached_sumlogs_;
mutable TaggedObject::Tag valid_cache_tag_;
mutable bool cached_valid_;
// AW: I removed this cache since it gets in the way for the
// quality function search
// /** Cache for FracToBound */
// mutable CachedResults<Number> frac_to_bound_cache_;
//@}
};
/** VectorSpace base class, corresponding to the Vector base class.
* For each Vector implementation, a corresponding VectorSpace has
* to be implemented. A VectorSpace is able to create new Vectors
* of a specific type. The VectorSpace should also store
* information that is common to all Vectors of that type. For
* example, the dimension of a Vector is stored in the VectorSpace
* base class.
*/
class VectorSpace : public ReferencedObject
{
public:
/** @name Constructors/Destructors */
//@{
/** Constructor, given the dimension of all vectors generated by
* this VectorSpace.
*/
VectorSpace(Index dim);
/** Destructor */
virtual ~VectorSpace()
{}
//@}
/** Pure virtual method for creating a new Vector of the
* corresponding type.
*/
virtual Vector* MakeNew() const=0;
/** Accessor function for the dimension of the vectors of this type.*/
Index Dim() const
{
return dim_;
}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** default constructor */
VectorSpace();
/** Copy constructor */
VectorSpace(const VectorSpace&);
/** Overloaded Equals Operator */
VectorSpace& operator=(const VectorSpace&);
//@}
/** Dimension of the vectors in this vector space. */
const Index dim_;
};
/* inline methods */
inline
Vector::~Vector()
{}
inline
Vector::Vector(const VectorSpace* owner_space)
:
TaggedObject(),
owner_space_(owner_space),
dot_cache_(10),
nrm2_cache_tag_(0),
asum_cache_tag_(0),
amax_cache_tag_(0),
max_cache_tag_(0),
min_cache_tag_(0),
sum_cache_tag_(0),
sumlogs_cache_tag_(0),
cached_valid_(0)
{
DBG_ASSERT(IsValid(owner_space_));
}
inline
Vector* Vector::MakeNew() const
{
return owner_space_->MakeNew();
}
inline
Vector* Vector::MakeNewCopy() const
{
// ToDo: We can probably copy also the cached values for Norms etc here
Vector* copy = MakeNew();
copy->Copy(*this);
return copy;
}
inline
void Vector::Copy(const Vector& x)
{
CopyImpl(x);
ObjectChanged();
// Also copy any cached scalar values from the original vector
// ToDo: Check if that is too much overhead
TaggedObject::Tag x_tag = x.GetTag();
if (x_tag == x.nrm2_cache_tag_) {
nrm2_cache_tag_ = GetTag();
cached_nrm2_ = x.cached_nrm2_;
}
if (x_tag == x.asum_cache_tag_) {
asum_cache_tag_ = GetTag();
cached_asum_ = x.cached_asum_;
}
if (x_tag == x.amax_cache_tag_) {
amax_cache_tag_ = GetTag();
cached_amax_ = x.cached_amax_;
}
if (x_tag == x.max_cache_tag_) {
max_cache_tag_ = GetTag();
cached_max_ = x.cached_max_;
}
if (x_tag == x.min_cache_tag_) {
min_cache_tag_ = GetTag();
cached_min_ = x.cached_min_;
}
if (x_tag == x.sum_cache_tag_) {
sum_cache_tag_ = GetTag();
cached_sum_ = x.cached_sum_;
}
if (x_tag == x.sumlogs_cache_tag_) {
sumlogs_cache_tag_ = GetTag();
cached_sumlogs_ = x.cached_sumlogs_;
}
}
inline
void Vector::Axpy(Number alpha, const Vector &x)
{
AxpyImpl(alpha, x);
ObjectChanged();
}
inline
Number Vector::Dot(const Vector &x) const
{
// The current implementation of the caching doesn't allow to have
// a dependency of something with itself. Therefore, we use the
// Nrm2 method if the dot product is to be taken with the vector
// itself. Might be more efficient anyway.
if (this==&x) {
Number nrm2 = Nrm2();
return nrm2*nrm2;
}
Number retValue;
if (!dot_cache_.GetCachedResult2Dep(retValue, this, &x)) {
retValue = DotImpl(x);
dot_cache_.AddCachedResult2Dep(retValue, this, &x);
}
return retValue;
}
inline
Number Vector::Nrm2() const
{
if (nrm2_cache_tag_ != GetTag()) {
cached_nrm2_ = Nrm2Impl();
nrm2_cache_tag_ = GetTag();
}
return cached_nrm2_;
}
inline
Number Vector::Asum() const
{
if (asum_cache_tag_ != GetTag()) {
cached_asum_ = AsumImpl();
asum_cache_tag_ = GetTag();
}
return cached_asum_;
}
inline
Number Vector::Amax() const
{
if (amax_cache_tag_ != GetTag()) {
cached_amax_ = AmaxImpl();
amax_cache_tag_ = GetTag();
}
return cached_amax_;
}
inline
Number Vector::Sum() const
{
if (sum_cache_tag_ != GetTag()) {
cached_sum_ = SumImpl();
sum_cache_tag_ = GetTag();
}
return cached_sum_;
}
inline
Number Vector::SumLogs() const
{
if (sumlogs_cache_tag_ != GetTag()) {
cached_sumlogs_ = SumLogsImpl();
sumlogs_cache_tag_ = GetTag();
}
return cached_sumlogs_;
}
inline
void Vector::ElementWiseSgn()
{
ElementWiseSgnImpl();
ObjectChanged();
}
inline
void Vector::Set(Number alpha)
{
// Could initialize caches here
SetImpl(alpha);
ObjectChanged();
}
inline
void Vector::ElementWiseDivide(const Vector& x)
{
ElementWiseDivideImpl(x);
ObjectChanged();
}
inline
void Vector::ElementWiseMultiply(const Vector& x)
{
ElementWiseMultiplyImpl(x);
ObjectChanged();
}
inline
void Vector::ElementWiseReciprocal()
{
ElementWiseReciprocalImpl();
ObjectChanged();
}
inline
void Vector::ElementWiseMax(const Vector& x)
{
// Could initialize some caches here
ElementWiseMaxImpl(x);
ObjectChanged();
}
inline
void Vector::ElementWiseMin(const Vector& x)
{
// Could initialize some caches here
ElementWiseMinImpl(x);
ObjectChanged();
}
inline
void Vector::ElementWiseAbs()
{
// Could initialize some caches here
ElementWiseAbsImpl();
ObjectChanged();
}
inline
void Vector::ElementWiseSqrt()
{
ElementWiseSqrtImpl();
ObjectChanged();
}
inline
void Vector::AddScalar(Number scalar)
{
// Could initialize some caches here
AddScalarImpl(scalar);
ObjectChanged();
}
inline
Number Vector::Max() const
{
if (max_cache_tag_ != GetTag()) {
cached_max_ = MaxImpl();
max_cache_tag_ = GetTag();
}
return cached_max_;
}
inline
Number Vector::Min() const
{
if (min_cache_tag_ != GetTag()) {
cached_min_ = MinImpl();
min_cache_tag_ = GetTag();
}
return cached_min_;
}
inline
void Vector::AddOneVector(Number a, const Vector& v1, Number c)
{
AddTwoVectors(a, v1, 0., v1, c);
}
inline
void Vector::AddTwoVectors(Number a, const Vector& v1,
Number b, const Vector& v2, Number c)
{
AddTwoVectorsImpl(a, v1, b, v2, c);
ObjectChanged();
}
inline
Number Vector::FracToBound(const Vector& delta, Number tau) const
{
/* AW: I avoid the caching here, since it leads to overhead in the
quality function search. Caches for this are in
CalculatedQuantities.
Number retValue;
std::vector<const TaggedObject*> tdeps(1);
tdeps[0] = &delta;
std::vector<Number> sdeps(1);
sdeps[0] = tau;
if (!frac_to_bound_cache_.GetCachedResult(retValue, tdeps, sdeps)) {
retValue = FracToBoundImpl(delta, tau);
frac_to_bound_cache_.AddCachedResult(retValue, tdeps, sdeps);
}
return retValue;
*/
return FracToBoundImpl(delta, tau);
}
inline
void Vector::AddVectorQuotient(Number a, const Vector& z,
const Vector& s, Number c)
{
AddVectorQuotientImpl(a, z, s, c);
ObjectChanged();
}
inline
bool Vector::HasValidNumbers() const
{
if (valid_cache_tag_ != GetTag()) {
cached_valid_ = HasValidNumbersImpl();
valid_cache_tag_ = GetTag();
}
return cached_valid_;
}
inline
Index Vector::Dim() const
{
return owner_space_->Dim();
}
inline
SmartPtr<const VectorSpace> Vector::OwnerSpace() const
{
return owner_space_;
}
inline
VectorSpace::VectorSpace(Index dim)
:
dim_(dim)
{}
} // namespace Ipopt
// Macro definitions for debugging vectors
#if COIN_IPOPT_VERBOSITY == 0
# define DBG_PRINT_VECTOR(__verbose_level, __vec_name, __vec)
#else
# define DBG_PRINT_VECTOR(__verbose_level, __vec_name, __vec) \
if (dbg_jrnl.Verbosity() >= (__verbose_level)) { \
if (dbg_jrnl.Jnlst()!=NULL) { \
(__vec).Print(dbg_jrnl.Jnlst(), \
J_ERROR, J_DBG, \
__vec_name, \
dbg_jrnl.IndentationLevel()*2, \
"# "); \
} \
}
#endif //if COIN_IPOPT_VERBOSITY == 0
#endif
+135
View File
@@ -0,0 +1,135 @@
// Copyright (C) 2004, 2008 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpZeroSymMatrix.hpp 2269 2013-05-05 11:32:40Z stefan $
//
// Authors: Carl Laird, Andreas Waechter IBM 2004-08-13
#ifndef __IPZEROSYMMATRIX_HPP__
#define __IPZEROSYMMATRIX_HPP__
#include "IpUtils.hpp"
#include "IpSymMatrix.hpp"
namespace Ipopt
{
/** Class for Symmetric Matrices with only zero entries.
*/
class ZeroSymMatrix : public SymMatrix
{
public:
/**@name Constructors / Destructors */
//@{
/** Constructor, taking the corresponding matrix space.
*/
ZeroSymMatrix(const SymMatrixSpace* owner_space);
/** Destructor */
~ZeroSymMatrix();
//@}
protected:
/**@name Methods overloaded from matrix */
//@{
virtual void MultVectorImpl(Number alpha, const Vector& x,
Number beta, Vector& y) const;
virtual void TransMultVectorImpl(Number alpha, const Vector& x,
Number beta, Vector& y) const;
virtual void ComputeRowAMaxImpl(Vector& rows_norms, bool init) const
{}
virtual void ComputeColAMaxImpl(Vector& cols_norms, bool init) const
{}
virtual void PrintImpl(const Journalist& jnlst,
EJournalLevel level,
EJournalCategory category,
const std::string& name,
Index indent,
const std::string& prefix) const;
//@}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
ZeroSymMatrix();
/** Copy Constructor */
ZeroSymMatrix(const ZeroSymMatrix&);
/** Overloaded Equals Operator */
void operator=(const ZeroSymMatrix&);
//@}
};
/** Class for matrix space for ZeroSymMatrix. */
class ZeroSymMatrixSpace : public SymMatrixSpace
{
public:
/** @name Constructors / Destructors */
//@{
/** Constructor, given the number of row and columns.
*/
ZeroSymMatrixSpace(Index dim)
:
SymMatrixSpace(dim)
{}
/** Destructor */
virtual ~ZeroSymMatrixSpace()
{}
//@}
/** Overloaded MakeNew method for the MatrixSpace base class.
*/
virtual Matrix* MakeNew() const
{
return MakeNewZeroSymMatrix();
}
/** Overloaded method from SymMatrixSpace base class
*/
virtual SymMatrix* MakeNewSymMatrix() const
{
return MakeNewZeroSymMatrix();
}
/** Method for creating a new matrix of this specific type. */
ZeroSymMatrix* MakeNewZeroSymMatrix() const
{
return new ZeroSymMatrix(this);
}
private:
/**@name Default Compiler Generated Methods
* (Hidden to avoid implicit creation/calling).
* These methods are not implemented and
* we do not want the compiler to implement
* them for us, so we declare them private
* and do not define them. This ensures that
* they will not be implicitly created/called. */
//@{
/** Default Constructor */
ZeroSymMatrixSpace();
/** Copy Constructor */
ZeroSymMatrixSpace(const ZeroSymMatrixSpace&);
/** Overloaded Equals Operator */
void operator=(const ZeroSymMatrixSpace&);
//@}
};
} // namespace Ipopt
#endif
+22
View File
@@ -0,0 +1,22 @@
/* src/Common/config_ipopt.h. Generated by configure. */
/* src/Common/config_ipopt.h.in. */
#ifndef __CONFIG_IPOPT_H__
#define __CONFIG_IPOPT_H__
/* Version number of project */
#define IPOPT_VERSION "3.12.8"
/* Major Version number of project */
#define IPOPT_VERSION_MAJOR 3
/* Minor Version number of project */
#define IPOPT_VERSION_MINOR 12
/* Release Version number of project */
#define IPOPT_VERSION_RELEASE 8
/* Define to the C type corresponding to Fortran INTEGER */
#define FORTRAN_INTEGER_TYPE int
#endif
+41
View File
@@ -0,0 +1,41 @@
/* Copyright (C) 2008 GAMS Development and others
All Rights Reserved.
This code is published under the Eclipse Public License.
$Id: PardisoLoader.h 2204 2013-04-13 13:49:26Z stefan $
Author: Stefan Vigerske
*/
#ifndef PARDISOLOADER_H_
#define PARDISOLOADER_H_
#ifdef __cplusplus
extern "C" {
#endif
/** Tries to load a dynamically linked library with Pardiso.
* Return a failure if the library cannot be loaded or not all Pardiso symbols are found.
* @param libname The name under which the Pardiso lib can be found, or NULL to use a default name (libpardiso.SHAREDLIBEXT).
* @param msgbuf A buffer where we can store a failure message. Assumed to be NOT NULL!
* @param msglen Length of the message buffer.
* @return Zero on success, nonzero on failure.
*/
int LSL_loadPardisoLib(const char* libname, char* msgbuf, int msglen);
/** Unloads a loaded Pardiso library.
* @return Zero on success, nonzero on failure.
*/
int LSL_unloadPardisoLib();
/** Indicates whether a Pardiso library has been successfully loaded.
* @return Zero if not loaded, nonzero if handle is loaded
*/
int LSL_isPardisoLoaded();
/** Returns name of the shared library that should contain Pardiso */
char* LSL_PardisoLibraryName();
#ifdef __cplusplus
}
#endif
#endif /*PARADISOLOADER_H_*/
+8
View File
@@ -0,0 +1,8 @@
#define IEEE_8087
#define Arith_Kind_ASL 1
#define Long int
#define Intcast (int)(long)
#define Double_Align
#define X64_bit_pointers
#define QNaN0 0x0
#define QNaN1 0xfff80000
File diff suppressed because it is too large Load Diff
+29
View File
@@ -0,0 +1,29 @@
/****************************************************************
Copyright (C) 1997 Lucent Technologies
All Rights Reserved
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name of Lucent or any of its entities
not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
****************************************************************/
#undef PSHVREAD
#ifndef ASL_PFG_included
#define ASL_PFG_included
#include "psinfo.h"
#endif /* ASL_PFG_included */
+30
View File
@@ -0,0 +1,30 @@
/****************************************************************
Copyright (C) 1997 Lucent Technologies
All Rights Reserved
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name of Lucent or any of its entities
not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
****************************************************************/
#undef PSHVREAD
#define PSHVREAD
#ifndef ASL_PFGH_included
#define ASL_PFGH_included
#include "psinfo.h"
#endif /* ASL_PFGH_included */
+159
View File
@@ -0,0 +1,159 @@
/*
*
* This file is part of MUMPS 4.10.0, built on Tue May 10 12:56:32 UTC 2011
*
*
* This version of MUMPS is provided to you free of charge. It is public
* domain, based on public domain software developed during the Esprit IV
* European project PARASOL (1996-1999). Since this first public domain
* version in 1999, research and developments have been supported by the
* following institutions: CERFACS, CNRS, ENS Lyon, INPT(ENSEEIHT)-IRIT,
* INRIA, and University of Bordeaux.
*
* The MUMPS team at the moment of releasing this version includes
* Patrick Amestoy, Maurice Bremond, Alfredo Buttari, Abdou Guermouche,
* Guillaume Joslin, Jean-Yves L'Excellent, Francois-Henry Rouet, Bora
* Ucar and Clement Weisbecker.
*
* We are also grateful to Emmanuel Agullo, Caroline Bousquet, Indranil
* Chowdhury, Philippe Combes, Christophe Daniel, Iain Duff, Vincent Espirat,
* Aurelia Fevre, Jacko Koster, Stephane Pralet, Chiara Puglisi, Gregoire
* Richard, Tzvetomila Slavova, Miroslav Tuma and Christophe Voemel who
* have been contributing to this project.
*
* Up-to-date copies of the MUMPS package can be obtained
* from the Web pages:
* http://mumps.enseeiht.fr/ or http://graal.ens-lyon.fr/MUMPS
*
*
* THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY
* EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
*
*
* User documentation of any code that uses this software can
* include this complete notice. You can acknowledge (using
* references [1] and [2]) the contribution of this package
* in any scientific publication dependent upon the use of the
* package. You shall use reasonable endeavours to notify
* the authors of the package of this publication.
*
* [1] P. R. Amestoy, I. S. Duff, J. Koster and J.-Y. L'Excellent,
* A fully asynchronous multifrontal solver using distributed dynamic
* scheduling, SIAM Journal of Matrix Analysis and Applications,
* Vol 23, No 1, pp 15-41 (2001).
*
* [2] P. R. Amestoy and A. Guermouche and J.-Y. L'Excellent and
* S. Pralet, Hybrid scheduling for the parallel solution of linear
* systems. Parallel Computing Vol 32 (2), pp 136-156 (2006).
*
*/
/* Mostly written in march 2002 (JYL) */
#ifndef DMUMPS_C_H
#define DMUMPS_C_H
#ifdef __cplusplus
extern "C" {
#endif
#include "mumps_compat.h"
/* Next line defines MUMPS_INT, DMUMPS_COMPLEX and DMUMPS_REAL */
#include "mumps_c_types.h"
#ifndef MUMPS_VERSION
/* Protected in case headers of other arithmetics are included */
#define MUMPS_VERSION "4.10.0"
#endif
#ifndef MUMPS_VERSION_MAX_LEN
#define MUMPS_VERSION_MAX_LEN 14
#endif
/*
* Definition of the (simplified) MUMPS C structure.
* NB: DMUMPS_COMPLEX are REAL types in s and d arithmetics.
*/
typedef struct {
MUMPS_INT sym, par, job;
MUMPS_INT comm_fortran; /* Fortran communicator */
MUMPS_INT icntl[40];
DMUMPS_REAL cntl[15];
MUMPS_INT n;
MUMPS_INT nz_alloc; /* used in matlab interface to decide if we
free + malloc when we have large variation */
/* Assembled entry */
MUMPS_INT nz;
MUMPS_INT *irn;
MUMPS_INT *jcn;
DMUMPS_COMPLEX *a;
/* Distributed entry */
MUMPS_INT nz_loc;
MUMPS_INT *irn_loc;
MUMPS_INT *jcn_loc;
DMUMPS_COMPLEX *a_loc;
/* Element entry */
MUMPS_INT nelt;
MUMPS_INT *eltptr;
MUMPS_INT *eltvar;
DMUMPS_COMPLEX *a_elt;
/* Ordering, if given by user */
MUMPS_INT *perm_in;
/* Orderings returned to user */
MUMPS_INT *sym_perm; /* symmetric permutation */
MUMPS_INT *uns_perm; /* column permutation */
/* Scaling (input only in this version) */
DMUMPS_REAL *colsca;
DMUMPS_REAL *rowsca;
/* RHS, solution, ouptput data and statistics */
DMUMPS_COMPLEX *rhs, *redrhs, *rhs_sparse, *sol_loc;
MUMPS_INT *irhs_sparse, *irhs_ptr, *isol_loc;
MUMPS_INT nrhs, lrhs, lredrhs, nz_rhs, lsol_loc;
MUMPS_INT schur_mloc, schur_nloc, schur_lld;
MUMPS_INT mblock, nblock, nprow, npcol;
MUMPS_INT info[40],infog[40];
DMUMPS_REAL rinfo[40], rinfog[40];
/* Null space */
MUMPS_INT deficiency;
MUMPS_INT *pivnul_list;
MUMPS_INT *mapping;
/* Schur */
MUMPS_INT size_schur;
MUMPS_INT *listvar_schur;
DMUMPS_COMPLEX *schur;
/* Internal parameters */
MUMPS_INT instance_number;
DMUMPS_COMPLEX *wk_user;
/* Version number: length=14 in FORTRAN + 1 for final \0 + 1 for alignment */
char version_number[MUMPS_VERSION_MAX_LEN + 1 + 1];
/* For out-of-core */
char ooc_tmpdir[256];
char ooc_prefix[64];
/* To save the matrix in matrix market format */
char write_problem[256];
MUMPS_INT lwk_user;
} DMUMPS_STRUC_C;
void MUMPS_CALL
dmumps_c( DMUMPS_STRUC_C * dmumps_par );
#ifdef __cplusplus
}
#endif
#endif /* DMUMPS_C_H */
+487
View File
@@ -0,0 +1,487 @@
/****************************************************************
Copyright (C) 1997-2001 Lucent Technologies
All Rights Reserved
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name of Lucent or any of its entities
not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
****************************************************************/
#ifndef FUNCADD_H_INCLUDED
#define FUNCADD_H_INCLUDED
#include "stdio1.h" /* for ANSI and any printing */
#ifndef VA_LIST
#define VA_LIST va_list
#endif
#ifdef _WIN32
#define Stdio_redefs
#endif
typedef struct cryptblock cryptblock;
#ifdef __cplusplus
#undef KR_headers
extern "C" {
#endif
#ifndef real
typedef double real;
#endif
typedef struct arglist arglist;
typedef struct function function;
typedef struct TVA TVA;
typedef struct AmplExports AmplExports;
typedef struct AuxInfo AuxInfo;
typedef struct TableInfo TableInfo;
typedef struct TMInfo TMInfo;
#ifndef No_arglist_def
#undef Const
#ifdef KR_headers
#define Const /* nothing */
#else
#define Const const
#endif
struct
arglist { /* Information sent to user-defined functions */
int n; /* number of args */
int nr; /* number of real input args */
int *at; /* argument types -- see DISCUSSION below */
real *ra; /* pure real args (IN, OUT, and INOUT) */
Const char **sa; /* symbolic IN args */
real *derivs; /* for partial derivatives (if nonzero) */
real *hes; /* for second partials (if nonzero) */
char *dig; /* if (dig && dig[i]) { partials w.r.t. */
/* ra[i] will not be used } */
Char *funcinfo; /* for use by the function (if desired) */
AmplExports *AE; /* functions made visible (via #defines below) */
function *f; /* for internal use by AMPL */
TVA *tva; /* for internal use by AMPL */
char *Errmsg; /* To indicate an error, set this to a */
/* description of the error. When derivs */
/* is nonzero and the error is that first */
/* derivatives cannot or are not computed, */
/* a single quote character (') should be */
/* the first character in the text assigned */
/* to Errmsg, followed by the actual error */
/* message. Similarly, if hes is nonzero */
/* and the error is that second derivatives */
/* are not or cannot be computed, a double */
/* quote character (") should be the first */
/* character in Errmsg, followed by the */
/* actual error message text. */
TMInfo *TMI; /* used in Tempmem calls */
Char *Private;
/* The following fields are relevant */
/* only when imported functions are called */
/* by AMPL commands (not declarations). */
int nin; /* number of input (IN and INOUT) args */
int nout; /* number of output (OUT and INOUT) args */
int nsin; /* number of symbolic input arguments */
int nsout; /* number of symbolic OUT and INOUT args */
};
typedef real (*rfunc) ANSI((arglist *));
typedef real (ufunc) ANSI((arglist *));
#endif /* No_arglist_def */
enum AMPLFUNC_AT_BITS { /* Intrepretation of at[i] when the type */
/* arg to addfunc has the */
/* FUNCADD_OUTPUT_ARGS bit on.*/
AMPLFUNC_INARG = 1, /* IN or INOUT */
AMPLFUNC_OUTARG = 2, /* OUT or INOUT */
AMPLFUNC_STRING = 4, /* Input value is a string (sa[i]) */
AMPLFUNC_STROUT = 8 /* String output value allowed */
};
enum FUNCADD_TYPE { /* bits in "type" arg to addfunc */
/* The type arg to addfunc should consist of one of the */
/* following values ... */
FUNCADD_REAL_VALUED = 0, /* real (double) valued function */
FUNCADD_STRING_VALUED = 2, /* char* valued function (AMPL only) */
FUNCADD_RANDOM_VALUED = 4, /* real random valued */
FUNCADD_012ARGS = 6, /* Special case: real random valued */
/* with 0 <= nargs <= 2 arguments */
/* passed directly, rather than in */
/* an arglist structure (AMPL only). */
/* possibly or-ed with the following... */
FUNCADD_STRING_ARGS = 1, /* allow string args */
FUNCADD_OUTPUT_ARGS = 16, /* allow output args (AMPL only) */
FUNCADD_TUPLE_VALUED = 32, /* not yet allowed */
/* internal use */
FUNCADD_NO_ARGLIST = 8,
FUNCADD_NO_DUPWARN = 64, /* no complaint if already defined */
FUNCADD_NONRAND_BUILTIN = 128 /* mean, variance, moment, etc. */
};
/* If a constraint involves an imported function and presolve fixes all
* the arguments of the function, AMPL may later need to ask the
* function for its partial derivatives -- even though the solver had
* no reason to call the function. If so, it will pass an arglist *al
* with al->derivs nonzero, and it will expect the function to set
* al->derivs[i] to the partial derivative of the function with respect
* to al->ra[i]. Solvers that need to evaluate an imported function
* work the same way -- they set al->derivs to a nonzero value if they
* require both the function value and its first derivatives. Solvers
* that expect Hessians to be supplied to them also set al->hes to a
* nonzero value if they require second derivatives at the current
* argument. In this case, the function should set
* al->hes[i + j*(j+1)/2] to the partial derivative of the function with
* respect to al->ra[i] and al->ra[j] for all 0 <= i <= j < al->nr.
*/
typedef void AddFunc ANSI((
const char *name,
rfunc f, /* cast f to (rfunc) if it returns char* */
int type, /* see FUNCADD_TYPE above */
int nargs, /* >= 0 ==> exactly that many args
* <= -1 ==> at least -(nargs+1) args
*/
void *funcinfo, /* for use by the function (if desired) */
AmplExports *ae
));
typedef void AddRand ANSI((
const char *name,
rfunc f, /* assumed to be a random function */
rfunc icdf, /* inverse CDF */
int type, /* FUNCADD_STRING_ARGS or 0 */
int nargs, /* >= 0 ==> exactly that many args
* <= -1 ==> at least -(nargs+1) args
*/
void *funcinfo, /* for use by the function (if desired) */
AmplExports *ae
));
typedef void (*RandSeedSetter) ANSI((void*, unsigned long));
typedef void AddRandInit ANSI((AmplExports *ae, RandSeedSetter, void*));
typedef void Exitfunc ANSI((void*));
struct
AuxInfo {
AuxInfo *next;
char *auxname;
void *v;
void (*f) ANSI((AmplExports*, void*, ...));
};
struct
AmplExports {
FILE *StdErr;
AddFunc *Addfunc;
long ASLdate;
int (*FprintF) ANSI((FILE*, const char*, ...));
int (*PrintF) ANSI((const char*, ...));
int (*SprintF) ANSI((char*, const char*, ...));
int (*VfprintF) ANSI((FILE*, const char*, VA_LIST));
int (*VsprintF) ANSI((char*, const char*, VA_LIST));
double (*Strtod) ANSI((const char*, char**));
cryptblock *(*Crypto) ANSI((char *key, size_t scrbytes));
Char *asl;
void (*AtExit) ANSI((AmplExports *ae, Exitfunc*, void*));
void (*AtReset) ANSI((AmplExports *ae, Exitfunc*, void*));
Char *(*Tempmem) ANSI((TMInfo*, size_t));
void (*Add_table_handler) ANSI((
int (*DbRead) (AmplExports *ae, TableInfo *TI),
int (*DbWrite)(AmplExports *ae, TableInfo *TI),
char *handler_info,
int flags,
void *Vinfo
));
Char *Private;
void (*Qsortv) ANSI((void*, size_t, size_t, int(*)(const void*,const void*,void*), void*));
/* More stuff for stdio in DLLs... */
FILE *StdIn;
FILE *StdOut;
void (*Clearerr) ANSI((FILE*));
int (*Fclose) ANSI((FILE*));
FILE* (*Fdopen) ANSI((int, const char*));
int (*Feof) ANSI((FILE*));
int (*Ferror) ANSI((FILE*));
int (*Fflush) ANSI((FILE*));
int (*Fgetc) ANSI((FILE*));
char* (*Fgets) ANSI((char*, int, FILE*));
int (*Fileno) ANSI((FILE*));
FILE* (*Fopen) ANSI((const char*, const char*));
int (*Fputc) ANSI((int, FILE*));
int (*Fputs) ANSI((const char*, FILE*));
size_t (*Fread) ANSI((void*, size_t, size_t, FILE*));
FILE* (*Freopen) ANSI((const char*, const char*, FILE*));
int (*Fscanf) ANSI((FILE*, const char*, ...));
int (*Fseek) ANSI((FILE*, long, int));
long (*Ftell) ANSI((FILE*));
size_t (*Fwrite) ANSI((const void*, size_t, size_t, FILE*));
int (*Pclose) ANSI((FILE*));
void (*Perror) ANSI((const char*));
FILE* (*Popen) ANSI((const char*, const char*));
int (*Puts) ANSI((const char*));
void (*Rewind) ANSI((FILE*));
int (*Scanf) ANSI((const char*, ...));
void (*Setbuf) ANSI((FILE*, char*));
int (*Setvbuf) ANSI((FILE*, char*, int, size_t));
int (*Sscanf) ANSI((const char*, const char*, ...));
char* (*Tempnam) ANSI((const char*, const char*));
FILE* (*Tmpfile) ANSI((void));
char* (*Tmpnam) ANSI((char*));
int (*Ungetc) ANSI((int, FILE*));
AuxInfo *AI;
char* (*Getenv) ANSI((const char*));
void (*Breakfunc) ANSI((int,void*));
Char *Breakarg;
/* Items available with ASLdate >= 20020501 start here. */
int (*SnprintF) ANSI((char*, size_t, const char*, ...));
int (*VsnprintF) ANSI((char*, size_t, const char*, VA_LIST));
AddRand *Addrand; /* for random function/inverse CDF pairs */
AddRandInit *Addrandinit; /* for adding a function to receive a new random seed */
};
extern const char *i_option_ASL, *ix_details_ASL[];
#define funcadd funcadd_ASL
#if defined(_WIN32) && !defined(__MINGW32__)
__declspec(dllexport)
#endif
extern void funcadd ANSI((AmplExports*)); /* dynamically linked */
extern void af_libnamesave_ASL ANSI((AmplExports*, const char *fullname, const char *name, int nlen));
extern void note_libuse_ASL ANSI((void)); /* If funcadd() does not provide any imported */
/* functions, it can call note_libuse_ASL() to */
/* keep the library loaded; note_libuse_ASL() is */
/* called, e.g., by the tableproxy table handler. */
#ifdef __cplusplus
}
#endif
typedef struct
DbCol {
real *dval;
char **sval;
} DbCol;
struct
TableInfo {
int (*AddRows) ANSI((TableInfo *TI, DbCol *cols, long nrows));
char *tname; /* name of this table */
char **strings;
char **colnames;
DbCol *cols;
char *Missing;
char *Errmsg;
void *Vinfo;
TMInfo *TMI;
int nstrings;
int arity;
int ncols;
int flags;
long nrows;
void *Private;
int (*Lookup) ANSI((real*, char**, TableInfo*));
long (*AdjustMaxrows) ANSI((TableInfo*, long new_maxrows));
void *(*ColAlloc) ANSI((TableInfo*, int ncol, int sval));
long maxrows;
};
enum { /* return values from (*DbRead)(...) and (*DbWrite)(...) */
DB_Done = 0, /* Table read or written. */
DB_Refuse = 1, /* Refuse to handle this table. */
DB_Error = 2 /* Error reading or writing table. */
};
enum { /* bits in flags field of TableInfo */
DBTI_flags_IN = 1, /* table has IN or INOUT entities */
DBTI_flags_OUT = 2, /* table has OUT or INOUT entities */
DBTI_flags_INSET = 4 /* table has "in set" phrase: */
/* DbRead could omit rows for */
/* which Lookup(...) == -1; AMPL */
/* will ignore such rows if DbRead */
/* offers them. */
};
#endif /* FUNCADD_H_INCLUDED */
#ifndef No_AE_redefs
/* Assume "{extern|static} AmplExports *ae;" is given elsewhere. */
#undef Stderr
#undef addfunc
#undef fprintf
#undef getenv
#undef printf
#undef sprintf
#undef snprintf
#undef strtod
#undef vfprintf
#undef vsprintf
#undef vsnprintf
#define Stderr (ae->StdErr)
#define addfunc(a,b,c,d,e) (*ae->Addfunc)(a,b,c,d,e,ae)
#define addrand(a,b,c,d,e,f) (*ae->Addrand)(a,b,c,d,e,f,ae)
#define addrandinit(a,b) (*ae->Addrandinit)(ae,a,b)
#define printf (*ae->PrintF)
#define fprintf (*ae->FprintF)
#define snprintf (*ae->SnprintF)
#define sprintf (*ae->SprintF)
#define strtod (*ae->Strtod)
#define vfprintf (*ae->VfprintF)
#define vsprintf (*ae->VsprintF)
#define vsnprintf (*ae->VsnprintF)
#define TempMem(x,y) (*ae->Tempmem)(x,y)
#define at_exit(x,y) (*ae->AtExit)(ae,x,y)
#define at_reset(x,y) (*ae->AtReset)(ae,x,y)
#define add_table_handler(a,b,c,d,e) (*ae->Add_table_handler)(a,b,c,d,e)
#define qsortv(a,b,c,d,e) (*ae->Qsortv)(a,b,c,d,e)
#define getenv(x) (*ae->Getenv)(x)
#ifdef Stdio_redefs
#undef clearerr
#undef fclose
#undef fdopen
#undef feof
#undef ferror
#undef fflush
#undef fgetc
#undef fgets
#undef fileno
#undef fopen
#undef fputc
#undef fputs
#undef fread
#undef freopen
#undef fscanf
#undef fseek
#undef ftell
#undef fwrite
#undef getc
#undef getchar
#undef gets
#undef pclose
#undef perror
#undef popen
#undef putc
#undef putchar
#undef puts
#undef rewind
#undef scanf
#undef setbuf
#undef setvbuf
#undef sscanf
#undef tempnam
#undef tmpfile
#undef tmpnam
#undef ungetc
#undef vprintf
#define clearerr (*ae->Clearerr)
#define fclose (*ae->Fclose)
#define fdopen (*ae->Fdopen)
#define feof (*ae->Feof)
#define ferror (*ae->Ferror)
#define fflush (*ae->Fflush)
#define fgetc (*ae->Fgetc)
#define fgets (*ae->Fgets)
#define fileno (*ae->Fileno)
#define fopen (*ae->Fopen)
#define fputc (*ae->Fputc)
#define fputs (*ae->Fputs)
#define fread (*ae->Fread)
#define freopen (*ae->Freopen)
#define fscanf (*ae->Fscanf)
#define fseek (*ae->Fseek)
#define ftell (*ae->Ftell)
#define fwrite (*ae->Fwrite)
#define getc (*ae->Fgetc)
#define getchar() (*ae->Getc)(ae->StdIn)
#define gets Error - use "fgets" rather than "gets"
#define pclose (*ae->Pclose)
#define perror (*ae->Perror)
#define popen (*ae->Popen)
#define putc (*ae->Fputc)
#define putchar(x) (*ae->Fputc)(ae->StdOut,(x))
#define puts (*ae->Puts)
#define rewind (*ae->Rewind)
#define scanf (*ae->Scanf)
#define setbuf (*ae->Setbuf)
#define setvbuf (*ae->Setvbuf)
#define sscanf (*ae->Sscanf)
#define tempnam (*ae->Tempnam)
#define tmpfile (*ae->Tmpfile)
#define tmpnam (*ae->Tmpnam)
#define ungetc (*ae->Ungetc)
#define vprintf(x,y) (*ae->VfprintF)(ae->StdOut,(x),(y))
#define Stdin (ae->StdIn)
#define Stdout (ae->StdOut)
#ifndef No_std_FILE_redefs /* may elicit compiler warnings */
#undef stdin
#undef stdout
#undef stderr
#define stdin (ae->StdIn)
#define stdout (ae->StdOut)
#define stderr (ae->StdErr)
#endif /* No_std_FILE_redefs */
#endif /* Stdio_redefs */
#endif /* ifndef No_AE_redefs */
/* DISCUSSION: the "at" field of an arglist...
*
* OUT and INOUT arguments are only permitted in AMPL commands,
* such as "let" and "call" commands (and not in declarations, e.g.,
* of constraints and variables).
*
* When addfunc was called with type <= 6 (so there can be no OUT or
* INOUT arguments), for 0 <= i < n,
* at[i] >= 0 ==> arg i is ra[at[i]]
* at[i] < 0 ==> arg i is sa[-(at[i]+1)].
*
* When addfunc was called with type & FUNCADD_OUTPUT_ARGS on (permitting
* OUT and INOUT arguments), arg i is in ra[i] or sa[i] (as explained
* below), derivs and hes are both null, and at[i] is the union of bits
* that describe arg i:
* AMPLFUNC_INARG = 1 ==> input arg;
* AMPLFUNC_OUTARG = 2 ==> output arg;
* AMPLFUNC_STROUT = 4 ==> can be assigned a string value.
*
* INOUT args have both the AMPLFUNC_INARG and the AMPLFUNC_OUTARG bits
* are on, i.e., (at[i] & 3) == 3.
*
* Symbolic OUT and INOUT arguments are a bit complicated. They can only
* correspond to symbolic parameters in AMPL, which may have either a
* string or a numeric value. Thus there is provision for specifying
* output values to be either numbers or strings. For simplicity, when
* the function accepts output arguments, ra[i] and sa[i] together describe
* argument i. In general (whentype & FUNCADD_OUTPUT_ARGS is nonzero in
* the addfunc call), the incoming value of argument i is ra[i]
* (a numeric value) if sa[i] is null and is otherwise sa[i].
* To assign a value to argument i, either assign a numeric value to
* ra[i] and set sa[i] = 0, or assign a non-null value to sa[i]
* (in which case ra[i] will be ignored). A value assigned to argument
* i is ignored unless at[i] & AMPLFUNC_OUTARG is nonzero; if so
* and if (at[i] & AMPLFUNC_STROUT) == 0, string values cause an error
* message.
*/
+206
View File
@@ -0,0 +1,206 @@
/****************************************************************
Copyright (C) 1997-1998, 2000-2001 Lucent Technologies
All Rights Reserved
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name of Lucent or any of its entities
not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
****************************************************************/
#ifndef GETSTUB_H_included
#define GETSTUB_H_included
#ifndef ASL_included
#include "asl.h"
#endif
typedef struct keyword keyword;
typedef char *
Kwfunc(Option_Info *oi, keyword *kw, char *value);
struct
keyword {
char *name;
Kwfunc *kf;
void *info;
char *desc;
};
#define KW(a,b,c,d) {a,b,(void*)(c),d}
#define nkeywds (int)(sizeof(keywds)/sizeof(keyword))
typedef fint Solver_KW_func(char*, fint);
typedef fint Fileeq_func(fint*, char*, fint);
struct
Option_Info {
char *sname; /* invocation name of solver */
char *bsname; /* solver name in startup "banner" */
char *opname; /* name of solver_options environment var */
keyword *keywds; /* key words */
int n_keywds; /* number of key words */
int flags; /* whether funcadd will be called, etc.: */
/* see the first enum below */
char *version; /* for -v and Ver_key_ASL() */
char **usage; /* solver-specific usage message */
Solver_KW_func *kwf; /* solver-specific keyword function */
Fileeq_func *feq; /* for nnn=filename */
keyword *options; /* command-line options (with -) before stub */
int n_options; /* number of options */
long driver_date; /* YYYYMMDD for driver */
/* For write_sol: */
int wantsol; /* write .sol file without -AMPL */
int nS; /* transmit S[i], 0 <= i < nS */
SufDesc *S;
/* For possible use by "nonstandard" Kwfunc's: */
char *uinfo;
/* Stuff provided/used by getopts (and getstops): */
ASL *asl;
char *eqsign;
int n_badopts; /* number of bad options: bail out if != 0*/
int option_echo;/* whether to echo: see the second enum below. */
/* Kwfunc's may set option_echo &= ~ASL_OI_echo to turn off all */
/* keyword echoing or option_echo &= ~ASL_OI_echothis to turn */
/* off echoing of the present keyword. If they detect but do */
/* not themselves report a bad value, they should set */
/* option_echo |= ASL_OI_badvalue. During command-line option */
/* processing (for -... args), (option_echo & ASL_OI_clopt) is */
/* nonzero. */
int nnl; /* internal use: copied to asl->i.need_nl_ */
};
enum { /* bits for Option_Info.flags */
ASL_OI_want_funcadd = 1,
ASL_OI_keep_underscores = 2,
ASL_OI_show_version = 4
} ;
enum { /* bits for Option_Info.option_echo */
ASL_OI_echo = 1,
ASL_OI_echothis = 2,
ASL_OI_clopt = 4,
ASL_OI_badvalue = 8,
ASL_OI_never_echo = 16,
ASL_OI_tabexpand = 32, /* have shownames() expand tabs */
ASL_OI_addnewline = 64, /* have shownames() add a newline */
/* after each keyword description */
ASL_OI_showname_bits = 96,
ASL_OI_defer_bsname = 128 /* print "bsname: " only if there */
/* are options to echo */
} ;
#ifdef __cplusplus
extern "C" {
#endif
/* Kwfuncs should invoke badopt_ASL() if they complain. */
extern void badopt_ASL (Option_Info*);
extern char *badval_ASL (Option_Info*, keyword*, char *value, char *badc);
extern char* get_opt_ASL (Option_Info*, char*);
extern int getopts_ASL (ASL*, char **argv, Option_Info*);
extern char* getstops_ASL (ASL*, char **argv, Option_Info*);
extern char* getstub_ASL (ASL*, char ***pargv, Option_Info*);
extern void show_version_ASL(Option_Info*);
extern char sysdetails_ASL[];
extern void usage_ASL(Option_Info*, int exit_code);
extern void usage_noexit_ASL(Option_Info*, int exit_code);
#define getstub(a,b) getstub_ASL((ASL*)asl,a,b)
#define getstops(a,b) getstops_ASL((ASL*)asl,a,b)
#define getopts(a,b) getopts_ASL((ASL*)asl,a,b)
#define CK_val CK_val_ASL /* known character value in known place */
#define C_val C_val_ASL /* character value in known place */
#define DA_val DA_val_ASL /* real (double) value in asl */
#define DK_val DK_val_ASL /* known real (double) value in known place */
#define DU_val DU_val_ASL /* real (double) value: offset from uinfo */
#define D_val D_val_ASL /* real (double) value in known place */
#define FI_val FI_val_ASL /* fint value in known place */
#define IA_val IA_val_ASL /* int value in asl */
#define IK0_val IK0_val_ASL /* int value 0 in known place */
#define IK1_val IK1_val_ASL /* int value 1 in known place */
#define IK_val IK_val_ASL /* known int value in known place */
#define IU_val IU_val_ASL /* int value: offset from uinfo */
#define I_val I_val_ASL /* int value in known place */
#define LK_val LK_val_ASL /* known Long value in known place */
#define LU_val LU_val_ASL /* Long value: offset from uinfo */
#define L_val L_val_ASL /* Long value in known place */
#define SU_val SU_val_ASL /* short value: offset from uinfo */
#define Ver_val Ver_val_ASL /* report version */
#define WS_val WS_val_ASL /* set wantsol in Option_Info */
extern char *Lic_info_add_ASL; /* for show_version_ASL() */
extern char WS_desc_ASL[]; /* desc for WS_val, constrained problems */
extern char WSu_desc_ASL[]; /* desc for WS_val, unconstrained problems */
extern Kwfunc C_val, CK_val, DA_val, DK_val, DU_val, D_val, FI_val, IA_val;
extern Kwfunc IK0_val, IK1_val, IK_val, IU_val, I_val, LK_val, LU_val;
extern Kwfunc L_val, Ver_val, WS_val;
extern Kwfunc SU_val;
/* Routines for converting Double (real), Long, and int values: */
extern char *Dval_ASL (Option_Info*, keyword*, char*, real*);
extern char *Ival_ASL (Option_Info*, keyword*, char*, int*);
extern char *Lval_ASL (Option_Info*, keyword*, char*, Long*);
#define voffset_of(t,c) ((void *)&((t*)0)->c)
/* Structs whose address can be the info field for known values... */
#define C_Known C_Known_ASL /* char* value for CK_val */
#define D_Known D_Known_ASL /* real (double) value for DK_val */
#define I_Known I_Known_ASL /* int value for IK_val */
#define L_Known L_Known_ASL /* Long value for LK_val */
typedef struct
C_Known {
char *val;
char **valp;
} C_Known;
typedef struct
D_Known {
real val;
real *valp;
} D_Known;
typedef struct
I_Known {
int val;
int *valp;
} I_Known;
typedef struct
L_Known {
Long val;
Long *valp;
} L_Known;
#ifdef __cplusplus
}
#endif
#endif /* GETSTUB_H_included */
+92
View File
@@ -0,0 +1,92 @@
/*
*
* This file is part of MUMPS 4.10.0, built on Tue May 10 12:56:32 UTC 2011
*
*
* This version of MUMPS is provided to you free of charge. It is public
* domain, based on public domain software developed during the Esprit IV
* European project PARASOL (1996-1999). Since this first public domain
* version in 1999, research and developments have been supported by the
* following institutions: CERFACS, CNRS, ENS Lyon, INPT(ENSEEIHT)-IRIT,
* INRIA, and University of Bordeaux.
*
* The MUMPS team at the moment of releasing this version includes
* Patrick Amestoy, Maurice Bremond, Alfredo Buttari, Abdou Guermouche,
* Guillaume Joslin, Jean-Yves L'Excellent, Francois-Henry Rouet, Bora
* Ucar and Clement Weisbecker.
*
* We are also grateful to Emmanuel Agullo, Caroline Bousquet, Indranil
* Chowdhury, Philippe Combes, Christophe Daniel, Iain Duff, Vincent Espirat,
* Aurelia Fevre, Jacko Koster, Stephane Pralet, Chiara Puglisi, Gregoire
* Richard, Tzvetomila Slavova, Miroslav Tuma and Christophe Voemel who
* have been contributing to this project.
*
* Up-to-date copies of the MUMPS package can be obtained
* from the Web pages:
* http://mumps.enseeiht.fr/ or http://graal.ens-lyon.fr/MUMPS
*
*
* THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY
* EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
*
*
* User documentation of any code that uses this software can
* include this complete notice. You can acknowledge (using
* references [1] and [2]) the contribution of this package
* in any scientific publication dependent upon the use of the
* package. You shall use reasonable endeavours to notify
* the authors of the package of this publication.
*
* [1] P. R. Amestoy, I. S. Duff, J. Koster and J.-Y. L'Excellent,
* A fully asynchronous multifrontal solver using distributed dynamic
* scheduling, SIAM Journal of Matrix Analysis and Applications,
* Vol 23, No 1, pp 15-41 (2001).
*
* [2] P. R. Amestoy and A. Guermouche and J.-Y. L'Excellent and
* S. Pralet, Hybrid scheduling for the parallel solution of linear
* systems. Parallel Computing Vol 32 (2), pp 136-156 (2006).
*
*/
#ifndef MUMPS_C_TYPES_H
#define MUMPS_C_TYPES_H
#define MUMPS_INT int
#define SMUMPS_COMPLEX float
#define SMUMPS_REAL float
#define DMUMPS_COMPLEX double
#define DMUMPS_REAL double
/* Complex datatypes */
typedef struct {float r,i;} mumps_complex;
typedef struct {double r,i;} mumps_double_complex;
#define CMUMPS_COMPLEX mumps_complex
#define CMUMPS_REAL float
#define ZMUMPS_COMPLEX mumps_double_complex
#define ZMUMPS_REAL double
#ifndef mumps_ftnlen
/* When passing a string, what is the type of the extra argument
* passed by value ? */
# define mumps_ftnlen int
#endif
#define MUMPS_ARITH_s 1
#define MUMPS_ARITH_d 2
#define MUMPS_ARITH_c 4
#define MUMPS_ARITH_z 8
#define MUMPS_ARITH_REAL ( MUMPS_ARITH_s | MUMPS_ARITH_d )
#define MUMPS_ARITH_CMPLX ( MUMPS_ARITH_c | MUMPS_ARITH_z )
#define MUMPS_ARITH_SINGLE ( MUMPS_ARITH_s | MUMPS_ARITH_c )
#define MUMPS_ARITH_DBL ( MUMPS_ARITH_d | MUMPS_ARITH_z )
#endif /* MUMPS_C_TYPES_H */
+78
View File
@@ -0,0 +1,78 @@
/*
*
* This file is part of MUMPS 4.10.0, built on Tue May 10 12:56:32 UTC 2011
*
*
* This version of MUMPS is provided to you free of charge. It is public
* domain, based on public domain software developed during the Esprit IV
* European project PARASOL (1996-1999). Since this first public domain
* version in 1999, research and developments have been supported by the
* following institutions: CERFACS, CNRS, ENS Lyon, INPT(ENSEEIHT)-IRIT,
* INRIA, and University of Bordeaux.
*
* The MUMPS team at the moment of releasing this version includes
* Patrick Amestoy, Maurice Bremond, Alfredo Buttari, Abdou Guermouche,
* Guillaume Joslin, Jean-Yves L'Excellent, Francois-Henry Rouet, Bora
* Ucar and Clement Weisbecker.
*
* We are also grateful to Emmanuel Agullo, Caroline Bousquet, Indranil
* Chowdhury, Philippe Combes, Christophe Daniel, Iain Duff, Vincent Espirat,
* Aurelia Fevre, Jacko Koster, Stephane Pralet, Chiara Puglisi, Gregoire
* Richard, Tzvetomila Slavova, Miroslav Tuma and Christophe Voemel who
* have been contributing to this project.
*
* Up-to-date copies of the MUMPS package can be obtained
* from the Web pages:
* http://mumps.enseeiht.fr/ or http://graal.ens-lyon.fr/MUMPS
*
*
* THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY
* EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
*
*
* User documentation of any code that uses this software can
* include this complete notice. You can acknowledge (using
* references [1] and [2]) the contribution of this package
* in any scientific publication dependent upon the use of the
* package. You shall use reasonable endeavours to notify
* the authors of the package of this publication.
*
* [1] P. R. Amestoy, I. S. Duff, J. Koster and J.-Y. L'Excellent,
* A fully asynchronous multifrontal solver using distributed dynamic
* scheduling, SIAM Journal of Matrix Analysis and Applications,
* Vol 23, No 1, pp 15-41 (2001).
*
* [2] P. R. Amestoy and A. Guermouche and J.-Y. L'Excellent and
* S. Pralet, Hybrid scheduling for the parallel solution of linear
* systems. Parallel Computing Vol 32 (2), pp 136-156 (2006).
*
*/
/* Compatibility issues between various Windows versions */
#ifndef MUMPS_COMPAT_H
#define MUMPS_COMPAT_H
#if defined(_WIN32) && ! defined(__MINGW32__)
# define MUMPS_WIN32 1
#endif
#ifndef MUMPS_CALL
# ifdef MUMPS_WIN32
/* Modify/choose between next 2 lines depending
* on your Windows calling conventions */
/* # define MUMPS_CALL __stdcall */
# define MUMPS_CALL
# else
# define MUMPS_CALL
# endif
#endif
#if (__STDC_VERSION__ >= 199901L)
# define MUMPS_INLINE static inline
#else
# define MUMPS_INLINE
#endif
#endif /* MUMPS_COMPAT_H */
+77
View File
@@ -0,0 +1,77 @@
/*
*
* This file is part of MUMPS 4.10.0, built on Tue May 10 12:56:32 UTC 2011
*
*
* This version of MUMPS is provided to you free of charge. It is public
* domain, based on public domain software developed during the Esprit IV
* European project PARASOL (1996-1999). Since this first public domain
* version in 1999, research and developments have been supported by the
* following institutions: CERFACS, CNRS, ENS Lyon, INPT(ENSEEIHT)-IRIT,
* INRIA, and University of Bordeaux.
*
* The MUMPS team at the moment of releasing this version includes
* Patrick Amestoy, Maurice Bremond, Alfredo Buttari, Abdou Guermouche,
* Guillaume Joslin, Jean-Yves L'Excellent, Francois-Henry Rouet, Bora
* Ucar and Clement Weisbecker.
*
* We are also grateful to Emmanuel Agullo, Caroline Bousquet, Indranil
* Chowdhury, Philippe Combes, Christophe Daniel, Iain Duff, Vincent Espirat,
* Aurelia Fevre, Jacko Koster, Stephane Pralet, Chiara Puglisi, Gregoire
* Richard, Tzvetomila Slavova, Miroslav Tuma and Christophe Voemel who
* have been contributing to this project.
*
* Up-to-date copies of the MUMPS package can be obtained
* from the Web pages:
* http://mumps.enseeiht.fr/ or http://graal.ens-lyon.fr/MUMPS
*
*
* THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY
* EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
*
*
* User documentation of any code that uses this software can
* include this complete notice. You can acknowledge (using
* references [1] and [2]) the contribution of this package
* in any scientific publication dependent upon the use of the
* package. You shall use reasonable endeavours to notify
* the authors of the package of this publication.
*
* [1] P. R. Amestoy, I. S. Duff, J. Koster and J.-Y. L'Excellent,
* A fully asynchronous multifrontal solver using distributed dynamic
* scheduling, SIAM Journal of Matrix Analysis and Applications,
* Vol 23, No 1, pp 15-41 (2001).
*
* [2] P. R. Amestoy and A. Guermouche and J.-Y. L'Excellent and
* S. Pralet, Hybrid scheduling for the parallel solution of linear
* systems. Parallel Computing Vol 32 (2), pp 136-156 (2006).
*
*/
#ifndef MUMPS_MPI_H
#define MUMPS_MPI_H
/* We define all symbols as extern "C" for users who call MUMPS with its
libseq from a C++ driver. */
#ifdef __cplusplus
extern "C" {
#endif
/* This is the minimum to have the C interface of MUMPS work.
* Most of the time, users who need this file have no call to MPI functions in
* their own code. Hence it is not worth declaring all MPI functions here.
* However if some users come to request some more stub functions of the MPI
* standards, we may add them. But it is not worth doing it until then. */
typedef int MPI_Comm; /* Simple type for MPI communicator */
static MPI_Comm MPI_COMM_WORLD=(MPI_Comm)0;
int MPI_Init(int *pargc, char ***pargv);
int MPI_Comm_rank(int comm, int *rank);
int MPI_Finalize(void);
#ifdef __cplusplus
}
#endif
#endif /* MUMPS_MPI_H */
+260
View File
@@ -0,0 +1,260 @@
/****************************************************************
Copyright (C) 1997-1998, 2001 Lucent Technologies
All Rights Reserved
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name of Lucent or any of its entities
not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
****************************************************************/
#ifndef NLP_H_included
#define NLP_H_included
#ifndef ASL_included
#include "asl.h"
#endif
typedef struct argpair argpair;
typedef struct cde cde;
typedef struct cexp cexp;
typedef struct cexp1 cexp1;
typedef struct de de;
typedef union ei ei;
typedef struct expr expr;
typedef struct expr_f expr_f;
typedef struct expr_h expr_h;
typedef struct expr_if expr_if;
typedef struct expr_v expr_v;
typedef struct expr_va expr_va;
typedef struct funnel funnel;
typedef struct list list;
typedef real efunc ANSI((expr * A_ASL));
#define r_ops r_ops_ASL
#define obj1val obj1val_ASL
#define obj1grd obj1grd_ASL
#define con1val con1val_ASL
#define jac1val jac1val_ASL
#define con1ival con1ival_ASL
#define con1grd con1grd_ASL
#define lcon1val lcon1val_ASL
#define x1known x1known_ASL
union
ei {
expr *e;
expr **ep;
expr_if *eif;
expr_n *en;
int i;
plterm *p;
de *d;
real *rp;
derp *D;
cexp *ce;
};
struct
expr {
efunc *op;
int a;
real dL;
ei L, R;
real dR;
};
struct
expr_v {
efunc *op;
int a;
real v;
};
struct
expr_if {
efunc *op;
int a;
expr *e, *T, *F;
derp *D, *dT, *dF, *d0;
ei Tv, Fv;
expr_if *next, *next2;
};
struct
expr_va {
efunc *op;
int a;
ei L, R;
expr_va *next, *next2;
derp *d0;
};
struct
cde {
expr *e;
derp *d;
int zaplen;
};
struct
de {
expr *e;
derp *d;
ei dv;
};
struct
list {
list *next;
ei item;
};
struct
cexp1 {
expr *e;
int nlin;
linpart *L;
};
struct
cexp {
expr *e;
int nlin;
linpart *L;
funnel *funneled;
list *cref;
ei z;
int zlen;
derp *d;
int *vref;
};
struct
funnel {
funnel *next;
cexp *ce;
derp *fulld;
cplist *cl;
cde fcde;
};
struct
argpair {
expr *e;
union {
char **s;
real *v;
} u;
};
struct
expr_f {
efunc *op;
int a;
func_info *fi;
arglist *al;
argpair *ap, *ape, *sap, *sape;
expr *args[1];
};
struct
expr_h {
efunc *op;
int a;
char sym[1];
};
typedef struct
Edag1info {
cde *con_de_; /* constraint deriv. and expr. info */
cde *lcon_de_; /* logical constraints */
cde *obj_de_; /* objective deriv. and expr. info */
expr_v *var_e_; /* variable values (and related items) */
/* stuff for "defined" variables */
funnel *f_b_;
funnel *f_c_;
funnel *f_o_;
expr_v *var_ex_,
*var_ex1_;
cexp *cexps_;
cexp1 *cexps1_;
efunc **r_ops_;
char *c_class; /* class of each constraint: */
/* 0 = constant */
/* 1 = linear */
/* 2 = quadratic */
/* 3 = general nonlinear */
char *o_class; /* class of each objective */
char *v_class; /* class of each defined variable */
int c_class_max; /* max of c_class values */
int o_class_max; /* max of o_class values */
/* The above are only computed if requested */
/* by the ASL_find_c_class and */
/* ASL_find_o_class bits of the flags arg */
/* to pfgh_read() and pfg_read() */
} Edag1info;
typedef struct
ASL_fg {
Edagpars p;
Edaginfo i;
Edag1info I;
} ASL_fg;
#ifdef __cplusplus
extern "C" {
#endif
extern efunc *r_ops_ASL[];
extern void com1eval_ASL ANSI((ASL_fg*, int, int));
extern void comeval_ASL ANSI((ASL_fg*, int, int));
extern void funnelset_ASL ANSI((ASL_fg*, funnel *));
extern real obj1val ANSI((ASL*, int nobj, real *X, fint *nerror));
extern void obj1grd ANSI((ASL*, int nobj, real *X, real *G, fint *nerror));
extern void con1val ANSI((ASL*, real *X, real *F, fint *nerror));
extern void jac1val ANSI((ASL*, real *X, real *JAC, fint *nerror));
extern real con1ival ANSI((ASL*,int nc, real *X, fint *ne));
extern void con1grd ANSI((ASL*, int nc, real *X, real *G, fint *nerror));
extern int lcon1val ANSI((ASL*,int nc, real *X, fint *ne));
extern int x0_check_ASL ANSI((ASL_fg*, real *));
extern void x1known ANSI((ASL*, real*, fint*));
#ifdef __cplusplus
}
#endif
#define comeval(a,b) comeval_ASL((ASL_fg*)asl,a,b)
#define com1eval(a,b) com1eval_ASL((ASL_fg*)asl,a,b)
#define funnelset(a) funnelset_ASL((ASL_fg*)asl,a)
#define cexps asl->I.cexps_
#define cexps1 asl->I.cexps1_
#define con_de asl->I.con_de_
#define f_b asl->I.f_b_
#define f_c asl->I.f_c_
#define f_o asl->I.f_o_
#define lcon_de asl->I.lcon_de_
#define obj_de asl->I.obj_de_
#define var_e asl->I.var_e_
#define var_ex asl->I.var_ex_
#define var_ex1 asl->I.var_ex1_
#undef f_OPNUM
#define f_OPNUM (efunc*)f_OPNUM_ASL
#endif /* NLP_H_included */
+342
View File
@@ -0,0 +1,342 @@
/****************************************************************
Copyright (C) 1997-1998, 2000-2001 Lucent Technologies
All Rights Reserved
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name of Lucent or any of its entities
not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
****************************************************************/
/* Variant of nlp.h for Hessian times vector computations. */
#ifndef NLP_H2_included
#define NLP_H2_included
#ifndef ASL_included
#include "asl.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef struct argpair2 argpair2;
typedef struct cde2 cde2;
typedef struct cexp2 cexp2;
typedef struct cexp21 cexp21;
typedef struct de2 de2;
typedef union ei2 ei2;
typedef struct expr2 expr2;
typedef struct expr2_f expr2_f;
typedef struct expr2_h expr2_h;
typedef struct expr2_if expr2_if;
typedef struct expr2_v expr2_v;
typedef struct expr2_va expr2_va;
typedef struct funnel2 funnel2;
typedef struct hes_fun hes_fun;
typedef struct list2 list2;
typedef union uir uir;
typedef real efunc2 ANSI((expr2* A_ASL));
typedef char *sfunc ANSI((expr2* A_ASL));
union
uir {
int i;
real r;
};
union
ei2 {
expr2 *e;
expr2 **ep;
expr2_if*eif;
expr_n *en;
expr2_v *ev;
int i;
plterm *p;
de2 *d;
real *rp;
derp *D;
cexp2 *ce;
};
struct
expr2 {
efunc2 *op;
int a; /* adjoint index (for gradient computation) */
expr2 *fwd, *bak;
uir dO; /* deriv of op w.r.t. t in x + t*p */
real aO; /* adjoint (in Hv computation) of op */
real adO; /* adjoint (in Hv computation) of dO */
real dL; /* deriv of op w.r.t. left operand */
ei2 L, R; /* left and right operands */
real dR; /* deriv of op w.r.t. right operand */
real dL2; /* second partial w.r.t. L, L */
real dLR; /* second partial w.r.t. L, R */
real dR2; /* second partial w.r.t. R, R */
};
struct
expr2_v {
efunc2 *op;
int a;
expr2 *fwd, *bak;
uir dO;
real aO, adO;
real v;
};
struct
expr2_if {
efunc2 *op;
int a;
expr2 *fwd, *bak;
uir dO;
real aO, adO;
expr2 *val, *vale, *valf, *e, *T, *Te, *Tf, *F, *Fe, *Ff;
derp *D, *dT, *dF, *d0;
ei2 Tv, Fv;
expr2_if *next, *next2;
derp *dTlast;
};
struct
expr2_va {
efunc2 *op;
int a;
expr2 *fwd, *bak;
uir dO;
real aO, adO;
expr2 *val, *vale, *valf;
ei2 L, R;
expr2_va *next, *next2;
derp *d0;
};
struct
cde2 {
expr2 *e, *ee, *ef;
derp *d;
int zaplen;
int com11, n_com1;
};
struct
de2 { /* for varargs */
expr2 *e, *ee, *ef;
derp *d;
ei2 dv;
derp *dlast; /* for sputhes setup */
};
struct
list2 {
list2 *next;
ei2 item;
};
struct
cexp21 {
expr2 *e, *ee, *ef;
linpart *L;
int nlin;
};
struct
cexp2 {
expr2 *e, *ee, *ef;
linpart *L;
int nlin;
funnel2 *funneled;
list2 *cref;
ei2 z;
int zlen;
derp *d;
int *vref;
hes_fun *hfun;
};
struct
funnel2 {
funnel2 *next;
cexp2 *ce;
cde2 fcde;
derp *fulld;
cplist *cl;
};
struct
argpair2 {
expr2 *e;
union {
char **s;
real *v;
} u;
};
struct
expr2_f {
efunc2 *op;
int a;
expr2 *fwd, *bak;
uir dO;
real aO, adO;
func_info *fi;
arglist *al;
argpair2 *ap, *ape, *sap, *sape;
argpair2 *da; /* differentiable args -- nonconstant */
argpair2 *dae;
real **fh; /* Hessian info */
expr2 *args[1];
};
struct
expr2_h {
efunc2 *op;
int a;
char sym[1];
};
typedef struct
Edag2info {
cde2 *con2_de_; /* constraint deriv. and expr. info */
cde2 *lcon2_de_; /* logical constraints */
cde2 *obj2_de_; /* objective deriv. and expr. info */
expr2_v *var2_e_; /* variable values (and related items) */
/* stuff for "defined" variables */
funnel2 *f2_b_;
funnel2 *f2_c_;
funnel2 *f2_o_;
expr2_v *var2_ex_,
*var2_ex1_;
cexp2 *cexps2_, *cexpsc_, *cexpso_, *cexpse_;
cexp21 *cexps21_;
hes_fun *hesthread;
char *c_class; /* class of each constraint: */
/* 0 = constant */
/* 1 = linear */
/* 2 = quadratic */
/* 3 = general nonlinear */
char *o_class; /* class of each objective */
char *v_class; /* class of each defined variable */
int c_class_max; /* max of c_class values */
int o_class_max; /* max of o_class values */
/* The above are only computed if requested */
/* by the ASL_find_c_class and */
/* ASL_find_o_class bits of the flags arg */
/* to pfgh_read() and pfg_read() */
int x0kind_init;
} Edag2info;
typedef struct
ASL_fgh {
Edagpars p;
Edaginfo i;
Edag2info I;
} ASL_fgh;
extern efunc2 *r2_ops_ASL[];
extern void com21eval_ASL ANSI((ASL_fgh*, int, int));
extern void com2eval_ASL ANSI((ASL_fgh*, int, int));
extern void fun2set_ASL ANSI((ASL_fgh*, funnel2 *));
#ifdef __cplusplus
}
#endif
#ifndef SKIP_NL2_DEFINES
extern efunc2 f2_OPVARVAL_ASL;
#define cexpsc asl->I.cexpsc_
#define cexpse asl->I.cexpse_
#define cexpso asl->I.cexpso_
#define cexps1 asl->I.cexps21_
#define cexps asl->I.cexps2_
#define con_de asl->I.con2_de_
#define f_b asl->I.f2_b_
#define f_c asl->I.f2_c_
#define f_o asl->I.f2_o_
#define lcon_de asl->I.lcon2_de_
#define obj_de asl->I.obj2_de_
#define var_e asl->I.var2_e_
#define var_ex1 asl->I.var2_ex1_
#define var_ex asl->I.var2_ex_
#define argpair argpair2
#define cde cde2
#define cexp cexp2
#define cexp1 cexp21
#define de de2
#define ei ei2
#define expr expr2
#define expr_f expr2_f
#define expr_h expr2_h
#define expr_if expr2_if
#define expr_v expr2_v
#define expr_va expr2_va
#define funnel funnel2
#define list list2
#define com1eval com21eval_ASL
#define comeval com2eval_ASL
#define funnelset fun2set_ASL
#undef r_ops
#define r_ops r2_ops_ASL
#ifndef PSHVREAD
#define f_OPIFSYM f2_IFSYM_ASL
#define f_OPPLTERM f2_PLTERM_ASL
#define f_OPFUNCALL f2_FUNCALL_ASL
#define f_OP1POW f2_1POW_ASL
#define f_OP2POW f2_2POW_ASL
#define f_OPCPOW f2_CPOW_ASL
#define f_OPPLUS f2_PLUS_ASL
#define f_OPSUMLIST f2_SUMLIST_ASL
#define f_OPHOL f2_HOL_ASL
#define f_OPPOW f2_POW_ASL
#define f_OPVARVAL f2_VARVAL_ASL
#endif
/* operation classes (for H*v computation) */
#define Hv_binaryR 0
#define Hv_binaryLR 1
#define Hv_unary 2
#define Hv_vararg 3
#define Hv_if 4
#define Hv_plterm 5
#define Hv_sumlist 6
#define Hv_func 7
#define Hv_negate 8
#define Hv_plusR 9
#define Hv_plusL 10
#define Hv_plusLR 11
#define Hv_minusR 12
#define Hv_minusLR 13
#define Hv_timesR 14
#define Hv_timesL 15
#define Hv_timesLR 16
/* treat if as vararg, minusL as plusL, binaryL as unary */
#endif /* SKIP_NL2_DEFINES */
#undef f_OPNUM
#define f_OPNUM (efunc2*)f_OPNUM_ASL
#endif /* NLP_H2_included */
+70
View File
@@ -0,0 +1,70 @@
#define OPPLUS 0
#define OPMINUS 1
#define OPMULT 2
#define OPDIV 3
#define OPREM 4
#define OPPOW 5
#define OPLESS 6
#define MINLIST 11
#define MAXLIST 12
#define FLOOR 13
#define CEIL 14
#define ABS 15
#define OPUMINUS 16
#define OPOR 20
#define OPAND 21
#define LT 22
#define LE 23
#define EQ 24
#define GE 28
#define GT 29
#define NE 30
#define OPNOT 34
#define OPIFnl 35
#define OP_tanh 37
#define OP_tan 38
#define OP_sqrt 39
#define OP_sinh 40
#define OP_sin 41
#define OP_log10 42
#define OP_log 43
#define OP_exp 44
#define OP_cosh 45
#define OP_cos 46
#define OP_atanh 47
#define OP_atan2 48
#define OP_atan 49
#define OP_asinh 50
#define OP_asin 51
#define OP_acosh 52
#define OP_acos 53
#define OPSUMLIST 54
#define OPintDIV 55
#define OPprecision 56
#define OPround 57
#define OPtrunc 58
#define OPCOUNT 59
#define OPNUMBEROF 60
#define OPNUMBEROFs 61
#define OPATLEAST 62
#define OPATMOST 63
#define OPPLTERM 64
#define OPIFSYM 65
#define OPEXACTLY 66
#define OPNOTATLEAST 67
#define OPNOTATMOST 68
#define OPNOTEXACTLY 69
#define ANDLIST 70
#define ORLIST 71
#define OPIMPELSE 72
#define OP_IFF 73
#define OPALLDIFF 74
#define OPSOMESAME 75
#define OP1POW 76
#define OP2POW 77
#define OPCPOW 78
#define OPFUNCALL 79
#define OPNUM 80
#define OPHOL 81
#define OPVARVAL 82
#define N_OPS 83
+337
View File
@@ -0,0 +1,337 @@
/****************************************************************
Copyright (C) 1997, 1998, 2001 Lucent Technologies
All Rights Reserved
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name of Lucent or any of its entities
not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
****************************************************************/
#ifdef PSHVREAD
#ifndef PSINFO_H2_included
#define PSINFO_H2_included
#undef PSINFO_H_included
#ifndef NLP_H2_included
#include "nlp2.h"
#endif
#define cde cde2
#define la_ref la_ref2
#define linarg linarg2
#define range range2
#define rhead rhead2
#define psb_elem psb_elem2
#define psg_elem psg_elem2
#define ps_func ps_func2
#define dv_info dv_info2
#define split_ce split_ce2
#define ps_info ps_info2
#define psinfo psinfo2
#endif /* PSINFO_H2_included */
#else /* PSHVREAD */
#ifndef PSINFO_H1_included
#define PSINFO_H1_included
#undef PSINFO_H_included
#ifndef NLP_H_included
#include "nlp.h"
#endif
#endif
#endif /* PSHVREAD */
#ifndef PSINFO_H_included
#define PSINFO_H_included
typedef struct la_ref la_ref;
typedef struct linarg linarg;
typedef struct range range;
struct
la_ref {
la_ref *next;
expr **ep;
real c;
real scale;
};
struct
linarg {
linarg *hnext; /* for hashing */
linarg *tnext; /* next linear argument to this term */
linarg *lnext; /* for adjusting v->op */
la_ref *refs; /* references */
expr_v *v; /* variable that evaluates this linear term */
ograd *nz; /* the nonzeros */
int nnz; /* number of nonzeros (to help hashing) */
int termno; /* helps tell whether new to this term */
};
typedef struct
rhead {
range *next, *prev;
} rhead;
#ifndef PSINFO_H0_included
#define MBLK_KMAX 30
#endif /* PSINFO_H0_included */
typedef struct psb_elem psb_elem;
struct
range {
rhead rlist; /* list of all ranges */
range *hnext; /* for hashing U */
range *hunext; /* for hashing unit vectors */
int n; /* rows in U */
int nv; /* variables involved in U */
int nintv; /* number of internal variables (non-unit */
/* rows in U) */
int lasttermno; /* termno of prev. use in this term */
/* -1 ==> not yet used in this constr or obj. */
/* Set to least variable (1st = 0) in this */
/* range at the end of psedread. */
int lastgroupno; /* groupno at last use of this term */
unsigned int chksum; /* for hashing */
psb_elem *refs; /* constraints and objectives with this range */
int *ui; /* unit vectors defining this range */
/* (for n >= nv) */
linarg **lap; /* nonzeros in U */
int *cei; /* common expressions: union over refs */
real *hest; /* nonzero ==> internal Hessian triangle */
/* computed by hvpinit */
};
struct
psb_elem { /* basic element of partially-separable func */
psb_elem *next; /* for range.refs */
range *U;
int *ce; /* common exprs if nonzero: ce[i], 1 <= i <= ce[0] */
cde D; /* derivative and expr info */
int conno; /* constraint no. (if >= 0) or -2 - obj no. */
int termno;
int groupno;
};
typedef struct
psg_elem { /* group element details of partially-separable func */
real g0; /* constant term */
real g1; /* first deriv of g */
real g2; /* 2nd deriv of g */
real scale; /* temporary(?!!) until we introduce unary OPSCALE */
expr_n esum; /* esum.v = result of summing g0, E and L */
expr *g; /* unary operator */
expr *ge; /* "last" unary operator */
ograd *og; /* first deriv = g1 times og */
int nlin; /* number of linear terms */
int ns; /* number of nonlinear terms */
linpart *L; /* the linear terms */
psb_elem *E; /* the nonlinear terms */
} psg_elem;
typedef struct
ps_func {
int nb; /* number of basic terms */
int ng; /* number of group terms */
int nxval; /* for psgcomp */
psb_elem *b; /* the basic terms */
psg_elem *g; /* the group terms */
} ps_func;
typedef struct
dv_info { /* defined variable info */
ograd *ll; /* list of linear defined vars referenced */
linarg **nl; /* nonlinear part, followed by 0 */
real scale; /* scale factor for linear term */
linarg *lt; /* linear term of nonlinear defined var */
} dv_info;
typedef struct
split_ce {
range *r;
int *ce; /* common expressions */
} split_ce;
#ifdef PSHVREAD
struct
hes_fun {
hes_fun *hfthread;
cexp2 *c;
real *grdhes;
ograd *og;
expr_v **vp;
int n;
};
typedef struct Hesoprod Hesoprod;
struct
Hesoprod {
Hesoprod *next;
ograd *left, *right;
real coef;
};
typedef struct uHeswork uHeswork;
struct
uHeswork {
uHeswork *next;
int k;
range *r;
int *ui, *uie;
ograd *ogp[1]; /* scratch of length r->n */
};
typedef struct Umultinfo Umultinfo;
struct
Umultinfo {
Umultinfo *next;
ograd *og, *og0;
expr_v *v;
int i;
};
typedef struct Ihinfo Ihinfo;
struct
Ihinfo {
Ihinfo *next; /* for chaining ihinfo's with positive count */
range *r; /* list, on prev, of ranges with this ihd */
real *hest; /* hest memory to free */
int ihd; /* internal Hessian dimension, min(n,nv) */
int k; /* htcl(nr*(ihd*(ihd+1)/2)*sizeof(real)) */
int nr; /* number of ranges with this ihd */
};
#endif /* PSHVREAD */
typedef struct
ps_info {
Long merge; /* for noadjust = 1 */
ps_func *cps;
ps_func *ops;
dv_info *dv;
expr_v **vp; /* for values of common variables */
rhead rlist;
linarg *lalist; /* all linargs */
int *dvsp0; /* dvsp0[i] = subscript of first var into which */
/* cexp i was split, 0 <= i <= ncom */
int nc1; /* common expressions for just this function */
int ns0; /* initial number of elements */
int ncom; /* number of common expressions before splitting */
int ndupdt; /* duplicate linear terms in different terms */
int ndupst; /* duplicate linear terms in the same term */
int nlttot; /* total number of distinct linear terms */
int ndvspcand; /* # of defined variable candidates for splitting */
int ndvsplit; /* number of defined variables actually split */
int ndvspin; /* number of incoming terms from split defined vars */
int ndvspout; /* number of terms from split defined variables */
int max_var1_; /* used in psedread and pshvread */
int nv0_; /* used in psedread and pshvread */
#ifdef PSHVREAD
/* Stuff for partially separable Hessian computations... */
/* These arrays are allocated and zero-initialized by hes_setup, */
/* which also supplies the cei field to ranges. */
range **rtodo; /* rtodo[i] = ranges first incident on col i */
uHeswork **utodo; /* unit ranges affecting this col */
Hesoprod **otodo;/* otodo[i] = contributions to col i dispatched */
/* by previous rtodo entries */
Hesoprod *hop_free;
real *dOscratch;/* length = nmax (below) */
int *iOscratch; /* length = nmax */
Ihinfo *ihi;
Ihinfo *ihi1; /* first with positive count */
int hes_setup_called;
int nmax; /* max{r in ranges} r->n */
int ihdcur; /* Current max internal Hessian dimension, */
/* set by hvpinit. */
int ihdmax; /* max possible ihd */
int ihdmin; /* min possible ihd > 0 and <= ihdmax, or 0 */
int khesoprod; /* used in new_Hesoprod in sputhes.c */
int pshv_g1; /* whether pshv_prod should multiply by g1 */
int linmultr; /* linear common terms used in more than one range */
int linhesfun; /* linear common terms in Hessian funnels */
int nlmultr; /* nonlin common terms used in more than one range */
int nlhesfun; /* nonlin common terms in Hessian funnels */
int ncongroups; /* # of groups in constraints */
int nobjgroups; /* # of groups in objectives */
int nhvprod; /* # of Hessian-vector products at this Hessian */
int npsgcomp; /* Has psgcomp been called? For sphes_setup. */
expr_va *valist; /* for sphes_setup */
expr_if *iflist; /* for sphes_setup */
int *zlsave; /* for S->_zl */
real *oyow; /* for xpsg_check */
int onobj; /* for xpsg_check */
int onxval; /* for xpsg_check */
int nynz; /* for xpsg_check */
int ndhmax; /* set by hvpinit_ASL */
#endif /* PSHVREAD */
split_ce *Split_ce; /* for sphes_setup */
} ps_info;
#ifdef PSHVREAD
typedef struct
ASL_pfgh {
Edagpars p;
Edaginfo i;
Char *mblk_free[MBLK_KMAX];
Edag2info I;
ps_info2 P;
} ASL_pfgh;
#else
typedef struct
ASL_pfg {
Edagpars p;
Edaginfo i;
Char *mblk_free[MBLK_KMAX];
Edag1info I;
ps_info P;
} ASL_pfg;
#endif /* PSHVREAD */
#ifdef __cplusplus
extern "C" {
#endif
#ifndef PSINFO_H0_included
#define PSINFO_H0_included
typedef unsigned Long Ulong;
#endif /* PSINFO_H0_included */
#ifdef PSHVREAD
extern void duthes_ASL(ASL*, real *H, int nobj, real *ow, real *y);
extern void fullhes_ASL(ASL*, real*H, fint LH, int nobj, real*ow, real*y);
extern void hvpinit_ASL(ASL*, int ndhmax, int nobj, real *ow, real *y);
extern void ihd_clear_ASL(ASL_pfgh*);
extern ASL_pfgh *pscheck_ASL(ASL*, const char*);
extern void pshv_prod_ASL(ASL_pfgh*, range*r, int nobj, real*ow, real*y);
extern fint sphes_setup_ASL(ASL*, SputInfo**, int nobj, int ow, int y, int ul);
extern void sphes_ASL(ASL*, SputInfo**, real *H, int nobj, real*ow, real *y);
extern void xpsg_check_ASL(ASL_pfgh*, int nobj, real *ow, real *y);
#else /* PSHVREAD */
extern void xp1known_ASL(ASL*, real*, fint*);
#endif /* PSHVREAD */
#ifdef __cplusplus
}
#endif
#define pshv_prod(r,no,ow,y) pshv_prod_ASL(asl,r,no,ow,y)
#endif /* PSINFO_H_included */
+16
View File
@@ -0,0 +1,16 @@
#undef f_OPNUM
#define f_OPMULT r_ops[2]
#define f_OPPOW r_ops[5]
#define f_MINLIST r_ops[11]
#define f_MAXLIST r_ops[12]
#define f_ABS r_ops[15]
#define f_OPPLTERM r_ops[64]
#define f_OPIFSYM r_ops[65]
#define f_OP1POW r_ops[76]
#define f_OP2POW r_ops[77]
#define f_OPCPOW r_ops[78]
#define f_OPFUNCALL r_ops[79]
#define f_OPNUM r_ops[80]
#define f_OPHOL r_ops[81]
#define f_OPVARVAL r_ops[82]
#define N_OPS 83
+103
View File
@@ -0,0 +1,103 @@
/****************************************************************
Copyright (C) 1997-1999 Lucent Technologies
All Rights Reserved
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name of Lucent or any of its entities
not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
****************************************************************/
/* stdio1.h -- for using Printf, Fprintf, Sprintf while
* retaining the system-supplied printf, fprintf, sprintf.
*/
#ifndef STDIO1_H_included
#define STDIO1_H_included
#ifndef STDIO_H_included /* allow suppressing stdio.h */
#include <stdio.h> /* in case it's already included, */
#endif /* e.g., by cplex.h */
#ifdef KR_headers
#ifndef _SIZE_T
#define _SIZE_T
typedef unsigned int size_t;
#endif
#define ANSI(x) ()
#include "varargs.h"
#ifndef Char
#define Char char
#endif
#else
#define ANSI(x) x
#include "stdarg.h"
#ifndef Char
#define Char void
#endif
#endif
#ifndef NO_STDIO1
#ifdef __cplusplus
extern "C" {
#endif
extern int Fprintf ANSI((FILE*, const char*, ...));
extern int Printf ANSI((const char*, ...));
extern int Sprintf ANSI((char*, const char*, ...));
extern int Snprintf ANSI((char*, size_t, const char*, ...));
extern void Perror ANSI((const char*));
extern int Vfprintf ANSI((FILE*, const char*, va_list));
extern int Vsprintf ANSI((char*, const char*, va_list));
extern int Vsnprintf ANSI((char*, size_t, const char*, va_list));
#ifdef PF_BUF
extern FILE *stderr_ASL;
extern void (*pfbuf_print_ASL) ANSI((char*));
extern char *pfbuf_ASL;
extern void fflush_ASL ANSI((FILE*));
#ifdef fflush
#define old_fflush_ASL fflush
#undef fflush
#endif
#define fflush fflush_ASL
#endif
#ifdef __cplusplus
}
#endif
#undef printf
#undef fprintf
#undef sprintf
#undef perror
#undef vfprintf
#undef vsprintf
#define printf Printf
#define fprintf Fprintf
#undef snprintf /* for MacOSX */
#undef vsnprintf /* for MacOSX */
#define snprintf Snprintf
#define sprintf Sprintf
#define perror Perror
#define vfprintf Vfprintf
#define vsnprintf Vsnprintf
#define vsprintf Vsprintf
#endif /* NO_STDIO1 */
#endif /* STDIO1_H_included */
BIN
View File
Binary file not shown.
+35
View File
@@ -0,0 +1,35 @@
# libcoinasl.la - a libtool library file
# Generated by ltmain.sh - GNU libtool 1.5.22 (1.1220.2.365 2005/12/18 22:14:06)
#
# Please DO NOT delete this file!
# It is necessary for linking the library.
# The name that we can dlopen(3).
dlname=''
# Names of this library.
library_names=''
# The name of the static archive.
old_library='libcoinasl.a'
# Libraries that this one depends upon.
dependency_libs=' -lm -ldl'
# Version information for libcoinasl.
current=4
age=3
revision=6
# Is this an already installed library?
installed=yes
# Should we warn about portability when linking against -modules?
shouldnotlink=no
# Files to dlopen/dlpreopen
dlopen=''
dlpreopen=''
# Directory that this library needs to be installed in:
libdir='/home/batman/one/external/ipopt/lib'
Binary file not shown.
+35
View File
@@ -0,0 +1,35 @@
# libcoinblas.la - a libtool library file
# Generated by ltmain.sh - GNU libtool 1.5.22 (1.1220.2.365 2005/12/18 22:14:06)
#
# Please DO NOT delete this file!
# It is necessary for linking the library.
# The name that we can dlopen(3).
dlname=''
# Names of this library.
library_names=''
# The name of the static archive.
old_library='libcoinblas.a'
# Libraries that this one depends upon.
dependency_libs=''
# Version information for libcoinblas.
current=5
age=4
revision=6
# Is this an already installed library?
installed=yes
# Should we warn about portability when linking against -modules?
shouldnotlink=no
# Files to dlopen/dlpreopen
dlopen=''
dlpreopen=''
# Directory that this library needs to be installed in:
libdir='/home/batman/one/external/ipopt/lib'
Binary file not shown.
+35
View File
@@ -0,0 +1,35 @@
# libcoinlapack.la - a libtool library file
# Generated by ltmain.sh - GNU libtool 1.5.22 (1.1220.2.365 2005/12/18 22:14:06)
#
# Please DO NOT delete this file!
# It is necessary for linking the library.
# The name that we can dlopen(3).
dlname=''
# Names of this library.
library_names=''
# The name of the static archive.
old_library='libcoinlapack.a'
# Libraries that this one depends upon.
dependency_libs=' -L/usr/lib/gcc/x86_64-linux-gnu/5 -L/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/5/../../.. -lgfortran -lm -lquadmath'
# Version information for libcoinlapack.
current=6
age=5
revision=6
# Is this an already installed library?
installed=yes
# Should we warn about portability when linking against -modules?
shouldnotlink=no
# Files to dlopen/dlpreopen
dlopen=''
dlpreopen=''
# Directory that this library needs to be installed in:
libdir='/home/batman/one/external/ipopt/lib'
Binary file not shown.
+35
View File
@@ -0,0 +1,35 @@
# libcoinmumps.la - a libtool library file
# Generated by ltmain.sh - GNU libtool 1.5.22 (1.1220.2.365 2005/12/18 22:14:06)
#
# Please DO NOT delete this file!
# It is necessary for linking the library.
# The name that we can dlopen(3).
dlname=''
# Names of this library.
library_names=''
# The name of the static archive.
old_library='libcoinmumps.a'
# Libraries that this one depends upon.
dependency_libs=' -L/usr/lib/gcc/x86_64-linux-gnu/5 -L/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/5/../../.. -lgfortran -lm -lquadmath'
# Version information for libcoinmumps.
current=7
age=6
revision=0
# Is this an already installed library?
installed=yes
# Should we warn about portability when linking against -modules?
shouldnotlink=no
# Files to dlopen/dlpreopen
dlopen=''
dlpreopen=''
# Directory that this library needs to be installed in:
libdir='/home/batman/one/external/ipopt/lib'
BIN
View File
Binary file not shown.
+35
View File
@@ -0,0 +1,35 @@
# libipopt.la - a libtool library file
# Generated by ltmain.sh - GNU libtool 1.5.22 (1.1220.2.365 2005/12/18 22:14:06)
#
# Please DO NOT delete this file!
# It is necessary for linking the library.
# The name that we can dlopen(3).
dlname=''
# Names of this library.
library_names=''
# The name of the static archive.
old_library='libipopt.a'
# Libraries that this one depends upon.
dependency_libs=' /home/batman/one/external/ipopt/lib/libcoinmumps.la -lgfortran -lquadmath -ldl'
# Version information for libipopt.
current=11
age=10
revision=8
# Is this an already installed library?
installed=yes
# Should we warn about portability when linking against -modules?
shouldnotlink=no
# Files to dlopen/dlpreopen
dlopen=''
dlpreopen=''
# Directory that this library needs to be installed in:
libdir='/home/batman/one/external/ipopt/lib'
Binary file not shown.
+35
View File
@@ -0,0 +1,35 @@
# libipoptamplinterface.la - a libtool library file
# Generated by ltmain.sh - GNU libtool 1.5.22 (1.1220.2.365 2005/12/18 22:14:06)
#
# Please DO NOT delete this file!
# It is necessary for linking the library.
# The name that we can dlopen(3).
dlname=''
# Names of this library.
library_names=''
# The name of the static archive.
old_library='libipoptamplinterface.a'
# Libraries that this one depends upon.
dependency_libs=' /home/batman/one/external/ipopt/lib/libipopt.la /home/batman/one/external/ipopt/lib/libcoinmumps.la -lgfortran -lquadmath /home/batman/one/external/ipopt/lib/libcoinasl.la -ldl'
# Version information for libipoptamplinterface.
current=11
age=10
revision=8
# Is this an already installed library?
installed=yes
# Should we warn about portability when linking against -modules?
shouldnotlink=no
# Files to dlopen/dlpreopen
dlopen=''
dlpreopen=''
# Directory that this library needs to be installed in:
libdir='/home/batman/one/external/ipopt/lib'
+11
View File
@@ -0,0 +1,11 @@
prefix=/home/batman/one/external/ipopt
exec_prefix=${prefix}
libdir=${exec_prefix}/lib
includedir=${prefix}/include/coin/ThirdParty
Name: ASL
Description: AMPL Solver Library
URL: https://projects.coin-or.org/BuildTools
Version: 1.3.6
Libs: -L${libdir} -lcoinasl -lm -ldl
Cflags: -I${includedir}

Some files were not shown because too many files have changed in this diff Show More