Reference

Index

See the alphabetic index.

Alternatively, use the Search Page or look below.

Autodoc

template<class ModelConverter>
class mp::AbsConverter_MIP : public mp::BasicFuncConstrCvt<AbsConverter_MIP<ModelConverter>, ModelConverter>
#include <abs.h>

Converts abs for MIP.

Public Types

using Base = BasicFuncConstrCvt<AbsConverter_MIP<ModelConverter>, ModelConverter>

Base class.

using ItemType = AbsConstraint

Converted item type.

Public Functions

inline AbsConverter_MIP(ModelConverter &mc)

Constructor.

inline void ConvertCtxPos(const ItemType &ac, int)

Convert in positive context.

inline void ConvertCtxNeg(const ItemType &ac, int)

Convert in negative context.

inline void Convert(const ItemType &item, int i)

Generic Convert(), distinguishes context & result variable.

Distinguish positive and negative context because if only one of these is necessary, significant model reduction can be achieved in certain cases.

Responsible for adding presolve links, if any

The Impl can reimplement this

Parameters
  • item – the item to be converted

  • i – item index, used to create a presolve link

inline void ConvertCtxNeg(const ItemType &item, int)

Convert in negative context.

inline void ConvertCtxPos(const ItemType &item, int)

Convert in positive context.

inline const ModelConverter &GetMC() const

Reuse the stored ModelConverter.

inline ModelConverter &GetMC()

Reuse the stored ModelConverter.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

struct mp::ProblemFlattener::AlgConPrepare

Algebraic constraint flattening preparation info.

Public Members

LinTerms lt
QuadTerms qt
double lb
double ub
double const_term

Complementarity.

int compl_var
class mp::AlgConRange
#include <constr_algebraic.h>

Algebraic constraint range (template parameter)

Public Functions

inline AlgConRange(double l, double u)

Constructor.

inline int kind() const

kind placeholder

inline double lb() const

range lb()

inline double ub() const

range ub()

inline void negate()

negate

inline bool equals(const AlgConRange &r) const

operator==

inline bool is_valid(double bv) const

validity of the body value

Public Static Functions

static inline constexpr const char *GetTypeName()

Class name.

Private Members

double lb_
double ub_
struct mp::NLFeeder::AlgConRange
#include <nl-feeder.h>

  1. CONSTRAINT BOUNDS & COMPLEMENTARITY ///////

    • Algebraic constraint bounds (for a single constraint):

    • either range (lb, ub),

    • or complementarity info (k, cvar), when k>0.

    • For a complementarity constraint to hold, if cvar is at

    • its lower bound, then body >= 0; if cvar is at its upper

    • bound, then body <= 0;

    • and if cvar is strictly between its bounds, then body = 0.

    • The integer k in a complementarity constraint line indicates

    • which bounds on cvar are finite: 1 and 3 imply a finite

    • lower bound; 2 and 3 imply a finite upper bound; 0 (which

    • should not occur) would imply no finite bounds, i.e.,

    • body = 0 must always hold.

    • Example:

    • 
      
    • ampl: var x; var y; var z;

    • ampl: s.t. Compl1: x+y >= 3 complements x-z <= 15;

    • ampl: s.t. Compl2: -2 <= 2*y+3*z <= 13 complements 6*z-2*x;

    • ampl: expand;

    • subject to Compl1:

    • 3 <= x + y

    • complements

    • x - z <= 15;

    • subject to Compl2:

    • -2 <= 2*y + 3*z <= 13

    • complements

    • -2*x + 6*z;

    • ampl: solexpand;

    • Nonsquare complementarity system:

    • 4 complementarities including 2 equations

    • 5 variables

    • subject to Compl1.L:

    • x + y + Compl1$cvar = 0;

    • subject to Compl1.R:

    • -15 + x - z <= 0

    • complements

    • Compl1$cvar <= -3;

    • subject to Compl2.L:

    • 2*y + 3*z - Compl2$cvar = 0;

    • subject to Compl2.R:

    • -2*x + 6*z

    • complements

    • -2 <= Compl2$cvar <= 13;

Public Members

double L = {}
double U = {}
int k = {0}
int cvar = {0}
template<int kind_>
class mp::AlgConRhs
#include <constr_algebraic.h>

Algebraic constraint right-hand side (template parameter).

Kind: -2/-1/0/1/2 for < / <= / == / >= / >

Public Functions

inline AlgConRhs(double r)

Constructor.

inline double rhs() const

rhs()

inline double lb() const

lb(): this is a specialization of the range constraint

inline double ub() const

ub(): this is a specialization of the range constraint

inline void set_rhs(double v)

Set rhs.

inline void add_to_rhs(double v)

Add to RHS.

inline void negate()

negate

inline bool equals(const AlgConRhs &r) const

operator==

inline bool is_valid(double bv) const

validity of the body value

Public Static Functions

static inline std::string GetTypeName()

name

static inline const char *GetCmpName()

Comparison name as string.

static inline const char *GetCmpStr()

Comparison operator as string.

static inline constexpr int kind()

Kind.

Private Members

double rhs_

Private Static Attributes

static constexpr const char *kind_str_[] = {"LT", "LE", "EQ", "GE", "GT"}
static constexpr const char *kind_cmp_[] = {"<", "<=", "==", ">=", ">"}
struct mp::ProblemBuilder::AlgebraicCon
#include <problem-builder.h>

Public Functions

inline void set_dual(double value)
struct mp::internal::NLReader::AlgebraicConHandler : public mp::internal::NLReader<CON>::ItemHandler
#include <nl-reader.h>

Algebraic constraint handler.

Public Functions

inline explicit AlgebraicConHandler(NLReader &r)
inline int num_items() const
inline bool SkipExpr(int) const

Returns false because constraint expressions are always read.

inline Handler::LinearConHandler OnLinearExpr(int index, int num_terms)
inline void SetBounds(int index, double lb, double ub)
inline void SetInitialValue(int index, double value)

Public Static Attributes

static const ItemType TYPE = T

Protected Attributes

NLReader &reader_
struct mp::BasicProblem::AlgebraicConInfo

Algebraic constraint information.

Public Functions

inline AlgebraicConInfo()
inline AlgebraicConInfo(double lb, double ub)

Public Members

LinearExpr linear_expr

Linear part of an algebraic constraint expression.

Nonlinear parts are stored in nonlinear_cons_ to avoid overhead for linear problems.

double lb
double ub
template<class Body, class RhsOrRange>
class mp::AlgebraicConstraint : public mp::BasicConstraint, public Body, public RhsOrRange
#include <constr_algebraic.h>

Generic algebraic constraint.

Parameters
  • Body – linear or linear and higher-order terms

  • RhsOrRange – rhs or range

Public Types

using BodyType = Body

BodyType.

using RhsOrRangeType = RhsOrRange

RhsOrRangeType.

Public Functions

inline AlgebraicConstraint(Body le, RhsOrRange rr, bool fSort = true)

Constructor.

By default (fSort = true), it sorts terms. Pass fSort = false to skip if you populate the terms but do sorting later.

Parameters
  • le – linear / linear + higher-order terms

  • rr – rhs or range

inline const Body &GetBody() const

Body: linear or linear + higher-order terms, const.

inline Body &GetBody()

Body: linear or linear + higher-order terms.

inline RhsOrRange GetRhsOrRange() const

Range or RHS. Used for hash<>

inline const Body &GetArguments() const

Synonym, For PropagateResult()

inline bool empty() const

If no variable terms in the body.

inline double ComputeLowerSlack(ArrayRef<double> x) const

Compute lower slack.

template<class VarInfo>
inline Violation ComputeViolation(const VarInfo &x, bool logical = false) const

Compute violation.

For checking solver values, report violation amount (negative if holds with slack.) In logical mode, report 1/0 (what’s the violation amount for “x>0” when x==0?)

inline void sort_terms()

Sorting and merging terms, some solvers require.

inline bool is_normalized()

Is Normalized?

inline void negate()

Negate all terms.

inline bool operator==(const AlgebraicConstraint &lc) const

Testing API.

inline const char *GetName() const

Constraint name.

inline const char *name() const

Constraint name.

inline void SetName(std::string nm)

Set constraint name.

inline Context GetContext() const

Get context, if meaningful.

inline void SetContext(Context) const

Set context, if meaningful.

inline void AddContext(Context) const

Add (merge) context, if meaningful.

inline bool HasResultVar() const

Has result var (is functional)?

inline int GetResultVar() const

For functional constraints, result variable index.

template<class VarInfo>
inline Violation ComputeViolation(const VarInfo&) const

Compute violation.

Public Static Functions

static inline const char *GetTypeName()

Constraint type name.

static inline bool IsLogical()

Is logical?

static inline constexpr bool UsesContext()

Whether context is meaningful here.

template<class Body>
class mp::AlgebraicExpression : public Body
#include <expr_algebraic.h>

A template algebraic expression: Body (variable_terms) + constant_term.

Public Types

using BodyType = Body

Typedef BodyType.

using Constant = ConstructorHelper<double>

Helper “constant type”.

using Variable = ConstructorHelper<int>

Helper “variable type”.

Public Functions

AlgebraicExpression() = default

Default constructor.

inline AlgebraicExpression(Body bt, double ct) noexcept

From Body and const_term.

inline AlgebraicExpression(Constant c)

Constructor from helper “constant”.

inline AlgebraicExpression(Variable i)

Constructor from helper “variable”.

inline bool is_constant() const

Whether AlgebraicExpression represents a constant.

inline bool is_variable() const

true when constant=0 and 1 variable with coef 1.0

inline bool is_affine() const

if affine

inline const Body &GetBody() const

Get the body, const.

inline Body &GetBody()

Get the body.

inline const Body &GetArguments() const

Get the body, const.

inline Body &GetArguments()

Get the body.

inline const Body &GetAlgConBody() const

Get the body (variable terms) of a corresponding algebraic constraint.

inline double constant_term() const

The constant term.

inline void constant_term(double v)

Set constant term.

inline void add_to_constant(double a)

Add to constant.

template<class VarInfo>
inline double ComputeValue(const VarInfo &x) const

Compute value given a dense vector of variable values.

inline void negate()

Negate the ae.

inline void add(const AlgebraicExpression &ae)

Add another ae.

inline void subtract(AlgebraicExpression ae)

Subtract another ae.

inline void operator*=(double n)

Multiply by const.

inline bool operator==(const AlgebraicExpression &ae) const

operator==

Public Static Functions

static inline std::string GetTypeName()

Name.

Private Members

double constant_term_ = 0.0
template<class ModelConverter>
class mp::AllDiffConverter_MIP : public mp::BasicFuncConstrCvt<AllDiffConverter_MIP<ModelConverter>, ModelConverter>
#include <alldiff.h>

Converts alldiff for MIP.

Public Types

using Base = BasicFuncConstrCvt<AllDiffConverter_MIP<ModelConverter>, ModelConverter>

Base class.

using ItemType = AllDiffConstraint

Converted item type.

Public Functions

inline AllDiffConverter_MIP(ModelConverter &mc)

Constructor.

inline void ConvertCtxPos(const ItemType &alld, int)

Convert in positive context only.

inline void Convert(const ItemType &item, int i)

Generic Convert(), distinguishes context & result variable.

Distinguish positive and negative context because if only one of these is necessary, significant model reduction can be achieved in certain cases.

Responsible for adding presolve links, if any

The Impl can reimplement this

Parameters
  • item – the item to be converted

  • i – item index, used to create a presolve link

inline void ConvertCtxNeg(const ItemType &item, int)

Convert in negative context.

inline void ConvertCtxPos(const ItemType &item, int)

Convert in positive context.

inline const ModelConverter &GetMC() const

Reuse the stored ModelConverter.

inline ModelConverter &GetMC()

Reuse the stored ModelConverter.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

struct mp::SOLHandler::AMPLOptions
#include <sol-handler.h>

AMPL internal options.

Public Members

std::vector<long> options_

Option values.

bool has_vbtol_

Has vbtol?

double vbtol_

Vbtol.

struct AMPLOptions_C
#include <sol-handler-c.h>

AMPL internal options.

Public Members

int n_options_

Actual number of options.

long options_[MAX_AMPL_OPTIONS]

Option values.

int has_vbtol_

Whether vbtol specified.

double vbtol_

vbtol value

struct AMPLS_ModelTraits_T
#include <ampls-ccallbacks.h>

Model traits for license check.

Public Members

long long n_vars
long long n_alg_con
long long n_log_con
long long n_quad_con
long long n_conic_con
struct AMPLS_MP_Solver_T
#include <ampls-c-api.h>

An AMPLS solver instance.

Public Members

void *internal_info_

AMPLS internal info.

void *solver_info_

Extra info, managed by the specific solver.

void *user_info_

User info, free to assign.

struct AMPLSCOption_T
#include <ampls-c-api.h>

Public Members

const char *name
const char *description
int type
template<class ModelConverter>
class mp::AndConverter_MIP : public mp::BasicFuncConstrCvt<AndConverter_MIP<ModelConverter>, ModelConverter>
#include <logical_and.h>

Converts And/Forall for MIP.

Public Types

using Base = BasicFuncConstrCvt<AndConverter_MIP<ModelConverter>, ModelConverter>

Base class.

using ItemType = AndConstraint

Converted item type.

Public Functions

inline AndConverter_MIP(ModelConverter &mc)

Constructor.

inline void ConvertCtxPos(const ItemType &conj, int)

Convert in positive context.

inline void ConvertCtxNeg(const ItemType &conj, int)

Convert in negative context.

inline void Convert(const ItemType &item, int i)

Generic Convert(), distinguishes context & result variable.

Distinguish positive and negative context because if only one of these is necessary, significant model reduction can be achieved in certain cases.

Responsible for adding presolve links, if any

The Impl can reimplement this

Parameters
  • item – the item to be converted

  • i – item index, used to create a presolve link

inline void ConvertCtxNeg(const ItemType &item, int)

Convert in negative context.

inline void ConvertCtxPos(const ItemType &item, int)

Convert in positive context.

inline const ModelConverter &GetMC() const

Reuse the stored ModelConverter.

inline ModelConverter &GetMC()

Reuse the stored ModelConverter.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

struct mp::SolverApp::AppOutputHandler : public mp::OutputHandler

Public Functions

inline AppOutputHandler()
inline void HandleOutput(fmt::CStringRef output)

Public Members

bool has_output
size_t banner_size = 0
template<class Solver, class ProblemBuilder, class Writer = SolFileWriter>
class mp::internal::AppSolutionHandlerImpl : public mp::SolutionWriterImpl<Solver, ProblemBuilder, SolFileWriter>
#include <solver-io.h>

Solution handler for a solver application.

Extends SolutionWriterImpl by consideration of the -AMPL switch and the wantsol option.

Public Functions

inline AppSolutionHandlerImpl(fmt::StringRef stub, Solver &s, ProblemBuilder &b, ArrayRef<long> options, unsigned banner_size)
virtual void HandleSolution(int status, fmt::CStringRef message, const double *values, const double *dual_values, double obj_value)

Specialize HandleSolution()

inline SolFileWriter &sol_writer()

Returns the .sol writer.

virtual void HandleFeasibleSolution(int status, fmt::CStringRef message, const double *values, const double *dual_values, double)

Writes an intermediate solution to a .sol file.

inline virtual void HandleFeasibleSolution(fmt::CStringRef message, const double *values, const double *dual_values, double obj)

Deprecated: no status.

inline virtual void OverrideSolutionFileName(const std::string &fileName)

Override solution output file stub.

Protected Functions

inline Solver &solver()
inline ProblemBuilder &builder()
inline const std::string &stub() const

Private Members

unsigned banner_size_
struct mp::NLHandler::ArgHandler
#include <nl-reader.h>

A class (struct) that receives notifications of expression arguments. All argument handlers in mp::NLHandler are typedefs of this class, but subclasses of mp::NLHandler may define them as different classes.

Public Functions

inline void AddArg(Expr arg)

Receives notification of an argument.

template<typename T>
class mp::ArrayRef
#include <arrayref.h>

A reference to an immutable array which can be stored inside if ArrayRef<> is constructed from an rvalue std::vector.

Public Functions

inline ArrayRef() noexcept

Construct.

inline ArrayRef(const T *data, std::size_t size) noexcept

From pointer + size.

template<std::size_t SIZE>
inline ArrayRef(const T (&data)[SIZE]) noexcept

From C-array.

inline ArrayRef(ArrayRef &&other) noexcept

Rvalue ArrayRef, take over stored vector if any.

inline ArrayRef(const ArrayRef &other) noexcept

Lvalue ArrayRef, pure reference.

inline ArrayRef(std::vector<T> &&other) noexcept

Rvalue std::vector, take over.

inline ArrayRef(const std::vector<T> &other) noexcept

Lvalue std::vector, pure reference.

inline ArrayRef &operator=(ArrayRef &&other) noexcept

= Rvalue, take over vector if any

inline ArrayRef &operator=(const ArrayRef &other) noexcept

= Lvalue, pure reference

inline operator bool() const

operator bool()

inline bool empty() const

bool empty()

inline operator std::vector<T>() const &

Get vector<> as copy from a lvalue ArrayRef.

inline operator std::vector<T>() &&

Get vector<> as copy/move from an rvalue ArrayRef.

inline const T *data() const

data()

inline std::size_t size() const

size()

inline const T *begin() const

begin()

inline const T *end() const

end()

inline const T &operator[](std::size_t i) const

operator[]

Protected Functions

inline std::vector<T> move_or_copy()
template<class AR>
inline void init_from_rvalue(AR &&other)

Private Members

std::vector<T> save_
const T *data_ = nullptr
std::size_t size_ = 0
template<typename T>
class mp::internal::atomic
#include <solver-app-base.h>

Public Functions

inline atomic(T value = T())
inline operator T() const

Private Members

T value_
template<class ModelConverter>
class mp::pre::AutoLinkScope
#include <valcvt-link.h>

A class providing autolinking in the destructor (RAII).

Usage: create an object, and all conversions in its scope will be autolinked to the source node range (unless autolinking is switched off during the execution).

Public Functions

inline AutoLinkScope(ModelConverter &cvt, NodeRange src)

Constructor.

Parameters
  • cvt – the ModelConverter doing the autolinking

  • src – the source node for the links

inline ~AutoLinkScope()

Destructor.

Private Members

ModelConverter &cvt_
template<class CommonInfo>
class mp::Backend2ModelAPIConnector : public CommonInfo

A wrapper for CommonInfo providing some functionality to connect Backend to ModelAPI.

Parameters

CommonInfo – common information (e.g., env/model handlers) stored in both Backend and ModelAPI

Public Functions

inline CommonInfo *get_other()
inline void set_other(CommonInfo *other)

Set the other object.

This is standardly called from CreateModelManagerWithModelAPI()

inline void copy_common_info_to_other()

Copy into the other object.

Typically after initializing solver env/model

Private Members

CommonInfo *other_ = nullptr
class mp::BackendApp
#include <backend-app.h>

Backend app.

Reads command-line parameters like -AMPL and NL filename, installs handlers for screen output and signals, and calls backend class

Public Functions

inline BackendApp(std::unique_ptr<BasicBackend> pb)
virtual int Run(char **argv)

Runs the application.

It processes command-line arguments and, if the file name (stub) is specified, calls NLSolver class.

Parameters

argv – an array of command-line arguments terminated by a null pointer

Returns

app exit code

inline int GetResultCode() const

Get result code.

inline const BasicBackend &GetBackend() const

Get backend, const.

inline BasicBackend &GetBackend()

Get backend.

Protected Functions

virtual bool Init(char **argv)
virtual void InitHandlers()

Private Members

std::unique_ptr<BasicBackend> pb_
int result_code_ = 0
std::string nl_filename_
std::string filename_no_ext_
std::unique_ptr<internal::SignalHandler> p_sig_handler_
std::unique_ptr<internal::SolverAppOptionParser> p_option_parser_
OutputHandler output_handler_
class mp::BackendWithModelManager : public mp::BasicBackend
#include <backend-with-mm.h>

Backends using a separate Model Manager could derive from this.

Subclassed by mp::StdBackend< Impl >

Public Types

using Callbacks = CCallbacks

Callbacks typedef.

enum [anonymous]

Possible values for the wantsol option (can be combined with bitwise OR).

Values:

enumerator WRITE_SOL_FILE
enumerator PRINT_SOLUTION
enumerator PRINT_DUAL_SOLUTION
enumerator SUPPRESS_SOLVER_MSG
enum [anonymous]

The default precision used in FormatObjValue if the objective_precision env variable is not specified or 0.

Values:

enumerator DEFAULT_PRECISION
enum [anonymous]

Solver flags.

Values:

enumerator MULTIPLE_SOL

Multiple solutions support.

Makes Solver register “countsolutions” and “solutionstub” options and write every solution passed to HandleFeastibleSolution to a file solutionstub & i & “.sol” where i is a solution number.

enumerator MULTIPLE_OBJ

Multiple objectives support.

Makes Solver register the “multiobj” option

using WarningsMap = std::map<std::string, std::pair<int, std::string>>

Map to count warnings by types.

Stores just 1 message for each type.

enum [anonymous]

Flags for ParseOptions.

Values:

enumerator NO_OPTION_ECHO

Don’t echo options during parsing.

enumerator FROM_COMMAND_LINE

When options are passed from command line (not via environment var) the quotes are automatically removed and the input string split in substrings (accessible via argv)

typedef std::unique_ptr<SolverOption> OptionPtr

Smart ptr to an option.

using set_option_iterator = option_iterator_base<OptionSet::iterator>

Alias for writeable option iterator.

using option_iterator = option_iterator_base<OptionSet::const_iterator>

Alias for const option iterator.

using SRRegMap = std::set<RegEntry>

Registry map.

Public Functions

inline virtual void Init(char **argv) override

Initialize backend, incl.

solver options

Parameters

argv – the command-line arguments, NULL-terminated

inline virtual void ReportError(int solve_result, fmt::CStringRef msg) override

Can be overridden.

For example, if we know the output name, this should write .sol file with the solve_result and msg.

inline virtual void SetOptionData(char **argv, int f)

Provide cmdline solver options list and flags.

inline virtual bool ParseSolverOptions(char **argv, unsigned flags = 0)

Parse solver options such as “outlev=1” from env and argv.

Parameters
  • argv – (remaining part of) vector of cmdline strings

  • flags – 0 or Solver::NO_OPTION_ECHO

virtual void RunFromNLFile(const std::string &nl_filename, const std::string &filename_no_ext) = 0

Runs Solver given the NL file name.

virtual void ReadNL(const std::string &nl_filename, const std::string &filename_no_ext, char **opts = nullptr) = 0

Read NL.

This is also used by the AMPLS C API.

Parameters

opts – 0-terminated list of extra options, to be read after the [solver]_options nev var. All model-related options should be here (obj:…/objno/multiobj, cvt:…, acc:…), they are not effective after NL input.

virtual void InputExtras() = 0

Input warm start, suffixes, and all that can modify the model.

This is used by the AMPLS C API

virtual void ReportResults() = 0

Report results.

This is used by the AMPLS C API

inline virtual void InitOptionParsing()

Chance for the Backend to init solver environment, etc.

inline virtual void FinishOptionParsing()

Chance to consider options immediately (open cloud, etc)

inline virtual void Solve()

Having everything set up, solve the problem.

inline Callbacks &GetCallbacks()

Obtain callbacks.

inline void OverrideSolutionFile(const std::string &solFile)
inline std::string GetOverridenSolutionFile()
inline void ReportError(fmt::CStringRef format, const fmt::ArgList &args)

Reports an error by throwing it.

Usage: ReportError(“File not found: {}”) << filename;

inline std::string GetOptionFile(const SolverOption&) const

Name of the file with option settings, provided by tech:optionfile.

void UseOptionFile(const SolverOption&, fmt::StringRef value)

Read otpions from option file.

inline int GetWantSol(const SolverOption&) const

wantsol value

inline void SetWantSol(const SolverOption&, int value)

set wantsol

inline std::string GetSolutionStub(const SolverOption&) const

solution output filename stub

inline void SetSolutionStub(const SolverOption&, fmt::StringRef value)

Set sol stub.

inline int GetObjNo(const SolverOption&) const

Obj number.

inline void SetObjNo(const SolverOption &opt, int value)

Set obj number.

inline int GetTiming(const SolverOption&) const
inline void SetTiming(const SolverOption &opt, int value)
inline const char *name() const

Returns the solver name.

This is used to extract solver options from the env variable (solver_name)_options.

inline const char *long_name() const

Returns the long solver name.

This name is used in startup “banner”.

inline const char *exe_path() const

Returns the executable path.

inline void set_exe_path(const char *p)
inline const char *version() const

Returns the solver version.

inline long date() const

Returns the solver date in YYYYMMDD format.

inline int wantsol() const

Returns the value of the wantsol option which specifies what solution information to write in a stand-alone invocation (no -AMPL on the command line).

inline void set_wantsol(int value)
inline bool ampl_flag()
inline void set_ampl_flag(bool value = true)
inline bool verbose_mode() const

True if verbose mode.

Should be set by the implementation, otherwise it’s true

inline void set_verbose_mode(bool f)

Set verbosity, by the impl.

inline bool debug_mode() const

True if need to debug.

Outputs test infos etc

inline int objno_used() const

Returns the index of the objective to optimize starting from 1, 0 to not use objective.

inline int objno_specified() const

objno_specified(): actually even if not specified, it returns the objno to use (0 - feasibility, otherwise obj index).

Both multiobj() and objno_specified() are used in NLReader to select the objective(s), solvers should not use these accessors.

inline bool is_objno_specified() const

Whether user specified the option objno.

inline void notify_obj_added()

Notify Solver if an objective is added.

inline void notify_start_opts()

Notify Solver we start reading options.

inline void notify_end_opts()

Notify we are done.

inline bool multiobj() const

Returns true if multiobjective optimization is enabled.

Both multiobj and objno are used in NLReader to select the objective(s), solvers should not use these options.

inline int timing() const

>0 if the timing is enabled

inline ErrorHandler *error_handler()

Return error handler.

inline void set_error_handler(ErrorHandler *eh)

Set the error handler.

inline OutputHandler *output_handler()

Return output handler.

inline OutputHandler &get_output_handler()

Return output handler.

inline void set_output_handler(OutputHandler *oh)

Sets the output handler.

inline const Interrupter *interrupter() const

Interrupter, const.

inline Interrupter *interrupter()

Interrupter.

inline void set_interrupter(Interrupter *interrupter)

Set interrupter.

inline const char *solution_stub() const

Sol stub as char*.

inline bool need_multiple_solutions() const

Need mutiple solutions.

inline virtual void HandleOutput(fmt::CStringRef output) override

Override methods from base service classes.

inline virtual void HandleError(fmt::CStringRef message) override

Handle error.

inline virtual bool Stop() const override

The default implementation of Interrupter does nothing.

inline virtual void SetHandler(InterruptHandler, void*) override

Set interrupt handler.

inline virtual void HandleUnknownOption(const char *name)

Handle unknown option.

inline void Print(fmt::CStringRef format, const fmt::ArgList &args)

Variadic overload of ReportError()

Formats a string and prints it to stdout or, if an output handler is registered, sends it to the output handler.

const char *GetSolCheckWarningKey(bool f_recomp) const

Variadic overload of Print()

Get solution check warnings key name.

Parameters

f_recomp – whether with recomputed auxiliaries.

void AddWarning(std::string key, std::string msg, bool replace = false)

Add a warning.

Parameters
  • key – warning category

  • msg – detailed message

const std::pair<int, std::string> &GetWarning(const std::string &key)

Get a warning type.

void ClearWarning(const std::string &key)

Clear a warning type.

std::string GetWarnings() const

Get warnings as string.

void PrintWarnings()

Print warnings.

bool ShowVersion()

Prints version information.

DoubleFormatter FormatObjValue(double value)

Returns a formatter that writes value using objective precision.

Usage: Print(“objective {}”, FormatObjValue(obj_value));

virtual bool ParseOptions(char **argv, unsigned flags = 0, const ASLProblem *p = 0)

Parses solver options from the (solver)_options env variable and/or strings in argv.

For example, solver_options=’timelim=300’ solver /tmp/diet.nl -AMPL “basis=0”.

Returns

true if there were no errors and false otherwise. It accepts a pointer to the problem because some options may depend on problem features.

void ParseOptionString(const char *s, unsigned flags)

Parses a solver option string.

inline const WarningsMap &GetWarningsMap() const

Get warnings map.

inline WarningsMap &GetWarningsMap()
inline void SetConstraintListHeader(std::string clh)

Set constraint list header (printed at the start of -c)

inline void AddConstraintDescr(std::string cn, std::string cdescr)

Add constraint type description.

bool ShowConstraintDescriptions()

Show constraint descriptions.

inline virtual void RecordOutputTime()
inline virtual void RecordSetupTime()

Record setup time.

inline void SetReadTime(double read_time)
inline void SetConversionTime(double conv_time)
inline virtual void RecordSolveTime()

Record solve time.

inline int num_options() const

Returns the number of options.

inline SolverOption *GetOption(const char *name) const

Returns the option with specified name.

inline void set_option_header(const char *header)

Sets a text to be displayed before option descriptions.

inline void add_to_option_header(const char *header_more)

Add more text to be displayed before option descriptions.

void AddOption(OptionPtr opt)

Add an option.

template<class Value>
inline void AddOption(const char *name, const char *description, Value &value, Value lb, Value ub)

Same: stored option referencing a variable; min, max values.

Note

description “HIDDEN” means the option is not printed

SolverOption *FindOption(const char *name, bool wildcardvalues = false) const

Finds an option and returns a pointer to it if found or null otherwise.

If wildcardvalues==true, wildcarded options should have values (i.e., parsing real input)

inline const char *option_header() const

Returns the option header.

inline fmt::LongLong GetIntOption(const char *name) const

Returns the value of an integer option.

Throws OptionError if there is no such option or it has a different type.

inline void SetIntOption(const char *name, fmt::LongLong value)
inline double GetDblOption(const char *name) const
inline void SetDblOption(const char *name, double value)
inline std::string GetStrOption(const char *name) const
inline void SetStrOption(const char *name, fmt::StringRef value)
template<class Value>
inline void AddStoredOption(const char *name, const char *description, Value &value, ValueArrayRef values = ValueArrayRef())

Simple stored option referencing a variable.

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddStoredOption(const char *name, const char *description, Value &value, Value, Value)

Simple stored option referencing a variable; min, max values (they are unused but to deduce type; we are too lazy to maintain correct min/max between solver versions.)

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddListOption(const char *name, const char *description, Value &value, ValueArrayRef values = ValueArrayRef())

Add list option referencing a container.

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddListOption(const char *name, const char *description, Value &value, typename Value::value_type, typename Value::value_type)

Add list option referencing a container; min, max values (they are unused but to deduce type; we aree too lazy to maintain correct min/max between solver versions.)

Note

description “HIDDEN” means the option is not printed

inline void ReplaceOptionDescription(const char *name, const char *desc)

Replace option descr.

inline void AddToOptionDescription(const char *name, const char *desc_add)

Add to option descr.

void AddOptionSynonyms_Inline_Front(const char *names_list, const char *realName)

Add “inline” option synonyms.

The _Front version puts them in the front of the synonyms list and the 1st of them is used in the -a output for sorting.

void AddOptionSynonyms_Inline_Back(const char *names_list, const char *realName)

Add “inline” option synonyms.

The _Back version.

void AddOptionSynonyms_OutOfLine(const char *name, const char *realName)

Add an “out-of-line” synonym.

Creates extra entry under -=

template<typename Handler, typename Int>
inline void AddIntOption(const char *name, const char *description, Int (Handler::* get)(const SolverOption&) const, void (Handler::* set)(const SolverOption&, Int))

Adds an integer option.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddIntOption(const char *name, const char *description, int (Handler::* get)(const SolverOption&, const Info&) const, void (Handler::* set)(const SolverOption&, int, const Info&), const Info &info)

Adds an integer option with additional information.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddIntOption(const char *name_list, const char *description, int (Handler::* get)(const SolverOption&, Info) const, void (Handler::* set)(const SolverOption&, int, Info), Info info)

The same as above but with Info argument passed by value.

Note

description “HIDDEN” means the option is not printed

template<typename Handler>
inline void AddDblOption(const char *name, const char *description, double (Handler::* get)(const SolverOption&) const, void (Handler::* set)(const SolverOption&, double))

Adds a double option.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddDblOption(const char *name, const char *description, double (Handler::* get)(const SolverOption&, const Info&) const, void (Handler::* set)(const SolverOption&, double, const Info&), const Info &info)

Adds a double option with additional information.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddDblOption(const char *name, const char *description, double (Handler::* get)(const SolverOption&, Info) const, void (Handler::* set)(const SolverOption&, double, Info), Info info)

The same as above but with Info argument passed by value.

Note

description “HIDDEN” means the option is not printed

template<typename Handler>
inline void AddStrOption(const char *name, const char *description, std::string (Handler::* get)(const SolverOption&) const, void (Handler::* set)(const SolverOption&, fmt::StringRef), ValueArrayRef values = ValueArrayRef())

Adds a string option.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddStrOption(const char *name, const char *description, std::string (Handler::* get)(const SolverOption&, const Info&) const, void (Handler::* set)(const SolverOption&, fmt::StringRef, const Info&), const Info &info, ValueArrayRef values = ValueArrayRef())

Adds a string option with additional information.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddStrOption(const char *name, const char *description, std::string (Handler::* get)(const SolverOption&, Info) const, void (Handler::* set)(const SolverOption&, fmt::StringRef, Info), Info info, ValueArrayRef values = ValueArrayRef())

The same as above but with Info argument passed by value.

Note

description “HIDDEN” means the option is not printed

inline option_iterator option_begin() const

Get the start const-iterator.

inline option_iterator option_end() const

Get the end const-iterator.

inline set_option_iterator set_option_begin() const

Get the start writeable iterator.

inline set_option_iterator set_option_end() const

Get the end writeable iterator.

void AddSolveResults(const SRRegMap &sm, bool ifCanReplace = false)

Add a map with result descriptions.

inline const SRRegMap &GetSolveResultRegistry() const

Get the registry.

Public Static Functions

static std::string ToString(const WarningsMap::value_type &wrn)

Stringify a WarningsMap entry.

Protected Types

using PMM = std::unique_ptr<BasicModelManager>

Protected Functions

inline virtual void InitMetaInfoAndOptions()

Deriving backends can use this.

inline const BasicModelManager &GetMM() const
inline BasicModelManager &GetMM()
inline void SetMM(PMM pmm)
inline virtual void HandleSolution(int status, fmt::CStringRef msg, const double *x, const double *y, double obj)

Access to ModelManager’s interface.

inline virtual void HandleFeasibleSolution(int solve_code, fmt::CStringRef msg, const double *x, const double *y, double obj)
inline virtual ArrayRef<double> InitialValues()

Variables’ initial values.

inline virtual ArrayRef<int> InitialValuesSparsity()

Variables’ initial values: sparsity.

inline virtual ArrayRef<double> InitialDualValues()

Initial dual values.

inline virtual ArrayRef<int> InitialDualValuesSparsity()

Initial dual values.

template<class N>
inline ArrayRef<N> ReadSuffix(const SuffixDef<N> &suf)

Read unpresolved suffix.

inline virtual ArrayRef<int> ReadIntSuffix(const SuffixDef<int> &suf)
inline virtual ArrayRef<double> ReadDblSuffix(const SuffixDef<double> &suf)
inline virtual size_t GetSuffixSize(int kind)
inline virtual void ReportSuffix(const SuffixDef<int> &suf, ArrayRef<int> values)

Record suffix values which are written into .sol by HandleSolution() Does nothing if vector empty.

inline virtual void ReportSuffix(const SuffixDef<double> &suf, ArrayRef<double> values)
inline virtual void ReportIntSuffix(const SuffixDef<int> &suf, ArrayRef<int> values)
inline virtual void ReportDblSuffix(const SuffixDef<double> &suf, ArrayRef<double> values)
template<class N>
inline void ReportSingleSuffix(const SuffixDef<N> &suf, N value)

Report single value for all elements of the suffix.

inline const std::vector<bool> &IsVarInt() const

Access original (NL) model instance: integrality flags.

Used in solution rounding.

inline bool HasUnfixedIntVars() const

Solver-facing instance info: has unfixed integer variables?

inline char **GetArgvOptions() const

0-terminated list of custom options

inline int GetOptionFlags() const

option parser flags

void InitMetaInfoAndOptions(fmt::CStringRef name, fmt::CStringRef long_name, long date, int flags)

InitMetaInfoAndOptions.

Derived classes which want to provide the info after construction can use the default constructor and call this.

Parameters
  • date – The solver date in YYYYMMDD format.

  • flags – Bitwise OR of zero or more of the following values MULTIPLE_SOL MULTIPLE_OBJ

inline void set_long_name(fmt::StringRef name)
inline void add_to_long_name(fmt::StringRef name)
inline void set_version(fmt::StringRef version)
inline void add_to_version(fmt::StringRef version)
inline void set_license_info(fmt::StringRef license_info)
inline virtual std::string set_external_libs()
inline void set_read_flags(unsigned flags)

Sets the flags for Problem::Read.

inline Stats &stats()

Private Members

PMM p_model_mgr_
class mp::BackendWithValuePresolver : public mp::BasicValuePresolverKeeper

Subclassed by mp::FlatBackend< BaseBackend >

Protected Functions

inline void SetValuePresolver(pre::BasicValuePresolver *pPre)
inline const pre::BasicValuePresolver &GetValuePresolver() const
inline pre::BasicValuePresolver &GetValuePresolver()
template<typename Item>
class mp::BasicProblem::BasicAlgebraicCon : private Item
#include <problem.h>

An algebraic constraint.

This is a constraint of the form lb <= expr <= ub.

Public Functions

inline bool is_marked_deleted() const

Whether the alg con is marked as deleted.

inline double lb() const

Returns the lower bound on the constraint.

inline double ub() const

Returns the upper bound on the constraint.

inline double dual() const

Returns the dual value.

inline const LinearExpr &linear_expr() const

Returns the linear part of a constraint expression.

inline NumericExpr nonlinear_expr() const

Returns the nonlinear part of a constraint expression.

template<typename OtherItem>
inline bool operator==(BasicAlgebraicCon<OtherItem> other) const
template<typename OtherItem>
inline bool operator!=(BasicAlgebraicCon<OtherItem> other) const

Private Functions

inline BasicAlgebraicCon(typename Item::Problem *p, int index)

Private Static Functions

static inline int num_items(const BasicProblem &p)

Friends

friend class BasicProblem
class mp::BasicBackend : public mp::BasicSolver
#include <backend-base.h>

Abstract backend API.

Subclassed by mp::BackendWithModelManager

Public Types

using Callbacks = CCallbacks

Callbacks typedef.

enum [anonymous]

Possible values for the wantsol option (can be combined with bitwise OR).

Values:

enumerator WRITE_SOL_FILE
enumerator PRINT_SOLUTION
enumerator PRINT_DUAL_SOLUTION
enumerator SUPPRESS_SOLVER_MSG
enum [anonymous]

The default precision used in FormatObjValue if the objective_precision env variable is not specified or 0.

Values:

enumerator DEFAULT_PRECISION
enum [anonymous]

Solver flags.

Values:

enumerator MULTIPLE_SOL

Multiple solutions support.

Makes Solver register “countsolutions” and “solutionstub” options and write every solution passed to HandleFeastibleSolution to a file solutionstub & i & “.sol” where i is a solution number.

enumerator MULTIPLE_OBJ

Multiple objectives support.

Makes Solver register the “multiobj” option

using WarningsMap = std::map<std::string, std::pair<int, std::string>>

Map to count warnings by types.

Stores just 1 message for each type.

enum [anonymous]

Flags for ParseOptions.

Values:

enumerator NO_OPTION_ECHO

Don’t echo options during parsing.

enumerator FROM_COMMAND_LINE

When options are passed from command line (not via environment var) the quotes are automatically removed and the input string split in substrings (accessible via argv)

typedef std::unique_ptr<SolverOption> OptionPtr

Smart ptr to an option.

using set_option_iterator = option_iterator_base<OptionSet::iterator>

Alias for writeable option iterator.

using option_iterator = option_iterator_base<OptionSet::const_iterator>

Alias for const option iterator.

using SRRegMap = std::set<RegEntry>

Registry map.

Public Functions

virtual ~BasicBackend() = default

Virtual destructor.

inline virtual void Init(char **argv)

Initialize backend, incl.

solver options. Not parse options yet, as we need to parse cmdline arguments first.

Parameters

argv – the command-line arguments, 0-terminated

inline virtual void SetOptionData(char **argv, int f)

Provide cmdline solver options list and flags.

inline virtual bool ParseSolverOptions(char **argv, unsigned flags = 0)

Parse solver options such as “outlev=1” from env and argv.

Parameters
  • argv – (remaining part of) vector of cmdline strings

  • flags – 0 or Solver::NO_OPTION_ECHO

virtual void RunFromNLFile(const std::string &nl_filename, const std::string &filename_no_ext) = 0

Runs Solver given the NL file name.

virtual void ReadNL(const std::string &nl_filename, const std::string &filename_no_ext, char **opts = nullptr) = 0

Read NL.

This is also used by the AMPLS C API.

Parameters

opts – 0-terminated list of extra options, to be read after the [solver]_options nev var. All model-related options should be here (obj:…/objno/multiobj, cvt:…, acc:…), they are not effective after NL input.

virtual void InputExtras() = 0

Input warm start, suffixes, and all that can modify the model.

This is used by the AMPLS C API

virtual void ReportResults() = 0

Report results.

This is used by the AMPLS C API

inline virtual void InitOptionParsing()

Chance for the Backend to init solver environment, etc.

inline virtual void FinishOptionParsing()

Chance to consider options immediately (open cloud, etc)

inline virtual void Solve()

Having everything set up, solve the problem.

inline Callbacks &GetCallbacks()

Obtain callbacks.

inline void OverrideSolutionFile(const std::string &solFile)
inline std::string GetOverridenSolutionFile()
virtual void ReportError(int solve_result, fmt::CStringRef msg) = 0

Can be overridden.

For example, if we know the output name, this should write .sol file with the solve_result and msg.

inline std::string GetOptionFile(const SolverOption&) const

Name of the file with option settings, provided by tech:optionfile.

void UseOptionFile(const SolverOption&, fmt::StringRef value)

Read otpions from option file.

inline int GetWantSol(const SolverOption&) const

wantsol value

inline void SetWantSol(const SolverOption&, int value)

set wantsol

inline std::string GetSolutionStub(const SolverOption&) const

solution output filename stub

inline void SetSolutionStub(const SolverOption&, fmt::StringRef value)

Set sol stub.

inline int GetObjNo(const SolverOption&) const

Obj number.

inline void SetObjNo(const SolverOption &opt, int value)

Set obj number.

inline int GetTiming(const SolverOption&) const
inline void SetTiming(const SolverOption &opt, int value)
inline const char *name() const

Returns the solver name.

This is used to extract solver options from the env variable (solver_name)_options.

inline const char *long_name() const

Returns the long solver name.

This name is used in startup “banner”.

inline const char *exe_path() const

Returns the executable path.

inline void set_exe_path(const char *p)
inline const char *version() const

Returns the solver version.

inline long date() const

Returns the solver date in YYYYMMDD format.

inline int wantsol() const

Returns the value of the wantsol option which specifies what solution information to write in a stand-alone invocation (no -AMPL on the command line).

inline void set_wantsol(int value)
inline bool ampl_flag()
inline void set_ampl_flag(bool value = true)
inline bool verbose_mode() const

True if verbose mode.

Should be set by the implementation, otherwise it’s true

inline void set_verbose_mode(bool f)

Set verbosity, by the impl.

inline bool debug_mode() const

True if need to debug.

Outputs test infos etc

inline int objno_used() const

Returns the index of the objective to optimize starting from 1, 0 to not use objective.

inline int objno_specified() const

objno_specified(): actually even if not specified, it returns the objno to use (0 - feasibility, otherwise obj index).

Both multiobj() and objno_specified() are used in NLReader to select the objective(s), solvers should not use these accessors.

inline bool is_objno_specified() const

Whether user specified the option objno.

inline void notify_obj_added()

Notify Solver if an objective is added.

inline void notify_start_opts()

Notify Solver we start reading options.

inline void notify_end_opts()

Notify we are done.

inline bool multiobj() const

Returns true if multiobjective optimization is enabled.

Both multiobj and objno are used in NLReader to select the objective(s), solvers should not use these options.

inline int timing() const

>0 if the timing is enabled

inline ErrorHandler *error_handler()

Return error handler.

inline void set_error_handler(ErrorHandler *eh)

Set the error handler.

inline OutputHandler *output_handler()

Return output handler.

inline OutputHandler &get_output_handler()

Return output handler.

inline void set_output_handler(OutputHandler *oh)

Sets the output handler.

inline const Interrupter *interrupter() const

Interrupter, const.

inline Interrupter *interrupter()

Interrupter.

inline void set_interrupter(Interrupter *interrupter)

Set interrupter.

inline const char *solution_stub() const

Sol stub as char*.

inline bool need_multiple_solutions() const

Need mutiple solutions.

inline virtual void HandleOutput(fmt::CStringRef output) override

Override methods from base service classes.

inline virtual void HandleError(fmt::CStringRef message) override

Handle error.

inline virtual bool Stop() const override

The default implementation of Interrupter does nothing.

inline virtual void SetHandler(InterruptHandler, void*) override

Set interrupt handler.

inline virtual void HandleUnknownOption(const char *name)

Handle unknown option.

inline void ReportError(fmt::CStringRef format, const fmt::ArgList &args)

Reports an error by throwing it.

Usage: ReportError(“File not found: {}”) << filename;

inline void Print(fmt::CStringRef format, const fmt::ArgList &args)

Variadic overload of ReportError()

Formats a string and prints it to stdout or, if an output handler is registered, sends it to the output handler.

const char *GetSolCheckWarningKey(bool f_recomp) const

Variadic overload of Print()

Get solution check warnings key name.

Parameters

f_recomp – whether with recomputed auxiliaries.

void AddWarning(std::string key, std::string msg, bool replace = false)

Add a warning.

Parameters
  • key – warning category

  • msg – detailed message

const std::pair<int, std::string> &GetWarning(const std::string &key)

Get a warning type.

void ClearWarning(const std::string &key)

Clear a warning type.

std::string GetWarnings() const

Get warnings as string.

void PrintWarnings()

Print warnings.

bool ShowVersion()

Prints version information.

DoubleFormatter FormatObjValue(double value)

Returns a formatter that writes value using objective precision.

Usage: Print(“objective {}”, FormatObjValue(obj_value));

virtual bool ParseOptions(char **argv, unsigned flags = 0, const ASLProblem *p = 0)

Parses solver options from the (solver)_options env variable and/or strings in argv.

For example, solver_options=’timelim=300’ solver /tmp/diet.nl -AMPL “basis=0”.

Returns

true if there were no errors and false otherwise. It accepts a pointer to the problem because some options may depend on problem features.

void ParseOptionString(const char *s, unsigned flags)

Parses a solver option string.

inline const WarningsMap &GetWarningsMap() const

Get warnings map.

inline WarningsMap &GetWarningsMap()
inline void SetConstraintListHeader(std::string clh)

Set constraint list header (printed at the start of -c)

inline void AddConstraintDescr(std::string cn, std::string cdescr)

Add constraint type description.

bool ShowConstraintDescriptions()

Show constraint descriptions.

inline virtual void RecordOutputTime()
inline virtual void RecordSetupTime()

Record setup time.

inline void SetReadTime(double read_time)
inline void SetConversionTime(double conv_time)
inline virtual void RecordSolveTime()

Record solve time.

inline int num_options() const

Returns the number of options.

inline SolverOption *GetOption(const char *name) const

Returns the option with specified name.

inline void set_option_header(const char *header)

Sets a text to be displayed before option descriptions.

inline void add_to_option_header(const char *header_more)

Add more text to be displayed before option descriptions.

void AddOption(OptionPtr opt)

Add an option.

template<class Value>
inline void AddOption(const char *name, const char *description, Value &value, Value lb, Value ub)

Same: stored option referencing a variable; min, max values.

Note

description “HIDDEN” means the option is not printed

SolverOption *FindOption(const char *name, bool wildcardvalues = false) const

Finds an option and returns a pointer to it if found or null otherwise.

If wildcardvalues==true, wildcarded options should have values (i.e., parsing real input)

inline const char *option_header() const

Returns the option header.

inline fmt::LongLong GetIntOption(const char *name) const

Returns the value of an integer option.

Throws OptionError if there is no such option or it has a different type.

inline void SetIntOption(const char *name, fmt::LongLong value)
inline double GetDblOption(const char *name) const
inline void SetDblOption(const char *name, double value)
inline std::string GetStrOption(const char *name) const
inline void SetStrOption(const char *name, fmt::StringRef value)
template<class Value>
inline void AddStoredOption(const char *name, const char *description, Value &value, ValueArrayRef values = ValueArrayRef())

Simple stored option referencing a variable.

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddStoredOption(const char *name, const char *description, Value &value, Value, Value)

Simple stored option referencing a variable; min, max values (they are unused but to deduce type; we are too lazy to maintain correct min/max between solver versions.)

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddListOption(const char *name, const char *description, Value &value, ValueArrayRef values = ValueArrayRef())

Add list option referencing a container.

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddListOption(const char *name, const char *description, Value &value, typename Value::value_type, typename Value::value_type)

Add list option referencing a container; min, max values (they are unused but to deduce type; we aree too lazy to maintain correct min/max between solver versions.)

Note

description “HIDDEN” means the option is not printed

inline void ReplaceOptionDescription(const char *name, const char *desc)

Replace option descr.

inline void AddToOptionDescription(const char *name, const char *desc_add)

Add to option descr.

void AddOptionSynonyms_Inline_Front(const char *names_list, const char *realName)

Add “inline” option synonyms.

The _Front version puts them in the front of the synonyms list and the 1st of them is used in the -a output for sorting.

void AddOptionSynonyms_Inline_Back(const char *names_list, const char *realName)

Add “inline” option synonyms.

The _Back version.

void AddOptionSynonyms_OutOfLine(const char *name, const char *realName)

Add an “out-of-line” synonym.

Creates extra entry under -=

template<typename Handler, typename Int>
inline void AddIntOption(const char *name, const char *description, Int (Handler::* get)(const SolverOption&) const, void (Handler::* set)(const SolverOption&, Int))

Adds an integer option.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddIntOption(const char *name, const char *description, int (Handler::* get)(const SolverOption&, const Info&) const, void (Handler::* set)(const SolverOption&, int, const Info&), const Info &info)

Adds an integer option with additional information.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddIntOption(const char *name_list, const char *description, int (Handler::* get)(const SolverOption&, Info) const, void (Handler::* set)(const SolverOption&, int, Info), Info info)

The same as above but with Info argument passed by value.

Note

description “HIDDEN” means the option is not printed

template<typename Handler>
inline void AddDblOption(const char *name, const char *description, double (Handler::* get)(const SolverOption&) const, void (Handler::* set)(const SolverOption&, double))

Adds a double option.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddDblOption(const char *name, const char *description, double (Handler::* get)(const SolverOption&, const Info&) const, void (Handler::* set)(const SolverOption&, double, const Info&), const Info &info)

Adds a double option with additional information.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddDblOption(const char *name, const char *description, double (Handler::* get)(const SolverOption&, Info) const, void (Handler::* set)(const SolverOption&, double, Info), Info info)

The same as above but with Info argument passed by value.

Note

description “HIDDEN” means the option is not printed

template<typename Handler>
inline void AddStrOption(const char *name, const char *description, std::string (Handler::* get)(const SolverOption&) const, void (Handler::* set)(const SolverOption&, fmt::StringRef), ValueArrayRef values = ValueArrayRef())

Adds a string option.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddStrOption(const char *name, const char *description, std::string (Handler::* get)(const SolverOption&, const Info&) const, void (Handler::* set)(const SolverOption&, fmt::StringRef, const Info&), const Info &info, ValueArrayRef values = ValueArrayRef())

Adds a string option with additional information.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddStrOption(const char *name, const char *description, std::string (Handler::* get)(const SolverOption&, Info) const, void (Handler::* set)(const SolverOption&, fmt::StringRef, Info), Info info, ValueArrayRef values = ValueArrayRef())

The same as above but with Info argument passed by value.

Note

description “HIDDEN” means the option is not printed

inline option_iterator option_begin() const

Get the start const-iterator.

inline option_iterator option_end() const

Get the end const-iterator.

inline set_option_iterator set_option_begin() const

Get the start writeable iterator.

inline set_option_iterator set_option_end() const

Get the end writeable iterator.

void AddSolveResults(const SRRegMap &sm, bool ifCanReplace = false)

Add a map with result descriptions.

inline const SRRegMap &GetSolveResultRegistry() const

Get the registry.

Public Static Functions

static std::string ToString(const WarningsMap::value_type &wrn)

Stringify a WarningsMap entry.

Protected Functions

inline char **GetArgvOptions() const

0-terminated list of custom options

inline int GetOptionFlags() const

option parser flags

void InitMetaInfoAndOptions(fmt::CStringRef name, fmt::CStringRef long_name, long date, int flags)

InitMetaInfoAndOptions.

Derived classes which want to provide the info after construction can use the default constructor and call this.

Parameters
  • date – The solver date in YYYYMMDD format.

  • flags – Bitwise OR of zero or more of the following values MULTIPLE_SOL MULTIPLE_OBJ

inline void set_long_name(fmt::StringRef name)
inline void add_to_long_name(fmt::StringRef name)
inline void set_version(fmt::StringRef version)
inline void add_to_version(fmt::StringRef version)
inline void set_license_info(fmt::StringRef license_info)
inline virtual std::string set_external_libs()
inline void set_read_flags(unsigned flags)

Sets the flags for Problem::Read.

inline Stats &stats()

Private Members

Callbacks callbacks_
std::string solutionfileoverride_
char **argv_options_ = {nullptr}
int flag_options_ = {NO_OPTION_ECHO}
template<typename Arg, expr::Kind FIRST, expr::Kind LAST = FIRST>
class mp::BasicBinaryExpr : public mp::BasicExpr<FIRST, FIRST>
#include <expr.h>

A binary expression.

Base: base expression class. Arg: argument expression class.

Public Types

enum [anonymous]

Values:

Public Functions

inline Arg lhs() const

Returns the left-hand side (the first argument) of this expression.

inline Arg rhs() const

Returns the right-hand side (the second argument) of this expression.

Protected Types

typedef ExprBase::Impl Impl

Reuse ExprBase::Impl.

Private Types

typedef BasicExpr<FIRST, LAST> Base

Private Functions

MP_EXPR(Base)
template<typename Item>
class mp::BasicProblem::BasicCommonExpr : private Item
#include <problem.h>

A common expression.

Public Functions

inline const LinearExpr &linear_expr() const

Returns the linear part of the common expression.

inline NumericExpr nonlinear_expr() const

Returns the nonlinear part of the common expression.

template<typename OtherItem>
inline bool operator==(BasicCommonExpr<OtherItem> other) const
template<typename OtherItem>
inline bool operator!=(BasicCommonExpr<OtherItem> other) const

Private Functions

inline BasicCommonExpr(typename Item::Problem *p, int index)

Friends

friend class BasicProblem
class mp::BasicConstraint
#include <constr_base.h>

Custom constraints to derive from, so that overloaded default settings work.

Subclassed by mp::AlgebraicConstraint< Body, RhsOrRange >, mp::ComplementarityConstraint< Expr >, mp::FunctionalConstraint, mp::IndicatorConstraint< Con >, mp::SOS_1or2_Constraint< type >

Public Functions

inline const char *GetName() const

Constraint name.

inline const char *name() const

Constraint name.

inline void SetName(std::string nm)

Set constraint name.

inline Context GetContext() const

Get context, if meaningful.

inline void SetContext(Context) const

Set context, if meaningful.

inline void AddContext(Context) const

Add (merge) context, if meaningful.

inline bool HasResultVar() const

Has result var (is functional)?

inline int GetResultVar() const

For functional constraints, result variable index.

template<class VarInfo>
inline Violation ComputeViolation(const VarInfo&) const

Compute violation.

Public Static Functions

static inline constexpr const char *GetTypeName()

Constraint type name for messages.

static inline constexpr bool UsesContext()

Whether context is meaningful here.

Private Members

std::string name_
class mp::BasicConstraintKeeper
#include <constr_keeper.h>

Interface for an array of constraints of certain type.

Subclassed by mp::ConstraintKeeper< Converter, Backend, Constraint >

Public Types

using ConstraintType = BasicConstraint

Constraint type.

Public Functions

inline virtual ~BasicConstraintKeeper()

Destructor.

inline BasicConstraintKeeper(pre::BasicValuePresolver &pres, const char *nm, const char *optN)

Constructor.

virtual const std::string &GetDescription() const = 0

Constraint keeper description.

virtual Context GetContext(int i) const = 0

Get context of contraint i.

virtual void PropagateResult(BasicFlatConverter &cvt, int i, double lb, double ub, Context ctx) = 0

Propagate expression result of constraint i top-down.

virtual int GetResultVar(int i) const = 0

Result variable of constraint i. Returns -1 if none.

virtual bool ConvertAllNewWith(BasicFlatConverter &cvt) = 0

Convert all new items of this constraint.

This normally dispatches conversion (decomposition) to the Converter

Returns

whether any converted

virtual void MarkExprsForResultVars(BasicFlatConverter &cvt) = 0

Mark whether to keep result vars.

virtual void ConvertWithExpressions(BasicFlatConverter &cvt) = 0

Convert to use expressions.

inline ConstraintAcceptanceLevel GetChosenAcceptanceLevel() const

Query (user-chosen) acceptance level.

This is “combined” for constraint or expression

inline ExpressionAcceptanceLevel GetChosenAcceptanceLevelEXPR() const

Query (user-chosen) expression acceptance level.

virtual bool IfConverterConverts(BasicFlatConverter &cvt) const = 0

Converter’s ability to convert the constraint type.

virtual ConstraintAcceptanceLevel GetModelAPIAcceptance(const BasicFlatModelAPI&) const = 0

ModelAPI’s acceptance level for the constraint type.

This should not be used directly, instead: GetChosenAcceptanceLevel()

virtual ExpressionAcceptanceLevel GetModelAPIAcceptanceEXPR(const BasicFlatModelAPI&) const = 0

ModelAPI’s acceptance level for the expression type.

This should not be used directly, instead: GetChosenAcceptanceLevelEXPR()

virtual ExpressionAcceptanceLevel GetModelAPIAcceptance_EXPR_INTF(const BasicFlatModelAPI &ba) const = 0

Acceptance level of the overall expression interface in the ModelAPI.

virtual const std::type_info &GetTypeInfo() const = 0

Constraint type_info.

virtual int GetConstraintGroup(const BasicFlatModelAPI&) const = 0

Backend’s group number for the constraint type.

virtual int GetNumberOfAddable() const = 0

Report how many will be added to Backend.

virtual void AddUnbridgedToBackend(BasicFlatModelAPI &be, const std::vector<std::string> *vnames) = 0

This adds all unbridged items to the backend (without conversion)

virtual void LogConstraintGroup(BasicFlatModelAPI &be) = 0

This logs the constraint group.

inline const pre::ValueNode &GetValueNode() const

Value presolve node, const.

inline pre::ValueNode &GetValueNode()

Value presolve node.

inline pre::NodeRange AddValueNodeRange(int n = 1)

Create ValueNode range pointer: add n elements.

inline pre::NodeRange SelectValueNodeRange(int pos, int n = 1)

Create ValueNode range pointer: select n elements at certain pos.

inline const char *GetConstraintName() const

Constraint type name, e.g., ‘AbsConstraint’.

virtual const char *GetExprOrConstraintName() const = 0

Expression type, or, if appropriate, constraint type name, e.g., ‘Abs’.

inline virtual const char *GetAcceptanceOptionNames() const

Acceptance option names.

virtual const char *GetShortTypeName() const

Constraint type short name.

Ideally should be in the constraint itself, but currently we derive it from acceptance options.

inline void ConsiderAcceptanceOptions(BasicFlatConverter &cvt, const BasicFlatModelAPI &ma, Env &env)

See what options are available for this constraint: whether it is accepted natively by ModelAPI, as flat constraint or expression.

Add acceptance option(s) “acc:…”. Populate constraint list for -c output.

Note

This should be called before using the class.

virtual void MarkAsBridged(int i) = 0

Mark as bridged. Use index only.

virtual void MarkAsUnused(int i) = 0

Mark as unused. Use index only.

virtual bool IsUnused(int i) const = 0

Is constraint i unused?

virtual void CopyNamesFromValueNodes() = 0

Copy names from ValueNodes.

virtual double ComputeValue(int i, const VarInfoRecomp&) = 0

Compute result for constraint i (for functional constraints)

virtual void ComputeViolations(SolCheck&) = 0

Compute violations.

inline void SetLogger(BasicLogger *lg)

Set logger.

inline BasicLogger *GetLogger() const

Get logger, if provided and open and ok.

Protected Functions

void DoAddAcceptanceOptions(BasicFlatConverter &cvt, const BasicFlatModelAPI &ma, Env &env)
void DoPopulateConstraintList(BasicFlatConverter &cvt, const BasicFlatModelAPI &ma, Env &env)

For -c.

Private Members

pre::ValueNode value_node_
const char *const constr_name_
const char *const solver_opt_nm_
mutable std::string type_name_short_
mutable int acceptance_level_ = {-1}
int acc_level_item_ = {0}
mutable int acc_level_expr_ = {-1}
BasicLogger *exporter_ = {}
template<class Model>
class mp::BasicConverter : public mp::EnvKeeper
#include <converter-base.h>

BasicConverter<> is an interface for a class that takes a Model and translates it into the solver API.

Model can be a ProblemBuilder used by NLHandler for NL input, as done by ModelManagerWithProblemBuilder.

Public Types

using ModelType = Model

The ProblemBuilder a.k.a. Model type.

Public Functions

inline BasicConverter(Env &e)

Constructor.

virtual ~BasicConverter() = default

Destructor.

virtual const ModelType &GetModel() const = 0

Access the model instance, const.

virtual ModelType &GetModel() = 0

Access the model instance.

inline virtual void InitOptions()

Init solver options.

virtual void ConvertModel() = 0

Convert the model into the solver API.

virtual void FillModelTraits(AMPLS_ModelTraits&) = 0

Fill model traits.

virtual bool HasUnfixedIntVars() const = 0

Solver-facing model info: Has unfixed int vars?

inline const Env &GetEnv() const

GetEnv() const.

inline Env &GetEnv()

GetEnv()

template<expr::Kind FIRST, expr::Kind LAST = FIRST>
class mp::BasicExpr : private mp::internal::ExprBase
#include <expr.h>

namespace internal

An expression. A BasicExpr object represents a reference to an expression so it is cheap to construct and pass by value. A type safe way to process expressions of different types is by using ExprVisitor. Although this class is not intended for use in the client code, it is not placed in the internal namespace to enable argument- dependent lookup.

Public Types

enum [anonymous]

Values:

enumerator FIRST_KIND
enumerator LAST_KIND

Public Functions

inline BasicExpr()

Constructs a BasicExpr object representing a null reference to an expression.

The only operation permitted for such object is copying, assignment and check whether it is null using operator SafeBool.

template<typename Expr> inline  BasicExpr (Expr other, typename fmt::internal::EnableIf< static_cast< expr::Kind >(Expr::FIRST_KIND) >=FIRST &&static_cast< expr::Kind >(Expr::LAST_KIND)<=LAST, int >::type=0)

Construct from another expression.

Protected Types

typedef ExprBase::Impl Impl

Reuse ExprBase::Impl.

typedef BasicExpr Base

Base = BasicExpr.

Friends

friend class internal::ExprBase
friend class BasicExprFactory
template<typename ExprType>
friend ExprType UncheckedCast(Expr e)

internal::UnecheckCast & ExprBase::Create are friends because they need access to ExprBase::impl_ via a private base class.

template<typename Alloc>
class mp::BasicExprFactory : private Alloc
#include <expr.h>

namespace internal

An expression factory. Alloc: a memory allocator. Allocator requirements:

  1. The allocate function should return a pointer suitably aligned to hold an object of any fundamental alignment like operator new(std::size_t) does.

  2. The deallocate function should be able to handle 0 passed as the second argument.

Public Types

typedef BasicIteratedExprBuilder<CallExpr> CallExprBuilder
typedef BasicIteratedExprBuilder<IteratedExpr> IteratedExprBuilder
typedef IteratedExprBuilder NumberOfExprBuilder
typedef BasicIteratedExprBuilder<SymbolicNumberOfExpr> SymbolicNumberOfExprBuilder
typedef BasicIteratedExprBuilder<CountExpr> CountExprBuilder
typedef BasicIteratedExprBuilder<IteratedLogicalExpr> IteratedLogicalExprBuilder
typedef BasicIteratedExprBuilder<PairwiseExpr> PairwiseExprBuilder

Public Functions

inline explicit BasicExprFactory(Alloc alloc = Alloc())
inline virtual ~BasicExprFactory()
inline int num_functions() const

Returns the number of functions.

inline Function function(int index) const

Returns the function at the specified index.

inline Function AddFunction(fmt::StringRef name, int num_args, func::Type type = func::NUMERIC)

Adds a function.

name: Function name that may not be null-terminated.

inline void AddFunctions(int num_funcs)

Adds a function that will be defined later.

inline Function DefineFunction(int index, fmt::StringRef name, int num_args, func::Type type)

Defines a function.

inline NumericConstant MakeNumericConstant(double value)

Makes a numeric constant.

inline Reference MakeVariable(int index)

Makes a variable reference.

inline Reference MakeCommonExpr(int index)

Makes a common expression reference.

inline UnaryExpr MakeUnary(expr::Kind kind, NumericExpr arg)

Makes a unary expression.

inline BinaryExpr MakeBinary(expr::Kind kind, NumericExpr lhs, NumericExpr rhs)

Makes a binary expression.

inline IfExpr MakeIf(LogicalExpr condition, NumericExpr then_expr, NumericExpr else_expr)

Makes an if expression.

inline PLTermBuilder BeginPLTerm(int num_breakpoints)

Begins building a piecewise-linear term.

inline PLTerm EndPLTerm(PLTermBuilder builder, Reference arg)

Ends building a piecewise-linear term.

arg: argument that should be either a variable or a common expression.

inline CallExprBuilder BeginCall(Function func, int num_args)

Begins building a call expression.

inline CallExpr EndCall(CallExprBuilder builder)

Ends building a call expression.

inline IteratedExprBuilder BeginIterated(expr::Kind kind, int num_args)

Begins building an iterated expression.

inline IteratedExpr EndIterated(IteratedExprBuilder builder)

Ends building an iterated expression.

inline IteratedExprBuilder BeginSum(int num_args)
inline IteratedExpr EndSum(IteratedExprBuilder builder)
inline NumberOfExprBuilder BeginNumberOf(int num_args, NumericExpr arg0)

Begins building a numberof expression.

inline IteratedExpr EndNumberOf(NumberOfExprBuilder builder)

Ends building a numberof expression.

inline SymbolicNumberOfExprBuilder BeginSymbolicNumberOf(int num_args, Expr arg0)

Begins building a numberof expression.

inline SymbolicNumberOfExpr EndSymbolicNumberOf(SymbolicNumberOfExprBuilder builder)

Ends building a numberof expression.

inline CountExprBuilder BeginCount(int num_args)

Begins building a count expression.

inline CountExpr EndCount(CountExprBuilder builder)

Ends building a count expression.

inline LogicalConstant MakeLogicalConstant(bool value)

Makes a logical constant.

inline NotExpr MakeNot(LogicalExpr arg)

Makes a logical NOT expression.

inline BinaryLogicalExpr MakeBinaryLogical(expr::Kind kind, LogicalExpr lhs, LogicalExpr rhs)

Makes a binary logical expression.

inline RelationalExpr MakeRelational(expr::Kind kind, NumericExpr lhs, NumericExpr rhs)

Makes a relational expression.

inline LogicalCountExpr MakeLogicalCount(expr::Kind kind, NumericExpr lhs, CountExpr rhs)

Makes a logical count expression.

inline ImplicationExpr MakeImplication(LogicalExpr condition, LogicalExpr then_expr, LogicalExpr else_expr)

Makes an implication expression.

inline IteratedLogicalExprBuilder BeginIteratedLogical(expr::Kind kind, int num_args)

Begins building an iterated logical expression.

inline IteratedLogicalExpr EndIteratedLogical(IteratedLogicalExprBuilder builder)

Ends building an iterated logical expression.

inline PairwiseExprBuilder BeginPairwise(expr::Kind kind, int num_args)

Begins building a pairwise expression.

inline PairwiseExpr EndPairwise(PairwiseExprBuilder builder)

Ends building a pairwise expression.

inline StringLiteral MakeStringLiteral(fmt::StringRef value)

Makes a string literal.

inline SymbolicIfExpr MakeSymbolicIf(LogicalExpr condition, Expr then_expr, Expr else_expr)

Makes a symbolic if expression.

Private Functions

FMT_DISALLOW_COPY_AND_ASSIGN(BasicExprFactory)
template<typename ExprType>
inline ExprType::Impl *Allocate(expr::Kind kind, int extra_bytes = 0)

Allocates memory for an object of type ExprType::Impl.

extra_bytes: extra bytes to allocate at the end (can be negative).

template<typename T>
void Deallocate(const std::vector<T> &data)
inline Reference MakeReference(expr::Kind kind, int index)

Makes a reference expression.

template<typename ExprType, typename Arg>
inline ExprType MakeUnary(expr::Kind kind, Arg arg)
template<typename ExprType, typename LHS, typename RHS>
inline ExprType MakeBinary(expr::Kind kind, LHS lhs, RHS rhs)
template<typename ExprType, typename Arg>
inline ExprType MakeIf(LogicalExpr condition, Arg then_expr, Arg else_expr)
template<typename ExprType>
inline BasicIteratedExprBuilder<ExprType> BeginIterated(expr::Kind kind, int num_args)
template<typename ExprType>
inline ExprType EndIterated(BasicIteratedExprBuilder<ExprType> builder)
Function CreateFunction(const Function::Impl *&impl, fmt::StringRef name, int num_args, func::Type type)

Private Members

std::vector<const Expr::Impl*> exprs_
std::vector<const Function::Impl*> funcs_

Private Static Functions

static inline void Copy(fmt::StringRef src, char *dst)

Copies a string.

src: Reference to a source string that may not be null-terminated (.nl reader can generate such strings)

template<class ExprType = void*>
class mp::BasicExprModelAPI : public mp::BasicFlatModelAPI
#include <model_api_base.h>

ModelAPIs handling expression trees should derive from.

Public Types

using Expr = ExprType

Public Functions

inline void InitCustomOptions()

Placeholder for InitCustomOptions()

inline void PassFlatModelInfo(const FlatModelInfo *pfmi)

Pass on a FlatModelInfo object.

inline const FlatModelInfo *GetFlatModelInfo() const

Retrieve FlatModelInfo*.

inline void InitProblemModificationPhase(const FlatModelInfo*)

Chance to prepare problem update, e.g., allocate storage.

inline void FinishProblemModificationPhase()

Chance to end problem update.

inline void SetLinearObjective(int, const LinearObjective&)

Placeholder for SetLinearObjective()

inline void SetQuadraticObjective(int, const QuadraticObjective&)

Placeholder for SetQuadraticObjective()

template<class Constraint>
inline void AddConstraint(const Constraint&)

Placeholder for AddConstraint<>()

Public Static Functions

static inline const char *GetTypeName()

Placeholder for GetTypeName()

static inline const char *GetLongName()

Placeholder for GetLongName()

static inline int AcceptsQuadObj()

Whether accepting quadratic objectives: 0 - no, 1 - convex, 2 - nonconvex.

static inline constexpr ConstraintGroup GroupNumber(const BasicConstraint*)

Default constraint group.

static inline constexpr ConstraintAcceptanceLevel AcceptanceLevel(const BasicConstraint*)

By default, we say constraint XYZ is not accepted.

template<class FlatCon>
static inline constexpr ExpressionAcceptanceLevel AcceptanceLevel(const ExprWrapper<FlatCon>*)

By default, we say expression XYZ is not accepted.

static inline constexpr ExpressionAcceptanceLevel ExpressionInterfaceAcceptanceLevel()

By default, no expressions (global switch)

static inline constexpr bool AcceptsNonconvexQC()

Specifically, ask if the solver accepts non-convex quadratic constraints.

static inline constexpr bool CanMixConicQCAndQC()

Specifically, ask if the solver can mix conic quadratic (entered via dedicated API) and direct quadratic constraints.

static inline constexpr bool CanSOCPCornerCasesFromQC()

Ask if the solver can recognize SOCP corner cases (non-std representations such as xy>=1, see tests) from quadratic representations.

template<typename Impl, typename Result, typename ExprTypes>
class mp::BasicExprVisitor

A basic expression visitor that can be used with different expression hierarchies described by ExprTypes.

BasicExprVisitor uses the curiously recurring template pattern: http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern

Public Functions

inline virtual ~BasicExprVisitor()
MP_DEFINE_EXPR_TYPES(ExprTypes)
Result Visit(Expr e)
inline Result VisitUnsupported(Expr e)
inline Result VisitNumeric(NumericExpr e)
inline Result VisitLogical(LogicalExpr e)
inline Result VisitNumericConstant(NumericConstant c)
inline Result VisitVariable(Variable v)
inline Result VisitCommonExpr(CommonExpr e)
inline Result VisitUnary(UnaryExpr e)
inline Result VisitMinus(UnaryExpr e)
inline Result VisitAbs(UnaryExpr e)
inline Result VisitFloor(UnaryExpr e)
inline Result VisitCeil(UnaryExpr e)
inline Result VisitSqrt(UnaryExpr e)
inline Result VisitPow2(UnaryExpr e)
inline Result VisitExp(UnaryExpr e)
inline Result VisitLog(UnaryExpr e)
inline Result VisitLog10(UnaryExpr e)
inline Result VisitSin(UnaryExpr e)
inline Result VisitSinh(UnaryExpr e)
inline Result VisitCos(UnaryExpr e)
inline Result VisitCosh(UnaryExpr e)
inline Result VisitTan(UnaryExpr e)
inline Result VisitTanh(UnaryExpr e)
inline Result VisitAsin(UnaryExpr e)
inline Result VisitAsinh(UnaryExpr e)
inline Result VisitAcos(UnaryExpr e)
inline Result VisitAcosh(UnaryExpr e)
inline Result VisitAtan(UnaryExpr e)
inline Result VisitAtanh(UnaryExpr e)
inline Result VisitBinary(BinaryExpr e)

Visits a binary expression or a function taking two arguments.

inline Result VisitAdd(BinaryExpr e)
inline Result VisitSub(BinaryExpr e)
inline Result VisitLess(BinaryExpr e)
inline Result VisitMul(BinaryExpr e)
inline Result VisitDiv(BinaryExpr e)
inline Result VisitTruncDiv(BinaryExpr e)
inline Result VisitMod(BinaryExpr e)
inline Result VisitPow(BinaryExpr e)
inline Result VisitPowConstBase(BinaryExpr e)
inline Result VisitPowConstExp(BinaryExpr e)
inline Result VisitBinaryFunc(BinaryExpr e)
inline Result VisitAtan2(BinaryExpr e)
inline Result VisitPrecision(BinaryExpr e)
inline Result VisitRound(BinaryExpr e)
inline Result VisitTrunc(BinaryExpr e)
inline Result VisitIf(IfExpr e)
inline Result VisitPLTerm(PLTerm e)
inline Result VisitCall(CallExpr e)
inline Result VisitVarArg(VarArgExpr e)
inline Result VisitMin(VarArgExpr e)
inline Result VisitMax(VarArgExpr e)
inline Result VisitSum(SumExpr e)
inline Result VisitNumberOf(NumberOfExpr e)
inline Result VisitNumberOfSym(SymbolicNumberOfExpr e)
inline Result VisitCount(CountExpr e)
inline Result VisitLogicalConstant(LogicalConstant c)
inline Result VisitNot(NotExpr e)
inline Result VisitBinaryLogical(BinaryLogicalExpr e)
inline Result VisitOr(BinaryLogicalExpr e)
inline Result VisitAnd(BinaryLogicalExpr e)
inline Result VisitIff(BinaryLogicalExpr e)
inline Result VisitRelational(RelationalExpr e)
inline Result VisitLT(RelationalExpr e)
inline Result VisitLE(RelationalExpr e)
inline Result VisitEQ(RelationalExpr e)
inline Result VisitGE(RelationalExpr e)
inline Result VisitGT(RelationalExpr e)
inline Result VisitNE(RelationalExpr e)
inline Result VisitLogicalCount(LogicalCountExpr e)
inline Result VisitAtLeast(LogicalCountExpr e)
inline Result VisitAtMost(LogicalCountExpr e)
inline Result VisitExactly(LogicalCountExpr e)
inline Result VisitNotAtLeast(LogicalCountExpr e)
inline Result VisitNotAtMost(LogicalCountExpr e)
inline Result VisitNotExactly(LogicalCountExpr e)
inline Result VisitImplication(ImplicationExpr e)
inline Result VisitIteratedLogical(IteratedLogicalExpr e)
inline Result VisitExists(IteratedLogicalExpr e)
inline Result VisitForAll(IteratedLogicalExpr e)
inline Result VisitAllDiff(PairwiseExpr e)
inline Result VisitNotAllDiff(PairwiseExpr e)
inline Result VisitStringLiteral(StringLiteral e)
inline Result VisitSymbolicIf(SymbolicIfExpr e)
template<class Impl, class Converter, class Constraint>
class mp::BasicFCC

Helper class providing a default framework for assigning result to a functional expression, possibly adding a corresponding constraint on the result variable.

Public Types

using Var = typename Converter::Var

Public Functions

inline BasicFCC(Converter &cvt, Constraint &&fc) noexcept
inline VarOrConst Convert()

Convert array of arguments into a result (var or const), possibly adding extra constraint(s).

Returns

either a constant or a variable

inline void PreprocessArguments()
inline void AddResultVariable()
inline void AddConstraint()

Public Members

PreprocessInfo<Constraint> prepro_

Protected Functions

inline Converter &GetConverter()
inline Constraint &GetConstraint()
inline double lb() const
inline double ub() const
inline var::Type type() const
inline bool ResultIsConstant() const
inline bool ResultVarIsKnown() const
inline bool MapFind()
inline int GetResultVar() const
inline void SetResultVar(int r)

Private Members

Converter &converter_
Constraint constr_
class mp::BasicFileAppender : public mp::BasicLogger
#include <utils-file.h>

Class appending strings to file with given name.

Public Functions

virtual bool IsOpen() const override = 0

Is the log active and ok?

virtual bool Open(const std::string &fln, bool fErase) = 0

Open file.

virtual void Close() = 0

Close file.

template<class Str>
inline bool Append(const Str &s)

append string.

Returns

whether all ok.

virtual bool Append(const char*) override = 0

Append string.

Returns

whether all ok.

class mp::BasicFlatConverter
#include <constr_keeper.h>

Converters handling custom constraints should derive from.

Subclassed by mp::FlatConverter< Impl, ModelAPI, FlatModel< > >, mp::FlatConverter< Impl, ModelAPI, FlatModel >

Public Functions

inline int MapFind(const BasicConstraint&)

For Common Subexpression Elimination, we can use maps This stub returns empty Id.

template<class Con>
inline bool MapInsert(const Con&, int)

Returns false when we do have a map and entry duplicated (should not happen).

Can be conveniently overloaded

Public Static Functions

static inline constexpr double ConstraintCvtPriority(BasicConstraint*)

Default conversion priority.

static inline constexpr double Pi()

Value of Pi.

static inline constexpr double Infty()

Infinity.

static inline constexpr double MinusInfty()

-Infinity

static inline constexpr double PracticallyInf()

Pract inf.

static inline constexpr double PracticallyMinusInf()

Pract -inf.

class mp::BasicFlatModel

Class BasicFlatModel.

Provides abstract interface to a few items in FlatModel

Subclassed by mp::FlatModel< >, mp::FlatModel< ModelParams >

Public Types

using VarBndVec = std::vector<double>

Typedef VarBndVec.

Public Functions

inline virtual ~BasicFlatModel()

Virtual Destruct.

virtual const VarBndVec &GetVarLBs() const = 0

Provide variable lower bounds.

virtual const VarBndVec &GetVarUBs() const = 0

Provide variable upper bounds.

class mp::BasicFlatModelAPI
#include <model_api_base.h>

ModelAPIs handling custom flat constraints should derive from.

Subclassed by mp::BasicExprModelAPI< ExprType >

Public Functions

inline void InitCustomOptions()

Placeholder for InitCustomOptions()

inline void PassFlatModelInfo(const FlatModelInfo *pfmi)

Pass on a FlatModelInfo object.

inline const FlatModelInfo *GetFlatModelInfo() const

Retrieve FlatModelInfo*.

inline void InitProblemModificationPhase(const FlatModelInfo*)

Chance to prepare problem update, e.g., allocate storage.

inline void FinishProblemModificationPhase()

Chance to end problem update.

inline void SetLinearObjective(int, const LinearObjective&)

Placeholder for SetLinearObjective()

inline void SetQuadraticObjective(int, const QuadraticObjective&)

Placeholder for SetQuadraticObjective()

template<class Constraint>
inline void AddConstraint(const Constraint&)

Placeholder for AddConstraint<>()

Public Static Functions

static inline const char *GetTypeName()

Placeholder for GetTypeName()

static inline const char *GetLongName()

Placeholder for GetLongName()

static inline int AcceptsQuadObj()

Whether accepting quadratic objectives: 0 - no, 1 - convex, 2 - nonconvex.

static inline constexpr ConstraintGroup GroupNumber(const BasicConstraint*)

Default constraint group.

static inline constexpr ConstraintAcceptanceLevel AcceptanceLevel(const BasicConstraint*)

By default, we say constraint XYZ is not accepted.

static inline constexpr ExpressionAcceptanceLevel ExpressionInterfaceAcceptanceLevel()

By default, no expressions (global switch)

template<class FlatCon>
static inline constexpr ExpressionAcceptanceLevel AcceptanceLevel(const ExprWrapper<FlatCon>*)

By default, we say expression XYZ is not accepted.

static inline constexpr bool AcceptsNonconvexQC()

Specifically, ask if the solver accepts non-convex quadratic constraints.

static inline constexpr bool CanMixConicQCAndQC()

Specifically, ask if the solver can mix conic quadratic (entered via dedicated API) and direct quadratic constraints.

static inline constexpr bool CanSOCPCornerCasesFromQC()

Ask if the solver can recognize SOCP corner cases (non-std representations such as xy>=1, see tests) from quadratic representations.

Private Members

const FlatModelInfo *pfmi_ = {nullptr}
template<class Impl, class ModelConverter>
class mp::BasicFuncConstrCvt : public mp::BasicItemConverter<ModelConverter>
#include <redef_base.h>

A functional constraint converter.

Parameters
  • Impl – the final converter

  • ModelConverter

Subclassed by mp::FuncConConverter_MIP_CRTP< PowConstExponentConverter_MIP< ModelConverter >, ModelConverter, PowConstraint >, mp::FuncConConverter_MIP_CRTP< FuncConConverter_MIP< ModelConverter, FuncCon >, ModelConverter, FuncCon >, mp::FuncConConverter_MIP_CRTP< Impl, ModelConverter, FuncCon >

Public Types

using Base = BasicItemConverter<ModelConverter>

Base class.

Public Functions

inline BasicFuncConstrCvt(ModelConverter &mc)

Constructor.

template<class ItemType>
inline void Convert(const ItemType &item, int i)

Generic Convert(), distinguishes context & result variable.

Distinguish positive and negative context because if only one of these is necessary, significant model reduction can be achieved in certain cases.

Responsible for adding presolve links, if any

The Impl can reimplement this

Parameters
  • item – the item to be converted

  • i – item index, used to create a presolve link

template<class ItemType>
inline void ConvertCtxNeg(const ItemType &item, int)

Convert in negative context.

template<class ItemType>
inline void ConvertCtxPos(const ItemType &item, int)

Convert in positive context.

inline const ModelConverter &GetMC() const

Reuse the stored ModelConverter.

inline ModelConverter &GetMC()

Reuse the stored ModelConverter.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

template<typename Arg, expr::Kind K>
class mp::BasicIfExpr : public mp::BasicExpr<K>
#include <expr.h>

Public Types

enum [anonymous]

Values:

Public Functions

inline LogicalExpr condition() const
inline Arg then_expr() const
inline Arg else_expr() const

Public Static Attributes

static const expr::Kind KIND = K

Protected Types

typedef ExprBase::Impl Impl

Reuse ExprBase::Impl.

Private Types

typedef BasicExpr<K> Base

Private Functions

MP_EXPR(Base)
template<class Impl, class LinkEntry>
class mp::pre::BasicIndivEntryLink : public mp::pre::BasicLink
#include <valcvt-link.h>

A stub for links which process each entry individually, in contrast to Presolve…(LinkIndexRange …).

Some of such links could be optimized to store a range of transformations in each entry if that helps (but this could be an overoptimization?)

Usage: a derived class should define some methods Presolve…(const LinkEntry& ) and Postsolve…(const LinkEntry&).

We could allow default methods as follows: Those methods which are not defined, just copy values (which might be correct in some cases). Then, need a “default copy” method.

Using CRTP: https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern

Subclassed by mp::pre::BasicStaticIndivEntryLink< RangeCon2Slack< ModelConverter, RangeCon >, 3, 3, 1 >

Public Types

using ItemRangeList = std::vector<NodeRange>

Typedef item container.

Public Functions

inline BasicIndivEntryLink(ValuePresolver &pre)

Constructor.

inline void AddEntry(LinkEntry be)

Add entry.

inline virtual void ExportEntryItems(EntryItems &ei, int i) const override

Get source/target nodes for a given link entry.

This is used for graph export

virtual const char *GetTypeName() const = 0

Type name.

Protected Functions

inline void RegisterLinkIndex(int i)

Add a range of link entries to the Presolver’s list.

Every derived link should call either of the next two methods whenever adding a link entry. Version 1: add single link

inline void RegisterLinkIndexRange(LinkIndexRange)

Version 2: add a range of links.

Implement link range registration in global Presolver.

Private Members

std::deque<LinkEntry> entries_
template<class ModelConverter>
class mp::BasicItemConverter
#include <redef_base.h>

A base class for specific Item Converters, such as individual constraint converters.

Parameters

ModelConverter

Subclassed by mp::BasicFuncConstrCvt< SOS2Converter_MIP< ModelConverter >, ModelConverter >, mp::BasicFuncConstrCvt< QConeConverter< ModelConverter >, ModelConverter >, mp::BasicFuncConstrCvt< IfThenElseConverter_MIP< ModelConverter >, ModelConverter >, mp::BasicFuncConstrCvt< Cond_LE_LT_GT_GE_Converter_MIP< ModelConverter, AlgCon >, ModelConverter >, mp::BasicFuncConstrCvt< ComplementarityConverter_MIP< ModelConverter, ComplCon >, ModelConverter >, mp::BasicFuncConstrCvt< PLConverter_MIP< ModelConverter >, ModelConverter >, mp::BasicFuncConstrCvt< NumberofVarConverter_MIP< ModelConverter >, ModelConverter >, mp::BasicFuncConstrCvt< AndConverter_MIP< ModelConverter >, ModelConverter >, mp::BasicFuncConstrCvt< AllDiffConverter_MIP< ModelConverter >, ModelConverter >, mp::BasicFuncConstrCvt< AbsConverter_MIP< ModelConverter >, ModelConverter >, mp::BasicFuncConstrCvt< RQConeConverter< ModelConverter >, ModelConverter >, mp::BasicFuncConstrCvt< CondEQConverter_MIP< ModelConverter, AlgConBody >, ModelConverter >, mp::BasicFuncConstrCvt< NumberofConstConverter_MIP< ModelConverter >, ModelConverter >, mp::BasicFuncConstrCvt< MinOrMaxConverter_MIP< ModelConverter, sense >, ModelConverter >, mp::BasicFuncConstrCvt< ImplicationConverter_MIP< ModelConverter >, ModelConverter >, mp::BasicFuncConstrCvt< NotConverter_MIP< ModelConverter >, ModelConverter >, mp::BasicFuncConstrCvt< OrConverter_MIP< ModelConverter >, ModelConverter >, mp::BasicFuncConstrCvt< DivConverter_MIP< ModelConverter >, ModelConverter >, mp::BasicFuncConstrCvt< CountConverter_MIP< ModelConverter >, ModelConverter >, mp::BasicFuncConstrCvt< Impl, ModelConverter >, mp::IndicatorLinGEConverter_MIP< ModelConverter >, mp::IndicatorLinLEConverter_MIP< ModelConverter >, mp::IndicatorQuadConverter_MIP< ModelConverter, sens >, mp::QCConverter_MIP< ModelConverter, sens >, mp::RangeConstraintConverter< ModelConverter, AlgConBody >

Public Functions

inline BasicItemConverter(ModelConverter &mc)

Constructor.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

inline ModelConverter &GetMC()

Access ModelConverter.

Private Members

ModelConverter &mdl_cvt_
template<typename ArgType, expr::Kind FIRST, expr::Kind LAST = FIRST>
class mp::BasicIteratedExpr : public mp::BasicExpr<FIRST, FIRST>
#include <expr.h>

BasicIteratedExpr<ArgType>

Public Types

typedef ArgType Arg

Typedef Arg.

typedef internal::ExprIterator<Arg> iterator

An argument iterator.

enum [anonymous]

Values:

Public Functions

inline int num_args() const

Returns the number of arguments.

inline Arg arg(int index)

Returns an argument with the specified index.

inline iterator begin() const

begin()

inline iterator end() const

end()

Protected Types

typedef ExprBase::Impl Impl

Reuse ExprBase::Impl.

Private Types

typedef BasicExpr<FIRST, LAST> Base

Private Functions

MP_EXPR(Base)
template<typename ExprType>
class mp::BasicExprFactory::BasicIteratedExprBuilder

A variable argument expression builder.

Public Functions

inline void AddArg(typename ExprType::Arg arg)

Private Functions

inline explicit BasicIteratedExprBuilder(typename ExprType::Impl *impl)

Private Members

ExprType::Impl *impl_
int arg_index_

Friends

friend class BasicExprFactory
class mp::pre::BasicLink
#include <valcvt-link.h>

ValuePresolveLink interface.

A link is a node of the structural conversion graph. It contains an array of concrete nodes (‘link entries’), each describes a transformation from some source vars+cons+objs values into/from some target ones. All concrete nodes are of the same type.

Subclassed by mp::pre::BasicIndivEntryLink< Impl, std::array< int, NIndexes > >, mp::pre::BasicIndivEntryLink< Impl, LinkEntry >, mp::pre::CopyLink, mp::pre::Many2ManyLink

Public Types

using ItemRangeList = std::vector<NodeRange>

Typedef item container.

Public Functions

inline BasicLink(ValuePresolver &pre)

Constructor.

virtual ~BasicLink() = default

Virtual destructor.

virtual const char *GetTypeName() const = 0

Type name.

virtual void ExportEntryItems(EntryItems &ei, int i) const = 0

Get source/target nodes for a given link entry.

This is used for graph export

Protected Functions

inline void RegisterLinkIndex(int i)

Add a range of link entries to the Presolver’s list.

Every derived link should call either of the next two methods whenever adding a link entry. Version 1: add single link

inline void RegisterLinkIndexRange(LinkIndexRange)

Version 2: add a range of links.

Implement link range registration in global Presolver.

Private Members

ValuePresolver &value_presolver_
class mp::BasicLogger
#include <utils-string.h>

Class logging strings to file or screen or memory etc.

Subclassed by mp::BasicFileAppender

Public Functions

inline virtual ~BasicLogger()

Destruct.

virtual bool IsOpen() const = 0

Is the log active and ok?

template<class Str>
inline bool Append(const Str &s)

append string.

Returns

whether all ok.

virtual bool Append(const char*) = 0

Append string.

Returns

whether all ok.

template<typename Item>
class mp::BasicProblem::BasicLogicalCon : private Item
#include <problem.h>

A logical constraint.

Public Functions

inline LogicalExpr expr() const

Returns the constraint expression.

template<typename OtherItem>
inline bool operator==(BasicLogicalCon<OtherItem> rhs) const
template<typename OtherItem>
inline bool operator!=(BasicLogicalCon<OtherItem> rhs) const

Private Functions

inline BasicLogicalCon(typename Item::Problem *p, int index)

Private Static Functions

static inline int num_items(const BasicProblem &p)

Friends

friend class BasicProblem
class mp::BasicModelManager
#include <model-mgr-base.h>

Abstract Model Manager.

Standardizes the following tasks:

  • Input the model;

  • Access user-provided solution/suffixes;

  • Report solutions/suffixes.

Subclassed by mp::ModelManagerWithProblemBuilder< Converter >

Public Functions

inline virtual ~BasicModelManager()
virtual void InitOptions() = 0

Setup Model Manager’s solver options.

virtual void ReadNLModel(const std::string &nl_filename, const std::string &filename_no_ext, Checker_AMPLS_ModeltTraits, std::function<void()> after_header) = 0

Read NL model.

virtual ArrayRef<double> InitialValues() = 0

User-provided primal solution.

virtual ArrayRef<int> InitialValuesSparsity() = 0

User-provided primal solution: sparsity.

virtual ArrayRef<double> InitialDualValues() = 0

User-provided dual solution.

virtual ArrayRef<int> InitialDualValuesSparsity() = 0

User-provided dual solution: sparsity.

virtual ArrayRef<int> ReadSuffix(const SuffixDef<int> &suf) = 0

Read integer suffix.

virtual ArrayRef<double> ReadSuffix(const SuffixDef<double> &suf) = 0

Read double suffix.

virtual void ReportSuffix(const SuffixDef<int> &suf, ArrayRef<int> values) = 0

Report integer suffix.

virtual void ReportSuffix(const SuffixDef<double> &suf, ArrayRef<double> values) = 0

Report double suffix.

virtual size_t GetSuffixSize(int kind) = 0

Length of a suffix vector of given kind.

virtual void SetSolutionFileName(const std::string &fileName) = 0
virtual void HandleSolution(int, fmt::CStringRef, const double*, const double*, double) = 0

Report final solution.

virtual void HandleFeasibleSolution(int solve_code, fmt::CStringRef, const double*, const double*, double) = 0

Report intermediate solution.

virtual const std::vector<bool> &IsVarInt() const = 0

Integrality flags of the variables in the original instance.

Used for solution rounding

virtual bool HasUnfixedIntVars() const = 0

Has unfixed int vars? This is about the solver-facing instance.

template<typename T>
class mp::BasicMutSuffix : public mp::BasicSuffix<T>
#include <suffix.h>

A mutable suffix.

Public Types

typedef T Type

Public Functions

inline BasicMutSuffix()
inline void set_value(int index, T value)
inline ArrayRef<T> get_values() const
inline T value(int index) const
template<typename Visitor>
inline void VisitValues(Visitor &v) const

Private Functions

inline explicit BasicMutSuffix(const typename BasicSuffix<T>::Impl *impl)
inline explicit BasicMutSuffix(MutSuffix other)

Friends

friend class BasicSuffixSet
friend BasicMutSuffix Cast(MutSuffix s)
template<typename Item>
class mp::BasicProblem::BasicObjective : private Item
#include <problem.h>

An objective.

Public Functions

inline obj::Type type() const

Returns the type of the objective.

inline const LinearExpr &linear_expr() const

Returns the linear part of the objective expression.

inline NumericExpr nonlinear_expr() const

Returns the nonlinear part of the objective expression.

template<typename OtherItem>
inline bool operator==(BasicObjective<OtherItem> other) const
template<typename OtherItem>
inline bool operator!=(BasicObjective<OtherItem> other) const

Private Functions

inline BasicObjective(typename Item::Problem *p, int index)

Private Static Functions

static inline int num_items(const BasicProblem &p)

Friends

friend class BasicProblem
friend class MutObjective
template<typename ProblemParams = BasicProblemParams<>>
class mp::BasicProblem : public mp::BasicExprFactory<std::allocator<char>>, public mp::SuffixManager
#include <problem.h>

An optimization problem.

Subclassed by mp::ColProblem

Public Types

typedef mp::Function Function
typedef mp::Expr Expr
typedef mp::NumericExpr NumericExpr
typedef mp::LogicalExpr LogicalExpr
typedef mp::CountExpr CountExpr
typedef mp::Reference Reference
typedef internal::ExprTypes ExprTypes
typedef BasicProblemItem<const BasicProblem> ProblemItem
typedef BasicProblemItem<BasicProblem> MutProblemItem
typedef BasicVariable<ProblemItem> Variable

An optimization variable.

typedef Range<Variable> VarRange

A range of variables.

typedef LinearExprBuilder LinearObjBuilder
typedef BasicObjective<ProblemItem> Objective

An objective.

typedef Range<Objective> ObjRange

A range of objectives.

typedef LinearExprBuilder LinearConBuilder
typedef BasicAlgebraicCon<ProblemItem> AlgebraicCon

An algebraic constraint.

typedef Range<AlgebraicCon> AlgebraicConRange

A range of algebraic constraints.

typedef BasicLogicalCon<ProblemItem> LogicalCon
typedef Range<LogicalCon> LogicalConRange

A range of logical constraints.

typedef BasicCommonExpr<ProblemItem> CommonExpr
typedef SuffixHandler<int> IntSuffixHandler
typedef SuffixHandler<double> DblSuffixHandler
typedef BasicProblem Builder
typedef BasicIteratedExprBuilder<CallExpr> CallExprBuilder
typedef BasicIteratedExprBuilder<IteratedExpr> IteratedExprBuilder
typedef IteratedExprBuilder NumberOfExprBuilder
typedef BasicIteratedExprBuilder<SymbolicNumberOfExpr> SymbolicNumberOfExprBuilder
typedef BasicIteratedExprBuilder<CountExpr> CountExprBuilder
typedef BasicIteratedExprBuilder<IteratedLogicalExpr> IteratedLogicalExprBuilder
typedef BasicIteratedExprBuilder<PairwiseExpr> PairwiseExprBuilder
typedef MutSuffix Suffix
typedef MutIntSuffix IntSuffix
typedef mp::SuffixSet SuffixSet

Public Functions

inline const std::vector<bool> &IsVarInt() const

Deprecated.

inline BasicProblem()

Constructs an empty optimization problem.

template<class Solver>
inline explicit BasicProblem(const Solver&)

Placeholder, some APIs assume a ProblemBuilder to use a Solver.

inline int num_vars() const

Returns the number of variables.

inline const std::string &var_name(int i)

Normal variable name.

inline const std::string &dvar_name(int i)

Defined variable name.

inline const std::string &con_name(int i)

Constraint name.

inline const std::string &obj_name(int i)

Objective name.

inline const std::vector<std::string> &var_names()

Returns the variable names (if present).

After normal variables follow defined variables.

inline const std::vector<std::string> &con_names()

Returns the constraint names (if present).

inline const std::vector<std::string> &obj_names()

Returns the objective names (if present).

inline VarNamer GetVarNamer()

Obtain variable namer.

inline int num_objs() const

Returns the number of objectives.

inline int num_cons() const

Returns total number of constraints from the NL file.

inline int num_algebraic_cons() const

Returns the number of algebraic constraints.

inline int num_logical_cons() const

Returns the number of logical constraints.

inline bool has_nonlinear_cons() const

Return true if the problem has nonlinear constraints.

inline int num_common_exprs() const

Returns the number of common expressions.

inline VarRange vars() const

Returns a range representing all variables in this optimization problem. It can be used for iterating over variables:

for (auto var: problem.vars()) {
  ...
}

inline Variable var(int index) const

Returns the variable at the specified index.

inline MutVariable var(int index)
inline Variable AddVar(double lb, double ub, var::Type type = var::CONTINUOUS)

Adds a variable.

inline void AddVars(int num_vars, var::Type type)
inline void AddVars(int num_vars, const double *lb, const double *ub, const var::Type *type)
inline std::vector<int> AddVars(std::size_t nvars, double lb = -INFINITY, double ub = INFINITY, var::Type type = var::CONTINUOUS)

Add vector of variables. Type: var::CONTINUOUS by default.

inline void SetVarNames(std::vector<std::string> names)

Set name vectors.

inline void SetConNames(std::vector<std::string> names)
inline void SetObjNames(std::vector<std::string> names)
inline ObjRange objs() const

Returns a range representing all objectives in this optimization problem. It can be used for iterating over objectives:

for (auto obj: problem.objs()) {
  ...
}

inline Objective obj(int index) const

Returns the objective at the specified index.

inline MutObjective obj(int index)

Returns the mutable objective at the specified index.

LinearObjBuilder AddObj(obj::Type type, NumericExpr expr, int num_linear_terms = 0)

Adds an objective.

Returns a builder for the linear part of an objective expression.

inline LinearObjBuilder AddObj(obj::Type type, int num_linear_terms = 0)
inline void AddObjs(int num_objs)
inline AlgebraicConRange algebraic_cons() const

Returns a range representing all algebraic constraints in this optimization problem. It can be used for iterating over algebraic constraints:

for (auto con: problem.algebraic_cons()) {
  ...
}

inline AlgebraicCon algebraic_con(int index) const

Returns the algebraic constraint at the specified index.

inline MutAlgebraicCon algebraic_con(int index)

Returns the mutable algebraic constraint at the specified index.

inline MutAlgebraicCon AddCon(double lb, double ub)

Adds an algebraic constraint.

Returns a builder for the linear part of a constraint expression.

inline void AddAlgebraicCons(int num_cons)
inline LogicalConRange logical_cons() const

Returns a range representing all logical constraints in this optimization problem. It can be used for iterating over logical constraints:

for (auto con: problem.logical_cons()) {
  ...
}

inline LogicalCon logical_con(int index) const

Returns the logical constraint at the specified index.

inline MutLogicalCon logical_con(int index)

Returns the mutable logical constraint at the specified index.

inline void AddCon(LogicalExpr expr)

Adds a logical constraint.

inline void AddLogicalCons(int num_cons)
inline CommonExpr common_expr(int index) const

Returns the common expression at the specified index.

inline MutCommonExpr common_expr(int index)
inline MutCommonExpr AddCommonExpr(NumericExpr expr)

Adds a common expression (defined variable).

inline void AddCommonExprs(int num_exprs)
void SetComplementarity(int con_index, int var_index, ComplInfo info)

Sets a complementarity condition.

inline bool HasComplementarity() const

Returns true if the problem has complementarity conditions.

inline int GetComplementarityVariable(int i) const

Returns complementarity variable for algebraic constraint i.

Result > 0 means constraint i complements variable Result - 1.

inline ArrayRef<double> InitialValues() const

Variables’ initial values.

inline ArrayRef<int> InitialValuesSparsity() const

Variables’ initial values: sparsity pattern.

inline ArrayRef<double> InitialDualValues() const

Initial dual values.

inline ArrayRef<int> InitialDualValuesSparsity() const

Dual initial values: sparsity pattern.

int GetSuffixSize(suf::Kind kind)
template<typename T>
inline SuffixHandler<T> AddSuffix(fmt::StringRef name, int kind)
inline IntSuffixHandler AddIntSuffix(fmt::StringRef name, int kind, int = 0)

Adds an integer suffix.

name: Suffix name that may not be null-terminated.

inline DblSuffixHandler AddDblSuffix(fmt::StringRef name, suf::Kind kind, int)

Adds a double suffix.

name: Suffix name that may not be null-terminated.

template<class T>
inline void ReportSuffix(const SuffixDef<T> &sufdef, ArrayRef<T> values)
template<class T>
inline ArrayRef<T> ReadSuffix_OneTypeOnly(const SuffixDef<T> &sufdef)
inline ArrayRef<int> ReadIntSuffix(const SuffixDef<int> &sufdef)

Read integer suffix.

inline ArrayRef<double> ReadDblSuffix(const SuffixDef<double> &sufdef)

Read double suffix.

If absent but an integer suffix with the same name exists, take that

template<class T>
inline BasicMutSuffix<T> FindSuffix(const SuffixDef<T> &sufdef)
template<class T>
inline BasicMutSuffix<T> FindOrCreateSuffix(const SuffixDef<T> &sufdef)
void SetInfo(const NLProblemInfo &info)

Sets problem information and reserves memory for problem elements.

template<class Backend>
inline void PushModelTo(Backend &backend) const

Pushing the whole instance to a backend or converter.

A responsible backend should handle all essential items

inline BasicProblem &problem()

Returns the built problem.

This is used for compatibility with the problem builder API.

inline UnaryExpr MakeUnary(expr::Kind kind, NumericExpr arg)

Makes a unary expression.

inline BinaryExpr MakeBinary(expr::Kind kind, NumericExpr lhs, NumericExpr rhs)

Makes a binary expression.

inline IfExpr MakeIf(LogicalExpr condition, NumericExpr then_expr, NumericExpr else_expr)

Makes an if expression.

inline IteratedExprBuilder BeginIterated(expr::Kind kind, int num_args)

Begins building an iterated expression.

inline IteratedExpr EndIterated(IteratedExprBuilder builder)

Ends building an iterated expression.

inline int num_functions() const

Returns the number of functions.

inline Function function(int index) const

Returns the function at the specified index.

inline Function AddFunction(fmt::StringRef name, int num_args, func::Type type = func::NUMERIC)

Adds a function.

name: Function name that may not be null-terminated.

inline void AddFunctions(int num_funcs)

Adds a function that will be defined later.

inline Function DefineFunction(int index, fmt::StringRef name, int num_args, func::Type type)

Defines a function.

inline NumericConstant MakeNumericConstant(double value)

Makes a numeric constant.

inline Reference MakeVariable(int index)

Makes a variable reference.

inline Reference MakeCommonExpr(int index)

Makes a common expression reference.

inline PLTermBuilder BeginPLTerm(int num_breakpoints)

Begins building a piecewise-linear term.

inline PLTerm EndPLTerm(PLTermBuilder builder, Reference arg)

Ends building a piecewise-linear term.

arg: argument that should be either a variable or a common expression.

inline CallExprBuilder BeginCall(Function func, int num_args)

Begins building a call expression.

inline CallExpr EndCall(CallExprBuilder builder)

Ends building a call expression.

inline IteratedExprBuilder BeginSum(int num_args)
inline IteratedExpr EndSum(IteratedExprBuilder builder)
inline NumberOfExprBuilder BeginNumberOf(int num_args, NumericExpr arg0)

Begins building a numberof expression.

inline IteratedExpr EndNumberOf(NumberOfExprBuilder builder)

Ends building a numberof expression.

inline SymbolicNumberOfExprBuilder BeginSymbolicNumberOf(int num_args, Expr arg0)

Begins building a numberof expression.

inline SymbolicNumberOfExpr EndSymbolicNumberOf(SymbolicNumberOfExprBuilder builder)

Ends building a numberof expression.

inline CountExprBuilder BeginCount(int num_args)

Begins building a count expression.

inline CountExpr EndCount(CountExprBuilder builder)

Ends building a count expression.

inline LogicalConstant MakeLogicalConstant(bool value)

Makes a logical constant.

inline NotExpr MakeNot(LogicalExpr arg)

Makes a logical NOT expression.

inline BinaryLogicalExpr MakeBinaryLogical(expr::Kind kind, LogicalExpr lhs, LogicalExpr rhs)

Makes a binary logical expression.

inline RelationalExpr MakeRelational(expr::Kind kind, NumericExpr lhs, NumericExpr rhs)

Makes a relational expression.

inline LogicalCountExpr MakeLogicalCount(expr::Kind kind, NumericExpr lhs, CountExpr rhs)

Makes a logical count expression.

inline ImplicationExpr MakeImplication(LogicalExpr condition, LogicalExpr then_expr, LogicalExpr else_expr)

Makes an implication expression.

inline IteratedLogicalExprBuilder BeginIteratedLogical(expr::Kind kind, int num_args)

Begins building an iterated logical expression.

inline IteratedLogicalExpr EndIteratedLogical(IteratedLogicalExprBuilder builder)

Ends building an iterated logical expression.

inline PairwiseExprBuilder BeginPairwise(expr::Kind kind, int num_args)

Begins building a pairwise expression.

inline PairwiseExpr EndPairwise(PairwiseExprBuilder builder)

Ends building a pairwise expression.

inline StringLiteral MakeStringLiteral(fmt::StringRef value)

Makes a string literal.

inline SymbolicIfExpr MakeSymbolicIf(LogicalExpr condition, Expr then_expr, Expr else_expr)

Makes a symbolic if expression.

inline SuffixSet &suffixes(suf::Kind kind)

Returns a set of suffixes.

inline const SuffixSet &suffixes(suf::Kind kind) const

Protected Functions

template<class Backend>
inline void PushStandardMPItemsTo(Backend &backend) const
template<class Backend>
inline void InitProblemModificationPhase(Backend &backend) const
template<class Backend>
inline void PushVariablesTo(Backend &backend) const
template<class Backend>
inline void PushCommonExprTo(Backend &backend) const
template<class Backend>
inline void PushObjectivesTo(Backend &backend) const
template<class Backend>
inline void PushAlgebraicConstraintsTo(Backend &backend) const
template<class Backend>
inline void PushLogicalConstraintsTo(Backend &backend) const
template<class Backend>
inline void PushComplementarityConstraintsTo(Backend&) const
template<class Backend>
inline void FinishProblemModificationPhase(Backend &backend) const

Protected Static Functions

static const std::string &item_name(int i, std::vector<std::string> &names, int n, const char *stub, int n2 = std::numeric_limits<int>::max(), const char *stub2 = nullptr)

Return names[i].

Generate names[old_size…n-1] if needed, so that the whole vector is valid, even if only some variables/cons/objs were queried. From [n2], name ‘stub2’[i-n2] is given. If stub/stub2 ends with a ‘[’, ‘]’ is added after the index.

Private Functions

inline void SetNonlinearObjExpr(int obj_index, NumericExpr expr)

Set nonlinear objective expression.

inline void SetNonlinearConExpr(int con_index, NumericExpr expr)

Set nonlinear algebraic constraint expression.

inline void MarkAlgConDeleted(int con_index)

Mark algebraic constraint as deleted.

inline void MarkVarDeleted(int var_index)

Mark variable as deleted.

inline void SetInitialValue(int var_index, double value)

Sets the initial value for a variable.

inline void SetInitialDualValue(int con_index, double value)

Sets the initial value for a dual variable.

Private Members

std::vector<std::string> var_names_

Names.

std::vector<std::string> con_names_
std::vector<std::string> obj_names_
std::vector<Var> vars_
std::vector<bool> is_var_int_

Packed variable type information.

is_var_int_[i] specifies whether variable i is integer.

std::vector<bool> is_var_deleted_

Variable deleted flags.

Only markers

std::vector<bool> is_obj_max_

Packed objective type information.

is_obj_max_[i] specifies whether objective i is maximization.

std::vector<LinearExpr> linear_objs_

Linear parts of objective expessions.

std::vector<NumericExpr> nonlinear_objs_

Nonlinear parts of objective expressions.

The array can be empty if the problem is linear.

std::vector<AlgebraicConInfo> algebraic_cons_
std::vector<NumericExpr> nonlinear_cons_

Nonlinear parts of algebraic constraint expressions.

The array can be empty if the problem is linear.

std::vector<bool> is_alg_con_deleted_

Algebraic constraint deletion marker.

std::vector<unsigned> compl_vars_

Information about complementarity conditions.

compl_vars_[i] > 0 means constraint i complements variable compl_vars_[i] - 1. The array can be empty if there are no complementarity conditions.

std::vector<LogicalExpr> logical_cons_

Logical constraint expressions.

std::vector<LinearExpr> linear_exprs_

Linear parts of common expressions.

std::vector<NumericExpr> nonlinear_exprs_

Nonlinear parts of common expressions.

std::vector<double> initial_values_

Initial values for variables.

std::vector<int> iv_set_

Initial values for variables: sparsity.

std::vector<double> initial_dual_values_

Initial values for dual variables.

std::vector<int> idv_set_

Initial values for dual variables: sparsity.

template<typename ProblemType>
struct mp::BasicProblem::BasicProblemItem
#include <problem.h>

BasicProblemItem.

Subclassed by mp::BasicProblem< ProblemParams >::BasicAlgebraicCon< MutProblemItem >, mp::BasicProblem< ProblemParams >::BasicCommonExpr< MutProblemItem >, mp::BasicProblem< ProblemParams >::BasicLogicalCon< MutProblemItem >, mp::BasicProblem< ProblemParams >::BasicObjective< MutProblemItem >, mp::BasicProblem< ProblemParams >::BasicVariable< MutProblemItem >

Public Types

typedef ProblemType Problem

Public Functions

inline ProblemType *problem() const
inline int index() const
inline BasicProblemItem(ProblemType *p, int index)

Public Members

ProblemType *problem_
int index_
template<class A = int>
struct mp::BasicProblemParams
#include <problem.h>

Placeholder for whatever params of BasicProblem<>

Public Types

using Alloc = A
class mp::BasicSolutionHandler : public mp::SolutionHandler
#include <solver-base.h>

“Silent” solution handler

Public Functions

inline virtual void HandleFeasibleSolution(int, fmt::CStringRef, const double*, const double*, double)

Receives a feasible solution.

inline virtual void HandleFeasibleSolution(fmt::CStringRef, const double*, const double*, double)

Receives a feasible solution, no solve code.

Deprecated.

inline virtual void HandleSolution(int, fmt::CStringRef, const double*, const double*, double)

Receives the final solution or a notification that the problem is infeasible or unbounded.

inline virtual void OverrideSolutionFileName(const std::string&)

Override solution output file stub.

class mp::BasicSolver : private mp::ErrorHandler, private mp::OutputHandler, private mp::Interrupter, public mp::SolverOptionManager, public mp::SolveResultRegistry
#include <solver-base.h>

A minimal set of standard features for AMPL solver logic.

Can be used both for solver drivers, as well as for unit tests. Example:

class MySolver : public Solver {
 public:
  void GetTestOption(const char *name, int value, int info) {
    // Returns the option value; info is an arbitrary value passed as
    // the last argument to AddIntOption. It can be useful if the same
    // function handles multiple options.
    ...
  }
  void SetTestOption(const char *name, int value, int info) {
    // Set the option value; info is the same as in GetTestOption.
    ...
  }

  MySolver()  {
    AddIntOption("test", "This is a test option",
                 &MySolver::GetTestOption, &MySolver::SetTestOption, 42);
  }
}

Subclassed by mp::BasicBackend, mp::Solver

Public Types

enum [anonymous]

Possible values for the wantsol option (can be combined with bitwise OR).

Values:

enumerator WRITE_SOL_FILE
enumerator PRINT_SOLUTION
enumerator PRINT_DUAL_SOLUTION
enumerator SUPPRESS_SOLVER_MSG
enum [anonymous]

The default precision used in FormatObjValue if the objective_precision env variable is not specified or 0.

Values:

enumerator DEFAULT_PRECISION
enum [anonymous]

Solver flags.

Values:

enumerator MULTIPLE_SOL

Multiple solutions support.

Makes Solver register “countsolutions” and “solutionstub” options and write every solution passed to HandleFeastibleSolution to a file solutionstub & i & “.sol” where i is a solution number.

enumerator MULTIPLE_OBJ

Multiple objectives support.

Makes Solver register the “multiobj” option

using WarningsMap = std::map<std::string, std::pair<int, std::string>>

Map to count warnings by types.

Stores just 1 message for each type.

enum [anonymous]

Flags for ParseOptions.

Values:

enumerator NO_OPTION_ECHO

Don’t echo options during parsing.

enumerator FROM_COMMAND_LINE

When options are passed from command line (not via environment var) the quotes are automatically removed and the input string split in substrings (accessible via argv)

typedef std::unique_ptr<SolverOption> OptionPtr

Smart ptr to an option.

using set_option_iterator = option_iterator_base<OptionSet::iterator>

Alias for writeable option iterator.

using option_iterator = option_iterator_base<OptionSet::const_iterator>

Alias for const option iterator.

using SRRegMap = std::set<RegEntry>

Registry map.

Public Functions

inline std::string GetOptionFile(const SolverOption&) const

Name of the file with option settings, provided by tech:optionfile.

void UseOptionFile(const SolverOption&, fmt::StringRef value)

Read otpions from option file.

inline int GetWantSol(const SolverOption&) const

wantsol value

inline void SetWantSol(const SolverOption&, int value)

set wantsol

inline std::string GetSolutionStub(const SolverOption&) const

solution output filename stub

inline void SetSolutionStub(const SolverOption&, fmt::StringRef value)

Set sol stub.

inline int GetObjNo(const SolverOption&) const

Obj number.

inline void SetObjNo(const SolverOption &opt, int value)

Set obj number.

inline int GetTiming(const SolverOption&) const
inline void SetTiming(const SolverOption &opt, int value)
inline const char *name() const

Returns the solver name.

This is used to extract solver options from the env variable (solver_name)_options.

inline const char *long_name() const

Returns the long solver name.

This name is used in startup “banner”.

inline const char *exe_path() const

Returns the executable path.

inline void set_exe_path(const char *p)
inline const char *version() const

Returns the solver version.

inline long date() const

Returns the solver date in YYYYMMDD format.

inline int wantsol() const

Returns the value of the wantsol option which specifies what solution information to write in a stand-alone invocation (no -AMPL on the command line).

inline void set_wantsol(int value)
inline bool ampl_flag()
inline void set_ampl_flag(bool value = true)
inline bool verbose_mode() const

True if verbose mode.

Should be set by the implementation, otherwise it’s true

inline void set_verbose_mode(bool f)

Set verbosity, by the impl.

inline bool debug_mode() const

True if need to debug.

Outputs test infos etc

inline int objno_used() const

Returns the index of the objective to optimize starting from 1, 0 to not use objective.

inline int objno_specified() const

objno_specified(): actually even if not specified, it returns the objno to use (0 - feasibility, otherwise obj index).

Both multiobj() and objno_specified() are used in NLReader to select the objective(s), solvers should not use these accessors.

inline bool is_objno_specified() const

Whether user specified the option objno.

inline void notify_obj_added()

Notify Solver if an objective is added.

inline void notify_start_opts()

Notify Solver we start reading options.

inline void notify_end_opts()

Notify we are done.

inline bool multiobj() const

Returns true if multiobjective optimization is enabled.

Both multiobj and objno are used in NLReader to select the objective(s), solvers should not use these options.

inline int timing() const

>0 if the timing is enabled

inline ErrorHandler *error_handler()

Return error handler.

inline void set_error_handler(ErrorHandler *eh)

Set the error handler.

inline OutputHandler *output_handler()

Return output handler.

inline OutputHandler &get_output_handler()

Return output handler.

inline void set_output_handler(OutputHandler *oh)

Sets the output handler.

inline const Interrupter *interrupter() const

Interrupter, const.

inline Interrupter *interrupter()

Interrupter.

inline void set_interrupter(Interrupter *interrupter)

Set interrupter.

inline const char *solution_stub() const

Sol stub as char*.

inline bool need_multiple_solutions() const

Need mutiple solutions.

inline virtual void HandleOutput(fmt::CStringRef output) override

Override methods from base service classes.

inline virtual void HandleError(fmt::CStringRef message) override

Handle error.

inline virtual bool Stop() const override

The default implementation of Interrupter does nothing.

inline virtual void SetHandler(InterruptHandler, void*) override

Set interrupt handler.

inline virtual void HandleUnknownOption(const char *name)

Handle unknown option.

inline void ReportError(fmt::CStringRef format, const fmt::ArgList &args)

Reports an error by throwing it.

Usage: ReportError(“File not found: {}”) << filename;

inline void Print(fmt::CStringRef format, const fmt::ArgList &args)

Variadic overload of ReportError()

Formats a string and prints it to stdout or, if an output handler is registered, sends it to the output handler.

const char *GetSolCheckWarningKey(bool f_recomp) const

Variadic overload of Print()

Get solution check warnings key name.

Parameters

f_recomp – whether with recomputed auxiliaries.

void AddWarning(std::string key, std::string msg, bool replace = false)

Add a warning.

Parameters
  • key – warning category

  • msg – detailed message

const std::pair<int, std::string> &GetWarning(const std::string &key)

Get a warning type.

void ClearWarning(const std::string &key)

Clear a warning type.

std::string GetWarnings() const

Get warnings as string.

void PrintWarnings()

Print warnings.

bool ShowVersion()

Prints version information.

DoubleFormatter FormatObjValue(double value)

Returns a formatter that writes value using objective precision.

Usage: Print(“objective {}”, FormatObjValue(obj_value));

virtual bool ParseOptions(char **argv, unsigned flags = 0, const ASLProblem *p = 0)

Parses solver options from the (solver)_options env variable and/or strings in argv.

For example, solver_options=’timelim=300’ solver /tmp/diet.nl -AMPL “basis=0”.

Returns

true if there were no errors and false otherwise. It accepts a pointer to the problem because some options may depend on problem features.

explicit BasicSolver()

Deafult / testing constructor.

inline virtual ~BasicSolver()

Virtual destructor.

void ParseOptionString(const char *s, unsigned flags)

Parses a solver option string.

inline const WarningsMap &GetWarningsMap() const

Get warnings map.

inline WarningsMap &GetWarningsMap()
inline void SetConstraintListHeader(std::string clh)

Set constraint list header (printed at the start of -c)

inline void AddConstraintDescr(std::string cn, std::string cdescr)

Add constraint type description.

bool ShowConstraintDescriptions()

Show constraint descriptions.

inline virtual void RecordOutputTime()
inline virtual void RecordSetupTime()

Record setup time.

inline void SetReadTime(double read_time)
inline void SetConversionTime(double conv_time)
inline virtual void RecordSolveTime()

Record solve time.

inline int num_options() const

Returns the number of options.

inline SolverOption *GetOption(const char *name) const

Returns the option with specified name.

inline void set_option_header(const char *header)

Sets a text to be displayed before option descriptions.

inline void add_to_option_header(const char *header_more)

Add more text to be displayed before option descriptions.

void AddOption(OptionPtr opt)

Add an option.

template<class Value>
inline void AddOption(const char *name, const char *description, Value &value, Value lb, Value ub)

Same: stored option referencing a variable; min, max values.

Note

description “HIDDEN” means the option is not printed

SolverOption *FindOption(const char *name, bool wildcardvalues = false) const

Finds an option and returns a pointer to it if found or null otherwise.

If wildcardvalues==true, wildcarded options should have values (i.e., parsing real input)

inline const char *option_header() const

Returns the option header.

inline fmt::LongLong GetIntOption(const char *name) const

Returns the value of an integer option.

Throws OptionError if there is no such option or it has a different type.

inline void SetIntOption(const char *name, fmt::LongLong value)
inline double GetDblOption(const char *name) const
inline void SetDblOption(const char *name, double value)
inline std::string GetStrOption(const char *name) const
inline void SetStrOption(const char *name, fmt::StringRef value)
template<class Value>
inline void AddStoredOption(const char *name, const char *description, Value &value, ValueArrayRef values = ValueArrayRef())

Simple stored option referencing a variable.

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddStoredOption(const char *name, const char *description, Value &value, Value, Value)

Simple stored option referencing a variable; min, max values (they are unused but to deduce type; we are too lazy to maintain correct min/max between solver versions.)

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddListOption(const char *name, const char *description, Value &value, ValueArrayRef values = ValueArrayRef())

Add list option referencing a container.

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddListOption(const char *name, const char *description, Value &value, typename Value::value_type, typename Value::value_type)

Add list option referencing a container; min, max values (they are unused but to deduce type; we aree too lazy to maintain correct min/max between solver versions.)

Note

description “HIDDEN” means the option is not printed

inline void ReplaceOptionDescription(const char *name, const char *desc)

Replace option descr.

inline void AddToOptionDescription(const char *name, const char *desc_add)

Add to option descr.

void AddOptionSynonyms_Inline_Front(const char *names_list, const char *realName)

Add “inline” option synonyms.

The _Front version puts them in the front of the synonyms list and the 1st of them is used in the -a output for sorting.

void AddOptionSynonyms_Inline_Back(const char *names_list, const char *realName)

Add “inline” option synonyms.

The _Back version.

void AddOptionSynonyms_OutOfLine(const char *name, const char *realName)

Add an “out-of-line” synonym.

Creates extra entry under -=

template<typename Handler, typename Int>
inline void AddIntOption(const char *name, const char *description, Int (Handler::* get)(const SolverOption&) const, void (Handler::* set)(const SolverOption&, Int))

Adds an integer option.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddIntOption(const char *name, const char *description, int (Handler::* get)(const SolverOption&, const Info&) const, void (Handler::* set)(const SolverOption&, int, const Info&), const Info &info)

Adds an integer option with additional information.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddIntOption(const char *name_list, const char *description, int (Handler::* get)(const SolverOption&, Info) const, void (Handler::* set)(const SolverOption&, int, Info), Info info)

The same as above but with Info argument passed by value.

Note

description “HIDDEN” means the option is not printed

template<typename Handler>
inline void AddDblOption(const char *name, const char *description, double (Handler::* get)(const SolverOption&) const, void (Handler::* set)(const SolverOption&, double))

Adds a double option.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddDblOption(const char *name, const char *description, double (Handler::* get)(const SolverOption&, const Info&) const, void (Handler::* set)(const SolverOption&, double, const Info&), const Info &info)

Adds a double option with additional information.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddDblOption(const char *name, const char *description, double (Handler::* get)(const SolverOption&, Info) const, void (Handler::* set)(const SolverOption&, double, Info), Info info)

The same as above but with Info argument passed by value.

Note

description “HIDDEN” means the option is not printed

template<typename Handler>
inline void AddStrOption(const char *name, const char *description, std::string (Handler::* get)(const SolverOption&) const, void (Handler::* set)(const SolverOption&, fmt::StringRef), ValueArrayRef values = ValueArrayRef())

Adds a string option.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddStrOption(const char *name, const char *description, std::string (Handler::* get)(const SolverOption&, const Info&) const, void (Handler::* set)(const SolverOption&, fmt::StringRef, const Info&), const Info &info, ValueArrayRef values = ValueArrayRef())

Adds a string option with additional information.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddStrOption(const char *name, const char *description, std::string (Handler::* get)(const SolverOption&, Info) const, void (Handler::* set)(const SolverOption&, fmt::StringRef, Info), Info info, ValueArrayRef values = ValueArrayRef())

The same as above but with Info argument passed by value.

Note

description “HIDDEN” means the option is not printed

inline option_iterator option_begin() const

Get the start const-iterator.

inline option_iterator option_end() const

Get the end const-iterator.

inline set_option_iterator set_option_begin() const

Get the start writeable iterator.

inline set_option_iterator set_option_end() const

Get the end writeable iterator.

void AddSolveResults(const SRRegMap &sm, bool ifCanReplace = false)

Add a map with result descriptions.

inline const SRRegMap &GetSolveResultRegistry() const

Get the registry.

Public Static Functions

static std::string ToString(const WarningsMap::value_type &wrn)

Stringify a WarningsMap entry.

Protected Functions

BasicSolver(fmt::CStringRef name, fmt::CStringRef long_name, long date, int flags)

Constructs a BasicSolver object.

Parameters
  • date – The solver date in YYYYMMDD format.

  • flags – Bitwise OR of zero or more of the following values MULTIPLE_SOL MULTIPLE_OBJ

void InitMetaInfoAndOptions(fmt::CStringRef name, fmt::CStringRef long_name, long date, int flags)

InitMetaInfoAndOptions.

Derived classes which want to provide the info after construction can use the default constructor and call this.

Parameters
  • date – The solver date in YYYYMMDD format.

  • flags – Bitwise OR of zero or more of the following values MULTIPLE_SOL MULTIPLE_OBJ

inline void set_long_name(fmt::StringRef name)
inline void add_to_long_name(fmt::StringRef name)
inline void set_version(fmt::StringRef version)
inline void add_to_version(fmt::StringRef version)
inline void set_license_info(fmt::StringRef license_info)
inline virtual std::string set_external_libs()
inline void set_read_flags(unsigned flags)

Sets the flags for Problem::Read.

inline Stats &stats()

Private Types

enum [anonymous]

Values:

enumerator SHOW_VERSION
enumerator AMPL_FLAG

Private Members

std::string name_
std::string long_name_
std::string exe_path_
std::string version_
std::string license_info_
long date_ = {0}
int wantsol_ = {0}
int obj_precision_ = {-1}
int objno_ = {-1}

Index of the objective to optimize starting from 1, 0 to ignore objective, or -1 to use the first objective if there is one.

bool obj_added_ = {false}

Flag whether an objective has been added.

bool opts_read_ = {false}

Flag whether options have been read.

int bool_options_ = {0}
int option_flag_save_ = 0
std::string option_file_save_
std::string solution_stub_
bool count_solutions_ = {false}
unsigned read_flags_ = {0}
bool verbose_ = {true}
bool debug_ = {false}
int timing_ = {0}
Stats stats_
bool multiobj_ = {false}
bool has_errors_ = {false}
OutputHandler *output_handler_ = {this}
ErrorHandler *error_handler_ = {this}
Interrupter *interrupter_ = {this}
WarningsMap warnings_

Warnings.

std::string constr_descr_header_

Constraint descriptions, printable by -c.

std::map<std::string, std::string> constr_descr_

Friends

friend class ASLProblem
template<class Impl, int NNodes, int NIndexes, int NSources>
class mp::pre::BasicStaticIndivEntryLink : public mp::pre::BasicIndivEntryLink<Impl, std::array<int, NIndexes>>
#include <valcvt-link.h>

A static indiv entry link has a fixed number (NNodes) of ValueNodes and indexes (NIndexes) into them.

Generally NNodes==. NSources < NIndexes is the number of source nodes/indexes (coming first in each LinkEntry, this is used for export).

Public Types

using Base = BasicIndivEntryLink<Impl, std::array<int, NIndexes>>

Base class.

using NodeList = std::array<ValueNode*, NNodes>

Typedef NodeList: list of ValueNode pointers.

A ValueNode is a node of the (structural) transformation graph and can store arrays of values for a list of model items

using LinkEntry = std::array<int, NIndexes>

Typedef: LinkEntry is just an array if node indexes.

using ItemRangeList = std::vector<NodeRange>

Typedef item container.

Public Functions

inline BasicStaticIndivEntryLink(ValuePresolver &pre, const NodeList &ndl)

Constructor.

inline void FillEntryItems(typename Base::EntryItems &ei, const LinkEntry &en) const

Get source/target nodes for a given link entry.

This is used for graph export

inline void AddEntry(std::array<int, NIndexes> be)

Add entry.

inline virtual void ExportEntryItems(EntryItems &ei, int i) const override

Get source/target nodes for a given link entry.

This is used for graph export

virtual const char *GetTypeName() const = 0

Type name.

Protected Functions

inline const ValueNode &GetNode(size_t i) const

Access whole node at specific index, const.

inline ValueNode &GetNode(size_t i)

Access whole node at specific index.

inline int GetInt(const LinkEntry &be, size_t pos) const

Access int value at the node pos at the index stored in be[pos].

Parameters
  • be – a LinkEntry

  • pos – node number from 0..NNodes-1

inline void SetInt(const LinkEntry &be, size_t pos, int i)

SetInt.

inline double GetDbl(const LinkEntry &be, size_t pos) const

Access double value at the node pos at the index stored in be[pos].

Parameters
  • be – a LinkEntry

  • pos – node number from 0..NNodes-1

inline void SetDbl(const LinkEntry &be, size_t pos, double i)

SetDbl.

inline const VCString &GetStr(const LinkEntry &be, size_t pos) const

Access string value at the node pos at the index stored in be[pos].

Parameters
  • be – a LinkEntry

  • pos – node number from 0..NNodes-1

inline void SetStr(const LinkEntry &be, size_t pos, VCString v)

SetStr.

inline void RegisterLinkIndex(int i)

Add a range of link entries to the Presolver’s list.

Every derived link should call either of the next two methods whenever adding a link entry. Version 1: add single link

inline void RegisterLinkIndexRange(LinkIndexRange)

Version 2: add a range of links.

Implement link range registration in global Presolver.

Private Members

NodeList ndl_
template<typename T>
class mp::BasicSuffix : private mp::internal::SuffixBase
#include <suffix.h>

BasicSuffix.

Subclassed by mp::BasicMutSuffix< T >

Public Types

typedef T Type

Public Functions

inline BasicSuffix()
inline ArrayRef<T> get_values() const
inline T value(int index) const
template<typename Visitor>
inline void VisitValues(Visitor &v) const

Private Functions

inline explicit BasicSuffix(const Impl *impl)
inline explicit BasicSuffix(Suffix other)

Friends

friend class internal::SuffixBase
friend class BasicMutSuffix< T >
friend class BasicSuffixSet
friend BasicSuffix Cast(Suffix s)

“inline” is used here instead of the definition to suppress bogus C4396 warnings in MSVC.

Casts a suffix to type SuffixType which must be a valid suffix type.

Returns a null suffix if s is not convertible to SuffixType.

template<typename Alloc>
class mp::BasicSuffixSet : private Alloc
#include <suffix.h>

A set of suffixes.

Public Functions

inline explicit BasicSuffixSet(Alloc alloc = Alloc())
virtual ~BasicSuffixSet()
template<typename T>
inline BasicMutSuffix<T> Add(fmt::StringRef name, int kind, int num_values, const SuffixTable &table = {})

Adds a suffix throwing Error if another suffix with the same name is in the set.

inline Suffix Find(fmt::StringRef name) const

Finds a suffix with the specified name.

inline MutSuffix Find(fmt::StringRef name)
template<typename T>
inline BasicSuffix<T> Find(fmt::StringRef name) const

Finds a suffix with the specified name and value type.

inline iterator begin() const
inline iterator end() const

Private Types

typedef Suffix::Impl SuffixImpl
typedef std::set<SuffixImpl, SuffixNameLess> Set

Private Functions

FMT_DISALLOW_COPY_AND_ASSIGN(BasicSuffixSet)
SuffixImpl *DoAdd(fmt::StringRef name, int kind, int num_values, const SuffixTable &table)
template<typename T>
inline T *Allocate(std::size_t size)
template<typename T>
inline void Deallocate(T *values, std::size_t size)

Private Members

Set set_
template<typename Arg, expr::Kind FIRST, expr::Kind LAST = FIRST>
class mp::BasicUnaryExpr : public mp::BasicExpr<FIRST, FIRST>
#include <expr.h>

A unary expression.

Base: base expression class.

Public Types

enum [anonymous]

Values:

Public Functions

inline Arg arg() const

Returns the argument of this expression.

Protected Types

typedef ExprBase::Impl Impl

Reuse ExprBase::Impl.

Private Types

typedef BasicExpr<FIRST, LAST> Base

Private Functions

MP_EXPR(Base)
class mp::pre::BasicValuePresolver : public mp::EnvKeeper
#include <valcvt-base.h>

ValuePresolver interface.

Addresses value pre- / postsolve (solutions, basis, etc)

Subclassed by mp::pre::ValuePresolverImpl

Public Functions

virtual ~BasicValuePresolver() = default

Virtual destructor.

inline BasicValuePresolver(Env &env)

Constructor.

virtual LIST_PRESOLVE_METHODS void Register (ValueNode *)=0

Register a ValueNode*.

virtual void Deregister(ValueNode*) = 0

Deregister a ValueNode*.

inline const Env &GetEnv() const

GetEnv() const.

inline Env &GetEnv()

GetEnv()

class mp::BasicValuePresolverKeeper
#include <valcvt-base.h>

Some backends need to keep reference to the value presolver for pre- / postsolving of suffix values etc.

Subclassed by mp::BackendWithValuePresolver

Protected Functions

inline void SetValuePresolver(pre::BasicValuePresolver *pPre)
inline const pre::BasicValuePresolver &GetValuePresolver() const
inline pre::BasicValuePresolver &GetValuePresolver()

Private Members

pre::BasicValuePresolver *pPresolver_ = nullptr
template<typename Item>
class mp::BasicProblem::BasicVariable : private Item
#include <problem.h>

An optimization variable.

Public Functions

inline bool is_marked_deleted() const

Whether the variable is marked as deleted.

inline double lb() const

Returns the lower bound on the variable.

inline double ub() const

Returns the upper bound on the variable.

inline var::Type type() const

Returns the type of the variable.

inline double value() const

Returns the value of the variable.

template<typename OtherItem>
inline bool operator==(BasicVariable<OtherItem> other) const
template<typename OtherItem>
inline bool operator!=(BasicVariable<OtherItem> other) const

Private Functions

inline BasicVariable(typename Item::Problem *p, int index)

Private Static Functions

static inline int num_items(const BasicProblem &p)

Friends

friend class BasicProblem
struct BCinfo

Public Members

int dp0
int dp1
int dplen
int dsign
int e0
int inexact
int nd
int nd0
int rounding
int scale
int uflchk
struct BF96

Public Members

unsigned int b0
unsigned int b1
unsigned int b2
int e
struct Bigint

Public Members

struct Bigint *next
int k
int maxwds
int sign
int wds
ULong x[1]
template<typename ExprReader = NumericExprReader>
struct mp::internal::NLReader::BinaryArgReader

A helper struct used to make sure that the arguments to a binary expression are read in the correct order and avoid errors of the form: MakeBinary(opcode, ReadNumericExpr(), ReadNumericExpr()) The above code is incorrect as the order of evaluation of arguments is unspecified.

Public Functions

inline BinaryArgReader(NLReader &r)

Public Members

ExprReader::Expr lhs
ExprReader::Expr rhs
class mp::BinaryFormatter
#include <nl-writer2-misc.h>

Binary formatter.

Public Functions

inline BinaryFormatter(NLUtils &u, bool, int)

Construct.

inline NLHeader::Format Mode() const

Mode query.

int apr(File&, const char*, ...)

Binary printf.

void nput(File&, double)

Binary nput.

inline NLUtils &Utils()

Retrieve utils.

Private Members

NLUtils &utils_
template<typename InputConverter = IdentityConverter>
class mp::internal::BinaryReader : private mp::internal::IdentityConverter, public mp::internal::BinaryReaderBase
#include <nl-reader.h>

Binary reader.

Public Functions

inline explicit BinaryReader(const ReaderBase &base)
template<typename Int>
inline Int ReadInt()
inline int ReadUInt()
inline double ReadDouble()
inline fmt::StringRef ReadString()
inline fmt::StringRef ReadName()

Reads a function or suffix name.

void ReportError(fmt::CStringRef format_str, const fmt::ArgList &args)
inline void ReadTillEndOfLine()
inline char ReadChar()
inline const char *ptr() const
inline void set_ptr(const char *ptr)
inline bool IsEOF(const char *ptr) const
inline bool IsEOF() const

Protected Functions

inline const char *Read(int length)

Reads length chars.

Protected Attributes

const char *ptr_
const char *start_
const char *end_
const char *token_
std::string name_
class mp::internal::BinaryReaderBase : public mp::internal::ReaderBase
#include <nl-reader.h>

Subclassed by mp::internal::BinaryReader< InputConverter >

Public Functions

void ReportError(fmt::CStringRef format_str, const fmt::ArgList &args)
inline void ReadTillEndOfLine()
inline char ReadChar()
inline const char *ptr() const
inline void set_ptr(const char *ptr)
inline bool IsEOF(const char *ptr) const
inline bool IsEOF() const

Protected Functions

inline explicit BinaryReaderBase(const ReaderBase &base)
inline const char *Read(int length)

Reads length chars.

Protected Attributes

const char *ptr_
const char *start_
const char *end_
const char *token_
std::string name_
class mp::BinaryReadError : public mp::Error
#include <nl-reader.h>

A read error with information about offset in a binary input.

Public Functions

inline BinaryReadError(const std::string &filename, std::size_t offset, fmt::CStringRef message)

Constructs the exception object.

inline ~BinaryReadError()

Destructs the exception object.

inline const std::string &filename() const

Returns the name of the file where error occurred.

inline std::size_t offset() const

Returns the offset in chars to the error location.

inline int exit_code() const

The exit code.

Protected Functions

inline void SetMessage(const std::string &message)
inline void init(fmt::CStringRef format_str, fmt::ArgList args)

Private Members

std::string filename_
std::size_t offset_
template<class Impl>
class mp::BoundComputations
#include <expr_bounds.h>

A mix-in base class providing expression bounds computation.

Subclassed by mp::FlatConverter< Impl, ModelAPI, FlatModel< > >, mp::FlatConverter< Impl, ModelAPI, FlatModel >

Public Functions

inline PreprocessInfoStd ComputeBoundsAndType(const LinTerms &lt)

ComputeBoundsAndType(LinTerms)

template<class Body>
inline PreprocessInfoStd ComputeBoundsAndType(const AlgebraicExpression<Body> &ae)

ComputeBoundsAndType(AlgebraicExpr<>)

inline PreprocessInfoStd ComputeBoundsAndType(const QuadTerms &qt)

ComputeBoundsAndType(QuadTerms)

inline PreprocessInfoStd ComputeBoundsAndType(const QuadAndLinTerms &qlt)

ComputeBoundsAndType(QuadAndLinearTerms)

template<class Var>
inline std::pair<double, double> ProductBounds(Var x, Var y) const

Product bounds.

Public Static Functions

static inline PreprocessInfoStd AddBoundsAndType(const PreprocessInfoStd &bnt1, const PreprocessInfoStd &bnt2)

Add / merge bounds and type.

struct mp::SOSExtraInfo::Bounds
#include <constr_general.h>

Bounds on the sum of variables.

Public Functions

inline Bounds(double lb = -1e100, double ub = 1e100)
inline bool operator==(const Bounds &b) const

Public Members

double lb_
double ub_
template<typename Handler>
class mp::OptionList::Builder
#include <option.h>

Public Functions

inline Builder(OptionList &options, Handler &h)
template<bool (Handler::* on_option)()>
inline void Add(char name, const char *description)

Adds an option.

on_option: method called when option has been parsed; returns true to continue parsing, false to stop

template<bool (Handler::* on_option)(const char*)>
inline void AddWithParam(char name, const char *description)

Adds an option.

on_option: method called when option has been parsed; returns true to continue parsing, false to stop

Private Members

OptionList &options_
Handler &handler_
class mp::CallExpr : public mp::BasicExpr<expr::CALL>
#include <expr.h>

namespace internal

A function call expression. Example: f(x), where f is a function and x is a variable.

Public Types

typedef Expr Arg

Argument type.

typedef internal::ExprIterator<Expr> iterator

An argument iterator.

enum [anonymous]

Values:

Public Functions

inline Function function() const

Query the function type.

inline int num_args() const

Returns the number of arguments.

inline Expr arg(int index)

Returns an argument with the specified index.

inline iterator begin() const

begin()

inline iterator end() const

end()

Protected Types

typedef ExprBase::Impl Impl

Reuse ExprBase::Impl.

typedef BasicExpr Base

Base = BasicExpr.

Private Functions

MP_EXPR(Base)
struct CAPIExample
#include <nlsol_ex_c_model.h>

C API example data.

Public Members

const int n_var
const int n_var_int
const int n_con
const int n_obj
const double *var_lb

Variables.

Put y first because continuous variables come before integer ones.

const double *var_ub
const char *const *var_name
const double *con_lb

Algebraic constraint bounds.

If we had nonlinear constraints, constraints would be reordered: nonlinear first. If we had logical constraints, they’d go last (represented by expressions only.)

const double *con_ub
const char *const *con_name
const int *row_nnz

Linear constraints.

If we had non-linear constraints, here would be their linear parts. They are presented sparse, but should include entries which can become nonzero in the Jacobian. Sparse vector per constraint

const SparseEntry *const *con_linpart
const int *col_sizes

Sizes of all Jacobian columns except the last.

const int n_con_nz
const int obj_sense

Obj sense: min/max.

const SparseEntry *obj_linpart

Objective: linear part.

Similar to the Jacobian, need all elements which can become nonzero.

int n_obj_nz
const char *obj_name
const double *ini_x

Primal initial guess (dense vector).

const double *ini_y

Primal dual guess (dense vector).

int n_suf

Suffixes.

const Suffix *suf
int binary_nl

Some technical stuff.

double *sol_dual_
double *sol_primal_
int objno_
int solve_code_
struct CCallbacks_T
#include <ampls-ccallbacks.h>

Set of callbacks provided to a driver for licensing issues.

Public Members

void *(*init)()

If provided, replacement function to create solver environment for a given solver.

Checker_AMPLS_ModeltTraits check

Check if model sizes are allowed; throw if not.

Parameters: n_vars, n_alg_con, n_log_con

const char *(*additionalText)()

Return additional text to be displayed on ‘-v’ output.

void (*diagnostics)()

Function called after failures to provide additional diagnostics.

template<typename T, T>
struct mp::internal::Check
#include <solver-base.h>

Public Functions

inline Check(int)
class mp::ColProblem : public mp::BasicProblem<>
#include <problem-builder.h>

An optimization problem with a column-wise constraint matrix.

Public Types

typedef mp::Function Function
typedef mp::Expr Expr
typedef mp::NumericExpr NumericExpr
typedef mp::LogicalExpr LogicalExpr
typedef mp::CountExpr CountExpr
typedef mp::Reference Reference
typedef internal::ExprTypes ExprTypes
typedef BasicProblemItem<const BasicProblem> ProblemItem
typedef BasicProblemItem<BasicProblem> MutProblemItem
typedef BasicVariable<ProblemItem> Variable

An optimization variable.

typedef Range<Variable> VarRange

A range of variables.

typedef LinearExprBuilder LinearObjBuilder
typedef BasicObjective<ProblemItem> Objective

An objective.

typedef Range<Objective> ObjRange

A range of objectives.

typedef LinearExprBuilder LinearConBuilder
typedef BasicAlgebraicCon<ProblemItem> AlgebraicCon

An algebraic constraint.

typedef Range<AlgebraicCon> AlgebraicConRange

A range of algebraic constraints.

typedef BasicLogicalCon<ProblemItem> LogicalCon
typedef Range<LogicalCon> LogicalConRange

A range of logical constraints.

typedef BasicCommonExpr<ProblemItem> CommonExpr
typedef SuffixHandler<int> IntSuffixHandler
typedef SuffixHandler<double> DblSuffixHandler
typedef BasicProblem Builder
typedef BasicIteratedExprBuilder<CallExpr> CallExprBuilder
typedef BasicIteratedExprBuilder<IteratedExpr> IteratedExprBuilder
typedef IteratedExprBuilder NumberOfExprBuilder
typedef BasicIteratedExprBuilder<SymbolicNumberOfExpr> SymbolicNumberOfExprBuilder
typedef BasicIteratedExprBuilder<CountExpr> CountExprBuilder
typedef BasicIteratedExprBuilder<IteratedLogicalExpr> IteratedLogicalExprBuilder
typedef BasicIteratedExprBuilder<PairwiseExpr> PairwiseExprBuilder
typedef MutSuffix Suffix
typedef MutIntSuffix IntSuffix
typedef mp::SuffixSet SuffixSet

Public Functions

inline ColProblem()
template<class Solver>
inline explicit ColProblem(const Solver&)
inline int col_start(int col_index) const
inline int row_index(int elt_index) const
inline double value(int elt_index) const
inline const int *col_starts() const
inline const int *row_indices() const
inline const double *values() const
inline ColProblem &problem()

Returns the built problem.

This is used for compatibility with the problem builder API.

inline const std::vector<bool> &IsVarInt() const

Deprecated.

inline int num_vars() const

Returns the number of variables.

inline const std::string &var_name(int i)

Normal variable name.

inline const std::string &dvar_name(int i)

Defined variable name.

inline const std::string &con_name(int i)

Constraint name.

inline const std::string &obj_name(int i)

Objective name.

inline const std::vector<std::string> &var_names()

Returns the variable names (if present).

After normal variables follow defined variables.

inline const std::vector<std::string> &con_names()

Returns the constraint names (if present).

inline const std::vector<std::string> &obj_names()

Returns the objective names (if present).

inline VarNamer GetVarNamer()

Obtain variable namer.

inline int num_objs() const

Returns the number of objectives.

inline int num_cons() const

Returns total number of constraints from the NL file.

inline int num_algebraic_cons() const

Returns the number of algebraic constraints.

inline int num_logical_cons() const

Returns the number of logical constraints.

inline bool has_nonlinear_cons() const

Return true if the problem has nonlinear constraints.

inline int num_common_exprs() const

Returns the number of common expressions.

inline VarRange vars() const

Returns a range representing all variables in this optimization problem. It can be used for iterating over variables:

for (auto var: problem.vars()) {
  ...
}

inline Variable var(int index) const

Returns the variable at the specified index.

inline MutVariable var(int index)
inline Variable AddVar(double lb, double ub, var::Type type = var::CONTINUOUS)

Adds a variable.

inline void AddVars(int num_vars, var::Type type)
inline void AddVars(int num_vars, const double *lb, const double *ub, const var::Type *type)
inline std::vector<int> AddVars(std::size_t nvars, double lb = -INFINITY, double ub = INFINITY, var::Type type = var::CONTINUOUS)

Add vector of variables. Type: var::CONTINUOUS by default.

inline void SetVarNames(std::vector<std::string> names)

Set name vectors.

inline void SetConNames(std::vector<std::string> names)
inline void SetObjNames(std::vector<std::string> names)
inline ObjRange objs() const

Returns a range representing all objectives in this optimization problem. It can be used for iterating over objectives:

for (auto obj: problem.objs()) {
  ...
}

inline Objective obj(int index) const

Returns the objective at the specified index.

inline MutObjective obj(int index)

Returns the mutable objective at the specified index.

LinearObjBuilder AddObj(obj::Type type, NumericExpr expr, int num_linear_terms = 0)

Adds an objective.

Returns a builder for the linear part of an objective expression.

inline LinearObjBuilder AddObj(obj::Type type, int num_linear_terms = 0)
inline void AddObjs(int num_objs)
inline AlgebraicConRange algebraic_cons() const

Returns a range representing all algebraic constraints in this optimization problem. It can be used for iterating over algebraic constraints:

for (auto con: problem.algebraic_cons()) {
  ...
}

inline AlgebraicCon algebraic_con(int index) const

Returns the algebraic constraint at the specified index.

inline MutAlgebraicCon algebraic_con(int index)

Returns the mutable algebraic constraint at the specified index.

inline MutAlgebraicCon AddCon(double lb, double ub)

Adds an algebraic constraint.

Returns a builder for the linear part of a constraint expression.

inline void AddCon(LogicalExpr expr)

Adds a logical constraint.

inline void AddAlgebraicCons(int num_cons)
inline LogicalConRange logical_cons() const

Returns a range representing all logical constraints in this optimization problem. It can be used for iterating over logical constraints:

for (auto con: problem.logical_cons()) {
  ...
}

inline LogicalCon logical_con(int index) const

Returns the logical constraint at the specified index.

inline MutLogicalCon logical_con(int index)

Returns the mutable logical constraint at the specified index.

inline void AddLogicalCons(int num_cons)
inline CommonExpr common_expr(int index) const

Returns the common expression at the specified index.

inline MutCommonExpr common_expr(int index)
inline MutCommonExpr AddCommonExpr(NumericExpr expr)

Adds a common expression (defined variable).

inline void AddCommonExprs(int num_exprs)
void SetComplementarity(int con_index, int var_index, ComplInfo info)

Sets a complementarity condition.

inline bool HasComplementarity() const

Returns true if the problem has complementarity conditions.

inline int GetComplementarityVariable(int i) const

Returns complementarity variable for algebraic constraint i.

Result > 0 means constraint i complements variable Result - 1.

inline ArrayRef<double> InitialValues() const

Variables’ initial values.

inline ArrayRef<int> InitialValuesSparsity() const

Variables’ initial values: sparsity pattern.

inline ArrayRef<double> InitialDualValues() const

Initial dual values.

inline ArrayRef<int> InitialDualValuesSparsity() const

Dual initial values: sparsity pattern.

int GetSuffixSize(suf::Kind kind)
template<typename T>
inline SuffixHandler<T> AddSuffix(fmt::StringRef name, int kind)
inline IntSuffixHandler AddIntSuffix(fmt::StringRef name, int kind, int = 0)

Adds an integer suffix.

name: Suffix name that may not be null-terminated.

inline DblSuffixHandler AddDblSuffix(fmt::StringRef name, suf::Kind kind, int)

Adds a double suffix.

name: Suffix name that may not be null-terminated.

template<class T>
inline void ReportSuffix(const SuffixDef<T> &sufdef, ArrayRef<T> values)
template<class T>
inline ArrayRef<T> ReadSuffix_OneTypeOnly(const SuffixDef<T> &sufdef)
inline ArrayRef<int> ReadIntSuffix(const SuffixDef<int> &sufdef)

Read integer suffix.

inline ArrayRef<double> ReadDblSuffix(const SuffixDef<double> &sufdef)

Read double suffix.

If absent but an integer suffix with the same name exists, take that

template<class T>
inline BasicMutSuffix<T> FindSuffix(const SuffixDef<T> &sufdef)
template<class T>
inline BasicMutSuffix<T> FindOrCreateSuffix(const SuffixDef<T> &sufdef)
void SetInfo(const NLProblemInfo &info)

Sets problem information and reserves memory for problem elements.

template<class Backend>
inline void PushModelTo(Backend &backend) const

Pushing the whole instance to a backend or converter.

A responsible backend should handle all essential items

inline UnaryExpr MakeUnary(expr::Kind kind, NumericExpr arg)

Makes a unary expression.

inline BinaryExpr MakeBinary(expr::Kind kind, NumericExpr lhs, NumericExpr rhs)

Makes a binary expression.

inline IfExpr MakeIf(LogicalExpr condition, NumericExpr then_expr, NumericExpr else_expr)

Makes an if expression.

inline IteratedExprBuilder BeginIterated(expr::Kind kind, int num_args)

Begins building an iterated expression.

inline IteratedExpr EndIterated(IteratedExprBuilder builder)

Ends building an iterated expression.

inline int num_functions() const

Returns the number of functions.

inline Function function(int index) const

Returns the function at the specified index.

inline Function AddFunction(fmt::StringRef name, int num_args, func::Type type = func::NUMERIC)

Adds a function.

name: Function name that may not be null-terminated.

inline void AddFunctions(int num_funcs)

Adds a function that will be defined later.

inline Function DefineFunction(int index, fmt::StringRef name, int num_args, func::Type type)

Defines a function.

inline NumericConstant MakeNumericConstant(double value)

Makes a numeric constant.

inline Reference MakeVariable(int index)

Makes a variable reference.

inline Reference MakeCommonExpr(int index)

Makes a common expression reference.

inline PLTermBuilder BeginPLTerm(int num_breakpoints)

Begins building a piecewise-linear term.

inline PLTerm EndPLTerm(PLTermBuilder builder, Reference arg)

Ends building a piecewise-linear term.

arg: argument that should be either a variable or a common expression.

inline CallExprBuilder BeginCall(Function func, int num_args)

Begins building a call expression.

inline CallExpr EndCall(CallExprBuilder builder)

Ends building a call expression.

inline IteratedExprBuilder BeginSum(int num_args)
inline IteratedExpr EndSum(IteratedExprBuilder builder)
inline NumberOfExprBuilder BeginNumberOf(int num_args, NumericExpr arg0)

Begins building a numberof expression.

inline IteratedExpr EndNumberOf(NumberOfExprBuilder builder)

Ends building a numberof expression.

inline SymbolicNumberOfExprBuilder BeginSymbolicNumberOf(int num_args, Expr arg0)

Begins building a numberof expression.

inline SymbolicNumberOfExpr EndSymbolicNumberOf(SymbolicNumberOfExprBuilder builder)

Ends building a numberof expression.

inline CountExprBuilder BeginCount(int num_args)

Begins building a count expression.

inline CountExpr EndCount(CountExprBuilder builder)

Ends building a count expression.

inline LogicalConstant MakeLogicalConstant(bool value)

Makes a logical constant.

inline NotExpr MakeNot(LogicalExpr arg)

Makes a logical NOT expression.

inline BinaryLogicalExpr MakeBinaryLogical(expr::Kind kind, LogicalExpr lhs, LogicalExpr rhs)

Makes a binary logical expression.

inline RelationalExpr MakeRelational(expr::Kind kind, NumericExpr lhs, NumericExpr rhs)

Makes a relational expression.

inline LogicalCountExpr MakeLogicalCount(expr::Kind kind, NumericExpr lhs, CountExpr rhs)

Makes a logical count expression.

inline ImplicationExpr MakeImplication(LogicalExpr condition, LogicalExpr then_expr, LogicalExpr else_expr)

Makes an implication expression.

inline IteratedLogicalExprBuilder BeginIteratedLogical(expr::Kind kind, int num_args)

Begins building an iterated logical expression.

inline IteratedLogicalExpr EndIteratedLogical(IteratedLogicalExprBuilder builder)

Ends building an iterated logical expression.

inline PairwiseExprBuilder BeginPairwise(expr::Kind kind, int num_args)

Begins building a pairwise expression.

inline PairwiseExpr EndPairwise(PairwiseExprBuilder builder)

Ends building a pairwise expression.

inline StringLiteral MakeStringLiteral(fmt::StringRef value)

Makes a string literal.

inline SymbolicIfExpr MakeSymbolicIf(LogicalExpr condition, Expr then_expr, Expr else_expr)

Makes a symbolic if expression.

inline SuffixSet &suffixes(suf::Kind kind)

Returns a set of suffixes.

inline const SuffixSet &suffixes(suf::Kind kind) const

Protected Functions

template<class Backend>
inline void PushStandardMPItemsTo(Backend &backend) const
template<class Backend>
inline void InitProblemModificationPhase(Backend &backend) const
template<class Backend>
inline void PushVariablesTo(Backend &backend) const
template<class Backend>
inline void PushCommonExprTo(Backend &backend) const
template<class Backend>
inline void PushObjectivesTo(Backend &backend) const
template<class Backend>
inline void PushAlgebraicConstraintsTo(Backend &backend) const
template<class Backend>
inline void PushLogicalConstraintsTo(Backend &backend) const
template<class Backend>
inline void PushComplementarityConstraintsTo(Backend&) const
template<class Backend>
inline void FinishProblemModificationPhase(Backend &backend) const

Protected Static Functions

static const std::string &item_name(int i, std::vector<std::string> &names, int n, const char *stub, int n2 = std::numeric_limits<int>::max(), const char *stub2 = nullptr)

Return names[i].

Generate names[old_size…n-1] if needed, so that the whole vector is valid, even if only some variables/cons/objs were queried. From [n2], name ‘stub2’[i-n2] is given. If stub/stub2 ends with a ‘[’, ‘]’ is added after the index.

Private Members

std::vector<int> col_starts_

Column-wise constraint matrix.

std::vector<int> row_indices_
std::vector<double> coefs_

Friends

friend class ColProblemBuilder
class mp::ColProblemBuilder : public mp::internal::NLProblemBuilder<ColProblem>
#include <problem-builder.h>

An NL handler that builds a problem with a column-wise constraint matrix.

Public Types

typedef ProblemBuilder::Function Function
typedef ProblemBuilder::Expr Expr
typedef ProblemBuilder::NumericExpr NumericExpr
typedef ProblemBuilder::LogicalExpr LogicalExpr
typedef ProblemBuilder::CountExpr CountExpr
typedef ProblemBuilder::Reference Reference
typedef ProblemBuilder::LinearObjBuilder LinearObjHandler
typedef ProblemBuilder::LinearConBuilder LinearConHandler
typedef ProblemBuilder::LinearExprBuilder LinearExprHandler
typedef ProblemBuilder::IntSuffixHandler IntSuffixHandler
typedef ProblemBuilder::DblSuffixHandler DblSuffixHandler
typedef ProblemBuilder::PLTermBuilder PLTermHandler
typedef ProblemBuilder::CallExprBuilder CallArgHandler
typedef ProblemBuilder::IteratedExprBuilder VarArgHandler
typedef ProblemBuilder::IteratedExprBuilder NumericArgHandler
typedef ProblemBuilder::NumberOfExprBuilder NumberOfArgHandler
typedef ProblemBuilder::SymbolicNumberOfExprBuilder SymbolicArgHandler
typedef ProblemBuilder::CountExprBuilder CountArgHandler
typedef ProblemBuilder::IteratedLogicalExprBuilder LogicalArgHandler
typedef ProblemBuilder::PairwiseExprBuilder PairwiseArgHandler

Public Functions

inline explicit ColProblemBuilder(ColProblem &p)
inline void OnHeader(const NLHeader &h)
inline ColumnSizeHandler OnColumnSizes()
inline LinearConHandler OnLinearConExpr(int con_index, int)
inline ColProblem &builder()

Get builder.

inline void AddVariables(const NLHeader &h)

Add variables.

inline void DoAddVars(int n, var::Type t, int &k)

DoAddVars: update counter k.

inline virtual int objno() const

objno(). virtual, so that SolverNLHandler can override

inline virtual bool multiobj() const

multiobj(). virtual, so that SolverNLHandler can override

inline virtual void notify_obj_added() const

notify_obj_added(). virtual, so that SolverNLHandler can override

inline int resulting_nobj(int nobj_header) const

Actual N objectives.

inline bool NeedObj(int obj_index) const

Whether need this objective.

inline int resulting_obj_index(int index) const

Final obj index for a given original index.

For multiobj, it’s the same. Otherwise it’s 0 (1st objective).

inline void OnObj(int index, obj::Type type, NumericExpr expr)
inline void OnAlgebraicCon(int index, NumericExpr expr)
inline void OnLogicalCon(int index, LogicalExpr expr)
inline void OnComplementarity(int con_index, int var_index, ComplInfo info)
inline LinearObjHandler OnLinearObjExpr(int obj_index, int num_linear_terms)
inline LinearExprHandler BeginCommonExpr(int index, int num_linear_terms)
inline void EndCommonExpr(int index, NumericExpr expr, int position)
inline void OnVarBounds(int index, double lb, double ub)
inline void OnConBounds(int index, double lb, double ub)
inline void OnInitialValue(int var_index, double value)
inline void OnInitialDualValue(int con_index, double value)
inline void OnFunction(int index, fmt::StringRef name, int num_args, func::Type type)
inline IntSuffixHandler OnIntSuffix(fmt::StringRef name, suf::Kind kind, int num_values)
inline DblSuffixHandler OnDblSuffix(fmt::StringRef name, suf::Kind kind, int num_values)
inline NumericExpr OnNumber(double value)
inline Reference OnVariableRef(int var_index)
inline Reference OnCommonExprRef(int expr_index)
inline NumericExpr OnUnary(expr::Kind kind, NumericExpr arg)
inline NumericExpr OnBinary(expr::Kind kind, NumericExpr lhs, NumericExpr rhs)
inline NumericExpr OnIf(LogicalExpr condition, NumericExpr then_expr, NumericExpr else_expr)
inline PLTermHandler BeginPLTerm(int num_breakpoints)
inline NumericExpr EndPLTerm(PLTermHandler handler, Reference arg)
inline CallArgHandler BeginCall(int func_index, int num_args)
inline NumericExpr EndCall(CallArgHandler handler)
inline VarArgHandler BeginVarArg(expr::Kind kind, int num_args)
inline NumericExpr EndVarArg(VarArgHandler handler)
inline NumericArgHandler BeginSum(int num_args)
inline NumericExpr EndSum(NumericArgHandler handler)
inline NumberOfArgHandler BeginNumberOf(int num_args, NumericExpr arg0)
inline NumericExpr EndNumberOf(NumberOfArgHandler handler)
inline SymbolicArgHandler BeginSymbolicNumberOf(int num_args, Expr arg0)
inline NumericExpr EndSymbolicNumberOf(SymbolicArgHandler handler)
inline CountArgHandler BeginCount(int num_args)
inline CountExpr EndCount(CountArgHandler handler)
inline LogicalExpr OnBool(bool value)
inline LogicalExpr OnNot(LogicalExpr arg)
inline LogicalExpr OnBinaryLogical(expr::Kind kind, LogicalExpr lhs, LogicalExpr rhs)
inline LogicalExpr OnRelational(expr::Kind kind, NumericExpr lhs, NumericExpr rhs)
inline LogicalExpr OnLogicalCount(expr::Kind kind, NumericExpr lhs, CountExpr rhs)
inline LogicalExpr OnImplication(LogicalExpr condition, LogicalExpr then_expr, LogicalExpr else_expr)
inline LogicalArgHandler BeginIteratedLogical(expr::Kind kind, int num_args)
inline LogicalExpr EndIteratedLogical(LogicalArgHandler handler)
inline PairwiseArgHandler BeginPairwise(expr::Kind kind, int num_args)
inline LogicalExpr EndPairwise(PairwiseArgHandler handler)
inline Expr OnString(fmt::StringRef value)
inline Expr OnSymbolicIf(LogicalExpr condition, Expr then_expr, Expr else_expr)
inline void EndInput()

Private Types

typedef internal::NLProblemBuilder<ColProblem> Base
class mp::NLWriter2::ColSizeWriter
#include <nl-writer2.h>

Write num_vars+num_rand_vars-1 column sizes.

Public Functions

inline ColSizeWriter(NLWriter2 &nlw, int k)

Construct.

inline void Write(int s)

Write next col’s size.

inline int GetNWritten() const

Report N written.

Private Members

NLWriter2 &nlw_
const int kind_
std::size_t sum_ = 0
int nWrt_ = 0
class mp::ColProblemBuilder::ColumnSizeHandler
#include <problem-builder.h>

Public Functions

inline void Add(int size)

Private Functions

inline explicit ColumnSizeHandler(ColProblem &p)

Private Members

ColProblem *problem_

Friends

friend class ColProblemBuilder
struct mp::internal::NLProblemBuilder::ColumnSizeHandler
#include <nl-reader.h>

Public Functions

inline void Add(int)
struct mp::NLHandler::ColumnSizeHandler
#include <nl-reader.h>

A class (struct) that receives notifications of Jacobian column sizes.

Public Functions

inline void Add(int size)

Receives notification of a Jacobian column size.

struct mp::ProblemBuilder::CommonExpr
#include <problem-builder.h>

Public Functions

inline LinearExprBuilder set_linear_expr(int num_linear_terms) const
inline void set_nonlinear_expr(NumericExpr expr) const
inline void set_position(int position) const
template<class Expr>
class mp::ComplementarityConstraint : public mp::BasicConstraint
#include <constr_general.h>

Complementarity constraint.

Expr complements a variable.

Parameters

Expr – an affine or quadratic functional expression

Public Types

using ExprType = Expr

The expression type.

Public Functions

inline ComplementarityConstraint(ExprType expr, int var)

Constructor.

inline const ExprType &GetExpression() const

Get constraint.

inline int GetVariable() const

Get variable.

template<class VarInfo>
inline Violation ComputeViolation(const VarInfo &x) const

Compute violation.

inline const char *GetName() const

Constraint name.

inline const char *name() const

Constraint name.

inline void SetName(std::string nm)

Set constraint name.

inline Context GetContext() const

Get context, if meaningful.

inline void SetContext(Context) const

Set context, if meaningful.

inline void AddContext(Context) const

Add (merge) context, if meaningful.

inline bool HasResultVar() const

Has result var (is functional)?

inline int GetResultVar() const

For functional constraints, result variable index.

Public Static Functions

static inline const char *GetTypeName()

Constraint type name.

static inline bool IsLogical()

Is logical?

static inline constexpr bool UsesContext()

Whether context is meaningful here.

Private Members

ExprType compl_expr_
int compl_var_
template<class ModelConverter, class ComplCon>
class mp::ComplementarityConverter_MIP : public mp::BasicFuncConstrCvt<ComplementarityConverter_MIP<ModelConverter, ComplCon>, ModelConverter>
#include <complement.h>

Converts Complementarity for MIP.

Public Types

using Base = BasicFuncConstrCvt<ComplementarityConverter_MIP<ModelConverter, ComplCon>, ModelConverter>

Base class.

using ItemType = ComplCon

Converted item type.

Public Functions

inline ComplementarityConverter_MIP(ModelConverter &mc)

Constructor.

inline void Convert(const ItemType &cc, int)

Convert in any context.

inline void Convert(const ItemType &item, int i)

Generic Convert(), distinguishes context & result variable.

Distinguish positive and negative context because if only one of these is necessary, significant model reduction can be achieved in certain cases.

Responsible for adding presolve links, if any

The Impl can reimplement this

Parameters
  • item – the item to be converted

  • i – item index, used to create a presolve link

inline void ConvertCtxNeg(const ItemType &item, int)

Convert in negative context.

inline void ConvertCtxPos(const ItemType &item, int)

Convert in positive context.

inline const ModelConverter &GetMC() const

Reuse the stored ModelConverter.

inline ModelConverter &GetMC()

Reuse the stored ModelConverter.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

class mp::ComplInfo
#include <common.h>

Complementarity constraint information.

Public Types

enum [anonymous]

Flags for the constructor.

Values:

enumerator INF_UB

Constraint upper bound is infinity (finite variable lower bound).

enumerator INF_LB

Constraint lower bound is -infinity (finite variable upper bound).

Public Functions

inline explicit ComplInfo(int flags)

Constructs a ComplInfo() object.

inline double con_lb() const

Constraint lower bound.

inline double con_ub() const

Constraint upper bound.

Private Members

int flags_
class mp::NLWriter2::ConBndWriter
#include <nl-writer2.h>

Write num_algebraic_cons constraint bounds.

Public Functions

inline ConBndWriter(NLWriter2 &nlw)

Construct.

template<class AlgConRange>
void WriteAlgConRange(AlgConRange)

Write range/complementarity for the next constraint.

inline int GetNWritten() const

Get N written.

Private Members

NLWriter2 &nlw_
int nWrt_ = 0
template<typename Handler, typename T, typename AccessorT = T>
class mp::SolverOptionManager::ConcreteOption : public mp::TypedSolverOption<T>
#include <solver-opt.h>

Handler should be a class derived from BasicSolver that will receive notifications about parsed options.

Public Types

enum Option_Type

Option type classifier, used in AMPLS.

Values:

enumerator BOOL
enumerator INT
enumerator DBL
enumerator STRING

Public Functions

template<class Solver>
inline ConcreteOption(const char *name, const char *description, Solver *s, Get get, Set set, ValueArrayRef values = ValueArrayRef())
inline void GetValue(T &value) const
inline void SetValue(typename internal::OptionHelper<T>::Arg value)
inline virtual void Write(fmt::Writer &w) override

Formats the option value.

Throws OptionError in case of error. Not called for flags.

inline virtual void Parse(const char *&s, bool splitString = false) override

Parses the string for an option value, throws an exception if the value is invalid.

Parameters
  • s – string to be parsed

  • splitString – set to true to identify that the options string has already been pre-parsed (by the command line interpreter) so it is now in the format of null terminated substrings. If parsed from the environment variable, the string is monolithic, space separated and quotes have to be considered.

inline virtual Option_Type type() override

Return type classifier.

inline const char *name() const

Return the option name.

const char *name_ASL() const

Return the ASL (not qualified) name as the first inline synonym - or the name itself if no synonyms are defined.

inline const std::vector<std::string> &inline_synonyms() const

Returns the “inline” synonyms.

void add_synonyms_front(const char *names_list)

Add additional “inline” synonyms.

void add_synonyms_back(const char *names_list)
inline bool is_hidden() const

Is hidden?

inline bool is_wildcard() const

Wildcards.

bool wc_match(const std::string &key)

Checks if matches, then saves key & body.

inline const std::string &wc_head() const
inline const std::string &wc_tail() const
inline const std::string &wc_key_last() const
inline const std::string &wc_keybody_last() const
inline std::string wc_key_last__std_form() const

Printing last parsed wc key in std form.

inline const char *description() const

Return/set the option description.

inline void set_description(const char *d)
inline void add_to_description(const char *d)
inline void format_description(fmt::MemoryWriter &writer, int indent = 0) const

Append the formatted description to the writer.

inline std::string format_description(int indent = 0) const

Get the formatted option description.

inline ValueArrayRef values() const

Returns the information about possible values.

inline virtual bool is_flag() const

Returns true if this option is a flag, i.e. it doesn’t take a value.

inline virtual void GetValue(fmt::LongLong&) const

Returns the option value.

inline virtual void GetValue(double&) const
inline virtual void GetValue(std::string&) const
inline virtual void GetValue(int &int_value) const
template<typename T>
inline T GetValue() const
inline virtual void SetValue(fmt::LongLong)

Sets the option value or throws InvalidOptionValue if the value is invalid.

inline virtual void SetValue(double)
inline virtual void SetValue(fmt::StringRef)
inline virtual void SetValue(int value)
inline virtual std::string echo_with_value()

Echo option name(s) [= value].

inline virtual std::string echo()

Echo option name(s).

Private Types

typedef AccessorT (Handler::* Get)(const SolverOption&) const
typedef void (Handler::* Set)(const SolverOption&, typename internal::OptionHelper<AccessorT>::Arg)

Private Members

Handler &handler_
Get get_
Set set_
template<typename Handler, typename T, typename Info, typename InfoArg = Info, typename AccessorT = T>
class mp::SolverOptionManager::ConcreteOptionWithInfo : public mp::TypedSolverOption<T>
#include <solver-opt.h>

Public Types

enum Option_Type

Option type classifier, used in AMPLS.

Values:

enumerator BOOL
enumerator INT
enumerator DBL
enumerator STRING

Public Functions

template<class Solver>
inline ConcreteOptionWithInfo(const char *name, const char *description, Solver *s, Get get, Set set, InfoArg info, ValueArrayRef values = ValueArrayRef())
inline ConcreteOptionWithInfo(const char *name, const char *description, Handler *s, Get get, Set set, InfoArg info, ValueArrayRef values = ValueArrayRef())
inline void GetValue(T &value) const
inline void SetValue(typename internal::OptionHelper<T>::Arg value)
inline virtual void Write(fmt::Writer &w) override

Formats the option value.

Throws OptionError in case of error. Not called for flags.

inline virtual void Parse(const char *&s, bool splitString = false) override

Parses the string for an option value, throws an exception if the value is invalid.

Parameters
  • s – string to be parsed

  • splitString – set to true to identify that the options string has already been pre-parsed (by the command line interpreter) so it is now in the format of null terminated substrings. If parsed from the environment variable, the string is monolithic, space separated and quotes have to be considered.

inline virtual Option_Type type() override

Return type classifier.

inline const char *name() const

Return the option name.

const char *name_ASL() const

Return the ASL (not qualified) name as the first inline synonym - or the name itself if no synonyms are defined.

inline const std::vector<std::string> &inline_synonyms() const

Returns the “inline” synonyms.

void add_synonyms_front(const char *names_list)

Add additional “inline” synonyms.

void add_synonyms_back(const char *names_list)
inline bool is_hidden() const

Is hidden?

inline bool is_wildcard() const

Wildcards.

bool wc_match(const std::string &key)

Checks if matches, then saves key & body.

inline const std::string &wc_head() const
inline const std::string &wc_tail() const
inline const std::string &wc_key_last() const
inline const std::string &wc_keybody_last() const
inline std::string wc_key_last__std_form() const

Printing last parsed wc key in std form.

inline const char *description() const

Return/set the option description.

inline void set_description(const char *d)
inline void add_to_description(const char *d)
inline void format_description(fmt::MemoryWriter &writer, int indent = 0) const

Append the formatted description to the writer.

inline std::string format_description(int indent = 0) const

Get the formatted option description.

inline ValueArrayRef values() const

Returns the information about possible values.

inline virtual bool is_flag() const

Returns true if this option is a flag, i.e. it doesn’t take a value.

inline virtual void GetValue(fmt::LongLong&) const

Returns the option value.

inline virtual void GetValue(double&) const
inline virtual void GetValue(std::string&) const
inline virtual void GetValue(int &int_value) const
template<typename T>
inline T GetValue() const
inline virtual void SetValue(fmt::LongLong)

Sets the option value or throws InvalidOptionValue if the value is invalid.

inline virtual void SetValue(double)
inline virtual void SetValue(fmt::StringRef)
inline virtual void SetValue(int value)
inline virtual std::string echo_with_value()

Echo option name(s) [= value].

inline virtual std::string echo()

Echo option name(s).

Private Types

typedef AccessorT (Handler::* Get)(const SolverOption&, InfoArg) const
typedef void (Handler::* Set)(const SolverOption&, typename internal::OptionHelper<AccessorT>::Arg, InfoArg)

Private Members

Handler &handler_
Get get_
Set set_
Info info_
template<class ValueType, class KeyType>
class mp::StdBackend::ConcreteOptionWrapper : public mp::SolverOptionManager::ConcreteOptionWithInfo<SolverOptionAccessor<ValueType, KeyType>, ValueType, KeyType>
#include <backend-std.h>

Public Types

enum Option_Type

Option type classifier, used in AMPLS.

Values:

enumerator BOOL
enumerator INT
enumerator DBL
enumerator STRING

Public Functions

inline ConcreteOptionWrapper(Impl *impl_, const char *name, const char *description, KeyType k, ValueArrayRef values = ValueArrayRef())
inline void GetValue(ValueType &value) const
inline virtual void GetValue(fmt::LongLong&) const

Returns the option value.

inline virtual void GetValue(double&) const
inline virtual void GetValue(std::string&) const
inline virtual void GetValue(int &int_value) const
template<typename T>
inline T GetValue() const
inline void SetValue(typename internal::OptionHelper<ValueType>::Arg value)
inline virtual void SetValue(fmt::LongLong)

Sets the option value or throws InvalidOptionValue if the value is invalid.

inline virtual void SetValue(double)
inline virtual void SetValue(fmt::StringRef)
inline virtual void SetValue(int value)
inline virtual void Write(fmt::Writer &w) override

Formats the option value.

Throws OptionError in case of error. Not called for flags.

inline virtual void Parse(const char *&s, bool splitString = false) override

Parses the string for an option value, throws an exception if the value is invalid.

Parameters
  • s – string to be parsed

  • splitString – set to true to identify that the options string has already been pre-parsed (by the command line interpreter) so it is now in the format of null terminated substrings. If parsed from the environment variable, the string is monolithic, space separated and quotes have to be considered.

inline virtual Option_Type type() override

Return type classifier.

inline const char *name() const

Return the option name.

const char *name_ASL() const

Return the ASL (not qualified) name as the first inline synonym - or the name itself if no synonyms are defined.

inline const std::vector<std::string> &inline_synonyms() const

Returns the “inline” synonyms.

void add_synonyms_front(const char *names_list)

Add additional “inline” synonyms.

void add_synonyms_back(const char *names_list)
inline bool is_hidden() const

Is hidden?

inline bool is_wildcard() const

Wildcards.

bool wc_match(const std::string &key)

Checks if matches, then saves key & body.

inline const std::string &wc_head() const
inline const std::string &wc_tail() const
inline const std::string &wc_key_last() const
inline const std::string &wc_keybody_last() const
inline std::string wc_key_last__std_form() const

Printing last parsed wc key in std form.

inline const char *description() const

Return/set the option description.

inline void set_description(const char *d)
inline void add_to_description(const char *d)
inline void format_description(fmt::MemoryWriter &writer, int indent = 0) const

Append the formatted description to the writer.

inline std::string format_description(int indent = 0) const

Get the formatted option description.

inline ValueArrayRef values() const

Returns the information about possible values.

inline virtual bool is_flag() const

Returns true if this option is a flag, i.e. it doesn’t take a value.

inline virtual std::string echo_with_value()

Echo option name(s) [= value].

inline virtual std::string echo()

Echo option name(s).

Private Members

SOAType soa_
template<class ModelConverter, class AlgCon>
class mp::Cond_LE_LT_GT_GE_Converter_MIP : public mp::BasicFuncConstrCvt<Cond_LE_LT_GT_GE_Converter_MIP<ModelConverter, AlgCon>, ModelConverter>
#include <cond_ineq.h>

Converts conditional <=, <, >, >= for MIP.

The comparison kind is given by con.GetConstraint().kind().

Public Types

using Base = BasicFuncConstrCvt<Cond_LE_LT_GT_GE_Converter_MIP<ModelConverter, AlgCon>, ModelConverter>

Base class.

using ItemType = ConditionalConstraint<AlgCon>

Converted item type.

Public Functions

inline Cond_LE_LT_GT_GE_Converter_MIP(ModelConverter &mc)

Constructor.

inline void ConvertCtxPos(const ItemType &cc, int)

Convert in positive context: resvar==1 –> (body) (cmp) (rhs)

inline void ConvertCtxNeg(const ItemType &cc, int)

Convert in negative context: resvar==0 –> (body) (!cmp) (rhs)

inline void Convert(const ItemType &item, int i)

Generic Convert(), distinguishes context & result variable.

Distinguish positive and negative context because if only one of these is necessary, significant model reduction can be achieved in certain cases.

Responsible for adding presolve links, if any

The Impl can reimplement this

Parameters
  • item – the item to be converted

  • i – item index, used to create a presolve link

inline void ConvertCtxNeg(const ItemType &item, int)

Convert in negative context.

inline void ConvertCtxPos(const ItemType &item, int)

Convert in positive context.

inline const ModelConverter &GetMC() const

Reuse the stored ModelConverter.

inline ModelConverter &GetMC()

Reuse the stored ModelConverter.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

Public Static Attributes

static constexpr int kind_input = AlgCon::kind()

Comparison kind.

Protected Functions

template<int kind>
inline void ConvertCondIneq(const ItemType &cc, int value, double eps)

Convert conditional inequality to indicator res==value ==> Body (Cmp<kind>) Rhs+eps.

template<class Con>
struct mp::CondConId
#include <constr_base.h>

Helper, conditional constraint Id.

Subclassed by mp::CustomFunctionalConstraint< Con, ParamArray0, LogicalFunctionalConstraintTraits, CondConId< Con > >

Public Static Functions

static inline const char *description()
static inline const char *GetTypeName()
template<class ModelConverter, class AlgConBody>
class mp::CondEQConverter_MIP : public mp::BasicFuncConstrCvt<CondEQConverter_MIP<ModelConverter, AlgConBody>, ModelConverter>
#include <cond_eq.h>

Converts conditional equality for MIP.

Public Types

using Base = BasicFuncConstrCvt<CondEQConverter_MIP<ModelConverter, AlgConBody>, ModelConverter>

Base class.

template<int kind>
using AlgCon = AlgebraicConstraint<AlgConBody, AlgConRhs<kind>>

Underlying algebraic constraint, parameterized by comparison type.

using ItemType = ConditionalConstraint<AlgCon<0>>

Converted item type.

Public Functions

inline CondEQConverter_MIP(ModelConverter &mc)

Constructor.

inline void Convert(const CondLinConEQ &eq0c, int i)

but reimplement Convert() for CondLinConEQ only: add filter

inline void ConvertCtxPos(const ItemType &eq0c, int)

Convert in positive context resvar==1 => body==d.

inline void ConvertCtxNeg(const ItemType &eq0c, int)

Convert in negative context resvar==0 ==> body!=d.

inline void Convert(const ItemType &item, int i)

Generic Convert(), distinguishes context & result variable.

Distinguish positive and negative context because if only one of these is necessary, significant model reduction can be achieved in certain cases.

Responsible for adding presolve links, if any

The Impl can reimplement this

Parameters
  • item – the item to be converted

  • i – item index, used to create a presolve link

inline void ConvertCtxNeg(const ItemType &item, int)

Convert in negative context.

inline void ConvertCtxPos(const ItemType &item, int)

Convert in positive context.

inline const ModelConverter &GetMC() const

Reuse the stored ModelConverter.

inline ModelConverter &GetMC()

Reuse the stored ModelConverter.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

template<class Con>
class mp::ConditionalConstraint : public mp::CustomFunctionalConstraint<Con, ParamArray0, LogicalFunctionalConstraintTraits, CondConId<Con>>
#include <constr_base.h>

A wrapper on a static constraint Con making it conditional.

Public Types

using ConType = Con

ConType.

using Arguments = ConType

Arguments.

using Base = CustomFunctionalConstraint<Con, ParamArray0, LogicalFunctionalConstraintTraits, CondConId<Con>>

Base class.

using Parameters = ParamArray0

Parameters typedef.

Public Functions

ConditionalConstraint() = default

Default constructor.

inline ConditionalConstraint(Arguments args) noexcept

Construct from arguments only.

inline ConditionalConstraint(int varr, Arguments args) noexcept

Construct from resvar and arguments.

inline const ConType &GetConstraint() const

Get the wrapped constraint, const.

inline ConType &GetConstraint()

Get the wrapped constraint.

inline bool operator==(const ConditionalConstraint &cc) const

Equality.

template<class VarVec>
inline Violation ComputeViolation(const VarVec &x)

Compute violation of a conditional constraint.

If the subconstr is violated but should hold, return the exact gap, despite this is a logical constraint. If the subconstr holds but should not, return the opposite gap. Similar to Indicator.

inline const Arguments &GetArguments() const

Get const Arguments&.

inline Arguments &GetArguments()

Get Arguments&.

inline const Parameters &GetParameters() const

Get const Parameters&.

inline Parameters &GetParameters()

Get Parameters&.

Violation ComputeViolation(const VarVec &x) const

Compute violation.

Should be here, after ComputeViolation() is specialized for some constraints.

template<class VarInfo>
inline Violation ComputeViolation(const VarInfo&) const

Compute violation.

inline int GetResultVar() const

Reuse GetResultVar()

inline int GetResultVar() const

Get result variable.

inline bool operator==(const FunctionalConstraint &dc) const

Basic operator==.

inline bool HasResultVar() const

Has result var (is functional)? We don’t store this info in the type (yet.)

inline void SetResultVar(int v)

Set result variable.

inline Context GetContext() const

Get it.

inline void SetContext(Context c) const

Set it.

inline void AddContext(Context c)

Add context.

inline void AddContext(Context) const

Add (merge) context, if meaningful.

inline const char *GetName() const

Constraint name.

inline const char *name() const

Constraint name.

inline void SetName(std::string nm)

Set constraint name.

Public Static Functions

static inline const char *GetTypeName()

Constraint type name for messages.

static inline constexpr bool UsesContext()

Whether context is meaningful.

static inline constexpr bool IsLogical()

Whether the constraint is logical.

static inline std::pair<double, double> GetAprioriBounds()

Apriori bounds on the result.

static inline const char *description()
struct mp::Convert1QC::ConeArgs
#include <cones.h>

Typedef for subexpression checkup result, whether it represents some part of an SOCP cone.

Public Functions

inline operator bool() const

operator bool

inline size_t size() const

size()

inline bool check() const

check()

Public Members

std::vector<double> coefs_
std::vector<int> vars_
double const_term = 0.0
double coef_extra = 0.0
std::vector<int> res_vars_to_delete_

Result vars of expressions to un-use.

struct mp::internal::NLReader::ConHandler : public mp::internal::NLReader<CON>::ItemHandler

Public Functions

inline explicit ConHandler(NLReader &r)
inline int num_items() const

Public Static Attributes

static const ItemType TYPE = T

Protected Attributes

NLReader &reader_
template<class MCType>
class mp::ConicConverter : public mp::MCKeeper<MCType>
#include <cones.h>

Functor to convert various constraints to cones.

Parameters

MCType – the main converter.

Public Types

using MCType = MCType

Typedef MCType.

Public Functions

inline virtual ~ConicConverter()
inline ConicConverter(MCType &mc)

Constructor.

inline void Run()

Run conversions.

Protected Functions

inline void RunQConesFromQC()
inline void RunQConesFromNonQC()
inline void RunExpCones()
inline void TryReformulateQPObjective()

Ideally also for exp/log terms.

inline bool HasAnyCones() const

Any cones at all.

inline bool HasAnyNonSOCPCones() const

any non-SOCP cones?

inline bool IfNeedSOCP2QC()
inline void SetupSOCP2QC()
inline void WarnOnMix()
template<class Con, template<class> class CvtBase>
inline void Walk()

Walk a single constraint type.

inline const MCType &MC() const

Retrieve the MC.

inline MCType &MC()
class mp::ConstraintConversionFailure
#include <redef_base.h>

Conversion failure helper.

Public Functions

inline ConstraintConversionFailure(const char *key, const char *msg) noexcept
inline const char *key() const

Failure type, used to display infos about failures.

inline const char *message() const

Detailed message, should help improve model.

Private Members

const char *key_
const char *msg_
class mp::ConstraintConversionGracefulFailure
#include <redef_base.h>

Graceful constraint conversion failure - no warnings.

Public Functions

inline ConstraintConversionGracefulFailure()
template<class Converter, class Backend, class Constraint>
class mp::ConstraintKeeper : public mp::BasicConstraintKeeper
#include <constr_keeper.h>

Specialize ConstraintKeeper for a given constraint type to store an array of such constraints.

Public Types

using ConstraintType = Constraint

Constraint type.

using FlatExprType = ExprWrapper<Constraint>

The corresponding flat expression type.

Public Functions

inline ConstraintKeeper(Converter &cvt, const char *nm, const char *optnm)

Constructor, adds this CK to the provided ConstraintManager Requires the CM to be already constructed.

inline virtual const char *GetExprOrConstraintName() const override

Expression type, or, if appropriate, constraint type name, e.g., ‘Abs’.

inline virtual const std::string &GetDescription() const override

Constrint Keeper description.

inline Backend &GetBackend(BasicFlatConverter &cvt)

Assume Converter has the Backend.

template<class ...Args>
inline int AddConstraint(int d, Args&&... args)

Add a pre-constructed constraint (or just arguments)

Returns

index of the new constraint

inline const Constraint &GetConstraint(int i) const

Get const constraint i.

inline Constraint &GetConstraint(int i)

Get constraint i.

inline int GetConstraintDepth(int i) const

Get constraint depth in the reformulation tree.

inline virtual Context GetContext(int i) const override

Get context of contraint i.

inline virtual void PropagateResult(BasicFlatConverter &cvt, int i, double lb, double ub, Context ctx) override

Propagate expression result of constraint i top-down.

inline virtual int GetResultVar(int i) const override

Result variable of constraint i. Returns -1 if none.

inline double ConversionPriority() const

Conversion priority. Uses that from Converter.

inline virtual bool ConvertAllNewWith(BasicFlatConverter &cvt) override

Convert all new items of this constraint.

This normally dispatches conversion (decomposition) to the Converter

Returns

whether any converted

inline virtual void MarkExprsForResultVars(BasicFlatConverter &cvt) override

Mark whether to keep result vars.

inline virtual void ConvertWithExpressions(BasicFlatConverter &cvt) override

Convert to use expressions.

inline virtual bool IfConverterConverts(BasicFlatConverter &cvt) const override

Converter’s ability to convert the constraint type.

inline virtual ConstraintAcceptanceLevel GetModelAPIAcceptance(const BasicFlatModelAPI &ba) const override

Acceptance level of this constraint type in the ModelAPI.

inline virtual ExpressionAcceptanceLevel GetModelAPIAcceptanceEXPR(const BasicFlatModelAPI &ba) const override

Acceptance level of the corresponding expression type in the ModelAPI.

inline virtual ExpressionAcceptanceLevel GetModelAPIAcceptance_EXPR_INTF(const BasicFlatModelAPI &ba) const override

Acceptance level of the overall expression interface in the ModelAPI.

inline virtual const std::type_info &GetTypeInfo() const override

Constraint type_info.

inline virtual int GetNumberOfAddable() const override

Report how many will be added to Backend.

inline virtual int GetConstraintGroup(const BasicFlatModelAPI &ba) const override

Group number of this constraint type in the Backend.

This is needed for pre- / postsolve to group solution values

inline virtual void AddUnbridgedToBackend(BasicFlatModelAPI &be, const std::vector<std::string> *pvnam) override

Add remaining constraints to Backend.

inline virtual void LogConstraintGroup(BasicFlatModelAPI &be) override

Log constraint group.

inline virtual void MarkAsBridged(int i) override

Mark cons[i] as reformulated.

Use index only.

inline virtual void MarkAsUnused(int i) override

Mark cons[i] as unused.

Use index only.

inline virtual bool IsUnused(int i) const override

Is constraint i unused?

inline virtual void CopyNamesFromValueNodes() override

Copy names from ValueNodes.

inline void CopyNames2ValueNodes()

Copy names to ValueNodes.

template<class Fn>
inline void ForEachActive(Fn fn)

ForEachActive().

Deletes every constraint where fn() returns true.

inline virtual double ComputeValue(int i, const VarInfoRecomp &vir) override

Compute result for constraint i (for functional constraints).

inline virtual void ComputeViolations(SolCheck &chk) override

Compute violations for this constraint type.

We do it for redefined (intermediate) ones too.

inline ConstraintAcceptanceLevel GetChosenAcceptanceLevel() const

Query (user-chosen) acceptance level.

This is “combined” for constraint or expression

inline ExpressionAcceptanceLevel GetChosenAcceptanceLevelEXPR() const

Query (user-chosen) expression acceptance level.

inline const pre::ValueNode &GetValueNode() const

Value presolve node, const.

inline pre::ValueNode &GetValueNode()

Value presolve node.

inline pre::NodeRange AddValueNodeRange(int n = 1)

Create ValueNode range pointer: add n elements.

inline pre::NodeRange SelectValueNodeRange(int pos, int n = 1)

Create ValueNode range pointer: select n elements at certain pos.

inline const char *GetConstraintName() const

Constraint type name, e.g., ‘AbsConstraint’.

inline virtual const char *GetAcceptanceOptionNames() const

Acceptance option names.

virtual const char *GetShortTypeName() const

Constraint type short name.

Ideally should be in the constraint itself, but currently we derive it from acceptance options.

inline void ConsiderAcceptanceOptions(BasicFlatConverter &cvt, const BasicFlatModelAPI &ma, Env &env)

See what options are available for this constraint: whether it is accepted natively by ModelAPI, as flat constraint or expression.

Add acceptance option(s) “acc:…”. Populate constraint list for -c output.

Note

This should be called before using the class.

inline void SetLogger(BasicLogger *lg)

Set logger.

inline BasicLogger *GetLogger() const

Get logger, if provided and open and ok.

Protected Functions

inline const Converter &GetConverter() const

Retrieve the Converter, const.

inline Converter &GetConverter()

Retrieve the Converter.

inline bool check_index(int i) const

Check constraint index.

inline bool ConvertAllFrom(int &i_last)

Convert all new constraints of this type.

inline void DoMarkForResultVars()
inline void DoCvtWithExprs()
inline void ConvertConstraint(Container &cnt, int i)

Call Converter’s RunConversion() and mark as “bridged”.

Parameters
  • cnt – the constraint container - actually redundant, as i is enough to find it. But for speed.

  • i – constraint index, needed for bridging

inline void MarkAsBridged(Container &cnt, int)

Mark item as reformulated.

inline void MarkAsUnused(Container &cnt, int)

Mark item as unused.

inline void ExportConstraint(int i_con, const Container &cnt)

Export (last added) constraint.

inline void ExportConStatus(int i_con, const Container &cnt, const std::vector<std::string> *pvnam, bool add2final)

Export constraint status.

This is called in the end, so printing the readable form.

inline void AddAllUnbridged(BasicFlatModelAPI &be, const std::vector<std::string> *pvnam)

Add all non-converted items to ModelAPI.

Export all constraints if desired.

void DoAddAcceptanceOptions(BasicFlatConverter &cvt, const BasicFlatModelAPI &ma, Env &env)
void DoPopulateConstraintList(BasicFlatConverter &cvt, const BasicFlatModelAPI &ma, Env &env)

For -c.

Private Members

Converter &cvt_
std::deque<Container> cons_
int i_cvt_last_ = -1
int n_bridged_or_unused_ = 0
const std::string desc_{std::string("ConstraintKeeper< ") + Converter::GetTypeName() + ", " + Backend::GetTypeName() + ", " + Constraint::GetTypeName() + " >"}
template<class ConstraintKeeper>
struct mp::ConstraintLocationHelper
#include <constr_keeper.h>

Full id of a constraint: CK + index This helper class is parameterized by the Keeper.

Public Functions

ConstraintLocationHelper() = default

Default constructor: no valid Id.

inline ConstraintLocationHelper(ConstraintKeeper *pck, int i) noexcept

Normal constructor.

inline operator bool() const

Checks if we store a constraint’s location.

inline bool HasId() const

Checks if we store a constraint’s location.

inline int GetResultVar() const

High-level getter.

inline const ConstraintKeeper::ConstraintType &GetConstraint() const

High-level getter.

inline ConstraintKeeper::ConstraintType &GetConstraint()

High-level getter.

inline ConstraintKeeper *GetCK() const

Get Keeper.

inline int GetIndex() const

Get index.

inline void SetCK(ConstraintKeeper *pck)

Set Keeper.

inline void SetIndex(int i)

Set index.

Public Members

ConstraintKeeper *pck_ = nullptr
int index_ = 0
class mp::ConstraintManager
#include <constr_keeper.h>

Manage ConstraintKeepers for different constraint types.

Subclassed by mp::FlatModel< >, mp::FlatModel< ModelParams >

Public Functions

inline void AddConstraintKeeper(BasicConstraintKeeper &ck, double priority)

Add a new CKeeper with given conversion priority (smaller = sooner)

inline void ConsiderAcceptanceOptions(BasicFlatConverter &cvt, const BasicFlatModelAPI &ma, Env &env)

This should be called after adding all constraint keepers.

inline void ConvertAllConstraints(BasicFlatConverter &cvt)

Convert all constraints (including any new appearing)

inline void MarkExprsForResultVars(BasicFlatConverter &cvt)

Mark which expressions should stay as FuncCons or just have a result variable.

inline void ConvertWithExpressions(BasicFlatConverter &cvt)

Convert to expression-based model.

inline void FillConstraintCounters(const BasicFlatModelAPI &mapi, FlatModelInfo &fmi) const

Fill counters of unbridged constraints.

inline void CopyNamesFromValueNodes()

Copy names from ValueNodes.

inline void AddUnbridgedConstraintsToBackend(BasicFlatModelAPI &be, const std::vector<std::string> *pvnam = nullptr) const

Add all unbridged constraints to Backend.

inline void LogConstraintGroups(BasicFlatModelAPI &be) const

Log constraint groups.

inline void ComputeViolations(SolCheck &chk)

Compute violations.

inline BasicFileAppender &GetFileAppender() const

Retrieve file logger.

Private Members

std::multimap<double, BasicConstraintKeeper&> con_keepers_
std::unique_ptr<BasicFileAppender> graph_exporter_app_ = {MakeFileAppender()}

Conversion graph exporter file appender.

template<class Impl>
class mp::ConstraintPreprocessors
#include <constr_prepro.h>

A mix-in base class providing preprocessors of flat constraints.

Currently used before adding a constraint (if not simplified to nothing).

Subclassed by mp::FlatConverter< Impl, ModelAPI, FlatModel< > >, mp::FlatConverter< Impl, ModelAPI, FlatModel >

Public Functions

template<class PreprocessInfo>
inline void PreprocessConstraint(LinearFunctionalConstraint &c, PreprocessInfo &prepro)

Preprocess LFC.

template<class PreprocessInfo>
inline void PreprocessConstraint(QuadraticFunctionalConstraint &c, PreprocessInfo &prepro)

Preprocess QFC.

template<class PreprocessInfo>
inline void PreprocessConstraint(PowConstraint &c, PreprocessInfo &prepro)

Preprocess Pow.

template<class PreprocessInfo>
inline void PreprocessConstraint(MinConstraint &c, PreprocessInfo &prepro)

Preprocess Min.

template<class PreprocessInfo>
inline void PreprocessConstraint(MaxConstraint &c, PreprocessInfo &prepro)

Preprocess Max.

template<class PreprocessInfo>
inline void PreprocessConstraint(AbsConstraint &c, PreprocessInfo &prepro)

When the result variable is set, the constraint is skipped.

template<class PreprocessInfo>
inline void PreprocessConstraint(CondLinConEQ &c, PreprocessInfo &prepro)

Preprocess CondLinConEQ.

template<class Body, int kind>
inline bool IsNormalized(ConditionalConstraint<AlgebraicConstraint<Body, AlgConRhs<kind>>> &cc)

See if the argument of a conditional algebraic constraint is normalized.

template<class PreprocessInfo>
inline void PreprocessConstraint(CondQuadConEQ &c, PreprocessInfo &prepro)

Preprocess CondQuadConEQ.

template<class PreprocessInfo, class CondAlgCon>
inline bool FixEqualityResult(CondAlgCon &c, PreprocessInfo &prepro)

Try and fix conditional equality result.

Returns

true if success

template<class PreprocessInfo>
inline bool ReuseEqualityBinaryVar(CondLinConEQ &c, PreprocessInfo &prepro)

Simplify conditional equality bin_var==0/1 by reusing bin_var or its complement.

template<class PreprocessInfo, class Body, int kind>
inline void PreprocessConstraint(ConditionalConstraint<AlgebraicConstraint<Body, AlgConRhs<kind>>> &cc, PreprocessInfo &prepro)

(Non)strict inequalities

template<class SubCon, class PreprocessInfo>
inline bool CheckEmptySubCon(const ConditionalConstraint<SubCon> &cc, PreprocessInfo &prepro)

Dave experiments with logic presolve.

Returns

true if constraint is empty and we should return the fixed result.

template<class PreprocessInfo>
inline void PreprocessConstraint(AndConstraint &con, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(OrConstraint &con, PreprocessInfo &prepro)
template<class Vec>
inline std::pair<int, int> count_fixed_01(const Vec &vec) const

Count N fixed binary vars.

template<class Con>
inline void IntegrateNested(Con &con)

Integrate nested constraints (And/Or)

template<class PreprocessInfo>
inline void PreprocessConstraint(AllDiffConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(NumberofConstConstraint &con, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(NumberofVarConstraint &con, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(CountConstraint &con, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(NotConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(DivConstraint &c, PreprocessInfo &prepro)

Preprocess Div.

template<class PreprocessInfo>
inline void PreprocessConstraint(IfThenConstraint &c, PreprocessInfo &prepro)

Preprocess IfThen.

template<class PreprocessInfo>
inline void PreprocessConstraint(ImplicationConstraint&, PreprocessInfo &prepro)

Preprocess IfThen.

template<class PreprocessInfo>
inline void PreprocessConstraint(ExpConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(ExpAConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(LogConstraint &c, PreprocessInfo&)
template<class PreprocessInfo>
inline void PreprocessConstraint(LogAConstraint &c, PreprocessInfo&)
template<class PreprocessInfo>
inline void PreprocessConstraint(SinConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(CosConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(TanConstraint&, PreprocessInfo&)

Preprocess Tan.

template<class PreprocessInfo>
inline void PreprocessConstraint(AsinConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(AcosConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(AtanConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(SinhConstraint&, PreprocessInfo&)
template<class PreprocessInfo>
inline void PreprocessConstraint(CoshConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(TanhConstraint&, PreprocessInfo &prepro)

Preprocess Tan.

template<class PreprocessInfo>
inline void PreprocessConstraint(AsinhConstraint&, PreprocessInfo&)
template<class PreprocessInfo>
inline void PreprocessConstraint(AcoshConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(AtanhConstraint&, PreprocessInfo&)
template<class PreprocessInfo>
inline void PreprocessConstraint(PLConstraint&, PreprocessInfo&)

Public Static Functions

static inline void PreprocessEqVarConst__unifyCoef(CondLinConEQ &c)

Normalize conditional equality coef * var == const.

template<class Impl>
class mp::ConstraintPropagatorsDown
#include <constr_prop_down.h>

A mix-in base class providing “down propagators” of flat constraints, i.e., from result bounds & context to arguments.

Subclassed by mp::FlatConverter< Impl, ModelAPI, FlatModel< > >, mp::FlatConverter< Impl, ModelAPI, FlatModel >

Public Functions

template<class Constraint>
inline void PropagateResult(Constraint &con, double lb, double ub, Context ctx)

By default, add mixed context for argument variables.

inline void PropagateResult(LinearFunctionalConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(QuadraticFunctionalConstraint &con, double lb, double ub, Context ctx)
template<class Body>
inline void PropagateResult(AlgebraicConstraint<Body, AlgConRange> &con)

Propagate a root algebraic range constraint.

template<class Body, int sens>
inline void PropagateResult(IndicatorConstraint<AlgebraicConstraint<Body, AlgConRhs<sens>>> &con, double lb, double ub, Context ctx)
template<int type>
inline void PropagateResult(SOS_1or2_Constraint<type> &con, double lb, double ub, Context)
template<class ExprBody>
inline void PropagateResult(ComplementarityConstraint<ExprBody> &con)

Propagate root complementarity constraint.

template<class ExprBody>
inline void PropagateResult(ComplementarityConstraint<ExprBody> &con, double lb, double ub, Context ctx)

Not used?

inline void PropagateResult(NotConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(AndConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(OrConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(IfThenConstraint &con, double lb, double ub, Context ctx)
template<class Array3>
inline void PropagateIfThenResultIntoCondition(Array3 args, Context ctx)

Context of the condition in IfThen.

Parameters
  • args – [condition, then, else] result variables

  • ctx – context of the overall expression

inline void PropagateResult(ImplicationConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(AllDiffConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(NumberofConstConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(NumberofVarConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(PowConstraint &con, double, double, Context ctx)
inline void PropagateResult(LogConstraint &con, double, double, Context ctx)
inline void PropagateResult(LogAConstraint &con, double, double, Context ctx)
inline void PropagateResult(ExpConstraint &con, double, double, Context ctx)
inline void PropagateResult(ExpAConstraint &con, double, double, Context ctx)
inline void PropagateResult(CondLinConEQ &con, double lb, double ub, Context ctx)
inline void PropagateResult(CondQuadConEQ &con, double lb, double ub, Context ctx)
template<class Body, int kind>
inline void PropagateResult(ConditionalConstraint<AlgebraicConstraint<Body, AlgConRhs<kind>>> &con, double lb, double ub, Context ctx)
template<class Args>
inline void PropagateResult2Args(const Args &vars, double lb, double ub, Context ctx)

Propagate given bounds & context into arguments of a constraint.

The default template assumes it just a vector of variables.

Parameters

lb, ub – bounds for each variable

inline void PropagateResult2Args(const LinTerms &lint, double lb, double ub, Context ctx)

Specialize: propagate result into LinTerms.

inline void PropagateResult2Args(const QuadAndLinTerms &qlt, double lb, double ub, Context ctx)

Specialize: propagate result into QuadAndLinTerms.

inline void PropagateResult2QuadAndLinTerms(const QuadAndLinTerms &qlt, double lb, double ub, Context ctx)

Propagate result into QuadAndLinTerms.

inline void PropagateResult2LinTerms(const LinTerms &lint, double, double, Context ctx)

Propagate result into LinTerms.

template<class Vec>
inline void PropagateResult2Vars(const Vec &vars, double lb, double ub, Context ctx)

Propagate given bounds & context into a vector of variables.

Parameters

lb, ub – bounds for each variable

inline void PropagateResult2QuadTerms(const QuadTerms &quadt, double, double, Context ctx)

Propagate result into QuadTerms.

template<class Impl>
class mp::Constraints2Expr
#include <constr_2_expr.h>

A mix-in base class facilitating “inlining” of some functional constraints into expression trees.

Subclassed by mp::FlatConverter< Impl, ModelAPI, FlatModel< > >, mp::FlatConverter< Impl, ModelAPI, FlatModel >

Public Functions

template<class Con>
inline void ConsiderMarkingResultAndArgVars(const Con &con, int i, ExpressionAcceptanceLevel eal)

Consider marking the result and argument variables as “explicit variables” (not expressions)

template<class Con>
inline void ConsiderMarkingArgumentsAsVars(const Con &con, int i, ExpressionAcceptanceLevel eal)

Generic request to consider marking arguments.

Protected Functions

template<class Body, class RhsOrRange>
inline void DoMarkArgsAsVars(const AlgebraicConstraint<Body, RhsOrRange>&, int)

Algebraic cons: no marking (when NLConstraint accepted?)

template<class Expr>
inline void DoMarkArgsAsVars(const ComplementarityConstraint<Expr> &cc, int)

Complementarity: only mark the var (NL accepts expressions for the expression part)

template<class Con>
inline void DoMarkArgsAsVars(const Con &con, int)

Generic arguments marking call.

Private Members

std::function<void(int)> MarkVar_ = [this](int v){     MPD( MarkAsResultVar(v) );}

(Argument) variable visitor

template<class Value>
struct mp::AlgebraicExpression::ConstructorHelper
#include <expr_algebraic.h>

Helper to construct AlgebraicExpression to represent something special.

Parameters

Value – stored value type

Public Members

Value v
class mp::ConstraintKeeper::Container
#include <constr_keeper.h>

Container for a single constraint.

Public Functions

inline Container(int d, Constraint &&c) noexcept
inline int GetDepth() const

Depth in redef tree.

inline bool IsBridged() const

Bridged (reformulated or just unused.) If only reformulated, can still be checked for solution correctness.

inline void MarkAsBridged()

Mark as bridged.

inline bool IsUnused() const

Unused (should not be checked)

inline void MarkAsUnused()

Mark as unused.

inline const Constraint &GetCon() const

Get the flat constraint, const &.

inline Constraint &GetCon()

Get the flat constraint &.

Private Members

FlatExprType con_
int depth_ = 0
bool is_bridged_ = false
bool is_unused_ = false
class rst::ContentHandler
#include <rstparser.h>

Public Functions

virtual ~ContentHandler()
virtual void StartBlock(BlockType type) = 0
virtual void EndBlock() = 0
virtual void HandleText(const char *text, std::size_t size) = 0
virtual void HandleDirective(const char *type) = 0
class mp::Context
#include <context.h>

Expression context.

Considering the relation (result) <-> (Expression):

  • CTX_POS: expression is implied by the boolean result

  • CTX_NEG: expression’s negation is implied by the neg result

  • CTX_MIX: expression is equivalent to the result variable

Public Types

enum CtxVal

Possible values.

Values:

enumerator CTX_NONE
enumerator CTX_POS
enumerator CTX_NEG
enumerator CTX_MIX

Public Functions

inline Context(CtxVal v = CTX_NONE) noexcept

Construct.

inline bool IsNone() const

Is CTX_NONE?

inline bool IsProperSubsetOf(Context other) const

Is a proper subset of other?

inline bool HasPositive() const

Has CTX_POS?

inline bool HasNegative() const

Has CTX_NEG?

inline bool IsPositive() const

Is CTX_POS?

inline bool IsNegative() const

Is CTX_NEG?

inline bool IsMixed() const

Has CTX_MIX?

inline CtxVal GetValue() const

Get value.

inline Context operator+()

Positivize.

inline Context operator-()

Negate.

inline Context &Add(Context ct)

Add (merge) new context.

Private Members

CtxVal value_ = CTX_NONE
template<class MCType, class Con, template<class> class CvtBase>
class Convert1
#include <cones.h>

Abstract converter for a single constraint.

Parameters
  • MCType – ModelConverter, e.g., FlatConverter.

  • Con – the source constraint type.

  • CvtBase – another class providing conversion methods DoRun for quadratic and linear constraints.

template<class MCType, class Body, template<class> class CvtBase>
class mp::Convert1<MCType, AlgebraicConstraint<Body, AlgConRange>, CvtBase> : public CvtBase<MCType>
#include <cones.h>

Converter for a single algebraic inequality constraint.

Receives range constraints and proceeds if they are inequalities.

Public Types

using ConType = AlgebraicConstraint<Body, AlgConRange>

Constraint type.

Public Functions

inline Convert1(MCType &mc)

Constructor.

inline bool operator()(const ConType &con, int i)

Run.

template<class MCType, class Body, int sens, template<class> class CvtBase>
class mp::Convert1<MCType, AlgebraicConstraint<Body, AlgConRhs<sens>>, CvtBase> : public CvtBase<MCType>
#include <cones.h>

Converter for a single algebraic inequality constraint.

Proper inequality constraints.

Public Types

using ConType = AlgebraicConstraint<Body, AlgConRhs<sens>>

The constraint type.

Public Functions

inline Convert1(MCType &mc)

Constructor.

inline bool operator()(const ConType &con, int i)

Run.

template<class MCType>
class mp::Convert1ExpC : public mp::MCKeeper<MCType>
#include <cones.h>

Declare base converter into exp cones.

Converter for a single linear / quadratic inequality constraint into an exponential cone.

Generic, receives only body and sense.

Public Types

using MCType = MCType

Typedef MCType.

Public Functions

inline Convert1ExpC(MCType &mc)

Constructor.

Protected Types

using RhsTraits = SubexprTraits<2>

RHS.

Protected Functions

inline bool DoRun(const QuadAndLinTerms &body, int sens, double rhs)

DoRun.

Body: quadratic.

Accept non-(+-1) coefficients.

Parameters
  • body – quadratic constraint body.

  • sens – -1 for <=, 1 for >=.

  • rhs – constraint’s rhs.

Returns

true iff converted.

inline bool DoRun(const LinTerms &lt, int sens, double rhs)

DoRun.

Body: linear, ax >= b exp(cz / b)

Accept non-(+-1) coefficients.

Parameters
  • sens – -1 for <=, 1 for >=.

  • rhs – constraint’s rhs.

Returns

true iff converted.

inline RhsTraits ClassifyRhsLin(double b, int v)

The RHS is just b * (v=exp(z))?

inline RhsTraits ClassifyRhsQuadr(double b, int y, int v1)

The RHS is by * (v1 = exp( v2 = cz / by )) or by * (v1 = exp( v2 = c / by ))? In our case, c/by is stored as [constvar=c/b]/y.

inline bool AddExpCone(const LinTerms &lt, double cterm, int lt_i_skip, int sens, RhsTraits r)

LHS: sens * (lt+cterm [no lt_i_skip element])

inline const MCType &MC() const

Retrieve the MC.

inline MCType &MC()
template<class MCType>
class mp::Convert1QC : public mp::MCKeeper<MCType>
#include <cones.h>

Declare a base converter into quadratic cones.

Converter for a single linear / quadratic inequality constraint into a Quadratic cone.

Generic, receives only body and sense.

Public Types

using MCType = MCType

Typedef MCType.

Public Functions

inline Convert1QC(MCType &mc)

Constructor.

Protected Functions

inline bool DoRun(const QuadAndLinTerms &body, int sens, double rhs)

DoRun.

Body: quadratic.

Accept non-(+-1) coefficients.

Parameters
  • body – quadratic constraint body.

  • sens – -1 for <=, 1 for >=.

  • rhs – constraint’s rhs.

Returns

true iff converted.

inline bool Characterize(const QuadTerms &qpterms, QPTermsTraits &qptt)

Characterize QP terms.

Returns

false iff not suitable

inline bool ProceedQCWithTraits(const QuadAndLinTerms &body, int sens, double rhs, const QPTermsTraits &qptt)

Proceed with a quadratic constraint provided traits.

Cases of StdSOC &#8212; in the “hacked form” x1^2 >= ||xk||^2:

  1. x^2 >= ||y||^2

  2. c^2 >= ||y||^2

  3. x^2 >= ||y||^2 + c^2

  4. 0 >= ||y||^2 + c^2 &#8212; fail?

Cases of RotSOC:

  1. 2xy >= ||z||^2 [ + c^2 ]

  2. 2 c1 y >= ||z||^2 [ + c2^2 ]

Returns

true iff cone added.

inline bool DoRun(const LinTerms &lint, int sens, double rhs)

DoRun.

Body: linear, i.e., var1 (or const) >= var2 (or const). In particular, the following cases.

Standard SOC.

  1. x >= ||y [ | const ]|| (sqrt, abs)

  2. const >= ||y [ | const ]||.

Rotated SOC.

  1. sqrt(k*x1*x2) >= ||z [ | const ]||.

  2. sqrt(k * x2) >= … (one var is const in lhs)

Considering const>=0. Accept non-(+-1) coefficients.

Parameters
  • sens – -1 for <=, 1 for >=.

  • rhs – constraint’s rhs.

Returns

true iff converted.

inline ConeArgs CheckNorm2(int res_var)

Check if the variable is defined by an expression representing ||.

||.

Returns

pair of (coef, var) vectors so that the cone is … >= sqrt(sum{ (coef_i * var*i)^2 })

template<class ConInfo>
inline ConeArgs CheckNorm2_Pow(const ConInfo &ci, int res_var)

Check if the variable is defined by an expression representing sqrt(c1 * x1^2 + …

[ + const ]).

template<class ConInfo>
inline ConeArgs CheckNorm2_Abs(const ConInfo &ci, int res_var)

Check if the variable is defined by an expression representing abs( c1*x1 ).

inline ConeArgs CheckSqrtXnXmNonneg(int res_var)

Check if the variable is defined by sqrt(xN*xM) with xN, xM >= 0.

inline bool ContinueRotatedSOC(const LinTerms &lint, int iX, int iY, const ConeArgs &lhs_args, const ConeArgs &rhs_args)

Continue processing a linear constraint x>=y, if y := ||.

|| and x is sqrt(xN*xM) or sqrt(k*x). Rotated Qcone.

Returns

true iff converted.

inline bool ContinueStdSOC(double cX, int vX, double cY, const ConeArgs &rhs_args)

Continue processing a linear constraint cX*x >= cY*y, if y := ||.

|| and x is not sqrt(xN*xM). Standard Qcone.

Returns

true iff converted.

inline bool AddRotatedQC(const QuadTerms &qpterms, const LinTerms &lint, double rhs, int iDiffVars)

Add rotated cone from pure-quadratic constraint.

inline bool AddStandardQC(const QuadTerms &qpterms, int iSame1, double rhs = 0.0, double rhs2 = 0.0)

Add standard cone from pure-quadratic constraint.

Parameters
  • iSame1 – if <0, use new fixed variable.

  • rhs – square of the new value if iSame1<0, i.e., the constraint is rhs >= ….

  • rhs2 – … >= … + rhs2

inline const MCType &MC() const

Retrieve the MC.

inline MCType &MC()
class mp::internal::TextReader::CopyableLocale : public mp::internal::Locale

Public Functions

inline CopyableLocale()
inline CopyableLocale(const CopyableLocale&)
inline CopyableLocale &operator=(const CopyableLocale&)
inline double strtod(const char *&str) const
class mp::pre::CopyLink : public mp::pre::BasicLink
#include <valcvt-link.h>

A specific link: each entry just copies a range of values.

Useful to transfer values between NL and internal model, internal model and solver, and in conversions preserving all values. Feature: copies values without comparing with existing values, in contrast to other links using Set() method. This is useful for objectives which use both CopyLink and One2ManyLink’s, to retrieve objective values and not max them out on duals, etc.

Public Types

using LinkEntry = std::pair<NodeRange, NodeRange>

Single link entry, stores src + dest ranges.

using CollectionOfEntries = std::deque<LinkEntry>

Collection of entries.

using ItemRangeList = std::vector<NodeRange>

Typedef item container.

Public Functions

inline CopyLink(ValuePresolver &pre)

Constructor.

inline virtual const char *GetTypeName() const override

Type name.

inline void AddEntry(LinkEntry be)

Add entry.

Instead of a new entry, tries to extend the last one if exists

inline virtual void ExportEntryItems(EntryItems &ei, int i) const override

Get source/target nodes for a given link entry.

This is used for graph export

Protected Functions

template<class T>
inline void CopySrcDest(LinkIndexRange ir)

Copy src -> dest for index range ir.

template<class T>
inline void CopyDestSrc(LinkIndexRange ir)

Copy src <- dest for index range ir. Loop backwards.

inline void RegisterLinkIndex(int i)

Add a range of link entries to the Presolver’s list.

Every derived link should call either of the next two methods whenever adding a link entry. Version 1: add single link

inline void RegisterLinkIndexRange(LinkIndexRange)

Version 2: add a range of links.

Implement link range registration in global Presolver.

Private Members

CollectionOfEntries entries_
template<class ModelConverter>
class mp::CountConverter_MIP : public mp::BasicFuncConstrCvt<CountConverter_MIP<ModelConverter>, ModelConverter>
#include <count.h>

Converts count() for MIP.

Public Types

using Base = BasicFuncConstrCvt<CountConverter_MIP<ModelConverter>, ModelConverter>

Base class.

using ItemType = CountConstraint

Converted item type.

Public Functions

inline CountConverter_MIP(ModelConverter &mc)

Constructor.

inline void Convert(const ItemType &cc, int)

Convert in any context.

inline void Convert(const ItemType &item, int i)

Generic Convert(), distinguishes context & result variable.

Distinguish positive and negative context because if only one of these is necessary, significant model reduction can be achieved in certain cases.

Responsible for adding presolve links, if any

The Impl can reimplement this

Parameters
  • item – the item to be converted

  • i – item index, used to create a presolve link

inline void ConvertCtxNeg(const ItemType &item, int)

Convert in negative context.

inline void ConvertCtxPos(const ItemType &item, int)

Convert in positive context.

inline const ModelConverter &GetMC() const

Reuse the stored ModelConverter.

inline ModelConverter &GetMC()

Reuse the stored ModelConverter.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

template<class Args, class Params, class NumOrLogic, class Id>
class mp::CustomFunctionalConstraint : public mp::FunctionalConstraint, public NumOrLogic, public Id
#include <constr_base.h>

A functional constraint with given arguments and further info as parameters.

Parameters
  • Args – arguments type

  • Params – parameters type

  • NumOrLogic – base class defining a numeric or logic constraint

  • Id – a struct with GetTypeName()

Public Types

using Arguments = Args

Arguments typedef.

using Parameters = Params

Parameters typedef.

Public Functions

CustomFunctionalConstraint() = default

Default constructor.

inline CustomFunctionalConstraint(Arguments args) noexcept

Construct from arguments only.

inline CustomFunctionalConstraint(Arguments args, Parameters prm) noexcept

Construct from arguments and parameters Might need to use explicit types when using initializer lists, in order to distinguish from the next 2 constructors.

inline CustomFunctionalConstraint(int varr, Arguments args) noexcept

Construct from resvar and arguments.

If Arguments = VarArray1, distinguish from the previous constructor by putting first int in just one {}

inline const Arguments &GetArguments() const

Get const Arguments&.

inline Arguments &GetArguments()

Get Arguments&.

inline const Parameters &GetParameters() const

Get const Parameters&.

inline Parameters &GetParameters()

Get Parameters&.

template<class VarVec>
Violation ComputeViolation(const VarVec &x) const

Compute violation.

Should be here, after ComputeViolation() is specialized for some constraints.

inline int GetResultVar() const

Reuse GetResultVar()

inline bool operator==(const FunctionalConstraint &dc) const

Basic operator==.

inline bool HasResultVar() const

Has result var (is functional)? We don’t store this info in the type (yet.)

inline int GetResultVar() const

Get result variable.

inline void SetResultVar(int v)

Set result variable.

inline Context GetContext() const

Get it.

inline void SetContext(Context c) const

Set it.

inline void AddContext(Context c)

Add context.

inline void AddContext(Context) const

Add (merge) context, if meaningful.

inline const char *GetName() const

Constraint name.

inline const char *name() const

Constraint name.

inline void SetName(std::string nm)

Set constraint name.

template<class VarInfo>
inline Violation ComputeViolation(const VarInfo&) const

Compute violation.

Public Static Functions

static inline const char *GetTypeName()

Constraint type name for messages.

static inline constexpr bool UsesContext()

Whether context is meaningful.

Private Members

Args args_
Params params_
struct mp::NLHandler::DblSuffixHandler
#include <nl-reader.h>

A class (struct) that receives notifications of double suffix values.

Public Functions

inline void SetValue(int index, double value)

Receives notification of a suffix value.

struct mp::DefaultFlatModelParams
#include <converter_model.h>

Public Types

using Var = int

Public Static Functions

static inline constexpr Var VoidVar()
class mp::NLWriter2::DefVarWriter
#include <nl-writer2.h>

Writer of a defined variable.

Public Functions

DefVarWriter(NLWriter2 &nlw, int nnzlin)

Construct.

SparseDblVecWriter GetLinExprWriter()

Write entries c*var[v] to the linear part of the defining expression.

All nnz entries should be written before the nonlinear expression. This method can be called only once.

ExprArgWriter GetExprWriter()

Retrieve the nonlinear expression writer.

Should be used after the linear expression.

Private Members

int nnzlin_
NLWriter2 &nlw_
class mp::NLWriter2::DefVarWriterFactory
#include <nl-writer2.h>

Write a sequence of defined variables, for example, all such used in a certain constraint.

Public Functions

inline DefVarWriterFactory(NLWriter2 &nlw, int k)

Construct.

For the meaning of k, see NLFeeder.

DefVarWriter StartDefVar(int index, int nnz, const char *descr = "")

Start writing a defined variable.

Parameters
  • index – defined variable index, used to reference it in subsequent expression graphs. Thus, the index should be >= num_vars, < num_vars+num_common_exprs. Providing the index explicitly, because classical NL likes special order of defined variables.

  • nnz – number of nonzeros in the linear part.

  • descr – meta-information - what is this variable, for example, “nl(t[2])”. Providing it here because it’s not included in ColNames().

Returns

A callback object writing a single defined variable.

Private Members

NLWriter2 &nlw_
int k_
template<class ModelConverter>
class mp::DivConverter_MIP : public mp::BasicFuncConstrCvt<DivConverter_MIP<ModelConverter>, ModelConverter>
#include <div.h>

Converts DIV (float division) for MIP.

Public Types

using Base = BasicFuncConstrCvt<DivConverter_MIP<ModelConverter>, ModelConverter>

Base class.

using ItemType = DivConstraint

Converted item type.

Public Functions

inline DivConverter_MIP(ModelConverter &mc)

Constructor.

inline void Convert(const ItemType &dc, int)

Convert in both contexts (full reification)

inline void Convert(const ItemType &item, int i)

Generic Convert(), distinguishes context & result variable.

Distinguish positive and negative context because if only one of these is necessary, significant model reduction can be achieved in certain cases.

Responsible for adding presolve links, if any

The Impl can reimplement this

Parameters
  • item – the item to be converted

  • i – item index, used to create a presolve link

inline void ConvertCtxNeg(const ItemType &item, int)

Convert in negative context.

inline void ConvertCtxPos(const ItemType &item, int)

Convert in positive context.

inline const ModelConverter &GetMC() const

Reuse the stored ModelConverter.

inline ModelConverter &GetMC()

Reuse the stored ModelConverter.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

Protected Functions

inline void ConvertWithConstDivisor(const ItemType &dc)

Convert with constant divisor.

inline void ConvertWithNonConstDivisor(const ItemType &dc)

Convert with non-constant divisor.

struct mp::BasicSolver::DoubleFormatter
#include <solver-base.h>

Formats a double-prec value.

Public Members

double value
int precision

Friends

inline friend void format(fmt::BasicFormatter<char> &f, const char*, DoubleFormatter df)
struct mp::internal::NLReader::DoubleReader

Public Functions

inline double operator()(Reader &r) const
template<class ProblemBuilder>
class mp::EasyModeler
#include <easy-modeler.h>

This class facilitates C++ operator overloading and other convenient stuff for mp expressions and ProblemBuilder functionality.

Public Types

using Builder = ProblemBuilder
using MP_NumExpr = typename Builder::NumericExpr

Public Functions

inline EasyModeler(ProblemBuilder &bld)
inline std::vector<NumExpr> AddVars(int nvars, double lb, double ub, var::Type type = var::CONTINUOUS)

Model building: variables.

inline std::vector<int> GetVarIndices(std::vector<NumExpr> &vars)

Variable indices.

inline Builder::MutAlgebraicCon AddAlgCon(double lb, NumExpr expr, double ub)

Model building: constraints.

Protected Functions

inline const Builder &GetBuilder() const
inline Builder &GetBuilder()

Private Members

Builder &pb_
class mp::EExpr : public mp::AlgebraicExpression<QuadAndLinTerms>
#include <eexpr.h>

Result expression type for expression conversions.

Public Types

using BodyType = QuadAndLinTerms

Typedef BodyType.

using Constant = ConstructorHelper<double>

Helper “constant type”.

using Variable = ConstructorHelper<int>

Helper “variable type”.

Public Functions

EExpr() = default

Default constructor.

inline EExpr(LinTerms lt)

Construct from LinTerms.

inline EExpr(Constant c)

Constructor from the Constant helper.

inline EExpr(Variable v)

Construct from the Variable helper.

inline EExpr(double c, int i)

Construct from c * var[i].

inline bool is_constant() const

Whether AlgebraicExpression represents a constant.

inline bool is_variable() const

true when constant=0 and 1 variable with coef 1.0

inline bool is_affine() const

if affine

inline const QuadAndLinTerms &GetBody() const

Get the body, const.

inline QuadAndLinTerms &GetBody()

Get the body.

inline const QuadAndLinTerms &GetArguments() const

Get the body, const.

inline QuadAndLinTerms &GetArguments()

Get the body.

inline const QuadAndLinTerms &GetAlgConBody() const

Get the body (variable terms) of a corresponding algebraic constraint.

inline double constant_term() const

The constant term.

inline void constant_term(double v)

Set constant term.

inline void add_to_constant(double a)

Add to constant.

inline double ComputeValue(const VarInfo &x) const

Compute value given a dense vector of variable values.

inline void negate()

Negate the ae.

inline void add(const AlgebraicExpression &ae)

Add another ae.

inline void add(const QuadAndLinTerms &qlt)

add body

inline void add(const LinTerms &le)

Add another LinTerms.

inline void add(const QuadTerms &li)
inline void subtract(AlgebraicExpression ae)

Subtract another ae.

inline void subtract(QuadTerms &&ae)
inline void operator*=(double n)

Multiply by const.

inline bool operator==(const AlgebraicExpression &ae) const

operator==

inline bool operator==(const QuadAndLinTerms &qlc) const

Test equality.

inline bool operator==(const LinTerms &lt) const

operator== for hashing and testing

inline bool operator==(const QuadTerms &qt) const

Testing API.

inline const LinTerms &GetLinTerms() const

Get LinTerms, const.

inline LinTerms &GetLinTerms()

Get LinTerms.

inline const QuadTerms &GetQPTerms() const

Get QuadTerms, const.

inline QuadTerms &GetQPTerms()

Get QuadTerms.

inline bool empty() const

empty?

inline bool is_linear() const

is linear?

inline bool is_quadratic() const

Is quadratic?

inline int get_representing_variable() const

return the single variable assuming true==is_variable()

inline bool is_normalized() const

Is normalized? Assume sorted.

inline void sort_terms()

Sort terms.

inline bool equals(const QuadAndLinTerms &qlc) const

Test equality.

inline void add_term(double c, int v)

add_term(c, v)

inline void add_term(double coef, int var1, int var2)

add_term(c, v1, v2)

Public Static Functions

static inline std::string GetTypeName()

Name.

Protected Functions

void sort_terms(bool force_sort = false)

This a a NASTY one (when not used).

Use it before adding constraints / objectives. Add same variables, eliminate 0’s. Can be used by LinCon’s etc Gurobi complains when 0’s / repeated entries.

inline bool equals(const LinTerms &lt) const

Equality. Assumes being sorted.

inline bool equals(const QuadTerms &qt) const

Test equality.

inline void add_term(double c, int v)

Add linear term.

inline void add_term(double coef, int var1, int var2)
inline bool check() const

Validate.

inline bool check() const

Validate.

inline size_t size() const

size()

inline int size() const

Size.

inline double coef(size_t i) const

coef[i]

inline double coef(int i) const
inline int var(size_t i) const

var[i]

inline const std::vector<double> &coefs() const

const vec& coefs()

inline const std::vector<double> &coefs() const
inline const std::vector<int> &vars() const

const vec& vars()

inline const double *pcoefs() const

Ptr to coefs.

inline const double *pcoefs() const
inline const int *pvars() const

Ptr to vars.

inline void set_coef(size_t i, double c)

Set coef.

inline void set_coef(int i, double c)
inline void reserve(size_t s)

Reserve size.

inline void reserve(std::size_t num_terms)
template<class Vec>
inline void add_terms(const Vec &v2)

Add terms from a vector of pairs {c, v}.

inline void preprocess()

preprocess / canonicalize

inline int capacity() const

Capacity.

inline const int *pvars1() const
inline const int *pvars2() const
inline const std::vector<int> &vars1() const
inline const std::vector<int> &vars2() const
inline int var1(size_t i) const
inline int var2(size_t i) const
inline void clear()

Clear.

Protected Static Functions

static inline constexpr bool is_linear()

Always linear.

class mp::internal::EndiannessConverter
#include <nl-reader.h>

Converter that changes the input endianness.

Public Functions

template<typename T>
inline T Convert(T value)

Private Functions

inline void Convert(char *data, std::size_t size)
struct mp::pre::BasicLink::EntryItems
#include <valcvt-link.h>

Container of source and target items for a certain link entry.

Used for graph export

Public Members

ItemRangeList src_items_
ItemRangeList dest_items_
class mp::EnvKeeper
#include <env.h>

Facilitate storing a reference to Env to access solver options, output handler, etc.

Subclassed by mp::BasicConverter< Problem >, mp::FlatConverter< Impl, ModelAPI, FlatModel< > >, mp::BasicConverter< Model >, mp::FlatConverter< Impl, ModelAPI, FlatModel >, mp::ModelManagerWithProblemBuilder< Converter >, mp::pre::BasicValuePresolver

Public Functions

inline EnvKeeper(Env &e)

Construct.

inline const Env &GetEnv() const

GetEnv() const.

inline Env &GetEnv()

GetEnv()

Private Members

Env &env_
class mp::Error : public fmt::internal::RuntimeError
#include <error.h>

A general error.

Subclassed by mp::BinaryReadError, mp::OptionError, mp::ReadError, mp::UnsupportedError

Public Functions

inline Error(fmt::CStringRef msg, int c = -1)

Costruct from message formatting arguments?

Construct from message and optional exit code

inline int exit_code() const

The exit code.

Protected Functions

inline Error()
inline void SetMessage(const std::string &message)
inline void init(fmt::CStringRef format_str, fmt::ArgList args)

Private Members

int exit_code_ = EXIT_FAILURE
class mp::ErrorHandler
#include <solver-base.h>

An interface for receiving errors reported via Solver::ReportError.

Subclassed by mp::BasicSolver

Public Functions

virtual void HandleError(fmt::CStringRef message) = 0

Protected Functions

inline virtual ~ErrorHandler()
struct ExampleModel
#include <nlsol_ex_mdl.h>

The ExampleModel struct.

A non-linear model with defined variables. Illustrates variable/constraint order, handling of nonlinearities, order of defined variables and their splitting into linear and non-linear parts.

Public Types

template<class Elem>
using SparseVec = std::vector<std::pair<int, Elem>>

Typedef SparseVec<>

Public Functions

inline mp::NLHeader Header() const

Return NL header.

inline std::vector<int> DefVarsInItem(int i) const

For some non-linear solvers (MINOS) it is necessary to provide defined variables, which are used in a single obj/con, just before that.

This info is returned here:

Parameters

i – i<0 for obj -i-1, i>0 for con i-1, i=0 for all other defvars.

Returns

list of defined variables for i.

template<class EWriter>
inline void WriteDVarExpr(int i, EWriter &ew) const

Write dvar expressions.

template<class EWriter>
inline void WriteConExpr(int i, EWriter &ew) const

Write constraint non-linear expressions.

template<class EWriter>
inline void WriteObjExpr(EWriter &ew) const

Public Members

double var_lb[n_var] = {0, 1.4}

Variables.

Put y first because it participates non-linearly both in constraints and the objective. This might be assumed by some NL solvers.

double var_ub[n_var] = {INFINITY, 30}
const char *var_name[n_var] = {"y", "x"}
double dvar_linpart[n_dvar][n_var] = {{0, 0}, {-5, 3}, {4, 0}, {2, 1}}
const char *dvar_name[n_dvar] = {"nl(t3)", "t2", "t3", "t1"}
double con_lb[n_con] = {-INFINITY, -30, -4}

Algebraic constraint bounds.

Constraints are reordered: nonlinear first. If we had logical constraints, they’d go last (represented by expressions only.)

double con_ub[n_con] = {119, INFINITY, 300}
const char *con_name[n_con] = {"C1_t2", "C2_t1t2t3", "C0_lin"}
SparseVec<double> con_linpart[n_con] = {{{0, 102}, {1, -53}}, {{0, 0}, {1, 0}}, {{0, -17}, {1, 5}}}

Algebraic constraints: linear parts.

Linear parts (columns of the Jacobian) are presented sparse, but should include entries which can become nonzero in the Jacobian. Thus, for C2_t1t2t3 we transmit the 0 elements.

In the linear part of C1_t2 we substitute t2. We could have put it into the nonlinear expression.

int col_sizes[n_var - 1] = {3}

Sizes of all Jacobian columns except the last.

int n_con_nz = 6
int obj_sense = 0

Obj sense: min.

SparseVec<double> obj_linpart = {{0, 17}, {1, 14}}

Objective: linear part.

Similar to the Jacobian, need all elements which can become nonzero.

We substitute t2 and the linear part of t3 here.

const char *obj_name = "Obj_t2t3"
int n_obj_nz = 2
double ini_x[n_var] = {0.11, 1.5}

Primal initial guess.

Suffix suf[n_suf] = {{"zork", 1, {5, 0, 0}}}
std::vector<double> sol_y_
std::vector<double> sol_x_
int objno_ = -2
int solve_result_ = -1
std::map<std::pair<std::string, int>, std::vector<double>> suf_out_

Public Static Attributes

static constexpr int n_var = 2
static constexpr int n_con = 3
static constexpr int n_obj = 1
static constexpr int n_dvar = 4

Defined variables.

It proves essential (IPOPT, MINOS) to split those defined variables, whose linear parts can be substituted into the constraints. In this example, this is done for t3: the non-linear part is extracted into a new defined variable nl(t3). Note that x, y are swapped!

static constexpr int n_suf = 1
class ExampleNLFeeder : public mp::NLFeeder<ExampleModel, void*>
#include <nlsol_ex_nl.h>

NLFeeder implementation for the nlsol_ex example.

Public Types

typedef void *Expr

The expression type.

Public Functions

inline ExampleNLFeeder(const ExampleModel &mdl, bool binary)

Construct.

inline mp::NLHeader Header()

Provide NLHeader.

This method is called first.

NLHeader summarizes the model and provides some technical parameters, such as text/binary NL format.

inline bool WantNLComments() const

NL comments?

inline const char *ObjDescription(int i)
inline int ObjType(int)
template<class ObjGradWriter>
inline void FeedObjGradient(int i, ObjGradWriter &gw)
template<class ObjExprWriter>
inline void FeedObjExpression(int i, ObjExprWriter &ew)
template<class DefVarWriterFactory>
inline void FeedDefinedVariables(int i, DefVarWriterFactory &dvw)
template<class VarBoundsWriter>
inline void FeedVarBounds(VarBoundsWriter &vbw)
template<class ConBoundsWriter>
inline void FeedConBounds(ConBoundsWriter &cbw)
inline const char *ConDescription(int i)
template<class ConLinearExprWriter>
inline void FeedLinearConExpr(int i, ConLinearExprWriter &clw)
template<class ConExprWriter>
inline void FeedConExpression(int i, ConExprWriter &ew)
template<class ColSizeWriter>
inline void FeedColumnSizes(ColSizeWriter &csw)
template<class IGWriter>
inline void FeedInitialGuesses(IGWriter &igw)
template<class SuffixWriterFactory>
inline void FeedSuffixes(SuffixWriterFactory &swf)
template<class RowObjNameWriter>
inline void FeedRowAndObjNames(RowObjNameWriter &wrt)
template<class ColNameWriter>
inline void FeedColNames(ColNameWriter &wrt)

Provide variable names.

inline int OutputPrecision() const

The maximum number of significant digits written.

The default value requests full precision, which might be the shortest representation that, when converted to binary and properly rounded, will give exactly the binary value stored in the computer.

inline bool WantBoundsFirst() const

Write bounds first? The default is yes in AMPL, controlled by (the value of option nl_permute) & 32 (the bit is 0 for yes).

Changing this option is deprecated, see https://netlib.org/ampl/changes.

inline int WantColumnSizes() const

Want Jacobian column sizes? Required by some nonlinear solvers.

Options: 0 - none, 1 - cumulative, 2 - non-cumulative. This option controls how ColSizeWriter writes the provided sizes (which should be non-cumulative).

inline void FeedObjGradient(int i, ObjGradWriterFactory&)

Feed gradient for objective i.

Should include entries for all potentially nonzero elements (sparsity pattern).

Implementation skeleton: if (obj_grad[i].size()) { auto svw = svwf.MakeVectorWriter(obj_grad[i].size()); for (size_t j=0; j<obj_grad.size(); ++j) svw.Write(obj_grad[j].var_index, obj_grad[j].coef); }

inline void FeedLinearConExpr(int i, ConLinearExprWriterFactory&)

Feed the linear part of algebraic constraint i.

For smooth solvers, should contain entries for all potential nonzeros (Jacobian sparsity pattern).

Implementation skeleton: if (con_grad[i].size()) { auto sv = svw.MakeVectorWriter(con_grad[i].size()); for (size_t j=0; j<con_grad.size(); ++j) sv.Write(con_grad[j].var_index, con_grad[j].coef); }

inline void FeedExpr(Expr e, ExprWriter&)

Feed native expression.

This method is recursively called from NLWriter, when Feeder uses ExprWriter::EPut(). Feeder should not call this method itself.

Details of ExprWriter: see NLWriter2.

inline void FeedPLSOS(PLSOSWriter&)

The below feature is for AMPL’s internal linearization of piecewise-linear functions.

For user-definable SOS constraints, use suffixes .sosno/.ref.

The below is a feeder interface for .sos/.sosref suffixes. The feeder can provide 3 sparse vectors:

  • .sos for variables: Each nonzero value defines SOS group number. Negative means SOS Type 2, positive - SOS Type 1.

  • .sos for constraints: Each nonzero value denotes a constraint used in a linearization of an SOS. The constraint can be deleted by the solver driver if using solver’s SOS.

  • .sosref for variables: SOS weights. Variables participating in an SOS having zero weights are involved in linearization and can be deleted if the solver accepts SOS natively.

Implementation: auto sosv = plsos.StartSOSVars(nvsos); for (int i=0; i<nvsos; ++i) sosv.Write(i, vsos[i]); if (ncsos) { auto sosc = plsos.StartSOSCons(ncsos); for …. } auto sosrefv = plsos.StartSOSREFVars(ac->nsosref); ….

inline FuncDef Function(int i)

Provide definition of function i, i=0..num_funcs-1.

inline void FeedRandomVariables(RandVarWriterFactory&)

  1. RANDOM VARIABLES ///////////////////// Random variables. Undocumented feature. SNL2006. Example: var z >= 0; let z.stage := 1; var x{0..1, 0..1} random := Uniform(0,2); for {i in 0..1, j in 0..1} {let x[i,j].stage := 1;}; display z.stage, x.stage; c: z * sum{i in 0..1, j in 0..1} x[i,j] <= 3 + Sample(Uniform(0,2));

Feed random variables. Indexes: num_vars+num_common_exprs .. num_vars+num_common_exprs+num_rand_vars-1.

Implementation skeleton: for(j = num_vars+num_common_exprs; j < num_vars+num_common_exprs+num_rand_vars; j++) { auto ew = rvw.StartRandVar(j, rand_var_comment(j)); ew.EPut(rand_var_root_expr(j)); }

inline void FeedInitialDualGuesses(IDGWriter&)

Initial dual guesses.

inline void FeedDelRowNames(DelRowNameWriter&)

Provide deleted row names.

inline void FeedUnusedVarNames(UnusedVarNameWriter&)

Provide unused variable names.

inline void FeedFixedVarNames(FixedVarNameWriter&)

Provide {fixed variable, extra info} pairs.

This includes defined eliminated variables.

Implementation: if ((output_desired) && wrt) for (….) wrt << typename Writer::StrStrValue { name[i].c_str(), comment[i].c_str() };

inline void FeedObjAdj(ObjOffsetWriter&)

Provide {obj name, constant term} pairs.

Implementation: if (wrt) for (….) wrt << typename Writer::StrDblValue { name[i].c_str(), (double)obj_offset[i] };

Protected Functions

inline const ExampleModel &Model() const
template<class GradWriterFactory, class SparseVec>
inline void WriteSparseVec(GradWriterFactory &gw, const SparseVec &vec)

Write sparse vector.

template<class GradWriterFactory, class DenseVec>
inline void WriteDense2Sparse(GradWriterFactory &gw, const DenseVec &vec)

Write dense vector as sparse, using provided writer factory.

template<class DenseVec>
inline int CountNNZ(const DenseVec &vec)

Count nnz.

template<class GradWriter, class DenseVec>
inline void WriteDense2Sparse_Pure(GradWriter &gw, const DenseVec &vec)

Write dense vector as sparse, given pure vector writer.

template<class GradWriter, size_t n>
inline void WriteDense2Sparse_Pure(GradWriter &gw, const double (&vec)[n])

Write dense vector as sparse, given pure vector writer.

Private Members

const ExampleModel &mdl_
bool binary_ = {true}
class ExampleSOLHandler : public mp::SOLHandler
#include <nlsol_ex_sol.h>

SOLHanlder2 implementation for the nlsol_ex example.

Public Functions

inline ExampleSOLHandler(ExampleModel &mdl)

Construct.

inline mp::NLHeader Header() const

The NLHeader used to write the NL file.

inline void OnSolveMessage(const char *s, int nbs)

Receive solve message.

The message always ends with ‘

’.

Parameters

nbs – number of backspaces in the original solve message. So many characters should be skipped from the message if printed straightaway. AMPL solver drivers can supply the message with initial backspaces to indicate that so many characters should be skipped when printing. For example, if the driver prints MINOS 5.51: and exits, and the message starts with that again, this part should be skipped just now.

inline int OnAMPLOptions(const AMPLOptions&)

Can be ignored by external systems.

Returns

non-zero to stop solution input.

template<class VecReader>
inline void OnDualSolution(VecReader &rd)

Dual values for algebraic constraints, if provided in the solution.

Number of values <= NumAlgCons(). Implementation:

duals.reserve(rd.Size()); while (rd.Size()) duals.push_back(rd.ReadNext());

template<class VecReader>
inline void OnPrimalSolution(VecReader &rd)

Variable values, if provided.

Number of values <= NumVars().

inline void OnObjno(int on)

Receive notification of the objective index used by the driver (solver option ‘objno’).

inline void OnSolveCode(int sr)

Receive notification of the solve code.

template<class SuffixReader>
inline void OnIntSuffix(SuffixReader &sr)

OnIntSuffix().

For constraints, can include values for logical constraints (after algebraic.) Sparse representation - can be empty (i.e., all values zero.)

const auto& si = sr.SufInfo(); int kind = si.Kind(); int nmax = nitems_max[kind & 3]; const std::string& name = si.Name(); const std::string& table = si.Table(); while (sr.Size()) { std::pair<int, int> val = sr.ReadNext(); if (val.first<0 || val.first>=nmax) { sr.SetError(mp::SOL_Read_Bad_Suffix, “bad suffix element index”); return; } suf[val.first] = val.second; } if (mp::SOL_Read_OK == sr.ReadResult()) // Can check RegisterSuffix(kind, name, table, suf);

template<class SuffixReader>
inline void OnDblSuffix(SuffixReader &sr)

Same as OnIntSuffix(), but sr.ReadNext() returns pair<int, double>

void PrintSolution(const std::string &stub)

Print solution.

Parameters

stub – stub filename used.

template<class VecReader>
inline void OnDualSolution(VecReader &rd)

Dual values for algebraic constraints, if provided in the solution.

Number of values <= NumAlgCons(). Implementation:

duals.reserve(rd.Size()); while (rd.Size()) duals.push_back(rd.ReadNext());

template<class VecReader>
inline void OnPrimalSolution(VecReader &rd)

Variable values, if provided.

Number of values <= NumVars().

template<class SuffixReader>
inline void OnIntSuffix(SuffixReader &sr)

OnIntSuffix().

For constraints, can include values for logical constraints (after algebraic.) Sparse representation - can be empty (i.e., all values zero.)

const auto& si = sr.SufInfo(); int kind = si.Kind(); int nmax = nitems_max[kind & 3]; const std::string& name = si.Name(); const std::string& table = si.Table(); while (sr.Size()) { std::pair<int, int> val = sr.ReadNext(); if (val.first<0 || val.first>=nmax) { sr.SetError(NLW2_SOLRead_Bad_Suffix, “bad suffix element index”); return; } suf[val.first] = val.second; } if (NLW2_SOLRead_OK == sr.ReadResult()) // Can check RegisterSuffix(kind, name, table, suf);

template<class SuffixReader>
inline void OnDblSuffix(SuffixReader &sr)

Same as OnIntSuffix(), but sr.ReadNext() returns pair<int, double>

Protected Functions

inline const ExampleModel &Model() const
inline ExampleModel &Model()

Private Members

ExampleModel &mdl_
class mp::NLWriter2::ExprArgWriter
#include <nl-writer2.h>

Expression argument writer.

An object of this class is returned by FuncPut() and Oput..() of the parent expression’s ExprWriter. This class acts as a proxy for ExprWriter’s of the arguments.

ExprArgWriter(na=1) is passed to write the root of a tree, such as of the tree for a certain constraint or a defined variable, or recursively, for a user expression type, when user calls EPut().

Public Functions

ExprArgWriter(NLWriter2 &nlw, int na)

Construct for na arguments.

~ExprArgWriter()

Destruct. Check that all arguments are written.

void EPut(typename FeederType::Expr e)

Write the next arg as Feeder’s native expression.

This recursively calls Feeder::FeedExpr().

void VPut(int v, const char *descr = "")

Write the next arg as ‘variable reference’.

0 <= index < num_vars is a solver variable; index >= num_vars is a defined variable.

void NPut(double x)

Write numeric constant expression.

void StrPut(const char*)

Write string constant expression.

ExprArgWriter FuncPut(int index, int nArgs, const char *descr = "")

Write the next arg as function call expression.

ExprArgWriter OPut1(int opcode, const char *descr = "")

Write the next arg as AMPL opcode for a unary op.

Returns

1-arg writer.

ExprArgWriter OPut2(int opcode, const char *descr = "")

Write AMPL opcode for a binary op.

ExprArgWriter OPut3(int opcode, const char *descr = "")

Write AMPL opcode for a 3-arg op.

ExprArgWriter OPutN(int opcode, int nArgs, const char *descr = "")

Write AMPL opcode for an iterated op (min, exists, sum, etc).

For a piecewise-linear expression, nArgs should be 2*(N slopes) and the arguments are: break points, slopes, argument variable.

template<class Opcode>
inline ExprArgWriter OPut1(Opcode oc)

Shortcut: OPut1( struct Opcode )

template<class Opcode>
inline ExprArgWriter OPut2(Opcode oc)

Shortcut: OPut2( struct Opcode )

template<class Opcode>
inline ExprArgWriter OPut3(Opcode oc)

Shortcut: OPut3( struct Opcode )

template<class Opcode>
inline ExprArgWriter OPutN(Opcode oc, int nArgs)

Shortcut: OPutN( struct Opcode, int nArgs )

Protected Functions

ExprWriter AddArg()

Add an argument explicitly.

Returns

the expr writer for the argument. Note that the ..Put. methods transfer their call to the result of an AddArg().

Private Members

NLWriter2 &nlw_
int nargs_
class mp::internal::ExprBase
#include <expr.h>

Class ExprBase.

Subclassed by mp::BasicExpr< expr::FIRST_REFERENCE, expr::LAST_REFERENCE >, mp::BasicExpr< expr::FIRST_LOGICAL_COUNT, expr::LAST_LOGICAL_COUNT >, mp::BasicExpr< FIRST, FIRST >, mp::BasicExpr< expr::STRING >, mp::BasicExpr< expr::CALL >, mp::BasicExpr< expr::NUMBER >, mp::BasicExpr< expr::BOOL >, mp::BasicExpr< K >, mp::BasicExpr< expr::PLTERM >, mp::BasicExpr< FIRST, LAST >

Public Functions

inline expr::Kind kind() const

Returns the expression kind.

inline operator SafeBool() const

Returns a value convertible to bool that can be used in conditions but not in comparisons and evaluates to “true” if this expression is not null and “false” otherwise.

Example: if (e) { /// Do something if e is not null. }

Protected Types

typedef void (ExprBase::* SafeBool)() const

Safe bool type.

Protected Functions

inline const Impl *impl() const

Returns a pointer to the implementation.

BasicExpr exposes impl() as a protected member while impl_ becomes private.

inline ExprBase()
template<typename ExprType>
inline ExprBase(ExprType e)

Protected Attributes

const Impl *impl_

Protected Static Functions

template<typename TargetExpr>
static inline TargetExpr Create(const ExprBase::Impl *impl)

Creates an expression from an implementation.

Private Functions

inline void True() const

A member function representing the true value of SafeBool.

Friends

friend class ExprIterator
struct mp::ProblemBuilder::ExprBuilder

Public Functions

inline void AddArg(ExprType arg)
template<typename Impl, typename Result>
class mp::ExprConverter : public mp::ExprVisitor<Impl, Result>
#include <expr-visitor.h>

Expression converter.

Converts logical count expressions to corresponding relational expressions. For example “atleast” is converted to “<=”.

Public Functions

inline Result VisitAtLeast(LogicalCountExpr e)
inline Result VisitAtMost(LogicalCountExpr e)
inline Result VisitExactly(LogicalCountExpr e)
inline Result VisitNotAtLeast(LogicalCountExpr e)
inline Result VisitNotAtMost(LogicalCountExpr e)
inline Result VisitNotExactly(LogicalCountExpr e)
MP_DEFINE_EXPR_TYPES(internal::ExprTypes)
Result Visit(Expr e)
inline Result VisitUnsupported(Expr e)
inline Result VisitNumeric(NumericExpr e)
inline Result VisitLogical(LogicalExpr e)
inline Result VisitNumericConstant(NumericConstant c)
inline Result VisitVariable(Variable v)
inline Result VisitCommonExpr(CommonExpr e)
inline Result VisitUnary(UnaryExpr e)
inline Result VisitMinus(UnaryExpr e)
inline Result VisitAbs(UnaryExpr e)
inline Result VisitFloor(UnaryExpr e)
inline Result VisitCeil(UnaryExpr e)
inline Result VisitSqrt(UnaryExpr e)
inline Result VisitPow2(UnaryExpr e)
inline Result VisitExp(UnaryExpr e)
inline Result VisitLog(UnaryExpr e)
inline Result VisitLog10(UnaryExpr e)
inline Result VisitSin(UnaryExpr e)
inline Result VisitSinh(UnaryExpr e)
inline Result VisitCos(UnaryExpr e)
inline Result VisitCosh(UnaryExpr e)
inline Result VisitTan(UnaryExpr e)
inline Result VisitTanh(UnaryExpr e)
inline Result VisitAsin(UnaryExpr e)
inline Result VisitAsinh(UnaryExpr e)
inline Result VisitAcos(UnaryExpr e)
inline Result VisitAcosh(UnaryExpr e)
inline Result VisitAtan(UnaryExpr e)
inline Result VisitAtanh(UnaryExpr e)
inline Result VisitBinary(BinaryExpr e)

Visits a binary expression or a function taking two arguments.

inline Result VisitAdd(BinaryExpr e)
inline Result VisitSub(BinaryExpr e)
inline Result VisitLess(BinaryExpr e)
inline Result VisitMul(BinaryExpr e)
inline Result VisitDiv(BinaryExpr e)
inline Result VisitTruncDiv(BinaryExpr e)
inline Result VisitMod(BinaryExpr e)
inline Result VisitPow(BinaryExpr e)
inline Result VisitPowConstBase(BinaryExpr e)
inline Result VisitPowConstExp(BinaryExpr e)
inline Result VisitBinaryFunc(BinaryExpr e)
inline Result VisitAtan2(BinaryExpr e)
inline Result VisitPrecision(BinaryExpr e)
inline Result VisitRound(BinaryExpr e)
inline Result VisitTrunc(BinaryExpr e)
inline Result VisitIf(IfExpr e)
inline Result VisitPLTerm(PLTerm e)
inline Result VisitCall(CallExpr e)
inline Result VisitVarArg(VarArgExpr e)
inline Result VisitMin(VarArgExpr e)
inline Result VisitMax(VarArgExpr e)
inline Result VisitSum(SumExpr e)
inline Result VisitNumberOf(NumberOfExpr e)
inline Result VisitNumberOfSym(SymbolicNumberOfExpr e)
inline Result VisitCount(CountExpr e)
inline Result VisitLogicalConstant(LogicalConstant c)
inline Result VisitNot(NotExpr e)
inline Result VisitBinaryLogical(BinaryLogicalExpr e)
inline Result VisitOr(BinaryLogicalExpr e)
inline Result VisitAnd(BinaryLogicalExpr e)
inline Result VisitIff(BinaryLogicalExpr e)
inline Result VisitRelational(RelationalExpr e)
inline Result VisitLT(RelationalExpr e)
inline Result VisitLE(RelationalExpr e)
inline Result VisitEQ(RelationalExpr e)
inline Result VisitGE(RelationalExpr e)
inline Result VisitGT(RelationalExpr e)
inline Result VisitNE(RelationalExpr e)
inline Result VisitLogicalCount(LogicalCountExpr e)
inline Result VisitImplication(ImplicationExpr e)
inline Result VisitIteratedLogical(IteratedLogicalExpr e)
inline Result VisitExists(IteratedLogicalExpr e)
inline Result VisitForAll(IteratedLogicalExpr e)
inline Result VisitAllDiff(PairwiseExpr e)
inline Result VisitNotAllDiff(PairwiseExpr e)
inline Result VisitStringLiteral(StringLiteral e)
inline Result VisitSymbolicIf(SymbolicIfExpr e)

Private Functions

inline RelationalExpr Convert(LogicalCountExpr e, expr::Kind kind)

Private Members

ExprFactory factory_
class mp::internal::ExprInfo
#include <common.h>

Public Members

int opcode
const char *str

Private Static Attributes

static const ExprInfo INFO[]

Friends

friend int nl_opcode(expr::Kind kind)
friend const char *str(expr::Kind kind)
template<typename ExprType>
class mp::internal::ExprIterator : public std::iterator<std::forward_iterator_tag, ExprType>
#include <expr.h>

An expression iterator.

Public Functions

inline explicit ExprIterator(const ExprBase::Impl *const *p = 0)
inline ExprType operator*() const
inline Proxy operator->() const
inline ExprIterator &operator++()
inline ExprIterator operator++(int)
inline bool operator==(ExprIterator other) const
inline bool operator!=(ExprIterator other) const

Private Members

const ExprBase::Impl *const *ptr_
struct mp::internal::ExprTypes
#include <expr.h>

Public Types

typedef mp::Expr Expr
typedef mp::NumericExpr NumericExpr
typedef mp::LogicalExpr LogicalExpr
typedef mp::NumericConstant NumericConstant
typedef mp::Reference Variable
typedef mp::Reference CommonExpr
typedef mp::UnaryExpr UnaryExpr
typedef mp::BinaryExpr BinaryExpr
typedef mp::IfExpr IfExpr
typedef mp::PLTerm PLTerm
typedef mp::CallExpr CallExpr
typedef mp::IteratedExpr VarArgExpr
typedef mp::IteratedExpr SumExpr
typedef mp::IteratedExpr NumberOfExpr
typedef mp::SymbolicNumberOfExpr SymbolicNumberOfExpr
typedef mp::CountExpr CountExpr
typedef mp::LogicalConstant LogicalConstant
typedef mp::NotExpr NotExpr
typedef mp::BinaryLogicalExpr BinaryLogicalExpr
typedef mp::RelationalExpr RelationalExpr
typedef mp::LogicalCountExpr LogicalCountExpr
typedef mp::ImplicationExpr ImplicationExpr
typedef mp::IteratedLogicalExpr IteratedLogicalExpr
typedef mp::PairwiseExpr PairwiseExpr
typedef mp::StringLiteral StringLiteral
typedef mp::SymbolicIfExpr SymbolicIfExpr

Public Static Functions

template<typename ExprType>
static inline ExprType Cast(Expr e)

Checked cast. See mp::Cast.

template<typename ExprType>
static inline ExprType UncheckedCast(Expr e)

Unchecked cast. See mp::internal::Cast.

template<typename Impl, typename Result>
class mp::ExprVisitor : public mp::BasicExprVisitor<Impl, Result, internal::ExprTypes>
#include <expr-visitor.h>

An expression visitor.

To use ExprVisitor define a subclass that implements some or all of the Visit* methods with the same signatures as the methods in ExprVisitor, for example, VisitDiv(BinaryExpr). Specify the subclass name as the Impl template parameter. Then calling BasicExprVisitor::Visit for some expression will dispatch to a Visit* method specific to the expression type. For example, if the expression is a division then VisitDiv(BinaryExpr) method of a subclass will be called. If the subclass doesn’t contain a method with this signature, then a corresponding method of BasicExprVisitor will be called.

Example: class MyExprVisitor : public ExprVisitor<MyExprVisitor, double> { public: double VisitAdd(BinaryExpr e) { return Visit(e.lhs()) + Visit(e.rhs()); } double VisitConstant(NumericConstant n) { return n.value(); } };

Subclassed by mp::ExprConverter< Impl, EExpr >, mp::ExprConverter< Impl, Result >

Public Functions

MP_DEFINE_EXPR_TYPES(internal::ExprTypes)
Result Visit(Expr e)
inline Result VisitUnsupported(Expr e)
inline Result VisitNumeric(NumericExpr e)
inline Result VisitLogical(LogicalExpr e)
inline Result VisitNumericConstant(NumericConstant c)
inline Result VisitVariable(Variable v)
inline Result VisitCommonExpr(CommonExpr e)
inline Result VisitUnary(UnaryExpr e)
inline Result VisitMinus(UnaryExpr e)
inline Result VisitAbs(UnaryExpr e)
inline Result VisitFloor(UnaryExpr e)
inline Result VisitCeil(UnaryExpr e)
inline Result VisitSqrt(UnaryExpr e)
inline Result VisitPow2(UnaryExpr e)
inline Result VisitExp(UnaryExpr e)
inline Result VisitLog(UnaryExpr e)
inline Result VisitLog10(UnaryExpr e)
inline Result VisitSin(UnaryExpr e)
inline Result VisitSinh(UnaryExpr e)
inline Result VisitCos(UnaryExpr e)
inline Result VisitCosh(UnaryExpr e)
inline Result VisitTan(UnaryExpr e)
inline Result VisitTanh(UnaryExpr e)
inline Result VisitAsin(UnaryExpr e)
inline Result VisitAsinh(UnaryExpr e)
inline Result VisitAcos(UnaryExpr e)
inline Result VisitAcosh(UnaryExpr e)
inline Result VisitAtan(UnaryExpr e)
inline Result VisitAtanh(UnaryExpr e)
inline Result VisitBinary(BinaryExpr e)

Visits a binary expression or a function taking two arguments.

inline Result VisitAdd(BinaryExpr e)
inline Result VisitSub(BinaryExpr e)
inline Result VisitLess(BinaryExpr e)
inline Result VisitMul(BinaryExpr e)
inline Result VisitDiv(BinaryExpr e)
inline Result VisitTruncDiv(BinaryExpr e)
inline Result VisitMod(BinaryExpr e)
inline Result VisitPow(BinaryExpr e)
inline Result VisitPowConstBase(BinaryExpr e)
inline Result VisitPowConstExp(BinaryExpr e)
inline Result VisitBinaryFunc(BinaryExpr e)
inline Result VisitAtan2(BinaryExpr e)
inline Result VisitPrecision(BinaryExpr e)
inline Result VisitRound(BinaryExpr e)
inline Result VisitTrunc(BinaryExpr e)
inline Result VisitIf(IfExpr e)
inline Result VisitPLTerm(PLTerm e)
inline Result VisitCall(CallExpr e)
inline Result VisitVarArg(VarArgExpr e)
inline Result VisitMin(VarArgExpr e)
inline Result VisitMax(VarArgExpr e)
inline Result VisitSum(SumExpr e)
inline Result VisitNumberOf(NumberOfExpr e)
inline Result VisitNumberOfSym(SymbolicNumberOfExpr e)
inline Result VisitCount(CountExpr e)
inline Result VisitLogicalConstant(LogicalConstant c)
inline Result VisitNot(NotExpr e)
inline Result VisitBinaryLogical(BinaryLogicalExpr e)
inline Result VisitOr(BinaryLogicalExpr e)
inline Result VisitAnd(BinaryLogicalExpr e)
inline Result VisitIff(BinaryLogicalExpr e)
inline Result VisitRelational(RelationalExpr e)
inline Result VisitLT(RelationalExpr e)
inline Result VisitLE(RelationalExpr e)
inline Result VisitEQ(RelationalExpr e)
inline Result VisitGE(RelationalExpr e)
inline Result VisitGT(RelationalExpr e)
inline Result VisitNE(RelationalExpr e)
inline Result VisitLogicalCount(LogicalCountExpr e)
inline Result VisitAtLeast(LogicalCountExpr e)
inline Result VisitAtMost(LogicalCountExpr e)
inline Result VisitExactly(LogicalCountExpr e)
inline Result VisitNotAtLeast(LogicalCountExpr e)
inline Result VisitNotAtMost(LogicalCountExpr e)
inline Result VisitNotExactly(LogicalCountExpr e)
inline Result VisitImplication(ImplicationExpr e)
inline Result VisitIteratedLogical(IteratedLogicalExpr e)
inline Result VisitExists(IteratedLogicalExpr e)
inline Result VisitForAll(IteratedLogicalExpr e)
inline Result VisitAllDiff(PairwiseExpr e)
inline Result VisitNotAllDiff(PairwiseExpr e)
inline Result VisitStringLiteral(StringLiteral e)
inline Result VisitSymbolicIf(SymbolicIfExpr e)
template<class Con>
class mp::ExprWrapper
#include <constr_base.h>

Wrap (functional) constraint to represent it as an expression.

(Solver)ModelAPI should only inspect it via the BasicExprModelAPI<>::GetExpr… methods.

Public Types

using FlatConType = Con

Constraint type.

Public Functions

inline ExprWrapper(Con c)

Construct.

inline const Con &GetFlatConstraint() const

Get const & (con)

inline Con &GetFlatConstraint()

Get & (con)

Private Members

Con con_flat_
class mp::NLWriter2::ExprWriter
#include <nl-writer2.h>

Actual expression writer.

Public Functions

inline ExprWriter(NLWriter2 &nlw)

Construct.

void EPut(typename FeederType::Expr e)

Write Feeder’s native expression.

This recursively calls Feeder::FeedExpr().

void VPut(int v, const char *descr = "")

Write expression ‘variable reference’.

0 <= index < num_vars is a solver variable; index >= num_vars is a defined variable.

void NPut(double x)

Write numeric constant expression.

void StrPut(const char*)

Write string constant expression.

ExprArgWriter FuncPut(int index, int nArgs, const char *descr = "")

Write the next arg as function call expression.

ExprArgWriter OPut1(int opcode, const char *descr = "")

Write the next arg as AMPL opcode for a unary op.

Returns

1-arg writer.

ExprArgWriter OPut2(int opcode, const char *descr = "")

Write AMPL opcode for a binary op.

ExprArgWriter OPut3(int opcode, const char *descr = "")

Write AMPL opcode for a 3-arg op.

ExprArgWriter OPutN(int opcode, int nArgs, const char *descr = "")

Write AMPL opcode for an iterated op (min, exists, sum, etc).

For a piecewise-linear expression, nArgs should be 2*(N slopes) and the arguments are: break points, slopes, argument variable.

template<class Opcode>
inline ExprArgWriter OPut1(Opcode oc)

Shortcut: OPut1( struct Opcode )

template<class Opcode>
inline ExprArgWriter OPut2(Opcode oc)

Shortcut: OPut2( struct Opcode )

template<class Opcode>
inline ExprArgWriter OPut3(Opcode oc)

Shortcut: OPut3( struct Opcode )

template<class Opcode>
inline ExprArgWriter OPutN(Opcode oc, int nArgs)

Shortcut: OPutN( struct Opcode, int nArgs )

Private Members

NLWriter2 &nlw_
template<class Converter, class Constraint>
class mp::FCC : public mp::BasicFCC<FCC<Converter, Constraint>, Converter, Constraint>

This is a helper to produce a ‘final’ FC converter avoiding using Impl Then it could be specialized for individual constraint types.

Public Types

using Var = typename Converter::Var

Public Functions

inline FCC(Converter &cvt, Constraint &&fc) noexcept
inline VarOrConst Convert()

Convert array of arguments into a result (var or const), possibly adding extra constraint(s).

Returns

either a constant or a variable

inline void PreprocessArguments()
inline void AddResultVariable()
inline void AddConstraint()

Public Members

PreprocessInfo<Constraint> prepro_

Protected Functions

inline Converter &GetConverter()
inline Constraint &GetConstraint()
inline double lb() const
inline double ub() const
inline var::Type type() const
inline bool ResultIsConstant() const
inline bool ResultVarIsKnown() const
inline bool MapFind()
inline int GetResultVar() const
inline void SetResultVar(int r)

Private Types

using Base = BasicFCC<FCC<Converter, Constraint>, Converter, Constraint>
class mp::StdBackend::FeasrelaxIO

Once Impl allows FEASRELAX, it should check this via feasrelax()

Public Functions

inline operator int() const

Mode!=1: if & how feasrelax should be done.

inline ArrayRef<double> lbpen() const

Penalty vectors.

inline ArrayRef<double> ubpen() const
inline ArrayRef<double> rhspen() const
inline void flag_orig_obj_available()

Call me if orig_obj_value() will be set.

inline double &orig_obj_value()

Access original objective value.

Private Members

int mode_ = 0

——————&#8212; INPUT ——————-&#8212;

std::vector<double> lbpen_

Empty vector means +inf penalties.

std::vector<double> ubpen_
std::vector<double> rhspen_
bool orig_obj_available_ = false

——————&#8212; OUTPUT, filled by Impl –&#8212;

double orig_obj_value_ = 0.0

Friends

friend class StdBackend
class mp::File
#include <nl-utils.h>

A wrapper for file I/O.

Public Functions

inline ~File()

Destructor.

inline File()

Constructor.

inline File(const File &f)

Constructor.

inline File(File &&f)

Constructor.

inline void operator=(const File &f)

copy assign

inline void operator=(File &&f) noexcept

move assign

inline operator bool() const

Check being open for now.

inline bool Open(const char *nm, const char *mode)

Open file.

inline void Close()

Close file.

void Printf(const char *format, ...)

Printf.

inline FILE *GetHandle() const

Obtain handler.

Private Members

FILE *f_ = {nullptr}
template<class BaseBackend>
class mp::FlatBackend : public BaseBackend, public mp::BackendWithValuePresolver
#include <backend_flat.h>

Solver Backends using ModelAPI+FlatConverter should derive from this.

This is a wrapper providing convenient methods to automatically pre- / popstsolve standard suffixes etc

Public Functions

inline Solution GetSolution() override

Default GetSolution() for flat backends.

Invokes postsolver.

inline ArrayRef<double> GetObjectiveValues() override

Redeclare GetObjectiveValues()

inline virtual ArrayRef<double> PrimalSolution()

Separate PrimalSolution() for flat backends.

Returns

empty vector if no primal solution.

inline virtual pre::ValueMapDbl DualSolution()

Separate DualSolution() for flat backends.

Returns

empty map if no dual solution.

inline virtual SensRangesPresolved GetSensRangesPresolved()

Obtain presolved sens info.

inline SensRanges GetSensRanges() override

Postsolve sensitivity info for flat backends.

Currenlty needs con… maps to be correctly populated

Protected Functions

inline pre::ModelValuesInt ReadModelSuffixInt(const ModelSuffixDef<int> &msd)

Convenience feature: Read int suffixes for several entities (var/con/obj).

Returns

suffix value map (can be checked for non-empty with operator bool())

inline pre::ModelValuesDbl ReadModelSuffixDbl(const ModelSuffixDef<double> &msd)

Read double suffixes for several entities (var/con/obj).

Returns

suffix value map (can be checked for non-empty with operator bool())

template<class T>
inline pre::MVOverEl<T> ReadModelSuffix(const ModelSuffixDef<T> &msd)

Implementation of ReadModelSuffix<>

inline void SetValuePresolver(pre::BasicValuePresolver *pPre)
inline const pre::BasicValuePresolver &GetValuePresolver() const
inline pre::BasicValuePresolver &GetValuePresolver()
template<class Impl, class ModelAPI, class FlatModel = FlatModel<>>
class mp::FlatConverter : public mp::BasicFlatConverter, public mp::FlatModel<>, public mp::BoundComputations<Impl>, public mp::ConstraintPreprocessors<Impl>, public mp::ConstraintPropagatorsDown<Impl>, public mp::Constraints2Expr<Impl>, public mp::SolutionChecker<Impl>, public mp::EnvKeeper
#include <converter.h>

FlatConverter: preprocesses and manages flat constraints.

Such constraints might need to be converted to others, which is handled by overloaded methods in derived classes.

Parameters
  • Impl – the final CRTP class

  • ModelAPI – the solver’s model API wrapper

  • FlatModel – internal representation of a flat model

Public Types

using Var = typename FlatModel::Var

Trying to use ‘Var’ instead of bare ‘int’.

using VarArray = std::vector<int>

Array of variable Id’s.

using ConInfo = AbstractConstraintLocation

Typedef ConInfo; constraint location.

using ModelType = FlatModel

The internal flat model type.

using ModelAPIType = ModelAPI

Typedef ModelAPIType. For tests.

using Params = DefaultFlatModelParams
using VarTypeVec = std::vector<var::Type>
using VarNameVec = std::vector<const char*>
using ObjList = std::vector<QuadraticObjective>

List of objectives.

using VarBndVec = std::vector<double>

Typedef VarBndVec.

Public Functions

inline FlatConverter(Env &e)

Construct with Env&.

inline void FixAsTrue(int resvar)

Fix the resulting variable of a logical expression as true and propagate positive ctx.

Currently this happens for all root-context logical constraints, i.e., we create an auxiliary variable which is later fixed to 1.

inline void PropagateResultOfInitExpr(int var, Context ctx)

Reverse propagate result variable of an expression.

inline void PropagateResultOfInitExpr(int var, double lb, double ub, Context ctx)

Reverse propagate result variable of an expression.

inline int Convert2Var(AffineExpr &&ee)

VISITOR ADAPTERS ///////////////////////////////////////// These are called to transform expressions, either by FlatCvt itself, or when flattening NL model.

From an affine expression: Adds a result variable r and constraint r == expr

inline int Convert2Var(QuadraticExpr &&ee)

From a quadratic expression: Adds a result variable r and constraint r == expr.

template<class FuncConstraint>
inline FCC<Impl, FuncConstraint>::VarOrConst AssignResult2Args(FuncConstraint &&fc)

Take FuncConstraint with arguments.

Prefer this over AddConstraint() for mapped functional constraints. If the result of the function can be presolved or is known via map, return it. Otherwise, create a result variable and add the constraint.

Returns

VarOrConst

template<class FuncConstraint>
inline FCC<Impl, FuncConstraint>::Var AssignResultVar2Args(FuncConstraint &&fc)

Same, but always return a variable.

template<class FuncConstraint>
inline void RedefineVariable(int res_var, FuncConstraint &&fc)

Replace functional expression defining a given variable.

inline void IncrementVarUsage(int v)

Variables’ reference counting /////////////////////////////////// Currently only for defined variables ////////////////////////////.

Use “+1” a variable

inline void DecrementVarUsage(int v)

Unuse result variable.

Actually this is to ‘unuse’ the init expression

  • might change naming. Throw if already not used.

inline void FixUnusedDefinedVars()

Fix unused defined vars.

Normally should delete them.

template<class Constraint>
inline void RunConversion(const Constraint &con, int i, int depth)

CUSTOM CONSTRAINTS CONVERSION ////////////////////////////.

RunConversion() of a constraint: Assume mixed context if not set.

template<class Con>
inline ConstraintAcceptanceLevel GetConstraintAcceptance(Con*) const

Query if a constraint type is natively accepted by the solver.

The parameter is only needed for type.

template<class Con>
inline int GetNumberOfAddable(Con*) const

Query the number of addable constraints of type.

template<class Constraint>
inline bool IfHasConversion(const Constraint *c)

Query if the constraint type can be converted.

This method should not be redefined; specialize IfHasCvt_impl instead.

template<class Constraint>
inline bool IfHasCvt_impl(const Constraint*)

Generic query if a constraint type can be converted.

Specialize this method, but normally it’s specialized by INSTALL_CONSTRAINT_CONVERTER.

template<class Constraint>
inline bool IfNeedsConversion(const Constraint &con, int i)

Query if the specific item of the constraint needs to be converted, despite being accepted by the ModelAPI.

For example, Gurobi only accepts Pow with non-negative argument. This method should not be redefined; specialize IfNeedsCvt_impl instead.

template<class Constraint>
inline bool IfNeedsCvt_impl(const Constraint&, int)

Generic query if a constraint needs to be converted, despite being accepted by the ModelAPI.

Specialize this method, or even ConstraintConverter::IfNeedsConversion (see class PowConstExponentConverter_MIP).

template<class Constraint>
inline bool ModelAPIAcceptsAndRecommends(const Constraint *pcon) const

Check whether ModelAPI accepts and recommends the constraint.

template<class Constraint>
inline void Convert(const Constraint &con, int)

Generic adapter for old non-bridged Convert() methods.

New way is to use the i parameter for bridging

template<class Constraint>
inline void Convert(const Constraint&)

By default, we complain about someone trying to convert an unknown constraint.

inline void Convert(const LinearFunctionalConstraint &ldc)

SOME SPECIFIC CONSTRAINT CONVERTERS ///////////////////////////////////// ///////////////////////////.

If backend does not like LFC, we redefine it here

inline void Convert(const QuadraticFunctionalConstraint &qdc)

If backend does not like QFC, we redefine it.

inline pre::NodeRange AddObjective(QuadraticObjective &&qo)

Add objective.

Currently handling quadratic objectives. Its quadratic terms will be empty for linear objectives.

Linking NL objectives straight into solver’s objectives. If any conversions are performed, need to have intermediate nodes, as for constraints

template<class Constraint>
inline pre::NodeRange AddConstraint(Constraint con)

ADD CUSTOM CONSTRAINT, does not propagate result (use AddConstraint_AS_ROOT() otherwise).

Use only for non-mapped constraints. For functional constraints stored __WITH_MAP, use AssignResult(Var)2Args(). Non-functional constraints cannot be unified currently. Takes ownership.

Returns

Node reference for the stored constraint

template<class Constraint>
inline pre::NodeRange AddConstraint_AS_ROOT(Constraint con)

ADD CUSTOM CONSTRAINT and propagate root-ness (use AddConstraint() otherwise).

Use only for non-mapped constraints. For functional constraints stored __WITH_MAP, use AssignResult(Var)2Args(). Takes ownership.

Returns

Node reference for the stored constraint

template<class Constraint>
inline const Constraint &GetConstraint(const ConInfo &ci) const

Retrieve constraint of specified type at location ci.

template<class Constraint>
inline const Constraint &GetConstraint(int i) const

Retrieve constraint of specified type at index i.

inline void MarkAsBridged(const ConInfo &ci)

Mark constraint as reformulated.

inline void MarkAsUnused(const ConInfo &ci)

Mark constraint as unused.

template<class Constraint>
inline pre::NodeRange SelectValueNode(int i)

Select value node i for constraint type Con.

inline void StartModelInput()

Handle start of model input.

inline void FinishModelInput()

Handle end of model input.

inline void CheckLinearCons()

Check linear constraints.

Solvers complain about close-to-0 coefficients, so fail on this in the debug build.

template<class Rhs>
inline void CheckLinearConType()
inline void PresolveNames()

Presolve item names.

template<class Con>
inline void TransferNames2Node(Con *pcon)
inline void FillModelTraits(AMPLS_ModelTraits &mt)

Fill model traits for license check.

To be called after ConvertModel(). KEEP THIS UP2DATE.

inline const ModelAPI &GetModelAPI() const

UTILITIES /////////////////////////////////.

Expose abstract Backend

inline ModelAPI &GetModelAPI()
inline const pre::ValuePresolver &GetValuePresolver() const

Expose ValuePresolver.

inline pre::ValuePresolver &GetValuePresolver()
inline pre::NodeRange MakeFixedVar(double value)
inline pre::NodeRange AddVar(double lb, double ub, var::Type type = var::CONTINUOUS)

Create or find a fixed variable.

inline pre::NodeRange AddVars(const typename BaseFlatModel::VarBndVec &lbs, const typename BaseFlatModel::VarBndVec &ubs, const typename BaseFlatModel::VarTypeVec &types)

Add several variables once.

Note

this is only to be called once for the original vars.

Returns

value node range for them

inline void AddVarNames(std::vector<std::string> names)
inline void AddConNames(std::vector<std::string> names)
inline void AddObjNames(std::vector<std::string> names)
inline pre::ValueNode &GetVarValueNode()

Reuse ValuePresolver’s target nodes for all variables.

template<class Constraint>
inline pre::ValueNode &GetValueNode(Constraint*)

Constraint type’s Value Node.

inline pre::ValueNode &GetObjValueNode()

Reuse ValuePresolver’s target nodes for all objectives.

inline int num_vars() const

Shortcut num_vars()

inline int is_var_original(int i) const

Shortcut is_var_original()

inline double lb(int var) const

Shortcut lb(var)

inline double ub(int var) const

Shortcut ub(var)

template<class VarArray>
inline double lb_array(const VarArray &va) const

lb_array()

template<class VarArray>
inline double ub_array(const VarArray &va) const

ub_array()

inline void set_var_lb(int var, double lb)

Set lb(var)

inline void set_var_ub(int var, double ub)

Set ub(var)

inline void set_var_lb_context(int var, double lb, Context ctx)

Set lb(var), propagate context if functional result.

inline void set_var_ub_context(int var, double ub, Context ctx)

Set ub(var), propagate context.

inline void set_var_bounds_context(int var, double lb, double ub, Context ctx)

Set bounds(var), propagate context.

inline void NarrowVarBounds(int var, double lb, double ub)

Narrow variable domain range.

inline var::Type var_type(int var) const

var_type()

inline bool is_fixed(int var) const

is_fixed()

inline double fixed_value(int var) const

fixed_value()

inline int MakeComplementVar(int bvar)

MakeComplementVar()

inline std::vector<int> AddVars_returnIds(std::size_t nvars, double lb = MinusInfty(), double ub = Infty(), var::Type type = var::CONTINUOUS)

Add vector of variables.

Type: var::CONTINUOUS by default

Returns

vector of the Ids of the new vars

inline bool is_var_integer(int var) const
inline bool HasInitExpression(int var) const

Variable has an init expr?

inline const ConInfo &GetInitExpression(int var) const

Get the init expr.

template<class ConType>
inline const ConType *GetInitExpressionOfType(int var)

Get the init expression pointer.

Returns

nullptr if no init expr or not this type

template<class ConType>
inline bool IsConInfoType(const ConInfo &ci) const

Check if the constraint location points to the constraint keeper used for this ConType.

inline pre::NodeRange AutoLink(pre::NodeRange nr)

Auto link node range nr.

The nodes of nr will be autolinked with auto_link_src_item_. Means, a link is created automatically, without the conversion/flattening code doing anything. This is used to propagate values via flattened expression trees and conversions, as well as to export the conversion tree.

inline bool DoingAutoLinking() const

Whether we should auto-link new items.

inline void TurnOffAutoLinking()

Turn off auto-linking for current conversion.

inline pre::NodeRange GetAutoLinkSource() const

Get autolink source node range.

inline void SetAutoLinkSource(pre::NodeRange nr)

Set autolink source node range.

inline const std::vector<pre::NodeRange> &GetAutoLinkTargets() const

Get autolink target node ranges.

inline const ModelType &GetModel() const

The internal flat model object, const ref.

inline ModelType &GetModel()

The internal flat model object, ref.

inline bool ModelAPIAcceptsQC() const

Whether the ModelAPI accepts quadratic constraints.

inline int ModelAPIAcceptsQuadraticCones() const

Whether the ModelAPI accepts quadratic cones.

inline void IncQC2SOCPAttempted()

Number of QC -> SOCP conversions.

inline void IncQC2SOCPSucceeded()
inline int NumQC2SOCPAttempted() const
inline int NumQC2SOCPSucceeded() const
inline void IncExpConeCounter()

Number of exp cones recognized.

inline int NumExpConesRecognized() const
inline int ModelAPIAcceptsExponentialCones()

Whether the ModelAPI accepts exp cones.

inline const std::string &graph_export_file() const

Graph export file.

inline int relax() const

Whether we should relax integrality.

inline int sol_check_mode() const

Solution checking options.

inline bool sol_check_infeas() const
inline bool sol_check_fail() const
inline double sol_feas_tol() const
inline double sol_feas_tol_rel() const
inline double sol_int_tol() const
inline int sol_round() const
inline int sol_prec() const
inline int sol_check_outlev() const
inline void InitOptions()

Init FlatConverter options.

inline bool CanPreprocess(int f) const

Wrapper about a specific preprocess option: checks whether preprocessAnything_ is on.

inline bool IfPreproEqResBounds() const

Whether preprocess equality result bounds.

inline bool IfPreproEqBinVar() const

Whether preprocess conditional equality of a binary variable.

inline bool IfPreproNestedAndsOrs() const

Whether inline nested forall, exists.

inline bool IfPassQuadObj() const

Whether we pass quad obj terms to the solver without linearization.

inline bool IfPassQuadCon() const

Whether we pass quad con terms to the solver without linearization.

inline bool IfQuadratizePowConstPosIntExp() const

Whether to quadratize pow(…, const_pos_int).

The fact that we use IfPassQuadCon() is much Gurobi-biased: v9.5 does not PL-linearize Pow for negative arguments

inline int IfPassSOCPCones() const

Recognition mode for SOCP cones.

inline int SOCP2QCMode() const

Mode for SOCP -> QC conversion.

inline void Setup2ConvertSOCP2QC()

Decide to convert SOCP -> QC.

inline bool IfConvertSOCP2QC() const

If decided to convert SOCP -> QC.

inline int IfPassExpCones() const

Recognition mode for exp cones.

inline void AddWarning(std::string key, std::string msg, bool replace = false)

AddWarning.

Parameters
  • key – warning category

  • msg – detailed message

inline pre::CopyLink &GetCopyLink()

CONSTRAINT CONVERTERS ///////////////////////// Constraint keepers and converters should be initialized after presolver_.

Convert linear range constraints, if not accepted by ModelAPI Convert quadratic range constraints, if necessary Convert quadratic cones, if necessary Convert rotated quadratic cones, if necessary ValuePresolve link copying values 1:1 between model items

inline pre::One2ManyLink &GetOne2ManyLink()

ValuePresolve link copying values 1:many.

inline pre::Many2OneLink &GetMany2OneLink()

ValuePresolve link copying values many:1.

inline int MapFind(const BasicConstraint&)

For Common Subexpression Elimination, we can use maps This stub returns empty Id.

template<class Con>
inline bool MapInsert(const Con&, int)

Returns false when we do have a map and entry duplicated (should not happen).

Can be conveniently overloaded

inline Var AddVar__basic(double lb = MinusInf(), double ub = Inf(), var::Type type = var::CONTINUOUS)

VARIABLES //////////////////////////////// Add variable, return its index.

inline void AddVars__basic(const VarBndVec &lbs, const VarBndVec &ubs, const VarTypeVec &types)

Add several variables.

This is only done once when we add original variables.

inline void AddVarNames(const std::vector<std::string> &names)

Set var names vector.

inline const char *var_name(int i) const

To be used only after names presolve.

inline const std::vector<double> &var_lb_vec() const
inline const std::vector<double> &var_ub_vec() const
inline const std::vector<var::Type> &var_type_vec() const
inline double lb_array(const VarArray &va) const
inline double lb_max_array(const VarArray &va) const
inline double ub_array(const VarArray &va) const
inline double ub_min_array(const VarArray &va) const
inline bool is_integer_var(int v) const
inline bool is_binary_var(int v) const

Returns true also when fixed.

inline var::Type common_type(const VarArray &va) const
inline void set_lb(int v, double l)
inline void set_ub(int v, double u)
inline void MarkAsResultVar(int v)

Mark as an explicit result variable.

inline bool IsResultVar(int v) const

Is the variable an explicit result var?

inline const ObjList &get_objectives() const

Get list of objectives, const.

inline ObjList &get_objectives()

Get list of objectives.

inline int num_objs() const

N obj.

inline const QuadraticObjective &get_obj(int i) const

Get obj [i].

inline bool HasQPObjective() const

Has a QP objective?

inline virtual const VarBndVec &GetVarLBs() const

Provide variable lower bounds.

inline virtual const VarBndVec &GetVarUBs() const

Provide variable upper bounds.

inline void PushModelTo(ModelAPI &mapi) const

EXPORT THE INSTANCE TO A ModelAPI //////////////.

Pushing the whole instance to the mapi.

inline const FlatModelInfo *GetModelInfo() const

Model info.

inline bool check_vars() const

Check var arrays.

inline void RelaxIntegrality()
inline BasicFileAppender &GetFileAppender() const

Retrieve file logger.

inline BasicFileAppender &GetFileAppender() const

Retrieve file logger.

inline void AddConstraintKeeper(BasicConstraintKeeper &ck, double priority)

Add a new CKeeper with given conversion priority (smaller = sooner)

inline void ConsiderAcceptanceOptions(BasicFlatConverter &cvt, const BasicFlatModelAPI &ma, Env &env)

This should be called after adding all constraint keepers.

inline void ConvertAllConstraints(BasicFlatConverter &cvt)

Convert all constraints (including any new appearing)

inline void MarkExprsForResultVars(BasicFlatConverter &cvt)

Mark which expressions should stay as FuncCons or just have a result variable.

inline void ConvertWithExpressions(BasicFlatConverter &cvt)

Convert to expression-based model.

inline void FillConstraintCounters(const BasicFlatModelAPI &mapi, FlatModelInfo &fmi) const

Fill counters of unbridged constraints.

inline void CopyNamesFromValueNodes()

Copy names from ValueNodes.

inline void AddUnbridgedConstraintsToBackend(BasicFlatModelAPI &be, const std::vector<std::string> *pvnam = nullptr) const

Add all unbridged constraints to Backend.

inline void LogConstraintGroups(BasicFlatModelAPI &be) const

Log constraint groups.

inline void ComputeViolations(SolCheck &chk)

Compute violations.

inline PreprocessInfoStd ComputeBoundsAndType(const LinTerms &lt)

ComputeBoundsAndType(LinTerms)

template<class Body>
inline PreprocessInfoStd ComputeBoundsAndType(const AlgebraicExpression<Body> &ae)

ComputeBoundsAndType(AlgebraicExpr<>)

inline PreprocessInfoStd ComputeBoundsAndType(const QuadTerms &qt)

ComputeBoundsAndType(QuadTerms)

inline PreprocessInfoStd ComputeBoundsAndType(const QuadAndLinTerms &qlt)

ComputeBoundsAndType(QuadAndLinearTerms)

template<class Var>
inline std::pair<double, double> ProductBounds(Var x, Var y) const

Product bounds.

template<class PreprocessInfo>
inline void PreprocessConstraint(LinearFunctionalConstraint &c, PreprocessInfo &prepro)

Preprocess LFC.

template<class PreprocessInfo>
inline void PreprocessConstraint(QuadraticFunctionalConstraint &c, PreprocessInfo &prepro)

Preprocess QFC.

template<class PreprocessInfo>
inline void PreprocessConstraint(PowConstraint &c, PreprocessInfo &prepro)

Preprocess Pow.

template<class PreprocessInfo>
inline void PreprocessConstraint(MinConstraint &c, PreprocessInfo &prepro)

Preprocess Min.

template<class PreprocessInfo>
inline void PreprocessConstraint(MaxConstraint &c, PreprocessInfo &prepro)

Preprocess Max.

template<class PreprocessInfo>
inline void PreprocessConstraint(AbsConstraint &c, PreprocessInfo &prepro)

When the result variable is set, the constraint is skipped.

template<class PreprocessInfo>
inline void PreprocessConstraint(CondLinConEQ &c, PreprocessInfo &prepro)

Preprocess CondLinConEQ.

template<class PreprocessInfo>
inline void PreprocessConstraint(CondQuadConEQ &c, PreprocessInfo &prepro)

Preprocess CondQuadConEQ.

template<class PreprocessInfo, class Body, int kind>
inline void PreprocessConstraint(ConditionalConstraint<AlgebraicConstraint<Body, AlgConRhs<kind>>> &cc, PreprocessInfo &prepro)

(Non)strict inequalities

template<class PreprocessInfo>
inline void PreprocessConstraint(AndConstraint &con, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(OrConstraint &con, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(AllDiffConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(NumberofConstConstraint &con, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(NumberofVarConstraint &con, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(CountConstraint &con, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(NotConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(DivConstraint &c, PreprocessInfo &prepro)

Preprocess Div.

template<class PreprocessInfo>
inline void PreprocessConstraint(IfThenConstraint &c, PreprocessInfo &prepro)

Preprocess IfThen.

template<class PreprocessInfo>
inline void PreprocessConstraint(ImplicationConstraint&, PreprocessInfo &prepro)

Preprocess IfThen.

template<class PreprocessInfo>
inline void PreprocessConstraint(ExpConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(ExpAConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(LogConstraint &c, PreprocessInfo&)
template<class PreprocessInfo>
inline void PreprocessConstraint(LogAConstraint &c, PreprocessInfo&)
template<class PreprocessInfo>
inline void PreprocessConstraint(SinConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(CosConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(TanConstraint&, PreprocessInfo&)

Preprocess Tan.

template<class PreprocessInfo>
inline void PreprocessConstraint(AsinConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(AcosConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(AtanConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(SinhConstraint&, PreprocessInfo&)
template<class PreprocessInfo>
inline void PreprocessConstraint(CoshConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(TanhConstraint&, PreprocessInfo &prepro)

Preprocess Tan.

template<class PreprocessInfo>
inline void PreprocessConstraint(AsinhConstraint&, PreprocessInfo&)
template<class PreprocessInfo>
inline void PreprocessConstraint(AcoshConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(AtanhConstraint&, PreprocessInfo&)
template<class PreprocessInfo>
inline void PreprocessConstraint(PLConstraint&, PreprocessInfo&)
template<class Body, int kind>
inline bool IsNormalized(ConditionalConstraint<AlgebraicConstraint<Body, AlgConRhs<kind>>> &cc)

See if the argument of a conditional algebraic constraint is normalized.

template<class PreprocessInfo, class CondAlgCon>
inline bool FixEqualityResult(CondAlgCon &c, PreprocessInfo &prepro)

Try and fix conditional equality result.

Returns

true if success

template<class PreprocessInfo>
inline bool ReuseEqualityBinaryVar(CondLinConEQ &c, PreprocessInfo &prepro)

Simplify conditional equality bin_var==0/1 by reusing bin_var or its complement.

template<class SubCon, class PreprocessInfo>
inline bool CheckEmptySubCon(const ConditionalConstraint<SubCon> &cc, PreprocessInfo &prepro)

Dave experiments with logic presolve.

Returns

true if constraint is empty and we should return the fixed result.

template<class Vec>
inline std::pair<int, int> count_fixed_01(const Vec &vec) const

Count N fixed binary vars.

template<class Con>
inline void IntegrateNested(Con &con)

Integrate nested constraints (And/Or)

template<class Constraint>
inline void PropagateResult(Constraint &con, double lb, double ub, Context ctx)

By default, add mixed context for argument variables.

inline void PropagateResult(LinearFunctionalConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(QuadraticFunctionalConstraint &con, double lb, double ub, Context ctx)
template<class Body>
inline void PropagateResult(AlgebraicConstraint<Body, AlgConRange> &con)

Propagate a root algebraic range constraint.

template<class Body, int sens>
inline void PropagateResult(IndicatorConstraint<AlgebraicConstraint<Body, AlgConRhs<sens>>> &con, double lb, double ub, Context ctx)
template<int type>
inline void PropagateResult(SOS_1or2_Constraint<type> &con, double lb, double ub, Context)
template<class ExprBody>
inline void PropagateResult(ComplementarityConstraint<ExprBody> &con)

Propagate root complementarity constraint.

template<class ExprBody>
inline void PropagateResult(ComplementarityConstraint<ExprBody> &con, double lb, double ub, Context ctx)

Not used?

inline void PropagateResult(NotConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(AndConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(OrConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(IfThenConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(ImplicationConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(AllDiffConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(NumberofConstConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(NumberofVarConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(PowConstraint &con, double, double, Context ctx)
inline void PropagateResult(LogConstraint &con, double, double, Context ctx)
inline void PropagateResult(LogAConstraint &con, double, double, Context ctx)
inline void PropagateResult(ExpConstraint &con, double, double, Context ctx)
inline void PropagateResult(ExpAConstraint &con, double, double, Context ctx)
inline void PropagateResult(CondLinConEQ &con, double lb, double ub, Context ctx)
inline void PropagateResult(CondQuadConEQ &con, double lb, double ub, Context ctx)
template<class Body, int kind>
inline void PropagateResult(ConditionalConstraint<AlgebraicConstraint<Body, AlgConRhs<kind>>> &con, double lb, double ub, Context ctx)
template<class Array3>
inline void PropagateIfThenResultIntoCondition(Array3 args, Context ctx)

Context of the condition in IfThen.

Parameters
  • args – [condition, then, else] result variables

  • ctx – context of the overall expression

template<class Args>
inline void PropagateResult2Args(const Args &vars, double lb, double ub, Context ctx)

Propagate given bounds & context into arguments of a constraint.

The default template assumes it just a vector of variables.

Parameters

lb, ub – bounds for each variable

inline void PropagateResult2Args(const LinTerms &lint, double lb, double ub, Context ctx)

Specialize: propagate result into LinTerms.

inline void PropagateResult2Args(const QuadAndLinTerms &qlt, double lb, double ub, Context ctx)

Specialize: propagate result into QuadAndLinTerms.

inline void PropagateResult2QuadAndLinTerms(const QuadAndLinTerms &qlt, double lb, double ub, Context ctx)

Propagate result into QuadAndLinTerms.

inline void PropagateResult2LinTerms(const LinTerms &lint, double, double, Context ctx)

Propagate result into LinTerms.

template<class Vec>
inline void PropagateResult2Vars(const Vec &vars, double lb, double ub, Context ctx)

Propagate given bounds & context into a vector of variables.

Parameters

lb, ub – bounds for each variable

inline void PropagateResult2QuadTerms(const QuadTerms &quadt, double, double, Context ctx)

Propagate result into QuadTerms.

template<class Con>
inline void ConsiderMarkingResultAndArgVars(const Con &con, int i, ExpressionAcceptanceLevel eal)

Consider marking the result and argument variables as “explicit variables” (not expressions)

template<class Con>
inline void ConsiderMarkingArgumentsAsVars(const Con &con, int i, ExpressionAcceptanceLevel eal)

Generic request to consider marking arguments.

inline bool CheckSolution(ArrayRef<double> x, const pre::ValueMapDbl &duals, ArrayRef<double> obj, void *p_extra)

Check postsolved & unpostsolved solutions in various ways.

Parameters

p_extra – !=0 means known infeas solution

inline ArrayRef<double> RecomputeAuxVars(ArrayRef<double> x)

Recompute auxiliary variables.

inline std::string DoCheckSol(ArrayRef<double> x, const pre::ValueMapDbl &duals, ArrayRef<double> obj, ArrayRef<double> x_raw, std::vector<double> &x_back, bool if_recomp_vals)

Check single unpostsolved solution.

Parameters

x_back – solution vector from realistic mode. It can be changed by the :round and :prec options. Its auxiliary vars are compared with recomputed expression values.

inline void CheckVars(SolCheck &chk)
inline void CheckCons(SolCheck &chk)

Includes logical constraints.

inline void CheckObjs(SolCheck &chk)
inline void GenerateViolationsReport(SolCheck &chk, bool)
inline void Gen1Viol(const ViolSummary &vs, fmt::MemoryWriter &wrt, bool f_max, const std::string &type)

Generate message about 1 violation.

Parameters

f_max – whether we need to print the maximal violations.

inline std::string Gen1ViolMax(bool f_max, double viol, const char *nm)

Stringify 1 maximal violation.

inline void GenConViol(const std::map<std::string, ViolSummArray<3>> &cvmap, fmt::MemoryWriter &wrt, int alg_log)

std::string classnm = alg_log ? “Logical” : “Algebraic”; wrt.write(classnm + ” expression violations:\n”);

inline const Env &GetEnv() const

GetEnv() const.

inline Env &GetEnv()

GetEnv()

Public Members

VarsRecomputeFn recomp_fn = [this](int i, const VarInfoRecomp& x) {if (MPCD( HasInitExpression(i) )) {const auto& iexpr =MPCD( GetInitExpression(i) );auto pCK = iexpr.GetCK();if (!pCK->IsUnused(iexpr.GetIndex()))return pCK->ComputeValue(iexpr.GetIndex(), x);}return x.get_x().get_x()[i];}

Functor to recompute auxiliary var i.

Public Static Functions

static inline const char *GetTypeName()

Class name.

static inline constexpr Var VoidVar()

‘Invalid’ var id

static inline bool ModelAPIAcceptsQuadObj()

Whether the ModelAPI accepts quadratic objectives.

static inline bool ModelAPIAcceptsNonconvexQC()

Whether the ModelAPI accepts nonconvex QC.

static inline bool ModelAPICanSOCPCornerCasesFromQC()

Ask if the solver can recognize SOCP corner cases (non-std representations such as xy>=1, see tests) from quadratic representations.

static inline bool ModelAPICanMixConicQCAndQC()

Whether the solver can mix conic quadratic (entered via dedicated API) and direct quadratic constraints.

static inline constexpr double ConstraintCvtPriority(BasicConstraint*)

Default conversion priority.

static inline constexpr double Pi()

Value of Pi.

static inline constexpr double Infty()

Infinity.

static inline constexpr double MinusInfty()

-Infinity

static inline constexpr double PracticallyInf()

Pract inf.

static inline constexpr double PracticallyMinusInf()

Pract -inf.

static inline constexpr double Inf()
static inline constexpr double MinusInf()
static inline bool is_integer_value(Num n)
static inline PreprocessInfoStd AddBoundsAndType(const PreprocessInfoStd &bnt1, const PreprocessInfoStd &bnt2)

Add / merge bounds and type.

static inline void PreprocessEqVarConst__unifyCoef(CondLinConEQ &c)

Normalize conditional equality coef * var == const.

Protected Types

using ClassType = FlatConverter<Impl, ModelAPI, FlatModel>
using BaseConverter = BasicFlatConverter
using BaseFlatModel = FlatModel

Protected Functions

inline int &VarUsageRef(int i)
inline void ConvertItems()

CUSTOM CONSTRAINTS CONVERSION ////////////////////////////.

inline void OpenGraphExporter()
inline void Convert2Cones()

Offload the conic logic to a functor.

inline void ConvertAllConstraints()

Can be called from ConvertMaps()

inline void ConvertMaps()

Default map conversions. Currently empty.

inline bool IfWantNLOutput() const

Option to actually use expressions if available.

inline void Convert2NL()

Convert some functional constraints to expressions.

inline void CloseGraphExporter()

Finish exporting the reformulation graph.

inline void PreprocessIntermediate()
inline void PreprocessFlatFinal()
inline void PreprocessNLFinal()
template<class Constraint>
inline pre::NodeRange AddConstraintAndTryNoteResultVariable(Constraint &&con)
inline void ConvertModel()
inline void PrepareConversion()
inline void WindupConversion()
inline pre::NodeRange DoAddVar(double lb = MinusInfty(), double ub = Infty(), var::Type type = var::CONTINUOUS)

Add variable. Type: var::CONTINUOUS by default.

inline void AddInitExpression(int var, const ConInfo &vi)

Add init expr for var.

inline void ReplaceInitExpression(int var, const ConInfo &vi)

Replace init expression for var.

STORE_CONSTRAINT_TYPE__NO_MAP (LinConRange, "acc:linrange acc:linrng") STORE_CONSTRAINT_TYPE__NO_MAP(QuadConRange

CONSTRAINT KEEPERS ///////////////////////// Constraint keepers and converters should be initialized after value_presolver_.

Define constraint keepers for all constraint types. No maps for static constraints. 2nd parameter: solver options for this constraint, in case it is accepted by the solver natively and is convertible by us.

template<class Constraint>
inline bool MapInsert(const Constraint &con, int i)

MapInsert.

Can be overloaded for more complex behavior.

Parameters
Returns

false when inserted a duplicate (should not happen)

template<class Constraint>
inline int MapFind__Impl(const Constraint &con)

MapFind__Impl.

Default version for functional constraints with a map.

Parameters

con – constraint reference

Returns

constraint index, or -1

template<class Constraint>
inline bool MapInsert__Impl(const Constraint &con, int i)

MapInsert__Impl.

Default version for functional constraints with a map.

Parameters
Returns

false when inserted a duplicate (should not happen)

inline void ExportVars (int i_start, const BndVec &lbs, const BndVec &ubs, const TypeVec types, const char *comment="Initial model information. " "Can be updated later with new bounds, names, etc.") const

Export new variables.

inline void ExportObjective(int i_obj, const QuadraticObjective &obj) const
inline void CreateFlatModelInfo(const BasicFlatModelAPI &mapi) const
inline void FillVarStats(FlatModelInfo *pfmi) const
inline void PushVariablesTo(Backend &backend) const
inline void PushObjectivesTo(Backend &backend) const
inline void PushCustomConstraintsTo(Backend &backend) const
inline FlatModelInfo *GetModelInfoWrt() const
template<class Body, class RhsOrRange>
inline void DoMarkArgsAsVars(const AlgebraicConstraint<Body, RhsOrRange>&, int)

Algebraic cons: no marking (when NLConstraint accepted?)

template<class Expr>
inline void DoMarkArgsAsVars(const ComplementarityConstraint<Expr> &cc, int)

Complementarity: only mark the var (NL accepts expressions for the expression part)

template<class Con>
inline void DoMarkArgsAsVars(const Con &con, int)

Generic arguments marking call.

Protected Attributes

acc __pad0__
acc acc

Protected Static Functions

static inline constexpr bool IfAcceptingNLOutput()

Whether solver CAN accept expressions.

Private Functions

inline int DefaultSOCPMode() const
inline int DefaultSOCP2QCMode() const
inline void InitOwnOptions()

Private Members

std::unordered_map<double, int> map_fixed_vars_
std::vector<ConInfo> var_info_
Options options_
const std::string solchkfailtext_{"Fail on MP solution check violations, with solve result " + std::to_string(sol::MP_SOLUTION_CHECK) + '.'}
std::string socp_mode_text_
std::string socp2qc_mode_text_
const mp::OptionValueInfo socp_values_ [3] = {{ "0", "Do not recognize SOCP forms", 0},{ "1", "Recognize from non-quadratic expressions only (sqrt, abs)", 1},{ "2","Recognize from quadratic and non-quadratic SOCP forms. ""Helpful if the solver does not recognize non-standard forms", 2}}
const mp::OptionValueInfo socp2qc_values_ [3] = {{ "0", "Do not convert", 0},{ "1", "Convertif no other cone types found, and ""not all original quadratics could be recognized as SOC, ""in particular if the objective is quadratic", 1},{ "2", "Always convert", 2}}
const mp::OptionValueInfo values_allexpr_acceptance_ [2] = {{ "0", "Not accepted, all expressions will be treated as flat constraints, ""or redefined", 0},{ "1", "Accepted. See the individual acc:... options", 1}}
ModelAPIType modelapi_

We store ModelApi in the converter for speed.

Should be before constraints

pre::ValuePresolver value_presolver_   = {     GetModel(), GetEnv(), (BasicLogger&)GetModel().GetFileAppender(),[this](ArrayRef<double> x,constpre::ValueMapDbl& y,         ArrayRef<double> obj,void* p_extra) -> bool {return !this->options_.solcheckmode_||MPD( CheckSolution(x, y, obj, p_extra) );}}

ValuePresolver: should be init before constraint keepers and links.

ConicConverter<Impl> conic_cvt_ = {*static_cast<Impl*>(this)}
int nQC2SOCPAttempted_ = 0
int nQC2SOCPSucceeded_ = 0
int nExpConesRecognized_ = 0
bool ifCvtSOCP2QC_ = 0
std::vector<int> refcnt_vars_
int constr_depth_ = 0
std::vector<std::string> var_names_

AMPL item names.

std::vector<std::string> con_names_
std::vector<std::string> obj_names_

Friends

friend class BasicFCC
friend class ConstraintKeeper
template<template<typename, typename, typename> class FlatCvt, class Backend, class Model = FlatModel<>>
class mp::FlatCvtImpl : public FlatCvt<FlatCvtImpl<FlatCvt, Backend, FlatModel<>>, Backend, FlatModel<>>
#include <converter.h>

A ‘final’ flat converter in a CRTP hierarchy.

Public Types

using Base = FlatCvt<FlatCvtImpl<FlatCvt, Backend, Model>, Backend, Model>

Base type.

Public Functions

inline FlatCvtImpl(Env &e)

Construct.

template<class ModelParams = DefaultFlatModelParams>
class mp::FlatModel : public mp::ConstraintManager, public mp::BasicFlatModel
#include <converter_model.h>

Class BasicFlatModel stores vars, objs, custom constraints to be used internally in a FlatConverter.

Public Types

using Params = ModelParams
using Var = typename Params::Var
using VarArray = std::vector<Var>
using VarTypeVec = std::vector<var::Type>
using VarNameVec = std::vector<const char*>
using ObjList = std::vector<QuadraticObjective>

List of objectives.

using VarBndVec = std::vector<double>

Typedef VarBndVec.

Public Functions

inline Var AddVar__basic(double lb = MinusInf(), double ub = Inf(), var::Type type = var::CONTINUOUS)

VARIABLES //////////////////////////////// Add variable, return its index.

inline void AddVars__basic(const VarBndVec &lbs, const VarBndVec &ubs, const VarTypeVec &types)

Add several variables.

This is only done once when we add original variables.

inline void AddVarNames(const std::vector<std::string> &names)

Set var names vector.

inline const char *var_name(int i) const

To be used only after names presolve.

inline int num_vars() const

N vars.

inline bool is_var_original(int i) const

Not auxiliary?

inline double lb(Var v) const
inline double ub(Var v) const
inline var::Type var_type(Var v) const
inline const std::vector<double> &var_lb_vec() const
inline const std::vector<double> &var_ub_vec() const
inline const std::vector<var::Type> &var_type_vec() const
template<class VarArray>
inline double lb_array(const VarArray &va) const
template<class VarArray>
inline double lb_max_array(const VarArray &va) const
template<class VarArray>
inline double ub_array(const VarArray &va) const
template<class VarArray>
inline double ub_min_array(const VarArray &va) const
inline bool is_fixed(int v) const
inline double fixed_value(int v) const
inline bool is_integer_var(int v) const
inline bool is_binary_var(int v) const

Returns true also when fixed.

template<class VarArray = std::initializer_list<int>>
inline var::Type common_type(const VarArray &va) const
inline void set_lb(int v, double l)
inline void set_ub(int v, double u)
inline void MarkAsResultVar(int v)

Mark as an explicit result variable.

inline bool IsResultVar(int v) const

Is the variable an explicit result var?

inline const ObjList &get_objectives() const

Get list of objectives, const.

inline ObjList &get_objectives()

Get list of objectives.

inline int num_objs() const

N obj.

inline const QuadraticObjective &get_obj(int i) const

Get obj [i].

inline bool HasQPObjective() const

Has a QP objective?

inline void AddObjective(QuadraticObjective &&obj)

Add an objective.

inline virtual const VarBndVec &GetVarLBs() const

Provide variable lower bounds.

inline virtual const VarBndVec &GetVarUBs() const

Provide variable upper bounds.

template<class ModelAPI>
inline void PushModelTo(ModelAPI &mapi) const

EXPORT THE INSTANCE TO A ModelAPI //////////////.

Pushing the whole instance to the mapi.

inline const FlatModelInfo *GetModelInfo() const

Model info.

inline bool check_vars() const

Check var arrays.

inline void RelaxIntegrality()
inline BasicFileAppender &GetFileAppender() const

Retrieve file logger.

inline void AddConstraintKeeper(BasicConstraintKeeper &ck, double priority)

Add a new CKeeper with given conversion priority (smaller = sooner)

inline void ConsiderAcceptanceOptions(BasicFlatConverter &cvt, const BasicFlatModelAPI &ma, Env &env)

This should be called after adding all constraint keepers.

inline void ConvertAllConstraints(BasicFlatConverter &cvt)

Convert all constraints (including any new appearing)

inline void MarkExprsForResultVars(BasicFlatConverter &cvt)

Mark which expressions should stay as FuncCons or just have a result variable.

inline void ConvertWithExpressions(BasicFlatConverter &cvt)

Convert to expression-based model.

inline void FillConstraintCounters(const BasicFlatModelAPI &mapi, FlatModelInfo &fmi) const

Fill counters of unbridged constraints.

inline void CopyNamesFromValueNodes()

Copy names from ValueNodes.

inline void AddUnbridgedConstraintsToBackend(BasicFlatModelAPI &be, const std::vector<std::string> *pvnam = nullptr) const

Add all unbridged constraints to Backend.

inline void LogConstraintGroups(BasicFlatModelAPI &be) const

Log constraint groups.

inline void ComputeViolations(SolCheck &chk)

Compute violations.

inline BasicFileAppender &GetFileAppender() const

Retrieve file logger.

Public Static Functions

static inline constexpr Var VoidVar()
static inline constexpr double Inf()
static inline constexpr double MinusInf()
template<class Num>
static inline bool is_integer_value(Num n)

Protected Functions

template<class BndVec = std::array<double, 1>, class TypeVec = std::array<var::Type, 1>> inline void ExportVars (int i_start, const BndVec &lbs, const BndVec &ubs, const TypeVec types, const char *comment="Initial model information. " "Can be updated later with new bounds, names, etc.") const

Export new variables.

inline void ExportObjective(int i_obj, const QuadraticObjective &obj) const
inline void CreateFlatModelInfo(const BasicFlatModelAPI &mapi) const
inline void FillVarStats(FlatModelInfo *pfmi) const
template<class Backend>
inline void PushVariablesTo(Backend &backend) const
template<class Backend>
inline void PushObjectivesTo(Backend &backend) const
template<class Backend>
inline void PushCustomConstraintsTo(Backend &backend) const
inline FlatModelInfo *GetModelInfoWrt() const

Private Members

VarBndVec var_lb_

Variables’ bounds.

VarBndVec var_ub_
VarTypeVec var_type_

Variables’ types.

std::vector<bool> var_result_

Whether the variable, being the result variable of a functional constraint, needs to stay a variable (vs being eliminated because the constraint is becoming an expression)

mutable VarNameVec var_names_

Variables’ names.

std::vector<std::string> var_names_storage_
int num_vars_orig_ = {0}

Number of original NL variables.

ObjList objs_

Objectives.

std::unique_ptr<FlatModelInfo> pfmi_ = {mp::CreateFlatModelInfo()}

Flat model info.

class mp::FlatModelInfo
#include <model_info.h>

Public interface for flat model info.

Information about the model can be used to initialize storage.

Subclassed by mp::FlatModelInfoImpl

Public Functions

inline virtual ~FlatModelInfo()

Virtual destructor.

virtual int NumUnfixedIntVars() const = 0

Number of unfixed integer variables.

virtual void SetNumUnfixedIntVars(int n) = 0

Set N unfixed int vars.

virtual int GetNumberOfConstraintsOfGroup(int ng) const = 0

Get number of constraints of certain group.

virtual int GetNumberOfConstraints(const std::type_info &nt) const = 0

Get number of constraints of single type.

virtual void InitConstraintCount() = 0

Initialize constraint counting.

virtual void AddNumberOfConstraints(const std::type_info &ti, int igroup, int nc) = 0

Add number of constraints of single type to the counter.

class mp::FlatModelInfoImpl : public mp::FlatModelInfo
#include <model_info.hpp>

Implementation of flat model info.

Public Types

using TypeInfoRef = std::reference_wrapper<const std::type_info>

For hashing of type_info.

using TypeInfoRefIntMap = std::unordered_map<TypeInfoRef, int, TypeInfoRefHasher, TypeInfoRefEqualTo>

Hash map of ints by TypeInfoRef.

using ConstrGroupIntMap = std::unordered_map<int, int>

Hash map of ints by constraint groups.

Public Functions

inline virtual int NumUnfixedIntVars() const override

Num unfixed int vars.

inline virtual void SetNumUnfixedIntVars(int n) override

Set N unfixed int vars.

inline virtual int GetNumberOfConstraintsOfGroup(int cg) const override

Get number of constraints of certain group.

inline virtual int GetNumberOfConstraints(const std::type_info &it) const override

Get number of constraints of single type.

inline virtual void InitConstraintCount() override

Initialize constraint counting.

inline virtual void AddNumberOfConstraints(const std::type_info &ti, int igroup, int nc) override

Add number of constraints of single type.

Private Members

TypeInfoRefIntMap ti_map_
ConstrGroupIntMap cg_map_
int nUnfxIntVars_ = 0
template<class ModelConverter, class FuncCon>
class mp::FuncConConverter_MIP : public mp::FuncConConverter_MIP_CRTP<FuncConConverter_MIP<ModelConverter, FuncCon>, ModelConverter, FuncCon>
#include <lin_approx.h>

Final CRTP class.

Public Types

using Base = FuncConConverter_MIP_CRTP<FuncConConverter_MIP<ModelConverter, FuncCon>, ModelConverter, FuncCon>

Typedef Base.

using ItemType = FuncCon

Converted item type.

Public Functions

inline FuncConConverter_MIP(ModelConverter &mc)

Constructor.

inline void Convert(const ItemType &con, int)

Convert in any context.

template<class ItemType>
inline void Convert(const ItemType &item, int i)

Generic Convert(), distinguishes context & result variable.

Distinguish positive and negative context because if only one of these is necessary, significant model reduction can be achieved in certain cases.

Responsible for adding presolve links, if any

The Impl can reimplement this

Parameters
  • item – the item to be converted

  • i – item index, used to create a presolve link

template<class ItemType>
inline void ConvertCtxNeg(const ItemType &item, int)

Convert in negative context.

template<class ItemType>
inline void ConvertCtxPos(const ItemType &item, int)

Convert in positive context.

inline const ModelConverter &GetMC() const

Reuse the stored ModelConverter.

inline ModelConverter &GetMC()

Reuse the stored ModelConverter.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

template<class Impl, class ModelConverter, class FuncCon>
class mp::FuncConConverter_MIP_CRTP : public mp::BasicFuncConstrCvt<Impl, ModelConverter>
#include <lin_approx.h>

Pl-approximates a FuncCon for MIP.

Public Types

using Base = BasicFuncConstrCvt<Impl, ModelConverter>

Base class.

using ItemType = FuncCon

Converted item type.

Public Functions

inline FuncConConverter_MIP_CRTP(ModelConverter &mc)

Constructor.

inline void Convert(const ItemType &con, int)

Convert in any context.

template<class ItemType>
inline void Convert(const ItemType &item, int i)

Generic Convert(), distinguishes context & result variable.

Distinguish positive and negative context because if only one of these is necessary, significant model reduction can be achieved in certain cases.

Responsible for adding presolve links, if any

The Impl can reimplement this

Parameters
  • item – the item to be converted

  • i – item index, used to create a presolve link

template<class ItemType>
inline void ConvertCtxNeg(const ItemType &item, int)

Convert in negative context.

template<class ItemType>
inline void ConvertCtxPos(const ItemType &item, int)

Convert in positive context.

inline const ModelConverter &GetMC() const

Reuse the stored ModelConverter.

inline ModelConverter &GetMC()

Reuse the stored ModelConverter.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

struct mp::NLFeeder::FuncDef
#include <nl-feeder.h>

Function definition.

Public Functions

inline const char *Name()
inline int NumArgs()
inline int Type()

Function type.

0 - numeric; 1 - symbolic.

struct mp::FuncGraphDomain
#include <lin_approx_core.h>

Function graph domain.

Public Functions

void intersect(const FuncGraphDomain &grDom)

Intersect the domain with another rectangle.

Public Members

double lbx

Bounds for x, y.

double ubx
double lby
double uby
class mp::Function
#include <expr.h>

A reference to a function.

Public Functions

inline Function()

Constructs a Function object representing a null reference to a function.

The only operation permitted for such object is copying, assignment and check whether it is null using operator SafeBool.

inline operator SafeBool() const

Returns a value convertible to bool that can be used in conditions but not in comparisons and evaluates to “true” if this function is not null and “false” otherwise.

Example: if (f) { /// Do something if f is not null. }

inline const char *name() const

Returns the name of this function.

inline int num_args() const

Returns the number of arguments.

inline func::Type type() const

Returns the type of this function.

inline bool operator==(Function other) const

Function::operator==.

inline bool operator!=(Function other) const

Function::operator!=.

Private Types

typedef void (Function::* SafeBool)() const

Safe bool type.

Private Functions

inline void True() const

A member function representing the true value of SafeBool.

inline explicit Function(const Impl *impl)

Private Members

const Impl *impl_

Friends

friend class CallExpr
friend class BasicExprFactory
class mp::ProblemBuilder::Function
#include <problem-builder.h>

class Function.

Public Functions

inline operator SafeBool() const

Returns a value convertible to bool that can be used in conditions but not in comparisons and evaluates to “true” if this function is not null and “false” otherwise.

Example: if (f) { // Do something if f is not null. }

Private Types

typedef void (Function::* SafeBool)() const

Safe bool type.

class mp::FunctionalConstraint : public mp::BasicConstraint
#include <constr_base.h>

A special constraint ‘var=…’, which defines a result variable.

Subclassed by mp::CustomFunctionalConstraint< Con, ParamArray0, LogicalFunctionalConstraintTraits, CondConId< Con > >, mp::CustomFunctionalConstraint< Args, Params, NumOrLogic, Id >, mp::LinearFunctionalConstraint, mp::QuadraticFunctionalConstraint

Public Functions

inline FunctionalConstraint(int v = -1)

Constructor.

Parameters

v – result variable

inline bool operator==(const FunctionalConstraint &dc) const

Basic operator==.

inline bool HasResultVar() const

Has result var (is functional)? We don’t store this info in the type (yet.)

inline int GetResultVar() const

Get result variable.

inline void SetResultVar(int v)

Set result variable.

inline Context GetContext() const

Get it.

inline void SetContext(Context c) const

Set it.

inline void AddContext(Context c)

Add context.

inline const char *GetName() const

Constraint name.

inline const char *name() const

Constraint name.

inline void SetName(std::string nm)

Set constraint name.

inline void AddContext(Context) const

Add (merge) context, if meaningful.

template<class VarInfo>
inline Violation ComputeViolation(const VarInfo&) const

Compute violation.

Public Static Functions

static inline constexpr const char *GetTypeName()

Constraint type name for messages.

static inline constexpr bool UsesContext()

Whether context is meaningful.

Private Members

int result_var_ = -1
mutable Context ctx
template<typename T>
class mp::internal::HasBuilder
#include <nl-reader.h>

Checks if T has a member type Builder.

Public Types

enum [anonymous]

Values:

enumerator value

Private Static Functions

template<typename U>
static fmt::internal::Yes &test(typename U::Builder*)
template<typename U>
static fmt::internal::No &test(...)
template<int kind>
struct std::hash<mp::AlgConRhs<kind>>
#include <constr_hash.h>

Partially specialize std::hash<> for mp::AlgConRhs<>

Public Functions

inline size_t operator()(mp::AlgConRhs<kind> x) const
template<class Body, class RangeOrRhs>
struct std::hash<mp::AlgebraicConstraint<Body, RangeOrRhs>>
#include <constr_hash.h>

which happens here: Partially specialize std::hash<> for AlgebraicConstraint<>

Assumes that std::hash<> is specialized for Body and RangeOrRhs

Public Functions

inline size_t operator()(const mp::AlgebraicConstraint<Body, RangeOrRhs> &x) const
template<class Body>
struct std::hash<mp::AlgebraicExpression<Body>>
#include <constr_hash.h>

Partially specialize std::hash<> for mp::AlgebraicExpr.

Public Functions

inline size_t operator()(const mp::AlgebraicExpression<Body> &x) const
template<>
struct std::hash<mp::LinTerms>
#include <constr_hash.h>

Specialize std::hash<> for mp::LinTerms.

Public Functions

inline size_t operator()(const mp::LinTerms &x) const
template<>
struct std::hash<mp::QuadAndLinTerms>
#include <constr_hash.h>

Specialize std::hash<> for mp::QuadAndLinTerms.

Public Functions

inline size_t operator()(const mp::QuadAndLinTerms &qe) const
template<>
struct std::hash<mp::QuadTerms>
#include <constr_hash.h>

Specialize std::hash<> for mp::QuadTerms.

Public Functions

inline size_t operator()(const mp::QuadTerms &qt) const
template<class Element, std::size_t N>
struct std::hash<std::array<Element, N>>
#include <constr_hash.h>

Specialize std::hash<> for std::array<>

Might assume std::hash<> specialized for elements

Public Functions

inline size_t operator()(const std::array<Element, N> &x) const
template<class Con>
struct std::hash<std::reference_wrapper<const mp::ConditionalConstraint<Con>>>
#include <constr_hash.h>

Partially specialize std::hash<> for ConditionalConstraint<>

Assumes that std::hash<> is specialized for Con

Public Functions

inline size_t operator()(std::reference_wrapper<const mp::ConditionalConstraint<Con>> x) const
template<class Args, class Params, class NumOrLogic, class Id>
struct std::hash<std::reference_wrapper<const mp::CustomFunctionalConstraint<Args, Params, NumOrLogic, Id>>>
#include <constr_hash.h>

Specialize std::hash<> for various expressions and constraints.

Remember we also need operator== for [std::reference_wrapper<> of] the compared types. Operator==’s are class memebrs, or defined in constraint_keeper.h. Partially specialize std::hash<> for CustomFunctionalConstraint<>

Assumes that std::hash<> is specialized for Arguments and Parameters

Public Functions

inline size_t operator()(std::reference_wrapper<const mp::CustomFunctionalConstraint<Args, Params, NumOrLogic, Id>> x) const
template<>
struct std::hash<std::reference_wrapper<const mp::LinearFunctionalConstraint>>
#include <constr_hash.h>

Specialize std::hash<> for mp::LinearFunctionalCon.

Public Functions

inline size_t operator()(std::reference_wrapper<const mp::LinearFunctionalConstraint> lfc) const
template<>
struct std::hash<std::reference_wrapper<const mp::QuadraticFunctionalConstraint>>
#include <constr_hash.h>

Specialize std::hash<> for mp::QuadraticFunctionalCon.

Public Functions

inline size_t operator()(std::reference_wrapper<const mp::QuadraticFunctionalConstraint> qfc) const
template<class Element, class Allocator>
struct std::hash<std::vector<Element, Allocator>>
#include <constr_hash.h>

Specialize std::hash<> for std::vector<>

Might assume std::hash<> specialized for elements

Public Functions

inline size_t operator()(const std::vector<Element, Allocator> &x) const
class mp::HashStreamerCombine

HashStreamerCombine.

Implements the HashStreamer interface using HashCombine()

Public Functions

inline HashStreamerCombine(std::size_t sd = 0)

Accumulation (stateful combination)

Constructor

template<class T>
inline void Add(const T &v)

Add value.

template<class T>
inline void AddArray(const T &v)

Add array.

template<class IT>
inline void AddRange(IT beg, const IT end)

Add range.

inline std::size_t FinalizeHashValue()

Finalize hash value.

Returns

the value

inline void Reset()

Reset state.

inline std::size_t FinalizeAndReset()

Finalize & reset.

Returns

hash value

Public Static Functions

template<class T>
static inline std::size_t HashArray(std::size_t seed, const T &v)

HashArray, one-off.

template<class IT>
static inline std::size_t HashRange(std::size_t seed, IT beg, const IT end)

HashRange, one-off.

Private Members

std::size_t seed_
std::size_t seed00_
class mp::internal::IdentityConverter
#include <nl-reader.h>

Converter that doesn’t change the input.

Subclassed by mp::internal::BinaryReader< InputConverter >

Public Functions

template<typename T>
inline T Convert(T value)
template<class ModelConverter>
class mp::IfThenElseConverter_MIP : public mp::BasicFuncConstrCvt<IfThenElseConverter_MIP<ModelConverter>, ModelConverter>
#include <ifthenelse.h>

Converts ITE for MIP.

Public Types

using Base = BasicFuncConstrCvt<IfThenElseConverter_MIP<ModelConverter>, ModelConverter>

Base class.

using ItemType = IfThenConstraint

Converted item type.

Public Functions

inline IfThenElseConverter_MIP(ModelConverter &mc)

Constructor.

inline void Convert(const ItemType &itc, int)

Convert in any context.

inline void Convert(const ItemType &item, int i)

Generic Convert(), distinguishes context & result variable.

Distinguish positive and negative context because if only one of these is necessary, significant model reduction can be achieved in certain cases.

Responsible for adding presolve links, if any

The Impl can reimplement this

Parameters
  • item – the item to be converted

  • i – item index, used to create a presolve link

inline void ConvertCtxNeg(const ItemType &item, int)

Convert in negative context.

inline void ConvertCtxPos(const ItemType &item, int)

Convert in positive context.

inline const ModelConverter &GetMC() const

Reuse the stored ModelConverter.

inline ModelConverter &GetMC()

Reuse the stored ModelConverter.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

Protected Functions

inline void ConvertIfThen_constantThenElse(const IfThenConstraint &itc)
inline void ConvertIfThen_variableThenElse(const IfThenConstraint &itc)
struct mp::IIS
#include <backend-mip.h>

IIS (postsolved).

Elements correspond to IISStatus

Public Members

std::vector<int> variis

Var and con IIS statuses.

std::vector<int> coniis
struct mp::BasicBinaryExpr::Impl : public Base::Impl

Public Members

const Base::Impl *lhs
const Base::Impl *rhs
struct mp::BasicIfExpr::Impl : public mp::internal::ExprBase::Impl

Public Functions

inline expr::Kind kind() const

Public Members

const Base::Impl *condition
const Base::Impl *then_expr
const Base::Impl *else_expr
struct mp::BasicIteratedExpr::Impl : public Base::Impl

Public Members

int num_args
const Base::Impl *args[1]
struct mp::BasicUnaryExpr::Impl : public Base::Impl

Public Members

const Base::Impl *arg
struct mp::CallExpr::Impl : public Base::Impl

Public Members

const Function::Impl *func
int num_args
const Base::Impl *args[1]
struct mp::Function::Impl

Public Members

func::Type type
int num_args
char name[1]
class mp::internal::ExprBase::Impl
#include <expr.h>

The following members are protected rather than private because they have to be accessible in subclasses, instances of BasicExpr.

This doesn’t violate encapsulation because this class is inherited privately and can be thought of as a part of BasicExpr that doesn’t depend on template parameters.

Public Functions

inline expr::Kind kind() const

Private Members

expr::Kind kind_

Only ExprFactory should be able to set Impl::kind_.

Friends

friend class mp::BasicExprFactory
struct mp::internal::SuffixBase::Impl
#include <suffix.h>

Public Functions

inline explicit Impl(fmt::StringRef name, int kind = 0, int num_values = 0, const SuffixTable &tab = {})
inline int kind_full() const
inline int kind_pure() const

Public Members

fmt::StringRef name

Name is stored as a StringRef rather than std::string to avoid dynamic memory allocation when using set::find.

mutable int kind
int num_values
void *values
int *int_values
double *dbl_values
union mp::internal::SuffixBase::Impl::[anonymous] [anonymous]
SuffixTable table
struct mp::LogicalConstant::Impl : public Base::Impl

Public Members

bool value
struct mp::LogicalCountExpr::Impl : public Base::Impl

Public Members

const Base::Impl *lhs
const Base::Impl *rhs
struct mp::NumericConstant::Impl : public Base::Impl

Public Members

double value
struct mp::PLTerm::Impl : public Base::Impl

Public Members

int num_breakpoints
const Base::Impl *arg
double data[1]
struct mp::Reference::Impl : public Base::Impl

Public Members

int index
struct mp::StringLiteral::Impl : public Base::Impl

Public Members

char value[1]
template<class ModelConverter>
class mp::ImplicationConverter_MIP : public mp::BasicFuncConstrCvt<ImplicationConverter_MIP<ModelConverter>, ModelConverter>
#include <impl.h>

Convert ImplicationConstraint into AndConstraint.

Public Types

using Base = BasicFuncConstrCvt<ImplicationConverter_MIP<ModelConverter>, ModelConverter>

Base class.

using ItemType = ImplicationConstraint

Converted item type.

Public Functions

inline ImplicationConverter_MIP(ModelConverter &mc)

Constructor.

inline void Convert(const ItemType &cc, int)

Convert in any context.

inline void Convert(const ItemType &item, int i)

Generic Convert(), distinguishes context & result variable.

Distinguish positive and negative context because if only one of these is necessary, significant model reduction can be achieved in certain cases.

Responsible for adding presolve links, if any

The Impl can reimplement this

Parameters
  • item – the item to be converted

  • i – item index, used to create a presolve link

inline void ConvertCtxNeg(const ItemType &item, int)

Convert in negative context.

inline void ConvertCtxPos(const ItemType &item, int)

Convert in positive context.

inline const ModelConverter &GetMC() const

Reuse the stored ModelConverter.

inline ModelConverter &GetMC()

Reuse the stored ModelConverter.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

struct mp::pre::IndexRange
#include <valcvt-base.h>

index range for some link or node

Public Functions

inline IndexRange(int b = 0, int e = -1)

Construct, possibly from a single index.

inline bool IsValid() const

Validate.

inline void Invalidate()

Invalidate.

inline int Size() const

Size()

inline bool operator==(const IndexRange &ir) const

operator==

inline bool operator!=(const IndexRange &ir) const

operator!=

inline bool IsSingleIndex() const

Represents just 1 index.

inline int GetSingleIndex() const

Return single index if it is.

inline explicit operator int() const

explicit operator int(): get single index

Public Members

int beg_ = 0

begin index

int end_ = 0

end (= last+1) index

template<class Con>
class mp::IndicatorConstraint : public mp::BasicConstraint
#include <constr_general.h>

Indicator: b==bv -> [constraint].

Public Functions

inline IndicatorConstraint(int b, int bv, Con con) noexcept

Constructor.

inline bool check() const
inline int get_binary_var() const

Getters.

inline int get_binary_value() const
inline bool is_binary_value_1() const
inline const Con &get_constraint() const
template<class VarInfo>
inline Violation ComputeViolation(const VarInfo &x) const

Compute violation.

inline const char *GetName() const

Constraint name.

inline const char *name() const

Constraint name.

inline void SetName(std::string nm)

Set constraint name.

inline Context GetContext() const

Get context, if meaningful.

inline void SetContext(Context) const

Set context, if meaningful.

inline void AddContext(Context) const

Add (merge) context, if meaningful.

inline bool HasResultVar() const

Has result var (is functional)?

inline int GetResultVar() const

For functional constraints, result variable index.

Public Static Functions

static inline const char *GetTypeName()

Constraint type name.

static inline bool IsLogical()

Is logical?

static inline constexpr bool UsesContext()

Whether context is meaningful here.

Private Members

const int b_ = -1
const int bv_ = 1
const Con con_
template<class ModelConverter>
class mp::IndicatorLinEQConverter_MIP : public mp::IndicatorLinLEConverter_MIP<ModelConverter>
#include <indicator_eq.h>

Convert IndicatorLinLE.

b==val ==> c’x==d

Public Types

using Base = IndicatorLinLEConverter_MIP<ModelConverter>

Base class.

using ItemType = IndicatorConstraintLinEQ

Converted item type.

Public Functions

inline IndicatorLinEQConverter_MIP(ModelConverter &mc)

Constructor.

inline void Convert(const ItemType &indc, int)

Conversion.

inline void Convert(const ItemType &indc, int)

Conversion.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

Protected Functions

inline void ConvertImplicationLE(int b, int val, double body_ub, LinConLE con)

Linearize (b==val ==> c’x<=d) via big-M.

inline void ConvertImplicationLE(int b, int val, double body_ub, LinConLE con)

Linearize (b==val ==> c’x<=d) via big-M.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

inline ModelConverter &GetMC()

Access ModelConverter.

template<class ModelConverter>
class mp::IndicatorLinGEConverter_MIP : public mp::BasicItemConverter<ModelConverter>
#include <indicator_ge.h>

Convert IndicatorLinGE b==val ==> c’x>=d.

Public Types

using Base = BasicItemConverter<ModelConverter>

Base class.

using ItemType = IndicatorConstraintLinGE

Converted item type.

Public Functions

inline IndicatorLinGEConverter_MIP(ModelConverter &mc)

Constructor.

inline void Convert(const ItemType &indc, int)

Conversion.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

Protected Functions

inline void ConvertImplicationGE(int b, int val, double body_lb, LinConGE con)

Linearize (b==val ==> c’x>=d) via big-M.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

inline ModelConverter &GetMC()

Access ModelConverter.

template<class ModelConverter>
class mp::IndicatorLinLEConverter_MIP : public mp::BasicItemConverter<ModelConverter>
#include <indicator_le.h>

Convert IndicatorLinLE b==val ==> c’x<=d.

Subclassed by mp::IndicatorLinEQConverter_MIP< ModelConverter >

Public Types

using Base = BasicItemConverter<ModelConverter>

Base class.

using ItemType = IndicatorConstraintLinLE

Converted item type.

Public Functions

inline IndicatorLinLEConverter_MIP(ModelConverter &mc)

Constructor.

inline void Convert(const ItemType &indc, int)

Conversion.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

Protected Functions

inline void ConvertImplicationLE(int b, int val, double body_ub, LinConLE con)

Linearize (b==val ==> c’x<=d) via big-M.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

inline ModelConverter &GetMC()

Access ModelConverter.

template<class ModelConverter, int sens>
class mp::IndicatorQuadConverter_MIP : public mp::BasicItemConverter<ModelConverter>
#include <indicator_quad.h>

Convert IndicatorQuad(LE/EQ/GE) b==val ==> c’x + x’Qx (<=/==/>=) d.

The quadratic part is moved into a separate constraint, thus producing a linear indicator of the respective type.

Public Types

using Base = BasicItemConverter<ModelConverter>

Base class.

using QuadCon = AlgebraicConstraint<QuadAndLinTerms, AlgConRhs<sens>>

Underlying algebraic constraint.

using LinCon = AlgebraicConstraint<LinTerms, AlgConRhs<sens>>

Resulting implied linear constraint.

using ItemType = IndicatorConstraint<QuadCon>

Converted item type.

using IndicatorLin = IndicatorConstraint<LinCon>

Resulting linear indicator.

Public Functions

inline IndicatorQuadConverter_MIP(ModelConverter &mc)

Constructor.

inline void Convert(const ItemType &indc, int)

Conversion.

Substitute constraint body by a new variable.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

Protected Functions

inline const ModelConverter &GetMC() const

Access const ModelConverter.

inline ModelConverter &GetMC()

Access ModelConverter.

class mp::Interrupter
#include <solver-base.h>

An interface for interrupting solution process.

When a solver is run in a terminal it should respond to SIGINT (Ctrl-C) by interrupting its execution and returning the best solution found. This can be done in two ways. The first one is to check the return value of Interrupter::Stop() periodically. The second is to register an object that implements the Interruptible interface.

Subclassed by mp::BasicSolver, mp::internal::SignalHandler

Public Functions

inline virtual ~Interrupter()
virtual bool Stop() const = 0

Returns true if the solution process should be stopped.

virtual void SetHandler(InterruptHandler handler, void *data) = 0

Sets a handler function.

The handler function must be safe to call from a signal handler. In particular, it must only call async-signal-safe library functions.

struct mp::internal::NLReader::IntReader

Public Functions

inline int operator()(Reader &r) const
struct mp::NLHandler::IntSuffixHandler
#include <nl-reader.h>

A class (struct) that receives notifications of integer suffix values.

Public Functions

inline void SetValue(int index, int value)

Receives notification of a suffix value.

class mp::InvalidOptionValue : public mp::OptionError
#include <solver-opt.h>

An exception thrown when an invalid value is provided for an option.

Public Functions

template<typename T>
inline InvalidOptionValue(fmt::StringRef name, T value, fmt::StringRef msg = "")
template<typename T>
inline InvalidOptionValue(const SolverOption &opt, T value, fmt::StringRef msg = "")
inline int exit_code() const

The exit code.

Protected Functions

inline void SetMessage(const std::string &message)
inline void init(fmt::CStringRef format_str, fmt::ArgList args)

Private Static Functions

template<typename T>
static inline std::string Format(fmt::StringRef name, T value, fmt::StringRef msg)
template<ItemType T>
class mp::internal::NLReader::ItemHandler

Subclassed by mp::internal::NLReader< Reader, Handler >::AlgebraicConHandler

Public Functions

inline explicit ItemHandler(NLReader &r)

Public Static Attributes

static const ItemType TYPE = T

Protected Attributes

NLReader &reader_
class mp::BasicProblem::Range::iterator : public std::iterator<std::forward_iterator_tag, T>
#include <problem.h>

Public Functions

inline const T *operator->() const
inline T operator*() const
inline iterator &operator++()
inline iterator operator++(int)
inline bool operator==(iterator other) const
inline bool operator!=(iterator other) const

Private Functions

inline iterator(const BasicProblem *p, int index)

Private Members

T item_

Friends

friend class Range< T >
class mp::BasicSuffixSet::iterator : public std::iterator<std::forward_iterator_tag, Suffix>
#include <suffix.h>

A suffix iterator.

Public Functions

inline iterator(typename Set::const_iterator it)
inline Suffix operator*() const
inline Proxy operator->() const
inline iterator &operator++()
inline iterator operator++(int)
inline bool operator==(iterator other) const
inline bool operator!=(iterator other) const

Private Members

Set::const_iterator it_
class mp::ColProblemBuilder::LinearConHandler
#include <problem-builder.h>

Public Functions

inline void AddTerm(int var_index, double coef)

Private Functions

inline LinearConHandler(ColProblem &p, int con_index)

Private Members

ColProblem *problem_
int con_index_

Friends

friend class ColProblemBuilder
class mp::LinearExpr
#include <problem.h>

Linear expression (not affine: no constant term) used in mp::BasicProblem<>

Public Types

typedef std::vector<Term>::const_iterator const_iterator
typedef std::vector<Term>::iterator iterator

Public Functions

inline LinearExpr()
template<class CoefVec = std::vector<double>, class VarVec = std::vector<int>>
inline LinearExpr(CoefVec &&c, VarVec &&v)
template<int N>
inline LinearExpr(const std::array<double, N> &c, const std::array<int, N> &v)
inline int num_terms() const
inline int capacity() const
inline int var_index(int i) const
inline double coef(int i) const
inline void set_coef(int i, double c)
inline const_iterator begin() const
inline const_iterator end() const
inline iterator begin()
inline iterator end()
inline void AddTerm(int var_index, double coef)
inline void AddTerms(const LinearExpr &li)
template<class CoefVec = std::vector<double>, class VarVec = std::vector<int>>
inline void ConstructFrom(CoefVec &&c, VarVec &&v)
inline void Reserve(std::size_t num_terms)
void SortTerms()

Private Members

std::vector<Term> terms_
class mp::BasicProblem::LinearExprBuilder
#include <problem.h>

Public Functions

inline explicit LinearExprBuilder(LinearExpr *expr)
inline void AddTerm(int var_index, double coef)

Private Members

LinearExpr *expr_
struct mp::ProblemBuilder::LinearExprBuilder
#include <problem-builder.h>

Public Functions

inline void AddTerm(int var_index, double coef)
struct mp::NLHandler::LinearExprHandler
#include <nl-reader.h>

A class (struct) that receives notifications of terms in the linear part of a common expression.

Public Functions

inline void AddTerm(int var_index, double coef)

Receives notification of a term in the linear expression.

class mp::LinearFunctionalConstraint : public mp::FunctionalConstraint, public mp::NumericFunctionalConstraintTraits

Linear Functional Constraint: r = affine_expr.

Public Types

using Arguments = AffineExpr

Typedef Arguments.

Public Functions

inline LinearFunctionalConstraint(AffineExpr &&ae) noexcept

A constructor ignoring result variable: use AssignResultToArguments() then.

Not sorting+merging

inline LinearFunctionalConstraint(int r, AffineExpr &&ae) noexcept

Constructor with result variable known.

Not sorting+merging

inline const AffineExpr &GetAffineExpr() const

Get the affine expr.

inline const Arguments &GetArguments() const

Get the arguments (affine expr)

inline LinConEQ to_linear_constraint() const

Produce corresp linear constraint.

inline int GetResultVar() const

using GetResultVar()

inline bool operator==(const FunctionalConstraint &dc) const

Basic operator==.

inline bool HasResultVar() const

Has result var (is functional)? We don’t store this info in the type (yet.)

inline int GetResultVar() const

Get result variable.

inline void SetResultVar(int v)

Set result variable.

inline Context GetContext() const

Get it.

inline void SetContext(Context c) const

Set it.

inline void AddContext(Context c)

Add context.

inline void AddContext(Context) const

Add (merge) context, if meaningful.

inline const char *GetName() const

Constraint name.

inline const char *name() const

Constraint name.

inline void SetName(std::string nm)

Set constraint name.

template<class VarInfo>
inline Violation ComputeViolation(const VarInfo&) const

Compute violation.

Public Static Functions

static inline const char *GetTypeName()

Constraint type name.

static inline constexpr bool UsesContext()

Whether context is meaningful.

static inline constexpr bool IsLogical()

Whether the constraint is logical.

static inline std::pair<double, double> GetAprioriBounds()

Apriori bounds on the result.

Private Members

AffineExpr affine_expr_
class mp::LinearObjective
#include <obj_std.h>

Linear objective incl. sense and name.

Subclassed by mp::QuadraticObjective

Public Functions

template<class CoefVec = std::initializer_list<double>, class VarVec = std::initializer_list<int>>
inline LinearObjective(obj::Type s, CoefVec &&c, VarVec &&v, std::string nm = {}) noexcept

Construct.

inline obj::Type obj_sense() const

Get sense.

inline const LinTerms &GetLinTerms() const

Get lin terms, const.

inline LinTerms &GetLinTerms()

Get lin terms.

inline int num_terms() const

Get N terms.

inline bool check() const

Validate.

inline const std::vector<double> &coefs() const

Coefs vector.

inline const std::vector<int> &vars() const

Var vector.

inline const char *name() const

Name.

inline void set_name(std::string nm)

Set name.

inline bool operator==(const LinearObjective &lc) const

Testing API.

Private Members

obj::Type sense_
LinTerms lt_
std::string name_
struct mp::pre::LinkRange
#include <valcvt-link.h>

Link range: range of conversion specifiers of certain type.

The link object is specified as well

Public Functions

inline bool TryExtendBy(LinkRange br)

Try & extend the range.

Returns

true iff extension worked, otherwise the caller would have to record the new range separately

Public Members

BasicLink &b_

Reference to BasicLink.

LinkIndexRange ir_

Link index range.

class mp::pre::LinkRangeList : private std::deque<LinkRange>
#include <valcvt.h>

Array of link ranges.

This defines a chain of transformations

Public Types

using Base = std::deque<LinkRange>

Base class typedef.

Public Functions

inline void Add(LinkRange br)

Add another range to the list, tries to extend the last range if possible.

class mp::LinTerms
#include <expr_affine.h>

Linear terms: c’x.

Subclassed by mp::AlgebraicExpression< LinTerms >, mp::QuadAndLinTerms

Public Functions

LinTerms() = default

Default constructor.

inline LinTerms(std::vector<double> c, std::vector<int> v) noexcept

Construct from 2 vectors.

template<size_t N>
inline LinTerms(std::array<double, N> &c, std::array<int, N> &v)

Construct from 2 std::array’s.

inline bool check() const

Validate.

inline bool empty() const

empty()

inline size_t size() const

size()

inline double coef(size_t i) const

coef[i]

inline int var(size_t i) const

var[i]

inline const std::vector<double> &coefs() const

const vec& coefs()

inline const std::vector<int> &vars() const

const vec& vars()

inline const double *pcoefs() const

Ptr to coefs.

inline const int *pvars() const

Ptr to vars.

inline bool is_variable() const

true when 1 variable with coef 1.0

inline int get_representing_variable() const

return the single variable assuming true==is_variable()

inline const LinTerms &GetLinTerms() const

Produce itself.

template<class VarInfo>
inline long double ComputeValue(const VarInfo &x) const

Compute value given a dense vector of variable values.

inline void set_coef(size_t i, double c)

Set coef.

inline void reserve(size_t s)

Reserve size.

inline void add_term(double c, int v)

Add linear term.

inline void add(const LinTerms &le)

Add another LinTerms.

template<class Vec>
inline void add_terms(const Vec &v2)

Add terms from a vector of pairs {c, v}.

inline bool is_normalized() const

Is normalized? Assume terms are sorted.

inline void negate()

Negate.

inline void operator*=(double n)

Multiply by const.

inline void preprocess()

preprocess / canonicalize

void sort_terms(bool force_sort = false)

This a a NASTY one (when not used).

Use it before adding constraints / objectives. Add same variables, eliminate 0’s. Can be used by LinCon’s etc Gurobi complains when 0’s / repeated entries.

inline bool equals(const LinTerms &lt) const

Equality. Assumes being sorted.

inline bool operator==(const LinTerms &lt) const

operator== for hashing and testing

Public Static Functions

static inline constexpr const char *GetTypeName()

Name.

static inline constexpr bool is_linear()

Always linear.

Private Members

std::vector<double> coefs_
std::vector<int> vars_
template<class Container>
class mp::SolverOptionManager::ListOption : public mp::TypedSolverOption<Container::value_type>
#include <solver-opt.h>

List option: references a container of values.

Any container with value_type, back() and push_back().

Public Types

using value_type = typename Container::value_type
enum Option_Type

Option type classifier, used in AMPLS.

Values:

enumerator BOOL
enumerator INT
enumerator DBL
enumerator STRING

Public Functions

inline ListOption(const char *name_list, const char *description, Container &v, ValueArrayRef values = ValueArrayRef())
inline void GetValue(value_type &v) const override
inline void SetValue(typename internal::OptionHelper<value_type>::Arg v) override
inline virtual void Write(fmt::Writer &w) override

Formats the option value.

Throws OptionError in case of error. Not called for flags.

inline virtual void Parse(const char *&s, bool splitString = false) override

Parses the string for an option value, throws an exception if the value is invalid.

Parameters
  • s – string to be parsed

  • splitString – set to true to identify that the options string has already been pre-parsed (by the command line interpreter) so it is now in the format of null terminated substrings. If parsed from the environment variable, the string is monolithic, space separated and quotes have to be considered.

inline virtual Option_Type type() override

Return type classifier.

inline const char *name() const

Return the option name.

const char *name_ASL() const

Return the ASL (not qualified) name as the first inline synonym - or the name itself if no synonyms are defined.

inline const std::vector<std::string> &inline_synonyms() const

Returns the “inline” synonyms.

void add_synonyms_front(const char *names_list)

Add additional “inline” synonyms.

void add_synonyms_back(const char *names_list)
inline bool is_hidden() const

Is hidden?

inline bool is_wildcard() const

Wildcards.

bool wc_match(const std::string &key)

Checks if matches, then saves key & body.

inline const std::string &wc_head() const
inline const std::string &wc_tail() const
inline const std::string &wc_key_last() const
inline const std::string &wc_keybody_last() const
inline std::string wc_key_last__std_form() const

Printing last parsed wc key in std form.

inline const char *description() const

Return/set the option description.

inline void set_description(const char *d)
inline void add_to_description(const char *d)
inline void format_description(fmt::MemoryWriter &writer, int indent = 0) const

Append the formatted description to the writer.

inline std::string format_description(int indent = 0) const

Get the formatted option description.

inline ValueArrayRef values() const

Returns the information about possible values.

inline virtual bool is_flag() const

Returns true if this option is a flag, i.e. it doesn’t take a value.

inline virtual void GetValue(fmt::LongLong&) const

Returns the option value.

inline virtual void GetValue(double&) const
inline virtual void GetValue(std::string&) const
inline virtual void GetValue(int &int_value) const
template<typename T>
inline T GetValue() const
inline virtual void SetValue(fmt::LongLong)

Sets the option value or throws InvalidOptionValue if the value is invalid.

inline virtual void SetValue(double)
inline virtual void SetValue(fmt::StringRef)
inline virtual void SetValue(int value)
inline virtual std::string echo_with_value()

Echo option name(s) [= value].

inline virtual std::string echo()

Echo option name(s).

Private Members

Container &value_
struct mp::internal::Locale
#include <nl-reader.h>

Public Functions

inline double strtod(const char *&str) const
class mp::LogicalConstant : public mp::BasicExpr<expr::BOOL>
#include <expr.h>

A logical constant.

Examples: 0, 1

Public Types

enum [anonymous]

Values:

Public Functions

inline bool value() const

Returns the value of this constant.

Protected Types

typedef ExprBase::Impl Impl

Reuse ExprBase::Impl.

typedef BasicExpr Base

Base = BasicExpr.

Private Functions

MP_EXPR(Base)
class mp::LogicalCountExpr : public mp::BasicExpr<expr::FIRST_LOGICAL_COUNT, expr::LAST_LOGICAL_COUNT>
#include <expr.h>

A logical count expression.

Examples: atleast 1 (x < y, x != y), where x and y are variables.

Public Types

enum [anonymous]

Values:

Public Functions

inline NumericExpr lhs() const

Returns the left-hand side (the first argument) of this expression.

inline CountExpr rhs() const

Returns the right-hand side (the second argument) of this expression.

Protected Types

typedef ExprBase::Impl Impl

Reuse ExprBase::Impl.

typedef BasicExpr Base

Base = BasicExpr.

Private Functions

MP_EXPR(Base)
struct mp::internal::NLReader::LogicalExprReader

Public Types

typedef LogicalExpr Expr

Public Functions

inline Expr Read(NLReader &r) const
class mp::LogicalFunctionalConstraintTraits
#include <constr_base.h>

A base class for logical functional constraint.

It provides default properties of such a constraint

Subclassed by mp::CustomFunctionalConstraint< Con, ParamArray0, LogicalFunctionalConstraintTraits, CondConId< Con > >

Public Static Functions

static inline constexpr bool IsLogical()

Whether the constraint is logical.

static inline std::pair<double, double> GetAprioriBounds()

Apriori bounds on the result.

class mp::pre::Many2ManyLink : public mp::pre::BasicLink
#include <valcvt-link.h>

A very general link: each entry copies values from/to every position of the source range into/from every position of the target range.

Is specialized by One2Many and Many2One, and is not recommended to be used directly. In the cases when such a Many2Many connection exists, consider splitting via a (dummy) intermediate node and linking via Many2One + One2Many. Example: Unary Encoding.

Subclassed by mp::pre::Many2OneLink, mp::pre::One2ManyLink

Public Types

using LinkEntry = std::pair<NodeRange, NodeRange>

Single link entry, stores src + dest ranges.

using CollectionOfEntries = std::deque<LinkEntry>

Collection of entries.

using ItemRangeList = std::vector<NodeRange>

Typedef item container.

Public Functions

inline Many2ManyLink(ValuePresolver &pre)

Constructor.

inline virtual const char *GetTypeName() const override

Type name.

inline void AddEntry(LinkEntry be)

Add entry.

Instead of a new entry, tries to extend the last one if exists

inline virtual void ExportEntryItems(EntryItems &ei, int i) const override

Get source/target nodes for a given link entry.

This is used for graph export

Protected Functions

template<class T>
inline void Distr(NodeRange nr1, NodeRange nr2)

Distribute values of type T from nr1 to nr2.

template<class T>
inline void Collect(NodeRange nr1, NodeRange nr2)

Collect values of type T from nr2 to nr1.

template<class T>
inline void DistributeFromSrc2Dest(LinkIndexRange ir)

Src -> dest for the entries index range ir.

template<class T>
inline void CollectFromDest2Src(LinkIndexRange ir)

Collect src <- dest for index range ir. Loop backwards.

inline void RegisterLinkIndex(int i)

Add a range of link entries to the Presolver’s list.

Every derived link should call either of the next two methods whenever adding a link entry. Version 1: add single link

inline void RegisterLinkIndexRange(LinkIndexRange)

Version 2: add a range of links.

Implement link range registration in global Presolver.

Private Members

CollectionOfEntries entries_
class mp::pre::Many2OneLink : public mp::pre::Many2ManyLink
#include <valcvt-link.h>

A specialization of Many2ManyLink: each entry just copies from a range of values into 1 target value.

Useful for globalizing conversions, to transfer values from several items into a new item

Public Types

using LinkEntry = std::pair<NodeRange, NodeRange>

Single link entry, stores src + dest ranges.

using CollectionOfEntries = std::deque<LinkEntry>

Collection of entries.

using ItemRangeList = std::vector<NodeRange>

Typedef item container.

Public Functions

inline Many2OneLink(ValuePresolver &pre)

Constructor.

inline virtual const char *GetTypeName() const override

Type name.

inline void AddEntry(LinkEntry be)

Add entry.

inline virtual void ExportEntryItems(EntryItems &ei, int i) const override

Get source/target nodes for a given link entry.

This is used for graph export

Protected Functions

template<class T>
inline void Distr(NodeRange nr1, NodeRange nr2)

Distribute values of type T from nr1 to nr2.

template<class T>
inline void Collect(NodeRange nr1, NodeRange nr2)

Collect values of type T from nr2 to nr1.

template<class T>
inline void DistributeFromSrc2Dest(LinkIndexRange ir)

Src -> dest for the entries index range ir.

template<class T>
inline void CollectFromDest2Src(LinkIndexRange ir)

Collect src <- dest for index range ir. Loop backwards.

inline void RegisterLinkIndex(int i)

Add a range of link entries to the Presolver’s list.

Every derived link should call either of the next two methods whenever adding a link entry. Version 1: add single link

inline void RegisterLinkIndexRange(LinkIndexRange)

Version 2: add a range of links.

Implement link range registration in global Presolver.

template<int sense>
struct MaxOrMinConstraint
#include <min_max.h>

Type parameterization.

template<>
struct mp::MaxOrMinConstraint<1>
#include <min_max.h>

MaxConstraint.

Public Types

using ItemType = MaxConstraint
template<>
struct mp::MaxOrMinConstraint<-1>
#include <min_max.h>

MinConstraint.

Public Types

using ItemType = MinConstraint
template<class ModelConverter>
class mp::MCKeeper
#include <cones.h>

A class to store a ref to ModelConverter.

Parameters

ModelConverter – the converter type.

Subclassed by mp::ConicConverter< Impl >

Public Types

using MCType = ModelConverter

Typedef MCType.

Public Functions

inline MCKeeper(MCType &mc)

Constructor.

Protected Functions

inline const MCType &MC() const

Retrieve the MC.

inline MCType &MC()

Private Members

MCType &mc_
template<typename File = fmt::File>
class mp::MemoryMappedFile : public mp::internal::MemoryMappedFileBase
#include <os.h>

Public Functions

inline MemoryMappedFile()
inline MemoryMappedFile(const File &file, std::size_t size)
inline void map(const File &file, std::size_t size)
inline void map(const File &file, fmt::CStringRef filename)
inline const char *start() const
inline std::size_t size() const

Protected Functions

void map(int fd, std::size_t size)
void unmap()
class mp::internal::MemoryMappedFileBase
#include <os.h>

Subclassed by mp::MemoryMappedFile< File >

Public Functions

inline const char *start() const
inline std::size_t size() const

Protected Functions

inline MemoryMappedFileBase()
inline ~MemoryMappedFileBase()
void map(int fd, std::size_t size)
void unmap()

Private Functions

FMT_DISALLOW_COPY_AND_ASSIGN(MemoryMappedFileBase)

Private Members

char *start_
std::size_t size_
template<class Formatter>
class mp::MiniJSONWriter
#include <util-json-write.h>

A lightweight JSON writer.

Does not require an intermediate representation of the data. Similar to https://github.com/giacomodrago/minijson_writer but the string buffer writer is a template parameter with method write() conformant to fmt::format.

Template Parameters

Formatter – consumes provided data (e.g., numbers/strings) to produce a JSON string/file.

Public Types

using Node = MiniJSONWriter

Declare Node.

A node is a JSON tree node (value, array, dict.)

Public Functions

inline MiniJSONWriter(Formatter &wrt)

Construct with provided Formatter wrt.

Node operator++()

Prefix++: make/ensure *this an array, add and return a new element.

Useful when writing complex elements or non-supported types manually.

Node operator[](std::string_view key)

operator[]: make/ensure *this a dictionary, add and return a new element at key.

Allows the syntax node[key] = val;, or node[key] << val1 << val2 ...;, but also writing a complex subtree manually.

template<class Value>
inline Node &operator<<(const Value &val)

operator<<: make/ensure *this an array and write val a new element.

Equivalent: ++(*this) = val; return *this;

Parameters

val – scalar, tuple or container. For non-supported types, write elements manually into auto jw_child = ++jw;, or define, e.g., Serialize(MiniJSONWriter , const YourType& ), to be used as follows: Serialize(++jw, obj[5]); (instead of jw << obj[5].)

Returns

*this.

template<class Value>
inline void operator=(const Value &val)

operator=: write val as a whole.

Note

Can be called only once on a single node.

Parameters

val – scalar, tuple or container. For non-supported types, write elements manually into auto jw_child = jw["data"];, or define, e.g., Serialize(MiniJSONWriter , const YourType& ), to be used as follows: Serialize(jw["data"], obj_data); (instead of jw["data"] = obj_data.)

template<class It>
inline Node &WriteSequence(It b, It e)

Write a sequence between two iterators.

Returns

*this

void Close()

Close node.

Call this before writing to any non-child nodes, if not exiting the scope which calls the destructor.

inline ~MiniJSONWriter()

Destructor.

Closes node by RAII.

inline MiniJSONWriter(MiniJSONWriter &&other)

Move construct.

Protected Types

enum class Kind

Kind enum.

Values:

enumerator Unset
enumerator Scalar
enumerator Array
enumerator Dict
enumerator Closed

Protected Functions

inline MiniJSONWriter(MiniJSONWriter &parent)

Construct a child.

template<class Value>
inline void Write(const Value &val)

Generic value write.

void EnsureUnset()

Make sure this node has not been written into.

void MakeScalarIfUnset()

If unset, mark scalar node.

void EnsureArray()

Make sure this is an array node.

void EnsureDictionary()

Make sure this is a dictionary node.

void EnsureCanWrite()

Make sure we can write another value/element.

void InsertElementSeparator()

Insert element separator if needed.

inline void DoWrite(const char *s)
inline void DoWrite(const std::string &s)
template<typename Arithmetic, typename std::enable_if_t<std::is_arithmetic_v<Arithmetic>, int> = 0>
inline void DoWrite(Arithmetic v)
template<typename C, typename T = std::decay_t<decltype(*begin(std::declval<C>()))>>
inline void DoWrite(const C &c)

Write a container.

template<typename ...Arg>
inline void DoWrite(const std::tuple<Arg...> &tup)

https://www.cppstories.com/2022/tuple-iteration-apply/

template<class Value>
inline void DoWriteScalar(const Value &val)
template<class Str>
inline void DoWriteString(const Str &val)

Private Members

Formatter &wrt_
Kind kind_ = {Kind::Unset}
int n_written_ = {}
template<class ModelConverter, int sense>
class mp::MinOrMaxConverter_MIP : public mp::BasicFuncConstrCvt<MinOrMaxConverter_MIP<ModelConverter, sense>, ModelConverter>
#include <min_max.h>

Convert Min and Max for MIP.

Public Types

using Base = BasicFuncConstrCvt<MinOrMaxConverter_MIP<ModelConverter, sense>, ModelConverter>

Base class.

using ItemType = typename MaxOrMinConstraint<sense>::ItemType

ItemType.

Public Functions

inline MinOrMaxConverter_MIP(ModelConverter &mc)

Constructor.

template<class MinOrMaxConstraint>
inline void ConvertCtxPos(const MinOrMaxConstraint &mc, int)

Convert in positive context.

template<class MinOrMaxConstraint>
inline void ConvertCtxNeg(const MinOrMaxConstraint &mc, int)

Convert in negative context.

template<class MinOrMaxConstraint>
inline void ConvertConvexPart(const MinOrMaxConstraint &mc)

Convert the convex part.

template<class MinOrMaxConstraint>
inline void ConvertNonConvexPart(const MinOrMaxConstraint &mc)

Convert the non-convex part.

inline void Convert(const ItemType &item, int i)

Generic Convert(), distinguishes context & result variable.

Distinguish positive and negative context because if only one of these is necessary, significant model reduction can be achieved in certain cases.

Responsible for adding presolve links, if any

The Impl can reimplement this

Parameters
  • item – the item to be converted

  • i – item index, used to create a presolve link

inline void ConvertCtxNeg(const ItemType &item, int)

Convert in negative context.

inline void ConvertCtxPos(const ItemType &item, int)

Convert in positive context.

inline const ModelConverter &GetMC() const

Reuse the stored ModelConverter.

inline ModelConverter &GetMC()

Reuse the stored ModelConverter.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

template<class Impl, class BaseBackend = StdBackend<Impl>>
class mp::MIPBackend : public mp::StdBackend<Impl>
#include <backend-mip.h>

MIP backend wrapper.

The MIP wrapper provides common functionality relative to MIP solvers; it implements the common suffixes and the logic shared across all MIP solvers < parameter for base class

Public Types

using MPSolverBase = BackendWithModelManager
using MPUtils = MPSolverBase
using Callbacks = CCallbacks

Callbacks typedef.

enum [anonymous]

Possible values for the wantsol option (can be combined with bitwise OR).

Values:

enumerator WRITE_SOL_FILE
enumerator PRINT_SOLUTION
enumerator PRINT_DUAL_SOLUTION
enumerator SUPPRESS_SOLVER_MSG
enum [anonymous]

The default precision used in FormatObjValue if the objective_precision env variable is not specified or 0.

Values:

enumerator DEFAULT_PRECISION
enum [anonymous]

Solver flags.

Values:

enumerator MULTIPLE_SOL

Multiple solutions support.

Makes Solver register “countsolutions” and “solutionstub” options and write every solution passed to HandleFeastibleSolution to a file solutionstub & i & “.sol” where i is a solution number.

enumerator MULTIPLE_OBJ

Multiple objectives support.

Makes Solver register the “multiobj” option

using WarningsMap = std::map<std::string, std::pair<int, std::string>>

Map to count warnings by types.

Stores just 1 message for each type.

enum [anonymous]

Flags for ParseOptions.

Values:

enumerator NO_OPTION_ECHO

Don’t echo options during parsing.

enumerator FROM_COMMAND_LINE

When options are passed from command line (not via environment var) the quotes are automatically removed and the input string split in substrings (accessible via argv)

typedef std::unique_ptr<SolverOption> OptionPtr

Smart ptr to an option.

using set_option_iterator = option_iterator_base<OptionSet::iterator>

Alias for writeable option iterator.

using option_iterator = option_iterator_base<OptionSet::const_iterator>

Alias for const option iterator.

using SRRegMap = std::set<RegEntry>

Registry map.

Public Functions

inline bool IsMIP() const override

IsMIP().

Basic version: does not consider PL or SOS or Q(C)P.

inline virtual bool IsQP() const

IsQP()

inline virtual bool IsQCP() const

IsQCP()

inline virtual bool CanBeMIP() const

Always add MIP start if supported: Gurobi 9.1.2 solves non-convex Q(C)P as MIP.

But model attributes don’t work before solve. Distinguish LP / non-LP instead?

inline virtual void MarkLazyOrUserCuts(ArrayRef<int>)

Set lazy/user cut attributes.

Negative suffix values are “user cuts”. Check lazy_/user_cuts() to see which kinds are allowed. Presolve the values if needed.

inline virtual SolutionBasis GetBasis()

Get/Set AMPL var/con statii.

The basis statuses of vars and cons. MIPBackend handles them in postsolved form (for the NL model) Impl has to perform value pre- / postsolve if needed Getter (returns postsolved basis)

inline virtual void SetBasis(SolutionBasis)

Setter (takes unpresolved basis)

inline virtual void AddPrimalDualStart(Solution)

General LP warm start, e.g., set primal/dual initial guesses for continuous case.

The specific Backend should presolve the values if needed.

inline virtual void AddMIPStart(ArrayRef<double>, ArrayRef<int>)

MIP warm start.

Provides solution hints (dense vector), as well as sparsity pattern (dense 0-1 vector), allowing partial MIP warm start. Presolve the values if needed.

inline virtual void VarPriorities(ArrayRef<int>)

Set branch and bound priority.

inline virtual ArrayRef<double> Ray()

Obtain unbounded/inf rays.

inline virtual ArrayRef<double> DRay()
inline virtual void ComputeIIS()

Compute the IIS and obtain relevant values (postsolved)

inline virtual IIS GetIIS()
inline virtual double MIPGap()

Get MIP Gap.

Should return AMPLInf() if not available

inline virtual double MIPGapAbs()

Should return AMPLInf() if not available.

inline virtual double BestDualBound()

Get MIP dual bound.

inline virtual SensRanges GetSensRanges()

Report sensitivity analysis suffixes.

inline virtual void InputExtras() override

Input warm start, suffixes, and all that can modify the model.

This is used by the AMPLS C API

inline virtual void InputMIPExtras()
inline virtual void InputLazyUserCuts()
inline virtual void ReportProblemSuffix(const char *suf_name, int val)

Report a suffix on the problem.

Mainly used for testing.

inline virtual void InputStartValues()
inline virtual void InputPrimalDualStartOrBasis()
inline virtual void InputMIPStart()
inline virtual void ReportStandardSuffixes() override

Report standard suffixes.

inline virtual void ReportStandardMIPSuffixes()
inline virtual void ReportBasis()
inline virtual void ReportRays()
inline virtual void CalculateAndReportIIS()
inline virtual void CalculateAndReportMIPGap()
inline virtual void ReportBestDualBound()
inline virtual void ReportSensitivity()
inline virtual void InitStandardOptions() override
virtual Solution GetSolution() = 0

Further, using virtual methods for convenience (CRTP not essential)

Placeholder for solution getter (postsolved, final solution)

virtual ArrayRef<double> GetObjectiveValues() = 0

Placeholder for objective values getter (postsolved, final solution) Used only if we don’t want the solution values, otherwise GetSolution() provides this.

inline virtual void RunFromNLFile(const std::string &nl_filename, const std::string &filename_no_ext) override

FeasRelax No API to overload, Impl should check:

  • feasrelax() returns feasrelax mode

  • feasrelax().(methods) give the API MIP solution rounding Nothing to do for the Impl, enabled by default Model export. Redefine to true and implement the method. Redefine this if you want some extensions to be written after solving instead. This is for compatibility wiht ASL drivers where ‘writeprob’ was used for native-format model and solution output #218. Solution export. Redefine to true and implement the method. Runs Solver given the NL file name. This is called from BackendApp.

inline virtual void ReadNL(const std::string &nl_filename, const std::string &filename_no_ext, char **opts) override

Detailed steps for AMPLS C API.

Read NL.

Parameters

opts – extra options (to be read after the [solver]_options env var). All model-related options should be here (obj:…/objno/multiobj, cvt:…, acc:…).

inline void SetSolutionFileName(const std::string &filename)
inline virtual void ReportResults() override

Report results.

inline virtual void InitMetaInfoAndOptions() override

Deriving backends can use this.

inline virtual void InitNamesAndVersion()
inline const MPUtils &GetMPUtils() const
inline MPUtils &GetMPUtils()
inline virtual void ReportSolutionViaSolver()

Write solution result in solver native format via solver’s output.

inline virtual void ExportModel(const std::vector<std::string> &filenames)

Write model.

inline bool need_multiple_solutions() const

Need mutiple solutions.

inline void Print(fmt::CStringRef format, const fmt::ArgList &args)

Variadic overload of ReportError()

Formats a string and prints it to stdout or, if an output handler is registered, sends it to the output handler.

inline void Print(fmt::CStringRef format, const fmt::ArgList &args)

Variadic overload of ReportError()

Formats a string and prints it to stdout or, if an output handler is registered, sends it to the output handler.

inline void add_to_long_name(fmt::StringRef name)
inline void add_to_version(fmt::StringRef version)
inline virtual void Init(char **argv) override

Initialize backend, incl.

solver options

Parameters

argv – the command-line arguments, NULL-terminated

inline virtual void ReportError(int solve_result, fmt::CStringRef msg) override

Can be overridden.

For example, if we know the output name, this should write .sol file with the solve_result and msg.

inline void ReportError(fmt::CStringRef format, const fmt::ArgList &args)

Reports an error by throwing it.

Usage: ReportError(“File not found: {}”) << filename;

inline virtual void SetOptionData(char **argv, int f)

Provide cmdline solver options list and flags.

inline virtual bool ParseSolverOptions(char **argv, unsigned flags = 0)

Parse solver options such as “outlev=1” from env and argv.

Parameters
  • argv – (remaining part of) vector of cmdline strings

  • flags – 0 or Solver::NO_OPTION_ECHO

inline virtual void InitOptionParsing()

Chance for the Backend to init solver environment, etc.

inline virtual void FinishOptionParsing()

Chance to consider options immediately (open cloud, etc)

inline Callbacks &GetCallbacks()

Obtain callbacks.

inline void OverrideSolutionFile(const std::string &solFile)
inline std::string GetOverridenSolutionFile()
inline std::string GetOptionFile(const SolverOption&) const

Name of the file with option settings, provided by tech:optionfile.

void UseOptionFile(const SolverOption&, fmt::StringRef value)

Read otpions from option file.

inline int GetWantSol(const SolverOption&) const

wantsol value

inline void SetWantSol(const SolverOption&, int value)

set wantsol

inline std::string GetSolutionStub(const SolverOption&) const

solution output filename stub

inline void SetSolutionStub(const SolverOption&, fmt::StringRef value)

Set sol stub.

inline int GetObjNo(const SolverOption&) const

Obj number.

inline void SetObjNo(const SolverOption &opt, int value)

Set obj number.

inline int GetTiming(const SolverOption&) const
inline void SetTiming(const SolverOption &opt, int value)
inline const char *name() const

Returns the solver name.

This is used to extract solver options from the env variable (solver_name)_options.

inline const char *long_name() const

Returns the long solver name.

This name is used in startup “banner”.

inline const char *exe_path() const

Returns the executable path.

inline void set_exe_path(const char *p)
inline const char *version() const

Returns the solver version.

inline long date() const

Returns the solver date in YYYYMMDD format.

inline int wantsol() const

Returns the value of the wantsol option which specifies what solution information to write in a stand-alone invocation (no -AMPL on the command line).

inline void set_wantsol(int value)
inline bool ampl_flag()
inline void set_ampl_flag(bool value = true)
inline bool verbose_mode() const

True if verbose mode.

Should be set by the implementation, otherwise it’s true

inline void set_verbose_mode(bool f)

Set verbosity, by the impl.

inline bool debug_mode() const

True if need to debug.

Outputs test infos etc

inline int objno_used() const

Returns the index of the objective to optimize starting from 1, 0 to not use objective.

inline int objno_specified() const

objno_specified(): actually even if not specified, it returns the objno to use (0 - feasibility, otherwise obj index).

Both multiobj() and objno_specified() are used in NLReader to select the objective(s), solvers should not use these accessors.

inline bool is_objno_specified() const

Whether user specified the option objno.

inline void notify_obj_added()

Notify Solver if an objective is added.

inline void notify_start_opts()

Notify Solver we start reading options.

inline void notify_end_opts()

Notify we are done.

inline bool multiobj() const

Returns true if multiobjective optimization is enabled.

Both multiobj and objno are used in NLReader to select the objective(s), solvers should not use these options.

inline int timing() const

>0 if the timing is enabled

inline ErrorHandler *error_handler()

Return error handler.

inline void set_error_handler(ErrorHandler *eh)

Set the error handler.

inline OutputHandler *output_handler()

Return output handler.

inline OutputHandler &get_output_handler()

Return output handler.

inline void set_output_handler(OutputHandler *oh)

Sets the output handler.

inline const Interrupter *interrupter() const

Interrupter, const.

inline Interrupter *interrupter()

Interrupter.

inline void set_interrupter(Interrupter *interrupter)

Set interrupter.

inline const char *solution_stub() const

Sol stub as char*.

inline virtual void HandleOutput(fmt::CStringRef output) override

Override methods from base service classes.

inline virtual void HandleError(fmt::CStringRef message) override

Handle error.

inline virtual bool Stop() const override

The default implementation of Interrupter does nothing.

inline virtual void SetHandler(InterruptHandler, void*) override

Set interrupt handler.

inline virtual void HandleUnknownOption(const char *name)

Handle unknown option.

const char *GetSolCheckWarningKey(bool f_recomp) const

Variadic overload of Print()

Get solution check warnings key name.

Parameters

f_recomp – whether with recomputed auxiliaries.

void AddWarning(std::string key, std::string msg, bool replace = false)

Add a warning.

Parameters
  • key – warning category

  • msg – detailed message

const std::pair<int, std::string> &GetWarning(const std::string &key)

Get a warning type.

void ClearWarning(const std::string &key)

Clear a warning type.

std::string GetWarnings() const

Get warnings as string.

void PrintWarnings()

Print warnings.

bool ShowVersion()

Prints version information.

DoubleFormatter FormatObjValue(double value)

Returns a formatter that writes value using objective precision.

Usage: Print(“objective {}”, FormatObjValue(obj_value));

virtual bool ParseOptions(char **argv, unsigned flags = 0, const ASLProblem *p = 0)

Parses solver options from the (solver)_options env variable and/or strings in argv.

For example, solver_options=’timelim=300’ solver /tmp/diet.nl -AMPL “basis=0”.

Returns

true if there were no errors and false otherwise. It accepts a pointer to the problem because some options may depend on problem features.

void ParseOptionString(const char *s, unsigned flags)

Parses a solver option string.

inline const WarningsMap &GetWarningsMap() const

Get warnings map.

inline WarningsMap &GetWarningsMap()
inline void SetConstraintListHeader(std::string clh)

Set constraint list header (printed at the start of -c)

inline void AddConstraintDescr(std::string cn, std::string cdescr)

Add constraint type description.

bool ShowConstraintDescriptions()

Show constraint descriptions.

inline virtual void RecordOutputTime()
inline virtual void RecordSetupTime()

Record setup time.

inline void SetReadTime(double read_time)
inline void SetConversionTime(double conv_time)
inline virtual void RecordSolveTime()

Record solve time.

inline int num_options() const

Returns the number of options.

inline SolverOption *GetOption(const char *name) const

Returns the option with specified name.

inline void set_option_header(const char *header)

Sets a text to be displayed before option descriptions.

inline void add_to_option_header(const char *header_more)

Add more text to be displayed before option descriptions.

void AddOption(OptionPtr opt)

Add an option.

template<class Value>
inline void AddOption(const char *name, const char *description, Value &value, Value lb, Value ub)

Same: stored option referencing a variable; min, max values.

Note

description “HIDDEN” means the option is not printed

SolverOption *FindOption(const char *name, bool wildcardvalues = false) const

Finds an option and returns a pointer to it if found or null otherwise.

If wildcardvalues==true, wildcarded options should have values (i.e., parsing real input)

inline const char *option_header() const

Returns the option header.

inline fmt::LongLong GetIntOption(const char *name) const

Returns the value of an integer option.

Throws OptionError if there is no such option or it has a different type.

inline void SetIntOption(const char *name, fmt::LongLong value)
inline double GetDblOption(const char *name) const
inline void SetDblOption(const char *name, double value)
inline std::string GetStrOption(const char *name) const
inline void SetStrOption(const char *name, fmt::StringRef value)
template<class Value>
inline void AddStoredOption(const char *name, const char *description, Value &value, ValueArrayRef values = ValueArrayRef())

Simple stored option referencing a variable.

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddStoredOption(const char *name, const char *description, Value &value, Value, Value)

Simple stored option referencing a variable; min, max values (they are unused but to deduce type; we are too lazy to maintain correct min/max between solver versions.)

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddListOption(const char *name, const char *description, Value &value, ValueArrayRef values = ValueArrayRef())

Add list option referencing a container.

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddListOption(const char *name, const char *description, Value &value, typename Value::value_type, typename Value::value_type)

Add list option referencing a container; min, max values (they are unused but to deduce type; we aree too lazy to maintain correct min/max between solver versions.)

Note

description “HIDDEN” means the option is not printed

inline void ReplaceOptionDescription(const char *name, const char *desc)

Replace option descr.

inline void AddToOptionDescription(const char *name, const char *desc_add)

Add to option descr.

void AddOptionSynonyms_Inline_Front(const char *names_list, const char *realName)

Add “inline” option synonyms.

The _Front version puts them in the front of the synonyms list and the 1st of them is used in the -a output for sorting.

void AddOptionSynonyms_Inline_Back(const char *names_list, const char *realName)

Add “inline” option synonyms.

The _Back version.

void AddOptionSynonyms_OutOfLine(const char *name, const char *realName)

Add an “out-of-line” synonym.

Creates extra entry under -=

template<typename Handler, typename Int>
inline void AddIntOption(const char *name, const char *description, Int (Handler::* get)(const SolverOption&) const, void (Handler::* set)(const SolverOption&, Int))

Adds an integer option.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddIntOption(const char *name, const char *description, int (Handler::* get)(const SolverOption&, const Info&) const, void (Handler::* set)(const SolverOption&, int, const Info&), const Info &info)

Adds an integer option with additional information.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddIntOption(const char *name_list, const char *description, int (Handler::* get)(const SolverOption&, Info) const, void (Handler::* set)(const SolverOption&, int, Info), Info info)

The same as above but with Info argument passed by value.

Note

description “HIDDEN” means the option is not printed

template<typename Handler>
inline void AddDblOption(const char *name, const char *description, double (Handler::* get)(const SolverOption&) const, void (Handler::* set)(const SolverOption&, double))

Adds a double option.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddDblOption(const char *name, const char *description, double (Handler::* get)(const SolverOption&, const Info&) const, void (Handler::* set)(const SolverOption&, double, const Info&), const Info &info)

Adds a double option with additional information.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddDblOption(const char *name, const char *description, double (Handler::* get)(const SolverOption&, Info) const, void (Handler::* set)(const SolverOption&, double, Info), Info info)

The same as above but with Info argument passed by value.

Note

description “HIDDEN” means the option is not printed

template<typename Handler>
inline void AddStrOption(const char *name, const char *description, std::string (Handler::* get)(const SolverOption&) const, void (Handler::* set)(const SolverOption&, fmt::StringRef), ValueArrayRef values = ValueArrayRef())

Adds a string option.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddStrOption(const char *name, const char *description, std::string (Handler::* get)(const SolverOption&, const Info&) const, void (Handler::* set)(const SolverOption&, fmt::StringRef, const Info&), const Info &info, ValueArrayRef values = ValueArrayRef())

Adds a string option with additional information.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddStrOption(const char *name, const char *description, std::string (Handler::* get)(const SolverOption&, Info) const, void (Handler::* set)(const SolverOption&, fmt::StringRef, Info), Info info, ValueArrayRef values = ValueArrayRef())

The same as above but with Info argument passed by value.

Note

description “HIDDEN” means the option is not printed

inline option_iterator option_begin() const

Get the start const-iterator.

inline option_iterator option_end() const

Get the end const-iterator.

inline set_option_iterator set_option_begin() const

Get the start writeable iterator.

inline set_option_iterator set_option_end() const

Get the end writeable iterator.

void AddSolveResults(const SRRegMap &sm, bool ifCanReplace = false)

Add a map with result descriptions.

inline const SRRegMap &GetSolveResultRegistry() const

Get the registry.

Public Members

USING_STD_FEATURES

Public Static Functions

static inline const char *GetSolverName()

Name displayed in messages.

static inline std::string GetSolverVersion()

And version.

static inline const char *GetAMPLSolverName()

AMPL solver name is used to parse solver options for the [name]_options environment variable.

This is only done if the [executable_name]_options variable is not provided.

static inline const char *GetAMPLSolverLongName()

Unused.

static inline long Date()

Unused.

static inline int Flags()

Default mp::Solver flags, used there to implement multiobj and .nsol.

static std::string ToString(const WarningsMap::value_type &wrn)

Stringify a WarningsMap entry.

Protected Types

using PMM = std::unique_ptr<BasicModelManager>

Protected Functions

inline const Options &GetMIPOptions() const
inline Options &GetMIPOptions()
inline int lazy_user_cuts() const
inline bool lazy_cuts() const

Whether we need to mark .lazy>0 cuts as ‘lazy’.

inline bool user_cuts() const

Whether we need to mark .lazy<0 cuts as ‘user’.

inline int basis() const
inline bool need_basis_in() const
inline bool need_basis_out() const
inline int warmstart() const
inline int priorities() const
inline int rays() const
inline bool need_ray_primal() const
inline bool need_ray_dual() const
inline int sensitivity() const
inline int need_fixed_MIP() const

Whether need duals/basis/sens from MIP Need at least duals when this option is on.

inline virtual void InitMIPOptions()
inline virtual void ObjPriorities(ArrayRef<int>)

MULTIOBJ support.

Placeholder: set objective priorities

inline virtual void ObjWeights(ArrayRef<double>)

Placeholder: set objective weights.

Presolve the values if needed

inline virtual void ObjAbsTol(ArrayRef<double>)

Placeholder: set objective abs tol Presolve the values if needed.

inline virtual void ObjRelTol(ArrayRef<double>)

Placeholder: set objective rel tol Presolve the values if needed.

inline virtual double Kappa()

MULTISOL support No API to overload, Impl should check need_multiple_solutions() and call ReportIntermediateSolution({x, pi, objvals}) for each (postsolve the values if needed)

Kappa estimate Placeholder: retrieve Kappa

virtual void Solve() override = 0

Solve, no model modification any more.

Can report intermediate results via ReportIntermediateSolution() during this, otherwise in ReportResults()

inline virtual void Report()

Report.

inline virtual void InputStdExtras()

Standard extras.

inline virtual void SetupTimerAndInterrupter()

Timer, interrupter.

inline virtual void SetupInterrupter()

Call SetInterrupter() which can be defined in Impl.

virtual void SetInterrupter(mp::Interrupter*) = 0

Placeholder for interrupt notifier in Impl.

inline virtual void ReportTimes()
inline virtual void InputFeasrelaxData()

Input feasrelax data Impl should presolve it if needed.

inline virtual void ReportSuffixes()

Report suffixes.

inline virtual void ReportKappa()

Report Kappa.

inline virtual void ReportCustomSuffixes()

Placeholder: report custom suffixes.

inline void ReportIntermediateSolution(Solution sol)

Callback.

Parameters

sol – postsolved solution. Normally report all alternative solutions, including the final one, before reporting the final solution via standard way (ReportSolution).

inline virtual void ReportSolution()

Report final solution.

inline virtual void ReportSolution2AMPL()

to AMPL via SOL file

inline virtual void Abort(int solve_code_now, std::string msg)

Abort.

inline void RoundSolution(std::vector<double> &sol, fmt::MemoryWriter &writer)

MIP solution rounding. Better use solver’s capabilities.

inline std::pair<int, double> DoRound(std::vector<double> &sol)
inline void ModifySolveCodeAndMessageAfterRounding(std::pair<int, double> rndres, fmt::MemoryWriter &writer)
inline virtual int SolveCode() const

Solve result number.

inline const char *SolveStatus() const

Solver result message.

inline void SetStatus(std::pair<int, std::string> stt)

Set solve result.

inline virtual bool IsProblemSolved() const

Following the taxonomy of the enum sol, returns true if we have an optimal solution or a feasible solution for a satisfaction problem.

inline virtual bool IsProblemSolvedOrFeasible() const

Solved or feasible.

inline virtual bool IsProblemIndiffInfOrUnb() const

Undecidedly infeas or unbnd.

inline virtual bool IsProblemInfOrUnb() const

Infeasible or unbounded.

inline virtual bool IsProblemInfeasible() const
inline virtual bool IsProblemUnbounded() const
inline virtual bool IsSolStatusRetrieved() const
inline bool IsFinite(double n) const

Use the solver’ inf.

inline void AddToSolverMessage(const std::string &msg)
inline bool onlyRecordOptions()
inline void RecordSolverOption(SlvOptionRecord sor)
inline void ReplaySolverOptions()
template<class KeyType, class ValueType = std::string>
inline void AddSolverOption(const char *name_list, const char *description, KeyType k, ValueType, ValueType)

Adding solver options of types int/double/string/…

The type is deduced from the two last parameters min, max (currently unused otherwise.) If min/max omitted, assume ValueType=std::string Assumes existence of Impl::Get/SetSolverOption(KeyType, ValueType(&))

template<class KeyType, class ValueType = std::string>
inline void AddSolverOption(const char *name_list, const char *description, KeyType k)

String-valued option.

template<class KeyType, class ValueType = std::string>
inline void AddSolverOption(const char *name_list, const char *description, KeyType k, ValueArrayRef values, ValueType defaultValue)

With value table.

Type deduced from defaultValue

template<class KeyType>
inline void AddSolverOption(const char *name_list, const char *description, KeyType k, ValueArrayRef values, const char *defaultValue)

With value table: specialize for const char*.

inline int exportKappa() const
inline FeasrelaxIO &feasrelax()

Feasrelax I/O data.

inline double lbpen() const
inline double ubpen() const
inline double rhspen() const
inline int round() const

Whether to round MIP solution and modify messages.

inline double round_reptol() const

MIP solution rounding reporting tolerance.

inline int exportFileMode() const

Return 2 if we only need to write the problem, 1 if solution and export are wanted, 0 if no export is needed or supported.

inline const std::vector<std::string> &export_file_names() const
inline virtual void InitCustomOptions()
void InitMetaInfoAndOptions(fmt::CStringRef name, fmt::CStringRef long_name, long date, int flags)

InitMetaInfoAndOptions.

Derived classes which want to provide the info after construction can use the default constructor and call this.

Parameters
  • date – The solver date in YYYYMMDD format.

  • flags – Bitwise OR of zero or more of the following values MULTIPLE_SOL MULTIPLE_OBJ

inline std::vector<double> FillFeasrelaxPenalty(ArrayRef<double> suf_pen, double pen, int n)

Returns {} if these penalties are +inf.

inline bool need_multiple_solutions() const

For Impl to check if user wants multiple solutions reported.

inline void add_to_long_name(fmt::StringRef name)
inline void add_to_version(fmt::StringRef version)
inline const BasicModelManager &GetMM() const
inline BasicModelManager &GetMM()
inline void SetMM(PMM pmm)
inline virtual void HandleSolution(int status, fmt::CStringRef msg, const double *x, const double *y, double obj)

Access to ModelManager’s interface.

inline virtual void HandleFeasibleSolution(int solve_code, fmt::CStringRef msg, const double *x, const double *y, double obj)
inline virtual ArrayRef<double> InitialValues()

Variables’ initial values.

inline virtual ArrayRef<int> InitialValuesSparsity()

Variables’ initial values: sparsity.

inline virtual ArrayRef<double> InitialDualValues()

Initial dual values.

inline virtual ArrayRef<int> InitialDualValuesSparsity()

Initial dual values.

template<class N>
inline ArrayRef<N> ReadSuffix(const SuffixDef<N> &suf)

Read unpresolved suffix.

inline virtual ArrayRef<int> ReadIntSuffix(const SuffixDef<int> &suf)
inline virtual ArrayRef<double> ReadDblSuffix(const SuffixDef<double> &suf)
inline virtual size_t GetSuffixSize(int kind)
inline virtual void ReportSuffix(const SuffixDef<int> &suf, ArrayRef<int> values)

Record suffix values which are written into .sol by HandleSolution() Does nothing if vector empty.

inline virtual void ReportSuffix(const SuffixDef<double> &suf, ArrayRef<double> values)
inline virtual void ReportIntSuffix(const SuffixDef<int> &suf, ArrayRef<int> values)
inline virtual void ReportDblSuffix(const SuffixDef<double> &suf, ArrayRef<double> values)
template<class N>
inline void ReportSingleSuffix(const SuffixDef<N> &suf, N value)

Report single value for all elements of the suffix.

inline const std::vector<bool> &IsVarInt() const

Access original (NL) model instance: integrality flags.

Used in solution rounding.

inline bool HasUnfixedIntVars() const

Solver-facing instance info: has unfixed integer variables?

inline char **GetArgvOptions() const

0-terminated list of custom options

inline int GetOptionFlags() const

option parser flags

inline void set_long_name(fmt::StringRef name)
inline void set_version(fmt::StringRef version)
inline void set_license_info(fmt::StringRef license_info)
inline virtual std::string set_external_libs()
inline void set_read_flags(unsigned flags)

Sets the flags for Problem::Read.

inline Stats &stats()

Protected Attributes

const mp::OptionValueInfo values_01_noyes_0default_[2] = {{"0", "No (default)", 0}, {"1", "Yes.", 1}}
const mp::OptionValueInfo values_01_noyes_1default_[2] = {{"0", "No", 0}, {"1", "Yes (default)", 1}}
const mp::OptionValueInfo values_autonoyes_[3] = {{"-1", "Automatic choice (default)", 0}, {"0", "No", 0}, {"1", "Yes.", 1}}
const mp::OptionValueInfo values_autonomodaggr_[4] = {{"-1", "Automatic choice (default)", 0}, {"0", "No", 0}, {"1", "Yes, moderate", 1}, {"2", "Yes, aggressive.", 2}}
const mp::OptionValueInfo values_autonoconsaggr_[4] = {{"-1", "Automatic choice (default)", -1}, {"0", "No", 0}, {"1", "Conservative", 1}, {"2", "Aggressive.", 2}}
const mp::OptionValueInfo values_basis_[4] = {{"0", "No", 0}, {"1", "Use incomingbasis(if provided)", 1}, {"2", "Return finalbasis", 2}, {"3", "Both (1 + 2 = default)", 3}}
const mp::OptionValueInfo values_warmstart_[3] = {{"0", "No", 0}, {"1", "Yes (for LP: if there is no incoming alg:basis) (default)", 1}, {"2", "Yes (for LP: ignoring the incoming alg:basis, if any.)", 2}}
const mp::OptionValueInfo values_rays_[4] = {{"0", "Neither", 0}, {"1", "Just .unbdd", 1}, {"2", "Just .dunbdd", 2}, {"3", "Both (default)", 3}}
bool onlyRecordOptions_ = false

Protected Static Functions

static inline constexpr double AMPLInf()

AMPL’s inf.

static inline constexpr double AMPLMinusInf()

AMPL’s -inf.

Private Members

Options mipStoredOptions_
const SuffixDef<int> suf_varstatus = {"sstatus", suf::VAR | suf::OUTPUT}
const SuffixDef<int> suf_constatus = {"sstatus", suf::CON | suf::OUTPUT}
const SuffixDef<int> suf_testvarstatus = {"test_sstatus", suf::VAR | suf::OUTPUT}

Testing API Output suffix values to check they were read correctly.

const SuffixDef<int> suf_testconstatus = {"test_sstatus", suf::CON | suf::OUTPUT}
const SuffixDef<double> suf_testvarini = {"test_ini_pri", suf::VAR | suf::OUTPUT}

Testing API Output primal/dual initials to check they were read correctly.

const SuffixDef<double> suf_testconini = {"test_ini_dua", suf::CON | suf::OUTPUT}
const SuffixDef<double> suf_testMIPini = {"test_ini_mip", suf::VAR | suf::OUTPUT}

Testing API Output MIP initials to check they were read correctly.

const SuffixDef<int> suf_varpriority = {"priority", suf::VAR | suf::INPUT}
const SuffixDef<double> suf_unbdd = {"unbdd", suf::VAR | suf::OUTPUT}
const SuffixDef<double> suf_dunbdd = {"dunbdd", suf::CON | suf::OUTPUT}
const SuffixTable iis_table  ="\n""0 non not in the iis\n""1 low at lower bound\n""2 fix fixed\n""3 upp at upper bound\n""4 mem member\n""5 pmem possible member\n""6 plow possibly at lower bound\n""7 pupp possibly at upper bound\n""8 bug\n"
const SuffixDef<int> sufIISCon = {"iis", suf::CON | suf::OUTPUT, iis_table}
const SuffixDef<int> sufIISVar = {"iis", suf::VAR | suf::OUTPUT, iis_table}
const SuffixDef<double> sufRelMipGapObj = {"relmipgap", suf::OBJ | suf::OUTPUT}
const SuffixDef<double> sufRelMipGapProb = {"relmipgap", suf::PROBLEM | suf::OUTPUT}
const SuffixDef<double> sufAbsMipGapObj = {"absmipgap", suf::OBJ | suf::OUTPUT}
const SuffixDef<double> sufAbsMipGapProb = {"absmipgap", suf::PROBLEM | suf::OUTPUT}
const SuffixDef<double> sufBestBoundObj = {"bestbound", suf::OBJ | suf::OUTPUT}
const SuffixDef<double> sufBestBoundProb = {"bestbound", suf::PROBLEM | suf::OUTPUT}
template<class Impl, class ModelAPI, class Model = FlatModel<>>
class mp::MIPFlatConverter : public mp::FlatConverter<Impl, ModelAPI, FlatModel<>>
#include <converter_mip.h>

MIPFlatConverter: converts flattened expressions for MIP.

Public Types

using BaseConverter = FlatConverter<Impl, ModelAPI, Model>

BaseConverter typedef.

using Var = typename FlatModel::Var

Trying to use ‘Var’ instead of bare ‘int’.

using VarArray = std::vector<int>

Array of variable Id’s.

using ConInfo = AbstractConstraintLocation

Typedef ConInfo; constraint location.

using ModelType = FlatModel<>

The internal flat model type.

using ModelAPIType = ModelAPI

Typedef ModelAPIType. For tests.

using Params = DefaultFlatModelParams
using VarTypeVec = std::vector<var::Type>
using VarNameVec = std::vector<const char*>
using ObjList = std::vector<QuadraticObjective>

List of objectives.

using VarBndVec = std::vector<double>

Typedef VarBndVec.

Public Functions

inline MIPFlatConverter(Env &e)

Constructor.

USE_BASE_CONSTRAINT_CONVERTERS(BaseConverter)

MIP CONSTRAINT CONVERTERS /////////////////////// Reuse default (empty) ones.

inline double ComparisonEps(int var) const

Abs.

And AllDiff Complementarity linear Complementarity quadratic Count Div CondLinEQ CondQuadEQ CondLinLE CondQuadLE CondLinLT CondQuadLT CondLinGE CondQuadGE CondLinGT CondQuadGT IfThenElse Implication ImplLE ImplEQ ImplGE ImplQuadLE ImplQuadEQ ImplQuadGE Min Max Not NumberofConst NumberofVar Or PLConstraint PowConstExp SOS2 Smooth nonlinear Multiplication Exp ExpA Log LogA Sin Cos Tan ASin ACos ATan Sinh Cosh Tanh ASinh ACosh ATanh Strict comparison tolerance. Need a big eps to avoid misinterpretation, at least the solver’s feasibility tolerance

inline double ComparisonEps(var::Type vartype) const

Strict comparison tolerance.

inline int MapFind(const CondLinConEQ &eq0c)

Specialize MapFind for CondLinConEQ.

We distinguish the case var==const

inline bool MapInsert(const CondLinConEQ &eq0c, int i)

Specialize MapInsert for CondLiConEQ.

inline void ConvertMaps()

Convert MIP-specific maps.

inline bool IfMightUseEqualityEncodingForVar(int var) const

Whether might use equality encoding for var.

inline std::vector<double> GetZZIExtendedColumn(int r, int k, int v0, int v1)

Obtain extended column k of ZZI encoding C^r.

inline void InitOptions()

Init MIPFlatConverter options.

inline double cmpEpsContinuous() const
inline double bigMDefault() const
inline double PLApproxRelTol() const
inline double PLApproxDomain() const
inline void FixAsTrue(int resvar)

Fix the resulting variable of a logical expression as true and propagate positive ctx.

Currently this happens for all root-context logical constraints, i.e., we create an auxiliary variable which is later fixed to 1.

inline void PropagateResultOfInitExpr(int var, Context ctx)

Reverse propagate result variable of an expression.

inline void PropagateResultOfInitExpr(int var, double lb, double ub, Context ctx)

Reverse propagate result variable of an expression.

inline int Convert2Var(AffineExpr &&ee)

VISITOR ADAPTERS ///////////////////////////////////////// These are called to transform expressions, either by FlatCvt itself, or when flattening NL model.

From an affine expression: Adds a result variable r and constraint r == expr

inline int Convert2Var(QuadraticExpr &&ee)

From a quadratic expression: Adds a result variable r and constraint r == expr.

inline FCC<Impl, FuncConstraint>::VarOrConst AssignResult2Args(FuncConstraint &&fc)

Take FuncConstraint with arguments.

Prefer this over AddConstraint() for mapped functional constraints. If the result of the function can be presolved or is known via map, return it. Otherwise, create a result variable and add the constraint.

Returns

VarOrConst

inline FCC<Impl, FuncConstraint>::Var AssignResultVar2Args(FuncConstraint &&fc)

Same, but always return a variable.

inline void RedefineVariable(int res_var, FuncConstraint &&fc)

Replace functional expression defining a given variable.

inline void IncrementVarUsage(int v)

Variables’ reference counting /////////////////////////////////// Currently only for defined variables ////////////////////////////.

Use “+1” a variable

inline void DecrementVarUsage(int v)

Unuse result variable.

Actually this is to ‘unuse’ the init expression

  • might change naming. Throw if already not used.

inline void FixUnusedDefinedVars()

Fix unused defined vars.

Normally should delete them.

inline void ConvertAllConstraints(BasicFlatConverter &cvt)

Convert all constraints (including any new appearing)

inline void RunConversion(const Constraint &con, int i, int depth)

CUSTOM CONSTRAINTS CONVERSION ////////////////////////////.

RunConversion() of a constraint: Assume mixed context if not set.

inline ConstraintAcceptanceLevel GetConstraintAcceptance(Con*) const

Query if a constraint type is natively accepted by the solver.

The parameter is only needed for type.

inline int GetNumberOfAddable(Con*) const

Query the number of addable constraints of type.

inline bool IfHasConversion(const Constraint *c)

Query if the constraint type can be converted.

This method should not be redefined; specialize IfHasCvt_impl instead.

inline bool IfHasCvt_impl(const Constraint*)

Generic query if a constraint type can be converted.

Specialize this method, but normally it’s specialized by INSTALL_CONSTRAINT_CONVERTER.

inline bool IfNeedsConversion(const Constraint &con, int i)

Query if the specific item of the constraint needs to be converted, despite being accepted by the ModelAPI.

For example, Gurobi only accepts Pow with non-negative argument. This method should not be redefined; specialize IfNeedsCvt_impl instead.

inline bool IfNeedsCvt_impl(const Constraint&, int)

Generic query if a constraint needs to be converted, despite being accepted by the ModelAPI.

Specialize this method, or even ConstraintConverter::IfNeedsConversion (see class PowConstExponentConverter_MIP).

inline bool ModelAPIAcceptsAndRecommends(const Constraint *pcon) const

Check whether ModelAPI accepts and recommends the constraint.

inline void Convert(const Constraint &con, int)

Generic adapter for old non-bridged Convert() methods.

New way is to use the i parameter for bridging

inline void Convert(const Constraint&)

By default, we complain about someone trying to convert an unknown constraint.

inline void Convert(const LinearFunctionalConstraint &ldc)

SOME SPECIFIC CONSTRAINT CONVERTERS ///////////////////////////////////// ///////////////////////////.

If backend does not like LFC, we redefine it here

inline void Convert(const QuadraticFunctionalConstraint &qdc)

If backend does not like QFC, we redefine it.

inline pre::NodeRange AddObjective(QuadraticObjective &&qo)

Add objective.

Currently handling quadratic objectives. Its quadratic terms will be empty for linear objectives.

Linking NL objectives straight into solver’s objectives. If any conversions are performed, need to have intermediate nodes, as for constraints

inline pre::NodeRange AddConstraint(Constraint con)

ADD CUSTOM CONSTRAINT, does not propagate result (use AddConstraint_AS_ROOT() otherwise).

Use only for non-mapped constraints. For functional constraints stored __WITH_MAP, use AssignResult(Var)2Args(). Non-functional constraints cannot be unified currently. Takes ownership.

Returns

Node reference for the stored constraint

inline pre::NodeRange AddConstraint_AS_ROOT(Constraint con)

ADD CUSTOM CONSTRAINT and propagate root-ness (use AddConstraint() otherwise).

Use only for non-mapped constraints. For functional constraints stored __WITH_MAP, use AssignResult(Var)2Args(). Takes ownership.

Returns

Node reference for the stored constraint

inline const Constraint &GetConstraint(const ConInfo &ci) const

Retrieve constraint of specified type at location ci.

inline const Constraint &GetConstraint(int i) const

Retrieve constraint of specified type at index i.

inline void MarkAsBridged(const ConInfo &ci)

Mark constraint as reformulated.

inline void MarkAsUnused(const ConInfo &ci)

Mark constraint as unused.

inline pre::NodeRange SelectValueNode(int i)

Select value node i for constraint type Con.

inline void StartModelInput()

Handle start of model input.

inline void FinishModelInput()

Handle end of model input.

inline void CheckLinearCons()

Check linear constraints.

Solvers complain about close-to-0 coefficients, so fail on this in the debug build.

inline void CheckLinearConType()
inline void PresolveNames()

Presolve item names.

inline void TransferNames2Node(Con *pcon)
inline void FillModelTraits(AMPLS_ModelTraits &mt)

Fill model traits for license check.

To be called after ConvertModel(). KEEP THIS UP2DATE.

inline const ModelAPI &GetModelAPI() const

UTILITIES /////////////////////////////////.

Expose abstract Backend

inline ModelAPI &GetModelAPI()
inline const pre::ValuePresolver &GetValuePresolver() const

Expose ValuePresolver.

inline pre::ValuePresolver &GetValuePresolver()
inline pre::NodeRange MakeFixedVar(double value)
inline pre::NodeRange AddVar(double lb, double ub, var::Type type = var::CONTINUOUS)

Create or find a fixed variable.

inline pre::NodeRange AddVars(const typename BaseFlatModel::VarBndVec &lbs, const typename BaseFlatModel::VarBndVec &ubs, const typename BaseFlatModel::VarTypeVec &types)

Add several variables once.

Note

this is only to be called once for the original vars.

Returns

value node range for them

inline void AddVarNames(std::vector<std::string> names)
inline void AddVarNames(const std::vector<std::string> &names)

Set var names vector.

inline void AddConNames(std::vector<std::string> names)
inline void AddObjNames(std::vector<std::string> names)
inline pre::ValueNode &GetVarValueNode()

Reuse ValuePresolver’s target nodes for all variables.

inline pre::ValueNode &GetValueNode(Constraint*)

Constraint type’s Value Node.

inline pre::ValueNode &GetObjValueNode()

Reuse ValuePresolver’s target nodes for all objectives.

inline int num_vars() const

Shortcut num_vars()

inline int is_var_original(int i) const

Shortcut is_var_original()

inline double lb(int var) const

Shortcut lb(var)

inline double ub(int var) const

Shortcut ub(var)

inline double lb_array(const VarArray &va) const

lb_array()

inline double lb_array(const VarArray &va) const
inline double ub_array(const VarArray &va) const

ub_array()

inline double ub_array(const VarArray &va) const
inline void set_var_lb(int var, double lb)

Set lb(var)

inline void set_var_ub(int var, double ub)

Set ub(var)

inline void set_var_lb_context(int var, double lb, Context ctx)

Set lb(var), propagate context if functional result.

inline void set_var_ub_context(int var, double ub, Context ctx)

Set ub(var), propagate context.

inline void set_var_bounds_context(int var, double lb, double ub, Context ctx)

Set bounds(var), propagate context.

inline void NarrowVarBounds(int var, double lb, double ub)

Narrow variable domain range.

inline var::Type var_type(int var) const

var_type()

inline bool is_fixed(int var) const

is_fixed()

inline double fixed_value(int var) const

fixed_value()

inline int MakeComplementVar(int bvar)

MakeComplementVar()

inline std::vector<int> AddVars_returnIds(std::size_t nvars, double lb = MinusInfty(), double ub = Infty(), var::Type type = var::CONTINUOUS)

Add vector of variables.

Type: var::CONTINUOUS by default

Returns

vector of the Ids of the new vars

inline bool is_var_integer(int var) const
inline bool HasInitExpression(int var) const

Variable has an init expr?

inline const ConInfo &GetInitExpression(int var) const

Get the init expr.

inline const ConType *GetInitExpressionOfType(int var)

Get the init expression pointer.

Returns

nullptr if no init expr or not this type

inline bool IsConInfoType(const ConInfo &ci) const

Check if the constraint location points to the constraint keeper used for this ConType.

inline pre::NodeRange AutoLink(pre::NodeRange nr)

Auto link node range nr.

The nodes of nr will be autolinked with auto_link_src_item_. Means, a link is created automatically, without the conversion/flattening code doing anything. This is used to propagate values via flattened expression trees and conversions, as well as to export the conversion tree.

inline bool DoingAutoLinking() const

Whether we should auto-link new items.

inline void TurnOffAutoLinking()

Turn off auto-linking for current conversion.

inline pre::NodeRange GetAutoLinkSource() const

Get autolink source node range.

inline void SetAutoLinkSource(pre::NodeRange nr)

Set autolink source node range.

inline const std::vector<pre::NodeRange> &GetAutoLinkTargets() const

Get autolink target node ranges.

inline const ModelType &GetModel() const

The internal flat model object, const ref.

inline ModelType &GetModel()

The internal flat model object, ref.

inline bool ModelAPIAcceptsQC() const

Whether the ModelAPI accepts quadratic constraints.

inline int ModelAPIAcceptsQuadraticCones() const

Whether the ModelAPI accepts quadratic cones.

inline void IncQC2SOCPAttempted()

Number of QC -> SOCP conversions.

inline void IncQC2SOCPSucceeded()
inline int NumQC2SOCPAttempted() const
inline int NumQC2SOCPSucceeded() const
inline void IncExpConeCounter()

Number of exp cones recognized.

inline int NumExpConesRecognized() const
inline int ModelAPIAcceptsExponentialCones()

Whether the ModelAPI accepts exp cones.

inline const std::string &graph_export_file() const

Graph export file.

inline int relax() const

Whether we should relax integrality.

inline int sol_check_mode() const

Solution checking options.

inline bool sol_check_infeas() const
inline bool sol_check_fail() const
inline double sol_feas_tol() const
inline double sol_feas_tol_rel() const
inline double sol_int_tol() const
inline int sol_round() const
inline int sol_prec() const
inline int sol_check_outlev() const
inline bool CanPreprocess(int f) const

Wrapper about a specific preprocess option: checks whether preprocessAnything_ is on.

inline bool IfPreproEqResBounds() const

Whether preprocess equality result bounds.

inline bool IfPreproEqBinVar() const

Whether preprocess conditional equality of a binary variable.

inline bool IfPreproNestedAndsOrs() const

Whether inline nested forall, exists.

inline bool IfPassQuadObj() const

Whether we pass quad obj terms to the solver without linearization.

inline bool IfPassQuadCon() const

Whether we pass quad con terms to the solver without linearization.

inline bool IfQuadratizePowConstPosIntExp() const

Whether to quadratize pow(…, const_pos_int).

The fact that we use IfPassQuadCon() is much Gurobi-biased: v9.5 does not PL-linearize Pow for negative arguments

inline int IfPassSOCPCones() const

Recognition mode for SOCP cones.

inline int SOCP2QCMode() const

Mode for SOCP -> QC conversion.

inline void Setup2ConvertSOCP2QC()

Decide to convert SOCP -> QC.

inline bool IfConvertSOCP2QC() const

If decided to convert SOCP -> QC.

inline int IfPassExpCones() const

Recognition mode for exp cones.

inline void AddWarning(std::string key, std::string msg, bool replace = false)

AddWarning.

Parameters
  • key – warning category

  • msg – detailed message

template<class Con>
inline bool MapInsert(const Con&, int)

Returns false when we do have a map and entry duplicated (should not happen).

Can be conveniently overloaded

inline pre::CopyLink &GetCopyLink()

CONSTRAINT CONVERTERS ///////////////////////// Constraint keepers and converters should be initialized after presolver_.

Convert linear range constraints, if not accepted by ModelAPI Convert quadratic range constraints, if necessary Convert quadratic cones, if necessary Convert rotated quadratic cones, if necessary ValuePresolve link copying values 1:1 between model items

inline pre::One2ManyLink &GetOne2ManyLink()

ValuePresolve link copying values 1:many.

inline pre::Many2OneLink &GetMany2OneLink()

ValuePresolve link copying values many:1.

inline int MapFind(const BasicConstraint&)

For Common Subexpression Elimination, we can use maps This stub returns empty Id.

inline Var AddVar__basic(double lb = MinusInf(), double ub = Inf(), var::Type type = var::CONTINUOUS)

VARIABLES //////////////////////////////// Add variable, return its index.

inline void AddVars__basic(const VarBndVec &lbs, const VarBndVec &ubs, const VarTypeVec &types)

Add several variables.

This is only done once when we add original variables.

inline const char *var_name(int i) const

To be used only after names presolve.

inline const std::vector<double> &var_lb_vec() const
inline const std::vector<double> &var_ub_vec() const
inline const std::vector<var::Type> &var_type_vec() const
inline double lb_max_array(const VarArray &va) const
inline double ub_min_array(const VarArray &va) const
inline bool is_integer_var(int v) const
inline bool is_binary_var(int v) const

Returns true also when fixed.

inline var::Type common_type(const VarArray &va) const
inline void set_lb(int v, double l)
inline void set_ub(int v, double u)
inline void MarkAsResultVar(int v)

Mark as an explicit result variable.

inline bool IsResultVar(int v) const

Is the variable an explicit result var?

inline const ObjList &get_objectives() const

Get list of objectives, const.

inline ObjList &get_objectives()

Get list of objectives.

inline int num_objs() const

N obj.

inline const QuadraticObjective &get_obj(int i) const

Get obj [i].

inline bool HasQPObjective() const

Has a QP objective?

inline virtual const VarBndVec &GetVarLBs() const

Provide variable lower bounds.

inline virtual const VarBndVec &GetVarUBs() const

Provide variable upper bounds.

inline void PushModelTo(ModelAPI &mapi) const

EXPORT THE INSTANCE TO A ModelAPI //////////////.

Pushing the whole instance to the mapi.

inline const FlatModelInfo *GetModelInfo() const

Model info.

inline bool check_vars() const

Check var arrays.

inline void RelaxIntegrality()
inline BasicFileAppender &GetFileAppender() const

Retrieve file logger.

inline BasicFileAppender &GetFileAppender() const

Retrieve file logger.

inline void AddConstraintKeeper(BasicConstraintKeeper &ck, double priority)

Add a new CKeeper with given conversion priority (smaller = sooner)

inline void ConsiderAcceptanceOptions(BasicFlatConverter &cvt, const BasicFlatModelAPI &ma, Env &env)

This should be called after adding all constraint keepers.

inline void MarkExprsForResultVars(BasicFlatConverter &cvt)

Mark which expressions should stay as FuncCons or just have a result variable.

inline void ConvertWithExpressions(BasicFlatConverter &cvt)

Convert to expression-based model.

inline void FillConstraintCounters(const BasicFlatModelAPI &mapi, FlatModelInfo &fmi) const

Fill counters of unbridged constraints.

inline void CopyNamesFromValueNodes()

Copy names from ValueNodes.

inline void AddUnbridgedConstraintsToBackend(BasicFlatModelAPI &be, const std::vector<std::string> *pvnam = nullptr) const

Add all unbridged constraints to Backend.

inline void LogConstraintGroups(BasicFlatModelAPI &be) const

Log constraint groups.

inline void ComputeViolations(SolCheck &chk)

Compute violations.

inline PreprocessInfoStd ComputeBoundsAndType(const LinTerms &lt)

ComputeBoundsAndType(LinTerms)

template<class Body>
inline PreprocessInfoStd ComputeBoundsAndType(const AlgebraicExpression<Body> &ae)

ComputeBoundsAndType(AlgebraicExpr<>)

inline PreprocessInfoStd ComputeBoundsAndType(const QuadTerms &qt)

ComputeBoundsAndType(QuadTerms)

inline PreprocessInfoStd ComputeBoundsAndType(const QuadAndLinTerms &qlt)

ComputeBoundsAndType(QuadAndLinearTerms)

template<class Var>
inline std::pair<double, double> ProductBounds(Var x, Var y) const

Product bounds.

template<class PreprocessInfo>
inline void PreprocessConstraint(LinearFunctionalConstraint &c, PreprocessInfo &prepro)

Preprocess LFC.

template<class PreprocessInfo>
inline void PreprocessConstraint(QuadraticFunctionalConstraint &c, PreprocessInfo &prepro)

Preprocess QFC.

template<class PreprocessInfo>
inline void PreprocessConstraint(PowConstraint &c, PreprocessInfo &prepro)

Preprocess Pow.

template<class PreprocessInfo>
inline void PreprocessConstraint(MinConstraint &c, PreprocessInfo &prepro)

Preprocess Min.

template<class PreprocessInfo>
inline void PreprocessConstraint(MaxConstraint &c, PreprocessInfo &prepro)

Preprocess Max.

template<class PreprocessInfo>
inline void PreprocessConstraint(AbsConstraint &c, PreprocessInfo &prepro)

When the result variable is set, the constraint is skipped.

template<class PreprocessInfo>
inline void PreprocessConstraint(CondLinConEQ &c, PreprocessInfo &prepro)

Preprocess CondLinConEQ.

template<class PreprocessInfo>
inline void PreprocessConstraint(CondQuadConEQ &c, PreprocessInfo &prepro)

Preprocess CondQuadConEQ.

template<class PreprocessInfo, class Body, int kind>
inline void PreprocessConstraint(ConditionalConstraint<AlgebraicConstraint<Body, AlgConRhs<kind>>> &cc, PreprocessInfo &prepro)

(Non)strict inequalities

template<class PreprocessInfo>
inline void PreprocessConstraint(AndConstraint &con, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(OrConstraint &con, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(AllDiffConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(NumberofConstConstraint &con, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(NumberofVarConstraint &con, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(CountConstraint &con, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(NotConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(DivConstraint &c, PreprocessInfo &prepro)

Preprocess Div.

template<class PreprocessInfo>
inline void PreprocessConstraint(IfThenConstraint &c, PreprocessInfo &prepro)

Preprocess IfThen.

template<class PreprocessInfo>
inline void PreprocessConstraint(ImplicationConstraint&, PreprocessInfo &prepro)

Preprocess IfThen.

template<class PreprocessInfo>
inline void PreprocessConstraint(ExpConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(ExpAConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(LogConstraint &c, PreprocessInfo&)
template<class PreprocessInfo>
inline void PreprocessConstraint(LogAConstraint &c, PreprocessInfo&)
template<class PreprocessInfo>
inline void PreprocessConstraint(SinConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(CosConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(TanConstraint&, PreprocessInfo&)

Preprocess Tan.

template<class PreprocessInfo>
inline void PreprocessConstraint(AsinConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(AcosConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(AtanConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(SinhConstraint&, PreprocessInfo&)
template<class PreprocessInfo>
inline void PreprocessConstraint(CoshConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(TanhConstraint&, PreprocessInfo &prepro)

Preprocess Tan.

template<class PreprocessInfo>
inline void PreprocessConstraint(AsinhConstraint&, PreprocessInfo&)
template<class PreprocessInfo>
inline void PreprocessConstraint(AcoshConstraint&, PreprocessInfo &prepro)
template<class PreprocessInfo>
inline void PreprocessConstraint(AtanhConstraint&, PreprocessInfo&)
template<class PreprocessInfo>
inline void PreprocessConstraint(PLConstraint&, PreprocessInfo&)
template<class Body, int kind>
inline bool IsNormalized(ConditionalConstraint<AlgebraicConstraint<Body, AlgConRhs<kind>>> &cc)

See if the argument of a conditional algebraic constraint is normalized.

template<class PreprocessInfo, class CondAlgCon>
inline bool FixEqualityResult(CondAlgCon &c, PreprocessInfo &prepro)

Try and fix conditional equality result.

Returns

true if success

template<class PreprocessInfo>
inline bool ReuseEqualityBinaryVar(CondLinConEQ &c, PreprocessInfo &prepro)

Simplify conditional equality bin_var==0/1 by reusing bin_var or its complement.

template<class SubCon, class PreprocessInfo>
inline bool CheckEmptySubCon(const ConditionalConstraint<SubCon> &cc, PreprocessInfo &prepro)

Dave experiments with logic presolve.

Returns

true if constraint is empty and we should return the fixed result.

template<class Vec>
inline std::pair<int, int> count_fixed_01(const Vec &vec) const

Count N fixed binary vars.

template<class Con>
inline void IntegrateNested(Con &con)

Integrate nested constraints (And/Or)

template<class Constraint>
inline void PropagateResult(Constraint &con, double lb, double ub, Context ctx)

By default, add mixed context for argument variables.

inline void PropagateResult(LinearFunctionalConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(QuadraticFunctionalConstraint &con, double lb, double ub, Context ctx)
template<class Body>
inline void PropagateResult(AlgebraicConstraint<Body, AlgConRange> &con)

Propagate a root algebraic range constraint.

template<class Body, int sens>
inline void PropagateResult(IndicatorConstraint<AlgebraicConstraint<Body, AlgConRhs<sens>>> &con, double lb, double ub, Context ctx)
template<int type>
inline void PropagateResult(SOS_1or2_Constraint<type> &con, double lb, double ub, Context)
template<class ExprBody>
inline void PropagateResult(ComplementarityConstraint<ExprBody> &con)

Propagate root complementarity constraint.

template<class ExprBody>
inline void PropagateResult(ComplementarityConstraint<ExprBody> &con, double lb, double ub, Context ctx)

Not used?

inline void PropagateResult(NotConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(AndConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(OrConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(IfThenConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(ImplicationConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(AllDiffConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(NumberofConstConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(NumberofVarConstraint &con, double lb, double ub, Context ctx)
inline void PropagateResult(PowConstraint &con, double, double, Context ctx)
inline void PropagateResult(LogConstraint &con, double, double, Context ctx)
inline void PropagateResult(LogAConstraint &con, double, double, Context ctx)
inline void PropagateResult(ExpConstraint &con, double, double, Context ctx)
inline void PropagateResult(ExpAConstraint &con, double, double, Context ctx)
inline void PropagateResult(CondLinConEQ &con, double lb, double ub, Context ctx)
inline void PropagateResult(CondQuadConEQ &con, double lb, double ub, Context ctx)
template<class Body, int kind>
inline void PropagateResult(ConditionalConstraint<AlgebraicConstraint<Body, AlgConRhs<kind>>> &con, double lb, double ub, Context ctx)
template<class Array3>
inline void PropagateIfThenResultIntoCondition(Array3 args, Context ctx)

Context of the condition in IfThen.

Parameters
  • args – [condition, then, else] result variables

  • ctx – context of the overall expression

template<class Args>
inline void PropagateResult2Args(const Args &vars, double lb, double ub, Context ctx)

Propagate given bounds & context into arguments of a constraint.

The default template assumes it just a vector of variables.

Parameters

lb, ub – bounds for each variable

inline void PropagateResult2Args(const LinTerms &lint, double lb, double ub, Context ctx)

Specialize: propagate result into LinTerms.

inline void PropagateResult2Args(const QuadAndLinTerms &qlt, double lb, double ub, Context ctx)

Specialize: propagate result into QuadAndLinTerms.

inline void PropagateResult2QuadAndLinTerms(const QuadAndLinTerms &qlt, double lb, double ub, Context ctx)

Propagate result into QuadAndLinTerms.

inline void PropagateResult2LinTerms(const LinTerms &lint, double, double, Context ctx)

Propagate result into LinTerms.

template<class Vec>
inline void PropagateResult2Vars(const Vec &vars, double lb, double ub, Context ctx)

Propagate given bounds & context into a vector of variables.

Parameters

lb, ub – bounds for each variable

inline void PropagateResult2QuadTerms(const QuadTerms &quadt, double, double, Context ctx)

Propagate result into QuadTerms.

template<class Con>
inline void ConsiderMarkingResultAndArgVars(const Con &con, int i, ExpressionAcceptanceLevel eal)

Consider marking the result and argument variables as “explicit variables” (not expressions)

template<class Con>
inline void ConsiderMarkingArgumentsAsVars(const Con &con, int i, ExpressionAcceptanceLevel eal)

Generic request to consider marking arguments.

inline bool CheckSolution(ArrayRef<double> x, const pre::ValueMapDbl &duals, ArrayRef<double> obj, void *p_extra)

Check postsolved & unpostsolved solutions in various ways.

Parameters

p_extra – !=0 means known infeas solution

inline ArrayRef<double> RecomputeAuxVars(ArrayRef<double> x)

Recompute auxiliary variables.

inline std::string DoCheckSol(ArrayRef<double> x, const pre::ValueMapDbl &duals, ArrayRef<double> obj, ArrayRef<double> x_raw, std::vector<double> &x_back, bool if_recomp_vals)

Check single unpostsolved solution.

Parameters

x_back – solution vector from realistic mode. It can be changed by the :round and :prec options. Its auxiliary vars are compared with recomputed expression values.

inline void CheckVars(SolCheck &chk)
inline void CheckCons(SolCheck &chk)

Includes logical constraints.

inline void CheckObjs(SolCheck &chk)
inline void GenerateViolationsReport(SolCheck &chk, bool)
inline void Gen1Viol(const ViolSummary &vs, fmt::MemoryWriter &wrt, bool f_max, const std::string &type)

Generate message about 1 violation.

Parameters

f_max – whether we need to print the maximal violations.

inline std::string Gen1ViolMax(bool f_max, double viol, const char *nm)

Stringify 1 maximal violation.

inline void GenConViol(const std::map<std::string, ViolSummArray<3>> &cvmap, fmt::MemoryWriter &wrt, int alg_log)

std::string classnm = alg_log ? “Logical” : “Algebraic”; wrt.write(classnm + ” expression violations:\n”);

inline const Env &GetEnv() const

GetEnv() const.

inline Env &GetEnv()

GetEnv()

Public Members

VarsRecomputeFn recomp_fn = [this](int i, const VarInfoRecomp& x) {if (MPCD( HasInitExpression(i) )) {const auto& iexpr =MPCD( GetInitExpression(i) );auto pCK = iexpr.GetCK();if (!pCK->IsUnused(iexpr.GetIndex()))return pCK->ComputeValue(iexpr.GetIndex(), x);}return x.get_x().get_x()[i];}

Functor to recompute auxiliary var i.

Public Static Functions

static inline constexpr const char *GetTypeName()

Class name for diagnostics.

static inline constexpr Var VoidVar()

‘Invalid’ var id

static inline bool ModelAPIAcceptsQuadObj()

Whether the ModelAPI accepts quadratic objectives.

static inline bool ModelAPIAcceptsNonconvexQC()

Whether the ModelAPI accepts nonconvex QC.

static inline bool ModelAPICanSOCPCornerCasesFromQC()

Ask if the solver can recognize SOCP corner cases (non-std representations such as xy>=1, see tests) from quadratic representations.

static inline bool ModelAPICanMixConicQCAndQC()

Whether the solver can mix conic quadratic (entered via dedicated API) and direct quadratic constraints.

static inline constexpr double ConstraintCvtPriority(BasicConstraint*)

Default conversion priority.

static inline constexpr double Pi()

Value of Pi.

static inline constexpr double Infty()

Infinity.

static inline constexpr double MinusInfty()

-Infinity

static inline constexpr double PracticallyInf()

Pract inf.

static inline constexpr double PracticallyMinusInf()

Pract -inf.

static inline constexpr double Inf()
static inline constexpr double MinusInf()
static inline bool is_integer_value(Num n)
static inline PreprocessInfoStd AddBoundsAndType(const PreprocessInfoStd &bnt1, const PreprocessInfoStd &bnt2)

Add / merge bounds and type.

static inline void PreprocessEqVarConst__unifyCoef(CondLinConEQ &c)

Normalize conditional equality coef * var == const.

Protected Types

using VarConstCmp = std::pair<int, double>

Result of IsVarConstCmp(): var, const.

using ClassType = FlatConverter<Impl, ModelAPI, FlatModel<>>
using BaseFlatModel = FlatModel<>

Protected Functions

inline int MapFind__VarConstCmp(int var, double val)

Return index of CondLinEQ for this val, if saved before.

inline bool MapInsert__VarConstCmp(int var, double val, int i)
inline void ConvertEqVarConstMaps()

Convert the var-to-const comparisons left until now.

inline bool WentWithoutEqEncForVar(int var, const SingleVarEqConstMap &map)

Managed to reformulate cond equalities without unary encoding?

inline bool DontNeedEqEncForVar(int var, const SingleVarEqConstMap &map)
Returns

true if don’t need UEnc for var

inline void GoWithoutEqEnc(int, const SingleVarEqConstMap &map)

Manually convert all comparisons for this variable.

inline void ConvertEqVarConstMap(int var, const SingleVarEqConstMap &map)
inline void CreateUnaryEncoding(int var, const SingleVarEqConstMap &map)

Create unary encoding once we go for it.

Adds a dummy UnaryEncodingConstraint for graph linking. Another design would be to have an “EqualityEncodingConstraint” and move all conversions there (indicators vs unary encoding.) That would partially automate linking. A benefit would be if some solver later supports them natively (IloDistribute?), now they are always converted below.

inline int &VarUsageRef(int i)
inline void ConvertItems()

CUSTOM CONSTRAINTS CONVERSION ////////////////////////////.

inline void OpenGraphExporter()
inline void Convert2Cones()

Offload the conic logic to a functor.

inline void ConvertAllConstraints()

Can be called from ConvertMaps()

inline bool IfWantNLOutput() const

Option to actually use expressions if available.

inline void Convert2NL()

Convert some functional constraints to expressions.

inline void CloseGraphExporter()

Finish exporting the reformulation graph.

inline void PreprocessIntermediate()
inline void PreprocessFlatFinal()
inline void PreprocessNLFinal()
inline pre::NodeRange AddConstraintAndTryNoteResultVariable(Constraint &&con)
inline void ConvertModel()
inline void PrepareConversion()
inline void WindupConversion()
inline pre::NodeRange DoAddVar(double lb = MinusInfty(), double ub = Infty(), var::Type type = var::CONTINUOUS)

Add variable. Type: var::CONTINUOUS by default.

inline void AddInitExpression(int var, const ConInfo &vi)

Add init expr for var.

inline void ReplaceInitExpression(int var, const ConInfo &vi)

Replace init expression for var.

STORE_CONSTRAINT_TYPE__NO_MAP (LinConRange, "acc:linrange acc:linrng") STORE_CONSTRAINT_TYPE__NO_MAP(QuadConRange

CONSTRAINT KEEPERS ///////////////////////// Constraint keepers and converters should be initialized after value_presolver_.

Define constraint keepers for all constraint types. No maps for static constraints. 2nd parameter: solver options for this constraint, in case it is accepted by the solver natively and is convertible by us.

inline bool MapInsert(const Constraint &con, int i)

MapInsert.

Can be overloaded for more complex behavior.

Parameters
  • con – the constraint

  • i – ConstraintKeeper index

Returns

false when inserted a duplicate (should not happen)

inline int MapFind__Impl(const Constraint &con)

MapFind__Impl.

Default version for functional constraints with a map.

Parameters

con – constraint reference

Returns

constraint index, or -1

inline bool MapInsert__Impl(const Constraint &con, int i)

MapInsert__Impl.

Default version for functional constraints with a map.

Parameters
  • con – the constraint

  • i – ConstraintKeeper index

Returns

false when inserted a duplicate (should not happen)

inline void ExportVars (int i_start, const BndVec &lbs, const BndVec &ubs, const TypeVec types, const char *comment="Initial model information. " "Can be updated later with new bounds, names, etc.") const

Export new variables.

inline void ExportObjective(int i_obj, const QuadraticObjective &obj) const
inline void CreateFlatModelInfo(const BasicFlatModelAPI &mapi) const
inline void FillVarStats(FlatModelInfo *pfmi) const
inline void PushVariablesTo(Backend &backend) const
inline void PushObjectivesTo(Backend &backend) const
inline void PushCustomConstraintsTo(Backend &backend) const
inline FlatModelInfo *GetModelInfoWrt() const
template<class Body, class RhsOrRange>
inline void DoMarkArgsAsVars(const AlgebraicConstraint<Body, RhsOrRange>&, int)

Algebraic cons: no marking (when NLConstraint accepted?)

template<class Expr>
inline void DoMarkArgsAsVars(const ComplementarityConstraint<Expr> &cc, int)

Complementarity: only mark the var (NL accepts expressions for the expression part)

template<class Con>
inline void DoMarkArgsAsVars(const Con &con, int)

Generic arguments marking call.

Protected Attributes

acc __pad0__
acc acc

Protected Static Functions

static inline std::pair<bool, VarConstCmp> IsVarConstCmp(const CondLinConEQ &con)

Check if con is a conditional var==const.

static inline constexpr bool IfAcceptingNLOutput()

Whether solver CAN accept expressions.

Private Types

using SingleVarEqConstMap = std::unordered_map<double, int>

For a single variable, map its equality comparisons for the comparison value (double), map the EQ0Constraint index.

using VarsEqConstMap = std::unordered_map<int, SingleVarEqConstMap>

A map keeping such maps for certain variables.

Private Functions

inline void InitOwnOptions()

Private Members

VarsEqConstMap map_vars_eq_const_
int n_map_cvt_cycles_ = 0
P_ZZI_Encoding p_zzi_ = {MakeZZIEncoding()}
Options options_
class ModelBuilder

Example using “easy” NLWriter2 API, mp::NLModel, to solve MIQP.

For full NLWriter2 API, see mp::NLFeeder and related tests/examples. Helper class to build model and check solution

Public Functions

inline mp::NLModel GetModel()

Obtain model.

Valid with *this’s lifetime.

inline bool Check(mp::NLSolution sol)

Check solution.

Protected Static Functions

static inline bool ApproxEqual(double n, double m)

Private Members

const char *prob_name_ = {"NLModel/NLSolver"}
std::vector<double> var_lb_ = {0, -3, 0, -1, -1, -2}
std::vector<double> var_ub_ = {0, 20, 1, 1e20, -1, 10}
std::vector<int> var_type_ = {0, 1, 1, 1, 0, 0}
std::vector<const char*> var_names_ = {"x1_4", "x2_6", "x3_5", "x4_3", "x5_1", "x6_2"}
NLW2_MatrixFormat A_format_ = {NLW2_MatrixFormatRowwise}
std::vector<size_t> A_start_ = {0, 4}
std::vector<int> A_index_ = {1, 2, 3, 5, 1, 2, 3, 5}
std::vector<double> A_value_ = {1, 1, 1, 1, 1, -1, -1, 1}
std::vector<double> row_lb_ = {15, 10}
std::vector<double> row_ub_ = {15, INFINITY}
std::vector<const char*> row_names_ = {"C1", "C2"}
NLW2_ObjSense obj_sense_ = {NLW2_ObjSenseMinimize}
double obj_c0_ = {3.24}
std::vector<double> obj_c_ = {0, 1, 0, 0, 0, 0}
NLW2_HessianFormat Q_format_ = {NLW2_HessianFormatSquare}
std::vector<size_t> Q_start_ = {0, 0, 0, 0, 2, 3}
std::vector<int> Q_index_ = {3, 5, 4}
std::vector<double> Q_value_ = {10, 12, 14}
const char *obj_name_ = {"obj[1]"}
std::vector<double> x_ref_ = {0, 5, 1, -1, -1, 10}

Solution.

double obj_val_ref_ = {-39.76}
class nlwpy::test::test_solve::ModelBuilder

Public Functions

def __init__(self)
def get_model(self)
def check(self, sol)

Public Members

prob_name_
var_lb_
var_ub_
var_type_
var_names_
A_format_
A_
row_lb_
row_ub_
row_names_
obj_sense_
obj_c0_
obj_c_
Q_format_
Q_
obj_name_
ini_x_i_

Extra input.

ini_x_v_
ini_y_i_
ini_y_v_
bas_x_
bas_y_

Basis statuses.

x_ref_

Solution.

obj_val_ref_

Private Functions

def _approx_equal(self, n, m)
template<class Converter>
class mp::ModelManagerWithProblemBuilder : public mp::BasicModelManager, public mp::EnvKeeper

Model Manager with a ProblemBuilder.

Reads a problem from an .nl file, writes solution(s).

ProblemBuilder is defined by the Converter and used as an intermediate instance storage.

ModelManagerWithProblemBuilder uses Converter to convert the instance, e.g., walk the NL tree and convert other constraints stored in a given ProblemBuilder which can be, e.g., mp::Problem.

The Converter must implement the BasicConverter<ProblemBuilder> interface.

Public Functions

inline ModelManagerWithProblemBuilder(std::unique_ptr<Converter> pc)
inline const Env &GetEnv() const

GetEnv() const.

inline Env &GetEnv()

GetEnv()

Public Static Functions

static inline const char *GetTypeName()

Class name.

Protected Types

using ConverterType = Converter

Convenience typedef.

using SolverType = BasicSolver

SolverType, needed by SolutionHandler.

using ProblemBuilder = typename ConverterType::ModelType

ProblemBuilder, needed by NL readers and solution handler.

Converter does not have to know this is a ProblemBuilder.

using SolverNLHandlerType = internal::SolverNLHandlerImpl<BasicSolver, ProblemBuilder, internal::NLProblemBuilder<ProblemBuilder>>

Protected Functions

inline virtual void InitOptions() override

Initialize solver options.

inline virtual void ReadNLModel(const std::string &nl_filename, const std::string &filename_no_ext, Checker_AMPLS_ModeltTraits cb_checkmodel, std::function<void()> after_header) override

Read NL model.

inline void ReadNLFile(const std::string &nl_filename, std::function<void()> after_header)

Read the NL file.

inline void ReadNames(const std::string &namebase)

Read var / con / obj names.

The .row file has cons + objs.

inline void SetObjNames(NameProvider &npco)

Obj names.

We have to consider that obj:no=n selects objective n.

Parameters

npcoNameProvider of row+obj names, read from .row or generated

inline void MakeProperSolutionHandler(const std::string &filename_no_ext)

Once NL header is read.

inline void ConvertModelAndUpdateBackend()

Says we finished problem modification, so we run model conversion and communicate the result into the ModelAPI.

inline const ProblemBuilder &GetPB() const
inline ProblemBuilder &GetPB()
inline const ProblemBuilder &GetModel() const
inline ProblemBuilder &GetModel()
inline const Converter &GetCvt() const
inline Converter &GetCvt()
inline void set_nl_read_result_handler(typename NLReadResult::HandlerType *ph)
inline const NLReadResult::HandlerType &get_nl_read_result_handler() const
inline NLReadResult::HandlerType &get_nl_read_result_handler()
inline bool HaveSolH() const
inline const SolutionHandler &GetSolH() const
inline SolutionHandler &GetSolH()
inline void SetSolHandler(SolutionHandler *psh)
inline void RemoveSolHandler()
inline virtual ArrayRef<double> InitialValues() override

Define original model access from BasicOriginalModelProxy.

inline virtual ArrayRef<int> InitialValuesSparsity() override

User-provided primal solution: sparsity.

inline virtual ArrayRef<double> InitialDualValues() override

User-provided dual solution.

inline virtual ArrayRef<int> InitialDualValuesSparsity() override

User-provided dual solution: sparsity.

inline virtual ArrayRef<int> ReadSuffix(const SuffixDef<int> &suf) override

Read integer suffix.

inline virtual ArrayRef<double> ReadSuffix(const SuffixDef<double> &suf) override

Read double suffix.

inline virtual void ReportSuffix(const SuffixDef<int> &suf, ArrayRef<int> values) override

Report integer suffix.

inline virtual void ReportSuffix(const SuffixDef<double> &suf, ArrayRef<double> values) override

Report double suffix.

inline virtual size_t GetSuffixSize(int kind) override

Length of a suffix vector of given kind.

inline virtual void SetSolutionFileName(const std::string &fileName) override
inline virtual void HandleSolution(int status, fmt::CStringRef msg, const double *x, const double *y, double obj) override

Report final solution.

inline virtual void HandleFeasibleSolution(int solve_code, fmt::CStringRef msg, const double *x, const double *y, double obj) override

Report intermediate solution.

inline virtual const std::vector<bool> &IsVarInt() const override

Integrality flags of the variables in the original instance.

Used for solution rounding

inline virtual bool HasUnfixedIntVars() const override

Has unfixed int vars? This is about the solver-facing instance.

inline int WantNames() const

Whether and what names.

Private Functions

inline void InitOwnOptions()

Private Members

const mp::OptionValueInfo values_want_names_ [4] = {{ "0", "No names", 0},{ "1", "(Default) Only provide names if at least one of "".col / .row name files was written by AMPL ""(AMPL: `option [<solver>_]auxfiles rc;`) ", 1},{ "2", "Readnames from AMPL, but create generic ""names if not provided", 2},{ "3", "Create generic names.", 3}}
Options options_
std::unique_ptr<Converter> pcvt_
NLReadResult nl_read_result_
std::unique_ptr<SolutionHandler> p_sol_handler_
template<class VMap>
class mp::pre::ModelValues
#include <valcvt-base.h>

Group of values or value nodes for variables, constraints, and objectives.

Public Types

using ParamType = typename VMap::ParamType

The extra parameter type, taken from VMap.

Public Functions

inline ModelValues(ParamType prm, const std::string &nm)

Constructor.

ModelValues(ModelValues&&) = default

Default move-copy.

ModelValues &operator=(ModelValues&&) = default

Default move-assign.

inline ModelValues(VMap v = {}, VMap c = {}, VMap o = {}, void *p_extra = nullptr)

Construct from values for vars, cons, objs (last 2 maps can be even legally omitted)

template<class VM2>
inline ModelValues(const ModelValues<VM2> &vm)

Construct from ModelValues<AnotherVMap>

template<class VM2>
inline ModelValues &operator=(const ModelValues<VM2> &vm)

Assign from ModelValues<AnotherVMap>

inline operator bool() const

operator bool

inline bool Empty() const

Empty(). True when all VMaps are.

inline const VMap &GetVarValues() const

Retrieve vars map, const.

inline VMap &GetVarValues()

Retrieve vars map.

inline const VMap &GetConValues() const

Retrieve cons map, const.

inline VMap &GetConValues()

Retrieve const map.

inline const VMap &GetObjValues() const

Retrieve objs map, const.

inline VMap &GetObjValues()

Retrieve objs map.

inline void *ExtraData() const

Extra data.

Private Members

std::string name_
VMap vars_
VMap cons_
VMap objs_
void *p_extra_ = {nullptr}
class mp::BasicProblem::MutAlgebraicCon : public mp::BasicProblem<ProblemParams>::BasicAlgebraicCon<MutProblemItem>
#include <problem.h>

A mutable algebraic constraint.

Public Functions

inline operator AlgebraicCon() const
inline void set_lb(double lb) const

Sets the lower bound on the constraint.

inline void set_ub(double ub) const

Sets the upper bound on the constraint.

inline void set_dual(double value) const

Sets the initial dual value.

inline LinearExpr &linear_expr() const

Returns the linear part of the constraint expression.

inline LinearConBuilder set_linear_expr(int num_linear_terms) const

Sets the linear part of the objective expression.

inline void set_nonlinear_expr(NumericExpr expr) const

Sets the nonlinear part of the constraint expression.

inline void unset_nonlinear_expr()

Unsets the nonlinear part of the constraint expression.

inline bool is_marked_deleted() const

Whether the alg con is marked as deleted.

inline double lb() const

Returns the lower bound on the constraint.

inline double ub() const

Returns the upper bound on the constraint.

inline double dual() const

Returns the dual value.

inline NumericExpr nonlinear_expr() const

Returns the nonlinear part of a constraint expression.

inline bool operator==(BasicAlgebraicCon<OtherItem> other) const
inline bool operator!=(BasicAlgebraicCon<OtherItem> other) const

Private Functions

inline MutAlgebraicCon(BasicProblem *p, int index)

Friends

friend class BasicProblem
class mp::BasicProblem::MutCommonExpr : public mp::BasicProblem<ProblemParams>::BasicCommonExpr<MutProblemItem>
#include <problem.h>

Public Functions

inline LinearExprBuilder set_linear_expr(int num_linear_terms) const
inline void set_nonlinear_expr(NumericExpr expr) const
inline void set_position(int) const
inline const LinearExpr &linear_expr() const

Returns the linear part of the common expression.

inline NumericExpr nonlinear_expr() const

Returns the nonlinear part of the common expression.

inline bool operator==(BasicCommonExpr<OtherItem> other) const
inline bool operator!=(BasicCommonExpr<OtherItem> other) const

Private Functions

inline MutCommonExpr(BasicProblem *p, int index)

Friends

friend class BasicProblem
class mp::BasicProblem::MutLogicalCon : public mp::BasicProblem<ProblemParams>::BasicLogicalCon<MutProblemItem>
#include <problem.h>

Public Functions

inline operator LogicalCon() const
inline void set_expr(LogicalExpr expr)
inline LogicalExpr expr() const

Returns the constraint expression.

inline bool operator==(BasicLogicalCon<OtherItem> rhs) const
inline bool operator!=(BasicLogicalCon<OtherItem> rhs) const

Private Functions

inline MutLogicalCon(BasicProblem *p, int index)

Friends

friend class BasicProblem
class mp::BasicProblem::MutObjective : public mp::BasicProblem<ProblemParams>::BasicObjective<MutProblemItem>
#include <problem.h>

A mutable objective.

Public Functions

inline operator Objective() const
inline void set_type(obj::Type type) const
inline LinearExpr &linear_expr() const

Returns the linear part of the objective expression.

inline LinearObjBuilder set_linear_expr(int num_linear_terms) const

Sets the linear part of the objective expression.

template<class EI>
inline void set_extra_info(EI ei) const

Sets the extra info of the objective expression.

inline void set_nonlinear_expr(NumericExpr expr) const

Sets the nonlinear part of the objective expression.

inline void unset_nonlinear_expr()

Unsets the nonlinear part of the objective.

inline obj::Type type() const

Returns the type of the objective.

inline NumericExpr nonlinear_expr() const

Returns the nonlinear part of the objective expression.

inline bool operator==(BasicObjective<OtherItem> other) const
inline bool operator!=(BasicObjective<OtherItem> other) const

Private Functions

inline MutObjective(BasicProblem *p, int index)

Friends

friend class BasicProblem
class mp::MutSuffix : public mp::Suffix
#include <suffix.h>

MutSuffix.

Public Functions

inline MutSuffix()
template<typename T>
inline MutSuffix(BasicMutSuffix<T> other)
template<typename Visitor>
inline void VisitValues(Visitor &v) const

Iterates over nonzero suffix values and sends them to the visitor.

Private Functions

inline explicit MutSuffix(const Impl *impl)

Friends

friend class BasicSuffixSet
class mp::BasicProblem::MutVariable : public mp::BasicProblem<ProblemParams>::BasicVariable<MutProblemItem>
#include <problem.h>

A mutable variable.

Public Functions

inline operator Variable() const
inline void set_lb(double lb) const
inline void set_ub(double ub) const
inline void set_value(double value) const

Sets the initial value.

inline bool is_marked_deleted() const

Whether the variable is marked as deleted.

inline double lb() const

Returns the lower bound on the variable.

inline double ub() const

Returns the upper bound on the variable.

inline var::Type type() const

Returns the type of the variable.

inline double value() const

Returns the value of the variable.

inline bool operator==(BasicVariable<OtherItem> other) const
inline bool operator!=(BasicVariable<OtherItem> other) const

Private Functions

inline MutVariable(BasicProblem *p, int index)

Friends

friend class BasicProblem
class mp::NameProvider
#include <nl-reader.h>

A variable or constraint name provider.

Caters for possible missing names.

Public Functions

NameProvider(fmt::CStringRef filename, fmt::CStringRef gen_name, std::size_t num_items)

Construct and read.

NameProvider(fmt::CStringRef gen_name, fmt::CStringRef n2 = "")

Construct without reading (generic names can be provided).

Parameters

n2 – second generic name, used from the 2nd index of name().

void ReadNames(fmt::CStringRef filename, std::size_t num_items)

Read names.

size_t number_read() const

Number of names read from file.

fmt::StringRef name(std::size_t index, std::size_t i2 = -1)

Returns the name of the item at specified index.

Parameters

i2 – if >=0, from this index, generic name 2 is used

std::vector<std::string> get_names(size_t n, size_t i2 = -1)

Return vector of names, length n.

If number_read() < n, generic names are filled.

Parameters

i2 – if >=0, from this index, generic name 2 is used

Private Members

std::vector<const char*> names_
std::string gen_name_
std::string gen_name_2_
internal::NameReader reader_
fmt::MemoryWriter writer_
class mp::internal::NameReader
#include <nl-reader.h>

A name file reader.

Public Functions

template<typename NameHandler>
inline void Read(fmt::CStringRef filename, NameHandler &handler)

Reads names from file filename by passing its contents to ReadNames().

Private Members

MemoryMappedFile mapped_file_
template<typename Handler, bool>
struct mp::internal::NLAdapter
#include <nl-reader.h>

Public Types

typedef Handler Type
typedef Handler &RefType
template<typename Handler>
struct mp::internal::NLAdapter<Handler, true>
#include <nl-reader.h>

Public Types

typedef NLProblemBuilder<typename Handler::Builder> Type
typedef Type RefType
template<typename Impl, typename ExprType>
class mp::NLFeeder
#include <nl-feeder.h>

NLFeeder: writes model details on request via provided callback objects. See the examples folder.

For the NL format, variables and constraints must have certain order.

Variable ordering:

first continuous, then integer. Some solvers might require more elaborate ordering, see NLHeader.

Constraint ordering:

first algebraic (including complementarity), then logical.

Some solvers might require nonlinear constraints first.

NLFeeder can be used as a base class for other feeders, or just be an interface prototype.

Subclassed examples:

@param: Impl is the final CRTP type derived from NLFeeder.

@param: ExprType is a type storing expressions from methods such as FeedExpr. If not used, it can be any default-constructible type.

Public Types

typedef ExprType Expr

The expression type.

Public Functions

inline NLHeader Header()

Provide NLHeader.

This method is called first.
NLHeader summarizes the model and provides some technical parameters, such as text/binary NL format.

inline bool WantNLComments() const

NL comments?

inline int OutputPrecision() const

The maximum number of significant digits written.

The default value requests full precision, which might be the shortest representation that, when converted to binary and properly rounded, will give exactly the binary value stored in the computer.

inline bool WantBoundsFirst() const

Write bounds first? The default is yes in AMPL, controlled by (the value of option nl_permute) & 32 (the bit is 0 for yes).

Changing this option is deprecated, see https://netlib.org/ampl/changes.

inline int WantColumnSizes() const

Want Jacobian column sizes? Required by some nonlinear solvers.

Options: 0 - none, 1 - cumulative, 2 - non-cumulative. This option controls how ColSizeWriter writes the provided sizes (which should be non-cumulative).

inline const char *ObjDescription(int i)

Description for objective function i (i in 0..num_objs-1).

With WantNLComments()==true, this is written to text-format NL as a comment.

inline int ObjType(int i)

Provide type of objective i.

  • 0 - minimization;

  • 1 - maximization.

template<class ObjGradWriterFactory>
inline void FeedObjGradient(int i, ObjGradWriterFactory&)

Feed gradient for objective i.

Should include entries for all potentially nonzero elements (sparsity pattern).

Implementation skeleton: if (obj_grad[i].size()) { auto svw = svwf.MakeVectorWriter(obj_grad[i].size()); for (size_t j=0; j<obj_grad.size(); ++j) svw.Write(obj_grad[j].var_index, obj_grad[j].coef); }

template<class ObjExprWriter>
inline void FeedObjExpression(int, ObjExprWriter &ew)

Feed nonlinear expression of objective i.

The default implementation below feeds constant 0 (linear models.)

Implementation example: ew.EPut(obj_root_expr[i]);

Details of ObjExprWriter: see NLWriter2.

template<class DefVarWriterFactory>
inline void FeedDefinedVariables(int i, DefVarWriterFactory&)

Defined variables.

Classical NL writes first the defined variables which are used in several places (constraints and/or objectives). Defined variables used in a single place (1 constraint, or 1 objective), are written just before the expression tree of their usage.

For most solvers, this requirement can be ignored and this method can return all defined variables in the first group (for i=0).

The method is guaranteed to be called in the following order:

  1. For i=0;

  2. For i>0, increasing, before constraint (i-1)’s expression;

  3. For i<0, decreasing, before objective (-i-1)’s expression.

Implementation skeleton: // dvar_index in num_vars..num_vars+num_defvars-1. for (int dvar_index: dvar_indexes[i]) { auto dv = dvw.StartDefVar(dvar_index, lin_nnz, name_or_comment); /////////// Write the linear part: auto linw = dv.GetLinExprWriter(); for (int i=0; i<lin_nnz; ++i) linw.Write(linexp_var[i], linexp_coef[i]); /////////// Write the expression tree: auto ew = dv.GetExprWriter(); ew.EPut(root_expr); }

Parameters

i

  • For i=0, feed a sequence of defined variables used in several constraints and/or objectives.

  • For i>0, feed the defined variables used solely in constraint i-1.

  • For i<0, feed the defined variables used solely in objective -i-1.

template<class VarBoundsWriter>
inline void FeedVarBounds(VarBoundsWriter&)

Bounds for variables (except defined variables).

Use +-inf for missing lower and/or upper bounds. Note that variable type is given by variable ordering, see NLHeader.

Implementation skeleton: for (int i = 0; i < hdr.num_vars; i++) vbw.WriteLbUb(lb[i], ub[i]);

template<class ConBoundsWriter>
inline void FeedConBounds(ConBoundsWriter&)

Bounds/complementarity for all algebraic constraints (num_algebraic_cons).

Implementation skeleton: for (int j=0; j<hdr.num_algebraic_cons; j++) { AlgConRange bnd; if (compl_var && compl_var[j]) { j = compl_var[j]-1; bnd.k = 0; if (vlb[j] > negInfinity) bnd.k = 1; if (vub[j] < Infinity) bnd.k |= 2; assert(bnd.k); bnd.cvar = j; } else { bnd.L = clb[j]; bnd.U = cub[j]; } cbw.WriteAlgConRange(bnd); }

inline const char *ConDescription(int)

Description of constraint i (i in 0..num_algebraic_cons+num_logical_cons-1).

With WantNLComments()==true, this is written to text-format NL as a comment.

template<class ConLinearExprWriterFactory>
inline void FeedLinearConExpr(int i, ConLinearExprWriterFactory&)

Feed the linear part of algebraic constraint i.

For smooth solvers, should contain entries for all potential nonzeros (Jacobian sparsity pattern).

Implementation skeleton: if (con_grad[i].size()) { auto sv = svw.MakeVectorWriter(con_grad[i].size()); for (size_t j=0; j<con_grad.size(); ++j) sv.Write(con_grad[j].var_index, con_grad[j].coef); }

template<class ConExprWriter>
inline void FeedConExpression(int, ConExprWriter &ew)

Feed nonlinear expression of constraint i.

Algebraic constraints (num_algebraic_cons) come before logical (num_logical_cons). For linear constraints, the expression should be constant 0, which is implemented as default.

template<class ExprWriter>
inline void FeedExpr(Expr e, ExprWriter&)

Feed native expression.

This method is recursively called from NLWriter, when Feeder uses ExprWriter::EPut(). Feeder should not call this method itself.

Details of ExprWriter: see NLWriter2.

template<class PLSOSWriter>
inline void FeedPLSOS(PLSOSWriter&)

The below feature is for AMPL’s internal linearization of piecewise-linear functions.

For user-definable SOS constraints, use suffixes .sosno/.ref.

The below is a feeder interface for .sos/.sosref suffixes. The feeder can provide 3 sparse vectors:

  • .sos for variables: Each nonzero value defines SOS group number. Negative means SOS Type 2, positive - SOS Type 1.

  • .sos for constraints: Each nonzero value denotes a constraint used in a linearization of an SOS. The constraint can be deleted by the solver driver if using solver’s SOS.

  • .sosref for variables: SOS weights. Variables participating in an SOS having zero weights are involved in linearization and can be deleted if the solver accepts SOS natively.

Implementation: auto sosv = plsos.StartSOSVars(nvsos); for (int i=0; i<nvsos; ++i) sosv.Write(i, vsos[i]); if (ncsos) { auto sosc = plsos.StartSOSCons(ncsos); for …. } auto sosrefv = plsos.StartSOSREFVars(ac->nsosref); ….

inline FuncDef Function(int i)

Provide definition of function i, i=0..num_funcs-1.

template<class RandVarWriterFactory>
inline void FeedRandomVariables(RandVarWriterFactory&)

  1. RANDOM VARIABLES ///////////////////// Random variables. Undocumented feature. SNL2006. Example: var z >= 0; let z.stage := 1; var x{0..1, 0..1} random := Uniform(0,2); for {i in 0..1, j in 0..1} {let x[i,j].stage := 1;}; display z.stage, x.stage; c: z * sum{i in 0..1, j in 0..1} x[i,j] <= 3 + Sample(Uniform(0,2));

Feed random variables. Indexes: num_vars+num_common_exprs .. num_vars+num_common_exprs+num_rand_vars-1.

Implementation skeleton: for(j = num_vars+num_common_exprs; j < num_vars+num_common_exprs+num_rand_vars; j++) { auto ew = rvw.StartRandVar(j, rand_var_comment(j)); ew.EPut(rand_var_root_expr(j)); }

template<class ColSizeWriter>
inline void FeedColumnSizes(ColSizeWriter&)

Jacobian column sizes (including potential nonzeros).

Should feed LP/Jacobian column sizes for all but the last variable.

This is called before writing Jacobian rows.

Implementation skeleton: if (WantColumnSizes()) for (int i=0; i < num_vars+num_rand_vars-1; ++i) csw.Write(col_size[i]);

template<class IGWriter>
inline void FeedInitialGuesses(IGWriter&)

Initial primal guesses.

Implementation: write all meaningfuls entries (incl. zeros.) if (ini_guess.size()) { auto ig = igw.MakeVectorWriter(ini_guess.size()); for (size_t i=0; i<ini_guess.size(); ++i) ig.Write(ini_guess[i].index_, ini_guess[i].value_); }

template<class IDGWriter>
inline void FeedInitialDualGuesses(IDGWriter&)

Initial dual guesses.

template<class SuffixWriterFactory>
inline void FeedSuffixes(SuffixWriterFactory&)

Feed suffixes.

For constraints, assume ordering: first algebraic, then logical.

Implementation: write all non-0 entries (0 is the default.) while (….) { auto sw = swf.StartIntSuffix( // or …DblSuffix suf_name, kind, n_nonzeros); for (int i=0; i<n_nonzeros; ++i) sw.Write(index[i], value[i]); }

template<class RowObjNameWriter>
inline void FeedRowAndObjNames(RowObjNameWriter &wrt)

FeedRowAndObjNames: Provide constraint, then objective names.

Name information is optional.

Implementation: if ((output_desired) && wrt) for (i: ….) wrt << name[i].c_str();

template<class DelRowNameWriter>
inline void FeedDelRowNames(DelRowNameWriter&)

Provide deleted row names.

template<class ColNameWriter>
inline void FeedColNames(ColNameWriter&)

Provide variable names.

template<class UnusedVarNameWriter>
inline void FeedUnusedVarNames(UnusedVarNameWriter&)

Provide unused variable names.

template<class FixedVarNameWriter>
inline void FeedFixedVarNames(FixedVarNameWriter&)

Provide {fixed variable, extra info} pairs.

This includes defined eliminated variables.

Implementation: if ((output_desired) && wrt) for (….) wrt << typename Writer::StrStrValue { name[i].c_str(), comment[i].c_str() };

template<class ObjOffsetWriter>
inline void FeedObjAdj(ObjOffsetWriter&)

Provide {obj name, constant term} pairs.

Implementation: if (wrt) for (….) wrt << typename Writer::StrDblValue { name[i].c_str(), (double)obj_offset[i] };

class mp::NLFeeder_Easy : public mp::NLFeeder<NLFeeder_Easy, void*>

Specialize NLFeeder for NLModel.

Public Types

typedef void *Expr

The expression type.

Public Functions

inline NLFeeder_Easy(const NLModel &nls, NLW2_NLOptionsBasic_C opts)

Construct.

inline NLHeader Header() const

NL header.

inline bool WantNLComments() const

NL comments?

inline const char *ObjDescription(int i)
inline int ObjType(int i)

Provide type of objective i.

0 - minimization; 1 - maximization.

template<class ObjGradWriterFactory>
inline void FeedObjGradient(int, ObjGradWriterFactory &svwf)

Feed gradient for objective i.

Should include entries for all potentially nonzero elements (sparsity pattern).

Implementation skeleton: if (obj_grad[i].size()) { auto svw = svwf.MakeVectorWriter(obj_grad[i].size()); for (size_t j=0; j<obj_grad.size(); ++j) svw.Write(obj_grad[j].var_index, obj_grad[j].coef); }

template<class ObjExprWriter>
inline void FeedObjExpression(int, ObjExprWriter &ew)

Feed nonlinear expression of objective i.

The default implementation below feeds constant 0 (linear models.)

Implementation example: ew.EPut(obj_root_expr[i]);

Details of ObjExprWriter: see NLWriter2.

template<class VarBoundsWriter>
inline void FeedVarBounds(VarBoundsWriter &vbw)

Bounds for variables (except defined variables).

Use +-inf for missing lower and/or upper bounds. Note that variable type is given by variable ordering, see NLHeader.

Implementation skeleton: for (int i = 0; i < hdr.num_vars; i++) vbw.WriteLbUb(lb[i], ub[i]);

template<class ConBoundsWriter>
inline void FeedConBounds(ConBoundsWriter &cbw)

Bounds/complementarity for all algebraic constraints (num_algebraic_cons).

Implementation skeleton: for (int j=0; j<hdr.num_algebraic_cons; j++) { AlgConRange bnd; if (compl_var && compl_var[j]) { j = compl_var[j]-1; bnd.k = 0; if (vlb[j] > negInfinity) bnd.k = 1; if (vub[j] < Infinity) bnd.k |= 2; assert(bnd.k); bnd.cvar = j; } else { bnd.L = clb[j]; bnd.U = cub[j]; } cbw.WriteAlgConRange(bnd); }

inline const char *ConDescription(int i)

Description of constraint i (i in 0..num_algebraic_cons+num_logical_cons-1).

With WantNLComments()==true, this is written to text-format NL as a comment.

template<class ConLinearExprWriterFactory>
inline void FeedLinearConExpr(int i, ConLinearExprWriterFactory &svw)

Feed the linear part of algebraic constraint i.

For smooth solvers, should contain entries for all potential nonzeros (Jacobian sparsity pattern).

For QP, only linear constraints.

Implementation skeleton: if (con_grad[i].size()) { auto sv = svw.MakeVectorWriter(con_grad[i].size()); for (size_t j=0; j<con_grad.size(); ++j) sv.Write(con_grad[j].var_index, con_grad[j].coef); }

template<class ColSizeWriter>
inline void FeedColumnSizes(ColSizeWriter &csw)

Jacobian column sizes (including potential nonzeros).

Should feed LP column sizes for all but the last variable.

Implementation skeleton: if (WantColumnSizes()) for (int i=0; i < num_vars+num_rand_vars-1; ++i) csw.Write(col_size[i]);

template<class IGWriter>
inline void FeedInitialGuesses(IGWriter &igw)

Initial primal guesses.

Implementation: if (ini_guess.size()) { auto ig = igw.MakeVectorWriter(ini_guess.size()); for (size_t i=0; i<ini_guess.size(); ++i) ig.Write(ini_guess[i].index_, ini_guess[i].value_); }

template<class IDGWriter>
inline void FeedInitialDualGuesses(IDGWriter &igw)

Initial dual guesses.

template<class SuffixWriterFactory>
inline void FeedSuffixes(SuffixWriterFactory &swf)

Feed suffixes.

For constraints, assume ordering: first algebraic, then logical.

Implementation: write all non-0 entries while (….) { auto sw = swf.StartIntSuffix( // or …DblSuffix suf_name, kind, n_nonzeros); for (int i=0; i<n_nonzeros; ++i) sw.Write(index[i], value[i]); }

template<class RowObjNameWriter>
inline void FeedRowAndObjNames(RowObjNameWriter &wrt)

FeedRowAndObjNames: Provide constraint, then objective names.

Name information is optional.

Implementation: if ((output_desired) && wrt) for (i: ….) wrt << name[i].c_str();

template<class ColNameWriter>
inline void FeedColNames(ColNameWriter &wrt)

Provide variable names.

inline void ExportPreproData(NLModel::PreprocessData &pd)
inline NLHeader Header()

Provide NLHeader.

This method is called first.
NLHeader summarizes the model and provides some technical parameters, such as text/binary NL format.

inline int OutputPrecision() const

The maximum number of significant digits written.

The default value requests full precision, which might be the shortest representation that, when converted to binary and properly rounded, will give exactly the binary value stored in the computer.

inline bool WantBoundsFirst() const

Write bounds first? The default is yes in AMPL, controlled by (the value of option nl_permute) & 32 (the bit is 0 for yes).

Changing this option is deprecated, see https://netlib.org/ampl/changes.

inline int WantColumnSizes() const

Want Jacobian column sizes? Required by some nonlinear solvers.

Options: 0 - none, 1 - cumulative, 2 - non-cumulative. This option controls how ColSizeWriter writes the provided sizes (which should be non-cumulative).

inline void FeedDefinedVariables(int i, DefVarWriterFactory&)

Defined variables.

Classical NL writes first the defined variables which are used in several places (constraints and/or objectives). Defined variables used in a single place (1 constraint, or 1 objective), are written just before the expression tree of their usage.

For most solvers, this requirement can be ignored and this method can return all defined variables in the first group (for i=0).

The method is guaranteed to be called in the following order:

  1. For i=0;

  2. For i>0, increasing, before constraint (i-1)’s expression;

  3. For i<0, decreasing, before objective (-i-1)’s expression.

Implementation skeleton: // dvar_index in num_vars..num_vars+num_defvars-1. for (int dvar_index: dvar_indexes[i]) { auto dv = dvw.StartDefVar(dvar_index, lin_nnz, name_or_comment); /////////// Write the linear part: auto linw = dv.GetLinExprWriter(); for (int i=0; i<lin_nnz; ++i) linw.Write(linexp_var[i], linexp_coef[i]); /////////// Write the expression tree: auto ew = dv.GetExprWriter(); ew.EPut(root_expr); }

Parameters

i

  • For i=0, feed a sequence of defined variables used in several constraints and/or objectives.

  • For i>0, feed the defined variables used solely in constraint i-1.

  • For i<0, feed the defined variables used solely in objective -i-1.

inline void FeedConExpression(int, ConExprWriter &ew)

Feed nonlinear expression of constraint i.

Algebraic constraints (num_algebraic_cons) come before logical (num_logical_cons). For linear constraints, the expression should be constant 0, which is implemented as default.

inline void FeedExpr(Expr e, ExprWriter&)

Feed native expression.

This method is recursively called from NLWriter, when Feeder uses ExprWriter::EPut(). Feeder should not call this method itself.

Details of ExprWriter: see NLWriter2.

inline void FeedPLSOS(PLSOSWriter&)

The below feature is for AMPL’s internal linearization of piecewise-linear functions.

For user-definable SOS constraints, use suffixes .sosno/.ref.

The below is a feeder interface for .sos/.sosref suffixes. The feeder can provide 3 sparse vectors:

  • .sos for variables: Each nonzero value defines SOS group number. Negative means SOS Type 2, positive - SOS Type 1.

  • .sos for constraints: Each nonzero value denotes a constraint used in a linearization of an SOS. The constraint can be deleted by the solver driver if using solver’s SOS.

  • .sosref for variables: SOS weights. Variables participating in an SOS having zero weights are involved in linearization and can be deleted if the solver accepts SOS natively.

Implementation: auto sosv = plsos.StartSOSVars(nvsos); for (int i=0; i<nvsos; ++i) sosv.Write(i, vsos[i]); if (ncsos) { auto sosc = plsos.StartSOSCons(ncsos); for …. } auto sosrefv = plsos.StartSOSREFVars(ac->nsosref); ….

inline FuncDef Function(int i)

Provide definition of function i, i=0..num_funcs-1.

inline void FeedRandomVariables(RandVarWriterFactory&)

  1. RANDOM VARIABLES ///////////////////// Random variables. Undocumented feature. SNL2006. Example: var z >= 0; let z.stage := 1; var x{0..1, 0..1} random := Uniform(0,2); for {i in 0..1, j in 0..1} {let x[i,j].stage := 1;}; display z.stage, x.stage; c: z * sum{i in 0..1, j in 0..1} x[i,j] <= 3 + Sample(Uniform(0,2));

Feed random variables. Indexes: num_vars+num_common_exprs .. num_vars+num_common_exprs+num_rand_vars-1.

Implementation skeleton: for(j = num_vars+num_common_exprs; j < num_vars+num_common_exprs+num_rand_vars; j++) { auto ew = rvw.StartRandVar(j, rand_var_comment(j)); ew.EPut(rand_var_root_expr(j)); }

inline void FeedDelRowNames(DelRowNameWriter&)

Provide deleted row names.

inline void FeedUnusedVarNames(UnusedVarNameWriter&)

Provide unused variable names.

inline void FeedFixedVarNames(FixedVarNameWriter&)

Provide {fixed variable, extra info} pairs.

This includes defined eliminated variables.

Implementation: if ((output_desired) && wrt) for (….) wrt << typename Writer::StrStrValue { name[i].c_str(), comment[i].c_str() };

inline void FeedObjAdj(ObjOffsetWriter&)

Provide {obj name, constant term} pairs.

Implementation: if (wrt) for (….) wrt << typename Writer::StrDblValue { name[i].c_str(), (double)obj_offset[i] };

Protected Types

using VarInfo = std::pair<int, int>

Variables info element.

Protected Functions

inline const NLModel &NLME() const
inline NLModel &NLME()
inline void Init()

Reorder variables, compute statistics.

inline void FillNonlinearVars()

Fill which vars are nonlinear in obj.

inline void PermuteVars()

Permute variables.

For QP it should be:

  • nonlinear continuous, int;

  • linear cont, bin, int.

inline int VPerm(int i) const

Var direct permutation.

inline int VPermInv(int i) const

Var inverse permutation.

inline void FillObjNonzeros()
inline void FillColSizes()
inline void FillHeader()

Private Members

NLModel nlme_
NLW2_NLOptionsBasic_C nlopt_
std::vector<bool> nlv_obj_
std::vector<VarInfo> var_perm_
std::vector<bool> obj_grad_supp_
std::vector<int> col_sizes_
NLHeader header_
template<typename File = fmt::File>
class mp::internal::NLFileReader
#include <nl-reader.h>

An .nl file reader.

Subclassed by mp::SolverApp< Solver, Reader >

Public Functions

inline NLFileReader()
inline const File &file()
template<typename Handler>
inline void Read(fmt::CStringRef filename, Handler &handler, int flags)

Opens and reads the file.

Private Functions

void Open(fmt::CStringRef filename)
void Read(fmt::internal::MemoryBuffer<char, 1> &array)

Reads the file into an array.

Private Members

File file_
std::size_t size_
std::size_t rounded_size_
template<typename Impl, typename ExprType>
class mp::NLHandler
#include <nl-reader.h>

An NL handler.

NLHandler can be used as a base class for other handlers. Subclasses only need to redefine methods that handle constructs they are interested in and, possibly, the types used by these methods.

Impl is a type derived from NLHandler that will receive notifications of unhandled constructs via OnUnhandled.

ExprType is a return type of expression handler methods such as OnUnary useful for building expression objects. If not used it can be any default-constructible type.

Subclassed by mp::NullNLHandler< Handler::Expr >

Public Types

typedef ExprType Expr

An expression type.

typedef Expr NumericExpr

A numeric expression type. It is a typedef of Expr but subclasses may define it as a different type convertible to Expr.

typedef Expr LogicalExpr

A logical expression type. It is a typedef of Expr but subclasses may define it as a different type convertible to Expr.

typedef Expr CountExpr

A count expression type. It is a typedef of Expr but subclasses may define it as a different type convertible to NumericExpr.

typedef Expr Reference

A reference expression type. It is a typedef of Expr but subclasses may define it as a different type convertible to NumericExpr.

typedef LinearExprHandler LinearObjHandler

A typedef of a class that receives notifications of terms in the linear part of an objective expression.

typedef LinearExprHandler LinearConHandler

A typedef of a class that receives notifications of terms in the linear part of a constraint expression.

typedef ArgHandler NumericArgHandler

A typedef of a class that receives notifications of numeric arguments.

typedef ArgHandler VarArgHandler

A typedef of a class that receives notifications of vararg expression arguments.

typedef ArgHandler CallArgHandler

A typedef of a class that receives notifications of call expression arguments.

typedef ArgHandler NumberOfArgHandler

A typedef of a class that receives notifications of numberof expression arguments.

typedef ArgHandler CountArgHandler

A typedef of a class that receives notifications of count expression arguments.

typedef ArgHandler LogicalArgHandler

A typedef of a class that receives notifications of logical arguments.

typedef ArgHandler PairwiseArgHandler

A typedef of a class that receives notifications of pairwise expression arguments.

typedef ArgHandler SymbolicArgHandler

A typedef of a class that receives notifications of symbolic (numeric or string) arguments.

Public Functions

inline virtual ~NLHandler()

Destroys the object.

inline void OnUnhandled(const char *kind)

Receives notification of an unhandled construct of the given kind.

Throws UnsupportedError.

inline void OnHeader(const NLHeader &h)

Receives notification of an NL header.

inline bool NeedObj(int obj_index) const

Returns true if the objective with index obj_index should be handled.

inline int resulting_obj_index(int obj_index) const

Returns final objective index (e.g., returns 0 if objno>0 and multiobj=0)

inline void OnObj(int index, obj::Type type, NumericExpr expr)

Receives notification of an objective type and the nonlinear part of an objective expression.

inline void OnAlgebraicCon(int index, NumericExpr expr)

Receives notification of the nonlinear part of an algebraic constraint expression.

inline void OnLogicalCon(int index, LogicalExpr expr)

Receives notification of a logical constraint expression.

inline LinearExprHandler BeginCommonExpr(int index, int num_linear_terms)

Receives notification of the beginning of a common expression (defined variable).

inline void EndCommonExpr(int index, NumericExpr expr, int position)

Receives notification of the end of a common expression.

inline void OnComplementarity(int con_index, int var_index, ComplInfo info)

Receives notification of a complementarity relation var_lb <= x <= var_ub complements con_lb <= body <= con_ub, where x is the variable at index var_index and body is the constraint body. info gives the constraint bounds.

inline LinearObjHandler OnLinearObjExpr(int obj_index, int num_linear_terms)

Receives notification of the linear part of an objective expression.

inline LinearConHandler OnLinearConExpr(int con_index, int num_linear_terms)

Receives notification of the linear part of a constraint expression.

inline LinearExprHandler OnLinearCommonExpr(int expr_index, int num_linear_terms)

Receives notification of the linear part of a common expression.

inline void OnVarBounds(int index, double lb, double ub)

Receives notification of variable bounds.

inline void OnConBounds(int index, double lb, double ub)

Receives notification of constraint bounds (ranges).

inline void OnInitialValue(int var_index, double value)

Receives notification of the initial value for a variable.

inline void OnInitialDualValue(int con_index, double value)

Receives notification of the initial value for a dual variable.

inline ColumnSizeHandler OnColumnSizes()

Receives notification of Jacobian column sizes.

inline void OnFunction(int index, fmt::StringRef name, int num_args, func::Type type)

Receives notification of a function. The name argument is a function name and it is not null-terminated.

inline IntSuffixHandler OnIntSuffix(fmt::StringRef name, suf::Kind kind, int num_values)

Receives notification of an integer suffix. The name argument is a suffix name and it is not null-terminated. kind specifies the suffix kind.

inline DblSuffixHandler OnDblSuffix(fmt::StringRef name, suf::Kind kind, int num_values)

Receives notification of a double suffix. The name argument is a suffix name and it is not null-terminated. kind specifies the suffix kind.

inline NumericExpr OnNumber(double value)

Receives notification of a number in a nonlinear expression.

inline Reference OnVariableRef(int var_index)

Receives notification of a variable reference.

inline Reference OnCommonExprRef(int expr_index)

Receives notification of a common expression (defined variable) reference.

inline NumericExpr OnUnary(expr::Kind kind, NumericExpr arg)

Receives notification of a unary expression.

inline NumericExpr OnBinary(expr::Kind kind, NumericExpr lhs, NumericExpr rhs)

Receives notification of a binary expression.

inline NumericExpr OnIf(LogicalExpr condition, NumericExpr then_expr, NumericExpr else_expr)

Receives notification of an if expression.

inline PLTermHandler BeginPLTerm(int num_breakpoints)

Receives notification of the beginning of a piecewise-linear term.

inline NumericExpr EndPLTerm(PLTermHandler handler, Reference arg)

Receives notification of the end of a piecewise-linear term.

arg: argument that is a variable or a common expression reference.

inline CallArgHandler BeginCall(int func_index, int num_args)

Receives notification of the beginning of a call expression.

inline NumericExpr EndCall(CallArgHandler handler)

Receives notification of the end of a call expression.

inline VarArgHandler BeginVarArg(expr::Kind kind, int num_args)

Receives notification of the beginning of a vararg expression.

inline NumericExpr EndVarArg(VarArgHandler handler)

Receives notification of the end of a vararg expression.

inline NumericArgHandler BeginSum(int num_args)

Receives notification of the beginning of a summation.

inline NumericExpr EndSum(NumericArgHandler handler)

Receives notification of the end of a summation.

inline CountArgHandler BeginCount(int num_args)

Receives notification of the beginning of a count expression.

inline CountExpr EndCount(CountArgHandler handler)

Receives notification of the end of a count expression.

inline NumberOfArgHandler BeginNumberOf(int num_args, NumericExpr arg0)

Receives notification of the beginning of a numberof expression.

inline NumericExpr EndNumberOf(NumberOfArgHandler handler)

Receives notification of the end of a numberof expression.

inline SymbolicArgHandler BeginSymbolicNumberOf(int num_args, Expr arg0)

Receives notification of the beginning of a symbolic numberof expression.

inline NumericExpr EndSymbolicNumberOf(SymbolicArgHandler handler)

Receives notification of the end of a symbolic numberof expression.

inline LogicalExpr OnBool(bool value)

Receives notification of a Boolean value.

inline LogicalExpr OnNot(LogicalExpr arg)

Receives notification of a logical not.

inline LogicalExpr OnBinaryLogical(expr::Kind kind, LogicalExpr lhs, LogicalExpr rhs)

Receives notification of a binary logical expression.

inline LogicalExpr OnRelational(expr::Kind kind, NumericExpr lhs, NumericExpr rhs)

Receives notification of a relational expression.

inline LogicalExpr OnLogicalCount(expr::Kind kind, NumericExpr lhs, CountExpr rhs)

Receives notification of a logical count expression.

inline LogicalExpr OnImplication(LogicalExpr condition, LogicalExpr then_expr, LogicalExpr else_expr)

Receives notification of an implication expression.

inline LogicalArgHandler BeginIteratedLogical(expr::Kind kind, int num_args)

Receives notification of the beginning of an iterated logical expression.

inline LogicalExpr EndIteratedLogical(LogicalArgHandler handler)

Receives notification of the end of an iterated logical expression.

inline PairwiseArgHandler BeginPairwise(expr::Kind kind, int num_args)

Receives notification of the beginning of a pairwise expression.

inline LogicalExpr EndPairwise(PairwiseArgHandler handler)

Receives notification of the end of a pairwise expression.

inline Expr OnString(fmt::StringRef value)

Receives notification of a string. The value argument is a string value and it is not null-terminated.

inline Expr OnSymbolicIf(LogicalExpr condition, Expr then_expr, Expr else_expr)

Receives notification of a symbolic if expression.

inline void EndInput()

Receives notification of the end of the input.

struct mp::NLHeader : public mp::NLProblemInfo, public mp::NLInfo, public mp::NLProblemInfo, public mp::NLInfo
#include <nl-header.h>

An NL header which contains information about problem dimensions, such as the number of variables and constraints, and the input format.

Base class: mp::ProblemInfo

Public Types

enum [anonymous]

Values:

enumerator TEXT

Text format.

The text format is fully portable meaning that an .nl file can be written on a machine of one architecture and then read on a machine of a different architecture.

enumerator BINARY

Binary format.

The binary format is not generally portable and should normally be used on a single machine.

enum [anonymous]

Values:

enumerator TEXT

Text format.

The text format is fully portable meaning that an .nl file can be written on a machine of one architecture and then read on a machine of a different architecture.

enumerator BINARY

Binary format.

The binary format is not generally portable and should normally be used on a single machine.

using Format = NLFormat

Input/output format.

using Format = NLFormat

Input/output format.

Public Functions

inline int num_integer_vars() const

Returns the number of integer variables (includes binary variables).

inline int num_integer_vars() const

Returns the number of integer variables (includes binary variables).

inline int num_continuous_vars() const

Returns the number of continuous variables.

inline int num_continuous_vars() const

Returns the number of continuous variables.

inline int num_common_exprs() const

Returns the total number of common expressions.

inline int num_common_exprs() const

Returns the total number of common expressions.

Public Members

int num_vars

Total number of variables.

int num_algebraic_cons

Number of algebraic constraints including ranges and equality constraints.

It doesn’t include logical constraints.

int num_objs

Total number of objectives.

int num_ranges

Number of ranges (constraints with -Infinity < LHS < RHS < Infinity).

int num_eqns

Number of equality constraints or -1 if unknown (AMPL prior to 19970627).

int num_logical_cons

Number of logical constraints.

int num_rand_vars

Number of random variables.

int num_rand_common_exprs

Number of random defined variables.

int num_rand_cons

Number of random constraints.

int num_rand_objs

Number of random objectives.

int num_rand_calls

Number of random calls.

int num_stages

Number of stages.

int num_nl_cons

Total number of nonlinear constraints.

int num_nl_objs

Total number of nonlinear objectives.

int num_compl_conds

Total number of complementarity conditions.

int num_nl_compl_conds

Number of nonlinear complementarity conditions.

int num_compl_dbl_ineqs

Number of complementarities involving double inequalities.

int num_compl_vars_with_nz_lb

Number of complemented variables with a nonzero lower bound.

int num_nl_net_cons

Number of nonlinear network constraints.

int num_linear_net_cons

Number of linear network constraints.

int num_nl_vars_in_cons

Number of nonlinear variables in constraints including nonlinear variables in both constraints and objectives.

int num_nl_vars_in_objs

Number of nonlinear variables in objectives including nonlinear variables in both constraints and objectives.

int num_nl_vars_in_both

Number of nonlinear variables in both constraints and objectives.

int num_linear_net_vars

Number of linear network variables (arcs).

int num_funcs

Number of functions.

int num_linear_binary_vars

Number of linear binary variables.

int num_linear_integer_vars

Number of linear non-binary integer variables.

int num_nl_integer_vars_in_both

Number of integer nonlinear variables in both constraints and objectives.

int num_nl_integer_vars_in_cons

Number of integer nonlinear variables just in constraints.

int num_nl_integer_vars_in_objs

Number of integer nonlinear variables just in objectives.

size_t num_con_nonzeros

Number of nonzeros in constraints’ Jacobian.

size_t num_obj_nonzeros

Number of nonzeros in all objective gradients.

int max_con_name_len

Length of longest constraint or objective name if names are available.

int max_var_name_len

Length of longest variable name if names are available.

int num_common_exprs_in_both

Number of common expressions that appear both in constraints and objectives.

int num_common_exprs_in_cons

Number of common expressions that appear in multiple constraints and don’t appear in objectives.

int num_common_exprs_in_objs

Number of common expressions that appear in multiple objectives and don’t appear in constraints.

int num_common_exprs_in_single_cons

Number of common expressions that only appear in a single constraint and don’t appear in objectives.

int num_common_exprs_in_single_objs

Number of common expressions that only appear in a single objective and don’t appear in constraints.

NLFormat format

Input/output format.

int num_ampl_options

The number of options reserved for AMPL use.

long ampl_options[MAX_AMPL_OPTIONS]

Values of options reserved for AMPL use.

Leave the default values if not using AMPL.

double ampl_vbtol

Extra info for writing a solution reserved for AMPL use.

Leave the default value if not using AMPL.

const char *prob_name

Problem name.

int arith_kind

Floating-point arithmetic kind used with binary format to check if an .nl file is written using a compatible representation of floating-point numbers. It is not used with the text format and normally set to NL_ARITH_UNKNOWN there.

int flags

Flags. Can be either 0 or mp::NLHeader::WANT_OUTPUT_SUFFIXES.

struct NLHeader_C
#include <nl-header-c.h>

An NL header which contains information about problem dimensions, such as the number of variables and constraints, and the input format.

Public Members

NLProblemInfo_C pi
NLInfo_C nli
struct mp::NLInfo : public NLInfo_C, public NLInfo_C
#include <nl-header.h>

NL info.

Subclassed by mp::NLHeader, mp::NLHeader

Public Types

enum [anonymous]

Values:

enumerator TEXT

Text format.

The text format is fully portable meaning that an .nl file can be written on a machine of one architecture and then read on a machine of a different architecture.

enumerator BINARY

Binary format.

The binary format is not generally portable and should normally be used on a single machine.

enum [anonymous]

Values:

enumerator TEXT

Text format.

The text format is fully portable meaning that an .nl file can be written on a machine of one architecture and then read on a machine of a different architecture.

enumerator BINARY

Binary format.

The binary format is not generally portable and should normally be used on a single machine.

using Format = NLFormat

Input/output format.

using Format = NLFormat

Input/output format.

Public Functions

inline NLInfo()

Construct default.

inline NLInfo()

Construct default.

Public Members

NLFormat format

Input/output format.

int num_ampl_options

The number of options reserved for AMPL use.

long ampl_options[MAX_AMPL_OPTIONS]

Values of options reserved for AMPL use.

Leave the default values if not using AMPL.

double ampl_vbtol

Extra info for writing a solution reserved for AMPL use.

Leave the default value if not using AMPL.

const char *prob_name

Problem name.

int arith_kind

Floating-point arithmetic kind used with binary format to check if an .nl file is written using a compatible representation of floating-point numbers. It is not used with the text format and normally set to NL_ARITH_UNKNOWN there.

int flags

Flags. Can be either 0 or mp::NLHeader::WANT_OUTPUT_SUFFIXES.

struct NLInfo_C
#include <nl-header-c.h>

NL technical info.

Subclassed by mp::NLInfo, mp::NLInfo

Public Members

NLFormat format

Input/output format.

int num_ampl_options

The number of options reserved for AMPL use.

long ampl_options[MAX_AMPL_OPTIONS]

Values of options reserved for AMPL use.

Leave the default values if not using AMPL.

double ampl_vbtol

Extra info for writing a solution reserved for AMPL use.

Leave the default value if not using AMPL.

const char *prob_name

Problem name.

int arith_kind

Floating-point arithmetic kind used with binary format to check if an .nl file is written using a compatible representation of floating-point numbers. It is not used with the text format and normally set to NL_ARITH_UNKNOWN there.

int flags

Flags. Can be either 0 or mp::NLHeader::WANT_OUTPUT_SUFFIXES.

class mp::NLModel
#include <nl-model.h>

Class NLModel.

Intermediate representation for special model types: (MI)LP, (MI)QP. For fully nonlinear models with expression trees, use NLSolver with NLFeeder/SOLHandler.

Note

All pointers should stay valid until loading the model into NLSolver.

Public Functions

inline NLModel(const char *probname = nullptr)

Construct.

Note

All pointers should stay valid until loading the model into NLSolver.

inline void SetCols(NLW2_ColData_C vd)

Add variables (all at once.)

Note

All pointers should stay valid until loading the model into NLSolver.

inline void SetColNames(const char *const *nm)

Add variable names.

Note

All pointers should stay valid until loading the model into NLSolver.

inline void SetRows(int nr, const double *rlb, const double *rub, NLW2_SparseMatrix_C A)

Add linear constraints (all at once).

Only rowwise matrix supported.

Note

All pointers should stay valid until loading the model into NLSolver.

inline void SetRowNames(const char *const *nm)

Add constraint names.

Note

All pointers should stay valid until loading the model into NLSolver.

inline void SetLinearObjective(NLW2_ObjSense sense, double c0, const double *c = nullptr)

Add linear objective (only single objective supported.) Coefficients: dense vector.

Note

All pointers should stay valid until loading the model into NLSolver.

inline void SetHessian(NLW2_HessianFormat format, NLW2_SparseMatrix_C Q)

Add Q for the objective quadratic part 0.5 @ x.T @ Q @ x.

Note

All pointers should stay valid until loading the model into NLSolver.

inline void SetObjName(const char *nm)

Set obj name.

Note

All pointers should stay valid until loading the model into NLSolver.

inline void SetWarmstart(NLW2_SparseVector_C ini_x)

Set initial solution.

Note

All pointers should stay valid until loading the model into NLSolver.

inline void SetDualWarmstart(NLW2_SparseVector_C ini_y)

Set dual initial solution.

Note

All pointers should stay valid until loading the model into NLSolver.

inline bool AddSuffix(NLSuffix suf)

Add suffix, e.g., basis statuses.

Note

SOS constraints can be modeled as suffixes for some AMPL solvers.

Returns

true iff new suffix added (vs replaced.)

std::string WriteNL(const std::string &file_stub, NLW2_NLOptionsBasic_C opts, NLUtils &ut, PreprocessData &pd)

Write to NL file.

Recommended usage via class NLSolver.

Returns

empty string iff ok.

double ComputeObjValue(const double *x) const

Compute objective value.

inline const char *ProbName() const

Get problem name.

inline NLW2_ColData_C ColData() const

Get variables.

inline const char *const *ColNames() const

Get var names.

inline const char *ColName(int i) const

Get var name [i].

inline NLW2_SparseMatrix_C GetA() const

Lin con matrix.

inline int NumCols() const

N cols.

inline int NumRows() const

N rows.

inline const double *RowLowerBounds() const

Row lb.

inline const double *RowUpperBounds() const

Row ub.

inline const char *const *RowNames() const

Row names.

inline const char *RowName(int i) const

Row name [i].

inline int ObjSense() const

Obj sense.

inline double ObjOffset() const

Obj offset.

inline const double *ObjCoefficients() const

Obj coefs.

inline int HessianFormat() const

Hessian format NLW2_HessianFormat…

inline NLW2_SparseMatrix_C Hessian() const

Hessian matrix.

inline const char *ObjName() const

Obj name.

inline NLW2_SparseVector_C Warmstart() const

Warm start.

inline NLW2_SparseVector_C DualWarmstart() const

Dual warm start.

inline const NLSuffixSet Suffixes() const

Suffixes.

Protected Functions

inline int SufSize(int kind) const

Private Members

const char *prob_name_ = {"mp::NLModel"}
NLW2_ColData_C vars_ = {}
const char *const *var_names_ = {}
NLW2_SparseMatrix_C A_ = {}
int num_row_ = {}
const double *row_lb_ = {}
const double *row_ub_ = {}
const char *const *row_names_ = {}
int obj_sense_ = {}
double obj_c0_ = {}
const double *obj_c_ = {}
int Q_format_ = {}
NLW2_SparseMatrix_C Q_ = {}
const char *obj_name_ = {"obj[1]"}
NLW2_SparseVector_C ini_y_ = {}
NLW2_SparseVector_C ini_x_ = {}
NLSuffixSet suffixes_
template<typename ProblemBuilder>
class mp::internal::NLProblemBuilder
#include <nl-reader.h>

An NL handler that constructs an optimization problem using ProblemBuilder.

Subclassed by mp::internal::SolverNLHandlerImpl< Solver, ProblemBuilder, NLProblemBuilder >

Public Types

typedef ProblemBuilder::Function Function
typedef ProblemBuilder::Expr Expr
typedef ProblemBuilder::NumericExpr NumericExpr
typedef ProblemBuilder::LogicalExpr LogicalExpr
typedef ProblemBuilder::CountExpr CountExpr
typedef ProblemBuilder::Reference Reference
typedef ProblemBuilder::LinearObjBuilder LinearObjHandler
typedef ProblemBuilder::LinearConBuilder LinearConHandler
typedef ProblemBuilder::LinearExprBuilder LinearExprHandler
typedef ProblemBuilder::IntSuffixHandler IntSuffixHandler
typedef ProblemBuilder::DblSuffixHandler DblSuffixHandler
typedef ProblemBuilder::PLTermBuilder PLTermHandler
typedef ProblemBuilder::CallExprBuilder CallArgHandler
typedef ProblemBuilder::IteratedExprBuilder VarArgHandler
typedef ProblemBuilder::IteratedExprBuilder NumericArgHandler
typedef ProblemBuilder::NumberOfExprBuilder NumberOfArgHandler
typedef ProblemBuilder::SymbolicNumberOfExprBuilder SymbolicArgHandler
typedef ProblemBuilder::CountExprBuilder CountArgHandler
typedef ProblemBuilder::IteratedLogicalExprBuilder LogicalArgHandler
typedef ProblemBuilder::PairwiseExprBuilder PairwiseArgHandler

Public Functions

inline explicit NLProblemBuilder(ProblemBuilder &builder)

Constructor.

virtual ~NLProblemBuilder() = default

Destructor. We have virtual functions.

inline ProblemBuilder &builder()

Get builder.

inline void OnHeader(const NLHeader &h)

OnHeader event.

inline void AddVariables(const NLHeader &h)

Add variables.

inline void DoAddVars(int n, var::Type t, int &k)

DoAddVars: update counter k.

inline virtual int objno() const

objno(). virtual, so that SolverNLHandler can override

inline virtual bool multiobj() const

multiobj(). virtual, so that SolverNLHandler can override

inline virtual void notify_obj_added() const

notify_obj_added(). virtual, so that SolverNLHandler can override

inline int resulting_nobj(int nobj_header) const

Actual N objectives.

inline bool NeedObj(int obj_index) const

Whether need this objective.

inline int resulting_obj_index(int index) const

Final obj index for a given original index.

For multiobj, it’s the same. Otherwise it’s 0 (1st objective).

inline void OnObj(int index, obj::Type type, NumericExpr expr)
inline void OnAlgebraicCon(int index, NumericExpr expr)
inline void OnLogicalCon(int index, LogicalExpr expr)
inline void OnComplementarity(int con_index, int var_index, ComplInfo info)
inline LinearObjHandler OnLinearObjExpr(int obj_index, int num_linear_terms)
inline LinearConHandler OnLinearConExpr(int con_index, int num_linear_terms)
inline LinearExprHandler BeginCommonExpr(int index, int num_linear_terms)
inline void EndCommonExpr(int index, NumericExpr expr, int position)
inline void OnVarBounds(int index, double lb, double ub)
inline void OnConBounds(int index, double lb, double ub)
inline void OnInitialValue(int var_index, double value)
inline void OnInitialDualValue(int con_index, double value)
inline ColumnSizeHandler OnColumnSizes()
inline void OnFunction(int index, fmt::StringRef name, int num_args, func::Type type)
inline IntSuffixHandler OnIntSuffix(fmt::StringRef name, suf::Kind kind, int num_values)
inline DblSuffixHandler OnDblSuffix(fmt::StringRef name, suf::Kind kind, int num_values)
inline NumericExpr OnNumber(double value)
inline Reference OnVariableRef(int var_index)
inline Reference OnCommonExprRef(int expr_index)
inline NumericExpr OnUnary(expr::Kind kind, NumericExpr arg)
inline NumericExpr OnBinary(expr::Kind kind, NumericExpr lhs, NumericExpr rhs)
inline NumericExpr OnIf(LogicalExpr condition, NumericExpr then_expr, NumericExpr else_expr)
inline PLTermHandler BeginPLTerm(int num_breakpoints)
inline NumericExpr EndPLTerm(PLTermHandler handler, Reference arg)
inline CallArgHandler BeginCall(int func_index, int num_args)
inline NumericExpr EndCall(CallArgHandler handler)
inline VarArgHandler BeginVarArg(expr::Kind kind, int num_args)
inline NumericExpr EndVarArg(VarArgHandler handler)
inline NumericArgHandler BeginSum(int num_args)
inline NumericExpr EndSum(NumericArgHandler handler)
inline NumberOfArgHandler BeginNumberOf(int num_args, NumericExpr arg0)
inline NumericExpr EndNumberOf(NumberOfArgHandler handler)
inline SymbolicArgHandler BeginSymbolicNumberOf(int num_args, Expr arg0)
inline NumericExpr EndSymbolicNumberOf(SymbolicArgHandler handler)
inline CountArgHandler BeginCount(int num_args)
inline CountExpr EndCount(CountArgHandler handler)
inline LogicalExpr OnBool(bool value)
inline LogicalExpr OnNot(LogicalExpr arg)
inline LogicalExpr OnBinaryLogical(expr::Kind kind, LogicalExpr lhs, LogicalExpr rhs)
inline LogicalExpr OnRelational(expr::Kind kind, NumericExpr lhs, NumericExpr rhs)
inline LogicalExpr OnLogicalCount(expr::Kind kind, NumericExpr lhs, CountExpr rhs)
inline LogicalExpr OnImplication(LogicalExpr condition, LogicalExpr then_expr, LogicalExpr else_expr)
inline LogicalArgHandler BeginIteratedLogical(expr::Kind kind, int num_args)
inline LogicalExpr EndIteratedLogical(LogicalArgHandler handler)
inline PairwiseArgHandler BeginPairwise(expr::Kind kind, int num_args)
inline LogicalExpr EndPairwise(PairwiseArgHandler handler)
inline Expr OnString(fmt::StringRef value)
inline Expr OnSymbolicIf(LogicalExpr condition, Expr then_expr, Expr else_expr)
inline void EndInput()

Private Functions

template<typename Obj>
inline void SetObj(const Obj &obj, obj::Type type, NumericExpr expr)
template<typename Item>
inline void SetBounds(const Item &item, double lb, double ub)

Sets bounds on a problem item (objective or constraint).

template<typename CommonExpr>
inline void SetCommonExpr(const CommonExpr &common_expr, NumericExpr expr, int position)

Private Members

ProblemBuilder &builder_
struct mp::NLProblemInfo : public NLProblemInfo_C, public NLProblemInfo_C
#include <nl-header.h>

Information about an optimization problem.

Full documentation on the NL format: technical report “Writing .nl Files” (https://ampl.github.io/nlwrite.pdf.)

Subclassed by mp::NLHeader, mp::NLHeader

Public Functions

inline NLProblemInfo()

Construct default.

inline int num_integer_vars() const

Returns the number of integer variables (includes binary variables).

inline int num_continuous_vars() const

Returns the number of continuous variables.

inline int num_common_exprs() const

Returns the total number of common expressions.

inline NLProblemInfo()

Construct default.

inline int num_integer_vars() const

Returns the number of integer variables (includes binary variables).

inline int num_continuous_vars() const

Returns the number of continuous variables.

inline int num_common_exprs() const

Returns the total number of common expressions.

Public Members

int num_vars

Total number of variables.

int num_algebraic_cons

Number of algebraic constraints including ranges and equality constraints.

It doesn’t include logical constraints.

int num_objs

Total number of objectives.

int num_ranges

Number of ranges (constraints with -Infinity < LHS < RHS < Infinity).

int num_eqns

Number of equality constraints or -1 if unknown (AMPL prior to 19970627).

int num_logical_cons

Number of logical constraints.

int num_rand_vars

Number of random variables.

int num_rand_common_exprs

Number of random defined variables.

int num_rand_cons

Number of random constraints.

int num_rand_objs

Number of random objectives.

int num_rand_calls

Number of random calls.

int num_stages

Number of stages.

int num_nl_cons

Total number of nonlinear constraints.

int num_nl_objs

Total number of nonlinear objectives.

int num_compl_conds

Total number of complementarity conditions.

int num_nl_compl_conds

Number of nonlinear complementarity conditions.

int num_compl_dbl_ineqs

Number of complementarities involving double inequalities.

int num_compl_vars_with_nz_lb

Number of complemented variables with a nonzero lower bound.

int num_nl_net_cons

Number of nonlinear network constraints.

int num_linear_net_cons

Number of linear network constraints.

int num_nl_vars_in_cons

Number of nonlinear variables in constraints including nonlinear variables in both constraints and objectives.

int num_nl_vars_in_objs

Number of nonlinear variables in objectives including nonlinear variables in both constraints and objectives.

int num_nl_vars_in_both

Number of nonlinear variables in both constraints and objectives.

int num_linear_net_vars

Number of linear network variables (arcs).

int num_funcs

Number of functions.

int num_linear_binary_vars

Number of linear binary variables.

int num_linear_integer_vars

Number of linear non-binary integer variables.

int num_nl_integer_vars_in_both

Number of integer nonlinear variables in both constraints and objectives.

int num_nl_integer_vars_in_cons

Number of integer nonlinear variables just in constraints.

int num_nl_integer_vars_in_objs

Number of integer nonlinear variables just in objectives.

size_t num_con_nonzeros

Number of nonzeros in constraints’ Jacobian.

size_t num_obj_nonzeros

Number of nonzeros in all objective gradients.

int max_con_name_len

Length of longest constraint or objective name if names are available.

int max_var_name_len

Length of longest variable name if names are available.

int num_common_exprs_in_both

Number of common expressions that appear both in constraints and objectives.

int num_common_exprs_in_cons

Number of common expressions that appear in multiple constraints and don’t appear in objectives.

int num_common_exprs_in_objs

Number of common expressions that appear in multiple objectives and don’t appear in constraints.

int num_common_exprs_in_single_cons

Number of common expressions that only appear in a single constraint and don’t appear in objectives.

int num_common_exprs_in_single_objs

Number of common expressions that only appear in a single objective and don’t appear in constraints.

struct NLProblemInfo_C
#include <nl-header-c.h>

Information about an optimization problem.

Full documentation on the NL format: technical report “Writing .nl Files” (https://ampl.github.io/nlwrite.pdf.)

Subclassed by mp::NLProblemInfo, mp::NLProblemInfo

Public Members

int num_vars

Total number of variables.

int num_algebraic_cons

Number of algebraic constraints including ranges and equality constraints.

It doesn’t include logical constraints.

int num_objs

Total number of objectives.

int num_ranges

Number of ranges (constraints with -Infinity < LHS < RHS < Infinity).

int num_eqns

Number of equality constraints or -1 if unknown (AMPL prior to 19970627).

int num_logical_cons

Number of logical constraints.

int num_rand_vars

Number of random variables.

int num_rand_common_exprs

Number of random defined variables.

int num_rand_cons

Number of random constraints.

int num_rand_objs

Number of random objectives.

int num_rand_calls

Number of random calls.

int num_stages

Number of stages.

int num_nl_cons

Total number of nonlinear constraints.

int num_nl_objs

Total number of nonlinear objectives.

int num_compl_conds

Total number of complementarity conditions.

int num_nl_compl_conds

Number of nonlinear complementarity conditions.

int num_compl_dbl_ineqs

Number of complementarities involving double inequalities.

int num_compl_vars_with_nz_lb

Number of complemented variables with a nonzero lower bound.

int num_nl_net_cons

Number of nonlinear network constraints.

int num_linear_net_cons

Number of linear network constraints.

int num_nl_vars_in_cons

Number of nonlinear variables in constraints including nonlinear variables in both constraints and objectives.

int num_nl_vars_in_objs

Number of nonlinear variables in objectives including nonlinear variables in both constraints and objectives.

int num_nl_vars_in_both

Number of nonlinear variables in both constraints and objectives.

int num_linear_net_vars

Number of linear network variables (arcs).

int num_funcs

Number of functions.

int num_linear_binary_vars

Number of linear binary variables.

int num_linear_integer_vars

Number of linear non-binary integer variables.

int num_nl_integer_vars_in_both

Number of integer nonlinear variables in both constraints and objectives.

int num_nl_integer_vars_in_cons

Number of integer nonlinear variables just in constraints.

int num_nl_integer_vars_in_objs

Number of integer nonlinear variables just in objectives.

size_t num_con_nonzeros

Number of nonzeros in constraints’ Jacobian.

size_t num_obj_nonzeros

Number of nonzeros in all objective gradients.

int max_con_name_len

Length of longest constraint or objective name if names are available.

int max_var_name_len

Length of longest variable name if names are available.

int num_common_exprs_in_both

Number of common expressions that appear both in constraints and objectives.

int num_common_exprs_in_cons

Number of common expressions that appear in multiple constraints and don’t appear in objectives.

int num_common_exprs_in_objs

Number of common expressions that appear in multiple objectives and don’t appear in constraints.

int num_common_exprs_in_single_cons

Number of common expressions that only appear in a single constraint and don’t appear in objectives.

int num_common_exprs_in_single_objs

Number of common expressions that only appear in a single objective and don’t appear in constraints.

template<typename Reader, typename Handler>
class mp::internal::NLReader
#include <nl-reader.h>

An NL reader.

Handler: a class implementing the NLHandler concept that receives notifications of NL constructs

Public Functions

inline NLReader(Reader &reader, const NLHeader &header, Handler &handler, int flags)
template<typename BoundHandler>
void ReadBounds()

Reads variable or constraint bounds.

void Read(Reader *bound_reader)

bound_reader: a reader after variable bounds section input

void Read()

Private Types

enum [anonymous]

Minimum number of arguments for an iterated expression that has a binary counterpart.

Examples: sum (+), forall (&&), exists (||).

Values:

enumerator MIN_ITER_ARGS
enum ItemType

Values:

enumerator VAR
enumerator OBJ
enumerator CON
enumerator PROB
typedef Handler::Expr Expr
typedef Handler::NumericExpr NumericExpr
typedef Handler::LogicalExpr LogicalExpr
typedef Handler::Reference Reference

Private Functions

double ReadConstant(char code)
inline double ReadConstant()
inline int ReadUInt(unsigned ub)

Reads a nonnegative integer and checks that it is less than ub.

ub is unsigned so that it can hold value INT_MAX + 1u.

inline int ReadUInt(unsigned lb, unsigned ub)

Reads a nonnegative integer and checks that it is in the range [lb, ub).

inline int ReadNumArgs(int min_args = MIN_ITER_ARGS)
inline Reference DoReadReference()

Reads a variable or a common expression reference.

inline Reference ReadReference()

Reads a variable or a common expression reference.

template<typename ExprReader, typename ArgHandler>
inline void DoReadArgs(int num_args, ArgHandler &arg_handler)
template<typename ExprReader, typename ArgHandler>
inline void ReadArgs(int num_args, ArgHandler &arg_handler)
inline int ReadOpCode()
inline Handler::CountExpr ReadCountExpr()
Expr ReadSymbolicExpr()

Reads a numeric or string expression.

inline NumericExpr ReadNumericExpr(bool ignore_zero = false)

Reads a numeric expression.

ignore_zero: if true, zero constants are ignored

NumericExpr ReadNumericExpr(char code, bool ignore_zero)
NumericExpr ReadNumericExpr(int opcode)
LogicalExpr ReadLogicalExpr()

Reads a logical expression.

LogicalExpr ReadLogicalExpr(int opcode)
template<typename LinearHandler>
void ReadLinearExpr()

Reads the linear part of an objective or constraint expression.

template<typename LinearHandler>
void ReadLinearExpr(int num_terms, LinearHandler linear_expr)
template<bool CUMULATIVE>
void ReadColumnSizes()

Reads column sizes, numbers of nonzeros in the first num_var − 1 columns of the Jacobian sparsity matrix.

template<typename ValueHandler>
void ReadInitialValues()

Reads initial values for primal or dual variables.

template<typename ValueReader, typename SuffixHandler>
inline void ReadSuffixValues(int num_values, int num_items, SuffixHandler &handler)
template<typename ItemInfo>
void ReadSuffix(int info)

Private Members

Reader &reader_
const NLHeader &header_
Handler &handler_
int flags_
int num_vars_and_exprs_
struct mp::ModelManagerWithProblemBuilder::NLReadResult

Public Types

using HandlerType = SolverNLHandlerType

Public Members

std::unique_ptr<HandlerType> handler_
struct mp::NLSolution
#include <nl-model.h>

Returned solution.

Public Functions

inline operator bool() const

Any result obtained from the solver?

Public Members

int solve_result_ = {-2}

Solve result.

If >-2, solver interaction successful. Then:

  • -1 unknown - unexpected termination

  • 0- 99 solved - optimal solution found

  • 100-199 solved? - optimal solution indicated, but error likely

  • 200-299 infeasible - constraints cannot be satisfied

  • 300-399 unbounded - objective can be improved without limit

  • 400-499 limit - stopped by a limit that you set (such as on iterations)

  • 500-999 failure - stopped by an error condition in the solver

Note

NLSolution is feasible (not proven optimal) if unbounded or limit and x_ populated.

Note

Individual solvers may have more specific values, see https://ampl.com/products/solvers/solvers-we-sell/.

int nbs_ = {}

Number of solve_message’s initial characters already printed on the screen.

std::string solve_message_

Solve message.

double obj_val_ = {}

Objective value.

Only returned by Solve(NLModel). Otherwise, after ReadSolution(), should be manually computed, e.g., by NLModel::ComputeObjValue().

std::vector<double> x_

Primals.

std::vector<double> y_

Duals.

NLSuffixSet suffixes_

Suffixes.

class mp::NLSolver
#include <nl-solver.h>

Class NLSolver.

Manager for solving optimization models via NL files. It performs zero-overhead model/solution transmission. In particular, it does not store any intermediate model/solution representation.

This class offers both full NL functionality, as well as a simplified interface for special model classes, see NLModel.

Usage with full API (see NLFeeder and SOLHandler interfaces for model/solution transmission, as well as tests/examples):

ExampleModel emdl;
ExampleNLFeeder nlf(emdl, binary);
ExampleSOLHandler esolh(emdl);
mp::NLUtils utils;
mp::NLSolver nlsol(&utils);
nlsol.SetFileStub(stub);
if (!nlsol.Solve(nlf, esolh, solver, sopts)) {
  printf("%s\n", nlsol.GetErrorMessage());
  return EXIT_FAILURE;
} else {
  esolh.PrintSolution(stub);
}

Public Functions

NLSolver()

Construct.

NLSolver(mp::NLUtils *put)

Construct.

Parameters

put – pointer to NLUtils or a derived object (optional).

~NLSolver()

Destruct.

inline void SetNLUtils(mp::NLUtils *p_ut)

Set NLUtils [OPTIONAL].

If not provided, default is used.

inline mp::NLUtils *GetNLUtils() const

Retrieve NLUtils.

void SetFileStub(std::string stub)

Set file stub [OPTIONAL].

Used for filename base of .nl, .col, row, etc. input files, as well as .sol output files.

Note

If not provided, a temporary filename is used; then, .nl is deleted upon object destruction.

inline const std::string &GetFileStub() const

Retrieve file stub.

inline void SetNLOptions(NLW2_NLOptionsBasic_C nlo)

Set some NL options for NLModel output [OPTIONAL].

If not provided, default is used.

Note

Not used for NLFeeder output.

inline NLW2_NLOptionsBasic_C GetNLOptions() const

Get NLOptions for NLModel output.

inline const char *GetErrorMessage() const

Get error message.

Nonempty iff error occurred.

inline NLW2_WriteNLResultCode GetLoadModelResultCode() const

Get model load result code.

inline NLW2_SOLReadResultCode GetSolReadResultCode() const

Get solution read result code.

inline NLSolution Solve(const NLModel &mdl, const std::string &solver, const std::string &solver_opts)

Load and solve an NLModel instance.

See LoadModel(), Solve(), ReadSolution() for details.

Returns

NLSolution object with computed obj_value_ (has operator bool() for checking if any result was obtained.)

template<class NLFeeder, class SOLHandler>
inline bool Solve(NLFeeder &nlf, SOLHandler &solh, const std::string &solver, const std::string &solver_opts)

Load and solve model using NLFeeder and SOLHandler.

See LoadModel(), Solve(), ReadSolution() for details.

Returns

true iff all ok.

bool LoadModel(const NLModel &mdl)

Write NL and any accompanying files.

NL file name base and some options can be provided, if non-defaults desired, via SetFileStub() and SetNLOptions().

Returns

true if all ok, otherwise see GetErrorMessage().

template<class NLFeeder>
bool LoadModel(NLFeeder &nlf)

Write NL and any accompanying files.

Parameters

nlf – NL feeder.

Returns

true if all ok, otherwise see GetErrorMessage() and GetLoadModelResultCode().

bool Solve(const std::string &solver, const std::string &solver_opts)

Solve after loading model.

Parameters
  • solver – solver executable, such as “gurobi”.

  • solver_opts – string of solver options, such as “outlev=1 writeprob=model.lp”.

Returns

true if all ok.

NLSolution ReadSolution()

Read solution after Solve() when the NL file was written from NLModel.

Note

To compute objective value, execute NLModel::ComputeObjValue() if x_ available.

Returns

NLSolution object (has operator bool() for checking if any result was obtained.)

template<class SOLHandler>
bool ReadSolution(SOLHandler &solh)

Read solution after Solve() when NL file was written from NLFeeder.

Parameters

solh – solution handler.

Returns

true if all ok, otherwise see GetErrorMessage() and, possibly, GetSolReadResultCode().

Protected Functions

void InitAutoStub()
void DestroyAutoStub()
inline mp::NLUtils &Utils() const

Private Members

mp::NLUtils utils_
mp::NLUtils *p_ut_ = nullptr
std::string pathstr_
std::string filestub_
bool filestubCustom_ = false
NLW2_NLOptionsBasic_C nl_opts_
std::unique_ptr<NLHeader> p_nlheader_
NLModel::PreprocessData pd_
std::string err_msg_
NLW2_WriteNLResultCode nl_result_ = {NLW2_WriteNL_Unset}
NLW2_SOLReadResultCode sol_result_ = {NLW2_SOLRead_Result_Not_Set}
class mp::NLStringRef
#include <nl.h>

A reference to a null-terminated string with size.

Public Functions

inline NLStringRef(const char *s)

Constructs a string reference object from a C string computing the size with std::strlen.

inline NLStringRef(const char *s, std::size_t size)

Constructs a string reference object from a C string and a size.

inline NLStringRef(const std::string &s)

Constructs a string reference from an std::string object.

inline const char *c_str() const

Returns the pointer to a C string.

inline std::size_t size() const

Returns the string size.

Private Members

const char *data_
std::size_t size_
struct mp::NLSuffix
#include <nl-model.h>

NL suffix type.

Public Functions

inline NLSuffix(std::string name, int kind, std::vector<double> v = {})

Construct.

inline NLSuffix(std::string name, std::string table, int kind, std::vector<double> v = {})

Construct.

inline bool operator<(const NLSuffix &s) const

operator<

Public Members

std::string name_ = {}

Name.

std::string table_ = {}

Suffix table.

int kind_ = {-1}

Kind.

VAR = 0, /**< Applies to variables. */ CON = 1, /**< Applies to constraints. */ OBJ = 2, /**< Applies to objectives. */ PROBLEM = 3 /**< Applies to problems. */

If the suffix should be delivered as real-valued, the kind_ should be bitwise-OR’ed with 0x4.

std::vector<double> values_ = {}

Values. Always double precision. Dense vector.

class mp::NLSuffixSet : private std::set<NLSuffix>
#include <nl-model.h>

NL suffix set.

Public Functions

inline bool Add(NLSuffix suf)

Add suffix.

Returns

true iff new suffix (not existed before.)

inline const NLSuffix *Find(const std::string &nm, int k) const

Find suffix.

Parameters

k – kind (only the first 2 bits are used.)

Returns

NLSuffix*, nullptr iff not found.

Protected Types

using Base = std::set<NLSuffix>
class mp::NLUtils
#include <nl-utils.h>

NL writer and SOL reader utilities.

It provides default facilities for logging and error handling.

Subclassed by mp::NLUtils_C_Impl

Public Functions

inline virtual ~NLUtils()

Destructor.

virtual File openf(const std::string &fname, int Close, const char *mode)

File opener.

Parameters

Close – remove file instead

virtual void log_message(const char *format, ...)

log message

virtual void log_warning(const char *format, ...)

log warning (e.g., cannot write name file)

inline virtual bool if_show_filenames()

Whether to show file names in the default openf() via log_message().

inline virtual void set_show_filenames(bool v)

Set: whether to show file names.

inline virtual void myexit(const std::string &msg)

Override this to your error handler.

Not using exceptions by default. Only called on a wrong output format string (internal error.)

Private Members

bool show_fln_ = {false}
class mp::NLUtils_C_Impl : public mp::NLUtils

Wrap NLUtils_C into a C++ class, in order to interface it for NLWriter2, NLReader2.

Public Functions

inline NLUtils_C_Impl(NLW2_NLUtils_C *pu)

Construct.

inline virtual void log_message(const char *format, ...) override

log message

inline virtual void log_warning(const char *format, ...) override

log warning

inline virtual void myexit(const std::string &msg) override

Override this to your error handler.

virtual File openf(const std::string &fname, int Close, const char *mode)

File opener.

Parameters

Close – remove file instead

inline virtual bool if_show_filenames()

Whether to show file names in the default openf() via log_message().

inline virtual void set_show_filenames(bool v)

Set: whether to show file names.

Protected Functions

inline const NLW2_NLUtils_C &NLU() const

Private Members

const NLW2_NLUtils_C nlu_c_
struct NLW2_AlgConRange_C
#include <nl-feeder-c.h>

  • Algebraic constraint bounds (for a single constraint):

  • either range (lb, ub),

  • or complementarity info (k, cvar), when k>0.

  • For a complementarity constraint to hold, if cvar is at

  • its lower bound, then body >= 0; if cvar is at its upper

  • bound, then body <= 0;

  • and if cvar is strictly between its bounds, then body = 0.

  • The integer k in a complementarity constraint line indicates

  • which bounds on cvar are finite: 1 and 3 imply a finite

  • lower bound; 2 and 3 imply a finite upper bound; 0 (which

  • should not occur) would imply no finite bounds, i.e.,

  • body = 0 must always hold.

  • Example:

  • 
    
  • ampl: var x; var y; var z;

  • ampl: s.t. Compl1: x+y >= 3 complements x-z <= 15;

  • ampl: s.t. Compl2: -2 <= 2*y+3*z <= 13 complements 6*z-2*x;

  • ampl: expand;

  • subject to Compl1:

  • 3 <= x + y

  • complements

  • x - z <= 15;

  • subject to Compl2:

  • -2 <= 2*y + 3*z <= 13

  • complements

  • -2*x + 6*z;

  • ampl: solexpand;

  • Nonsquare complementarity system:

  • 4 complementarities including 2 equations

  • 5 variables

  • subject to Compl1.L:

  • x + y + Compl1$cvar = 0;

  • subject to Compl1.R:

  • -15 + x - z <= 0

  • complements

  • Compl1$cvar <= -3;

  • subject to Compl2.L:

  • 2*y + 3*z - Compl2$cvar = 0;

  • subject to Compl2.R:

  • -2*x + 6*z

  • complements

  • -2 <= Compl2$cvar <= 13;

Public Members

double L
double U
int k
int cvar
struct NLW2_ColData_C

Variables’ data by pointers.

Public Members

int num_col_

Num vars.

const double *lower_

lower bounds

const double *upper_

upper bounds

const int *type_

type: see enum NLW2_VarType.

Set to NULL if all continuous.

struct NLW2_NLFeeder_C
#include <nl-feeder-c.h>

Wrap mp::NLFeeder for C API.

NLW2_NLFeeder_C: writes model details on request via provided callback objects. See the examples folder.

To fill some default values and methods, e.g., options and some methods like name feeders, call NLW2_MakeNLFeeder_C_Default() / NLW2_Destroy…().

2023-11: CURRENT IMPLEMENTATION SUPPORTS LINEAR MODELS.

For the NL format, variables and constraints must have certain order.

Variable ordering:** first continuous, then integer. Some solvers might require more elaborate ordering, see NLHeader_C.

Constraint ordering:** first algebraic (including complementarity), then logical. Some solvers might require nonlinear constraints first.

Public Members

void *p_user_data_

User data, provided as the 1st argument to the methods.

NLHeader_C (*Header)(void *p_user_data)

Set the below function pointers.

Provide NLHeader.

This method is called first.

NLHeader summarizes the model and provides some technical parameters, such as text/binary NL format.

int want_nl_comments_

Options. Safe to leave as by the default generator.

NL comments?

int output_precision_

The maximum number of significant digits written.

The default value 0 requests full precision, which might be the shortest representation that, when converted to binary and properly rounded, will give exactly the binary value stored in the computer.

int want_bounds_first_

Write bounds first? The default is 1 (yes) in AMPL, controlled by (the value of option nl_permute) & 32 (the bit is 0 for yes).

Changing this option is deprecated, see https://netlib.org/ampl/changes.

int want_column_sizes_

Want Jacobian column sizes? Required by some nonlinear solvers.

Options: 0 - none, 1 - cumulative (default), 2 - non-cumulative. This option controls how ColSizeWriter writes the provided sizes (which should be non-cumulative).

const char *(*ObjDescription)(void *p_user_data, int i)

Description for objective function i (i in 0..num_objs-1).

With WantNLComments()==true, this is written to text-format NL as a comment.

int (*ObjType)(void *p_user_data, int i)

Provide type of objective i.

0 - minimization; 1 - maximization.

int (*ObjGradientNNZ)(void *p_user_data, int i)

Number of nonzeros in the gradient for objective i.

Should include entries for all potentially nonzero elements (sparsity pattern).

void (*FeedObjGradient)(void *p_user_data, int i, void *p_api_data)

Feed gradient for objective i.

Should include entries for all potentially nonzero elements (sparsity pattern).

Implementation skeleton: for (size_t j=0; j<obj_grad_size[i]; ++j) NLW2_WriteSparseDblEntry(p_api_data, obj_grad_index[i][j], obj_grad_value[i][j]);

void (*FeedVarBounds)(void *p_user_data, void *p_api_data)

Feed nonlinear expression of objective i.

The default puts a constant 0.

Implementation example: ew.EPut(obj_root_expr[i]); Defined variables.

Classical NL writes first the defined variables which are used in several places (constraints and/or objectives). Defined variables used in a single place (1 constraint, or 1 objective), are written just before the expression tree of their usage.

For most solvers, this requirement can be ignored and this method can return all defined variables in the first group (for i=0).

The method is guaranteed to be called in the following order:

  1. For i=0;

  2. For i>0, increasing, before constraint (i-1)’s expression;

  3. For i<0, decreasing, before objective (-i-1)’s expression.

Implementation skeleton: // dvar_index in num_vars..num_vars+num_defvars-1. for (int dvar_index: dvar_indexes[i]) { auto dv = dvw.StartDefVar(dvar_index, lin_nnz, name_or_comment); /////////// Write the linear part: auto linw = dv.GetLinExprWriter(); for (int i=0; i<lin_nnz; ++i) linw.Write(linexp_var[i], linexp_coef[i]); /////////// Write the expression tree: auto ew = dv.GetExprWriter(); ew.EPut(root_expr); } Bounds for variables (except defined variables). Use +-inf for missing lower and/or upper bounds. Note that variable type is given by variable ordering, see NLHeader.

Implementation skeleton: for (int i = 0; i < hdr.num_vars; i++) NLW2_WriteVarLbUb(p_api_data, lb[i], ub[i]);

Parameters

i

  • For i=0, feed a sequence of defined variables used in several constraints and/or objectives.

  • For i>0, feed the defined variables used solely in constraint i-1.

  • For i<0, feed the defined variables used solely in objective -i-1.

void (*FeedConBounds)(void *p_user_data, void *p_api_data)

Bounds/complementarity for all algebraic constraints (num_algebraic_cons).

Implementation skeleton: for (int j=0; j<hdr.num_algebraic_cons; j++) { NLW2_AlgConRange_C bnd; if (compl_var && compl_var[j]) { j = compl_var[j]-1; bnd.k = 0; if (vlb[j] > negInfinity) bnd.k = 1; if (vub[j] < Infinity) bnd.k |= 2; assert(bnd.k); bnd.cvar = j; } else { bnd.k = 0; bnd.L = clb[j]; bnd.U = cub[j]; } NLW2_WriteAlgConRange(p_api_data, &bnd); }

const char *(*ConDescription)(void *p_user_data, int)

Description of constraint i (i in 0..num_algebraic_cons+num_logical_cons-1).

With WantNLComments()==true, this is written to text-format NL as a comment.

int (*LinearConExprNNZ)(void *p_user_data, int i)

Number of nonzeros in the linear part of constraint i.

Should include entries for all potentially nonzero elements (sparsity pattern).

void (*FeedLinearConExpr)(void *p_user_data, int i, void *p_api_data)

Feed the linear part of algebraic constraint i.

For smooth solvers, should contain entries for all potential nonzeros (Jacobian sparsity pattern).

Implementation skeleton: for (size_t j=0; j<con_grad.size(); ++j) NLW2_WriteSparseDblEntry(p_api_data, con_grad[j].var_index, con_grad[j].coef); }

void (*FeedColumnSizes)(void *p_user_data, void *p_api_data)

Feed nonlinear expression of constraint i.

Algebraic constraints (num_algebraic_cons) come before logical (num_logical_cons). For linear constraints, the expression should be constant 0. Feed native expression. This method is recursively called from NLWriter, when Feeder uses ExprWriter::EPut(). Feeder should not call this method itself.

Details of ExprWriter: see NLWriter2. The below feature is for AMPL’s internal linearization of piecewise-linear functions. For user-definable SOS constraints, use suffixes .sosno/.ref.

The below is a feeder interface for .sos/.sosref suffixes. The feeder can provide 3 sparse vectors:

  • .sos for variables: Each nonzero value defines SOS group number. Negative means SOS Type 2, positive - SOS Type 1.

  • .sos for constraints: Each nonzero value denotes a constraint used in a linearization of an SOS. The constraint can be deleted by the solver driver if using solver’s SOS.

  • .sosref for variables: SOS weights. Variables participating in an SOS having zero weights are involved in linearization and can be deleted if the solver accepts SOS natively.

Implementation: auto sosv = plsos.StartSOSVars(nvsos); for (int i=0; i<nvsos; ++i) sosv.Write(i, vsos[i]); if (ncsos) { auto sosc = plsos.StartSOSCons(ncsos); for …. } auto sosrefv = plsos.StartSOSREFVars(ac->nsosref); …. Function definition. Provide definition of function i, i=0..num_funcs-1.

  1. RANDOM VARIABLES ///////////////////// Random variables. Undocumented feature. SNL2006. Example: var z >= 0; let z.stage := 1; var x{0..1, 0..1} random := Uniform(0,2); for {i in 0..1, j in 0..1} {let x[i,j].stage := 1;}; display z.stage, x.stage; c: z * sum{i in 0..1, j in 0..1} x[i,j] <= 3 + Sample(Uniform(0,2));

Feed random variables. Indexes: num_vars+num_common_exprs .. num_vars+num_common_exprs+num_rand_vars-1.

Implementation skeleton: for(j = num_vars+num_common_exprs; j < num_vars+num_common_exprs+num_rand_vars; j++) { auto ew = rvw.StartRandVar(j, rand_var_comment(j)); ew.EPut(rand_var_root_expr(j)); } Jacobian column sizes (with potential nonzeros). Should feed column sizes for all but the last variable.

Implementation skeleton: if (WantColumnSizes()) for (int i=0; i < num_vars+num_rand_vars-1; ++i) NLW2_WriteColSize(col_size[i]);

int (*InitialGuessesNNZ)(void *p_user_data)

Initial primal guesses.

Implementation: write all meaningful entries (incl. zeros.) for (size_t i=0; i<n_ini_guess; ++i) NLW2_WriteSparseDblEntry( p_api_data, ini_index[i], ini_value[i]);

void (*FeedInitialGuesses)(void *p_user_data, void *p_api_data)
int (*InitialDualGuessesNNZ)(void *p_user_data)

Initial dual guesses.

void (*FeedInitialDualGuesses)(void *p_user_data, void *p_api_data)
void (*FeedSuffixes)(void *p_user_data, void *p_api_data)

Feed suffixes.

For constraints, assume ordering: first algebraic, then logical.

Implementation: write all non-0 entries (0 is the default.) while (….) { void* p_api_2 = NLW2_StartIntSuffix( // or …DblSuffix p_api_data, suf_name, kind, n_nonzeros); for (int i=0; i<n_nonzeros; ++i) NLW2_WriteSparseIntEntry(p_api_2, // or …DblEntry index[i], value[i]); // ^<- p_api_2 here }

int want_row_and_obj_names_

Want row/obj names?

int want_del_row_names_

Want del row names?

int want_col_names_

Want col names?

int want_unused_var_names_

Want unused var names?

int want_fixed_var_names_

Want fixed var names?

int want_obj_adj_

Want objective offsets?

void (*FeedRowAndObjNames)(void *p_user_data, void *p_api_data)

FeedRowAndObjNames: Provide constraint, then objective names.

Implementation: for (i: {algcons, logcons, objs}) NLW2_WriteName( p_api_data, con_obj_name[i] );

void (*FeedDelRowNames)(void *p_user_data, void *p_api_data)

Provide deleted row names.

void (*FeedColNames)(void *p_user_data, void *p_api_data)

Provide variable names.

void (*FeedUnusedVarNames)(void *p_user_data, void *p_api_data)

Provide unused variable names.

void (*FeedFixedVarNames)(void *p_user_data, void *p_api_data)

Provide {fixed variable, extra info} pairs.

This includes defined eliminated variables.

Implementation: for (….) NLW2_WriteNameAndComment( p_api_data, name[i], comment[i] );

void (*FeedObjAdj)(void *p_user_data, void *p_api_data)

Provide {obj name, constant term} pairs.

Implementation: for (….) NLW2_WriteNameAndNumber( p_api_data, name[i], obj_offset[i] );

class mp::NLW2_NLFeeder_C_Impl : public mp::NLFeeder<NLW2_NLFeeder_C_Impl, void*>
#include <nl-feeder-c-impl.h>

Implementation: Wrap NLW2_NLFeeder_C into a C++ class, in order to interface it for NLWriter2.

Public Types

using Base = NLFeeder<NLW2_NLFeeder_C_Impl, void*>

typedef base class

typedef void *Expr

The expression type.

Public Functions

inline NLW2_NLFeeder_C_Impl(NLW2_NLFeeder_C *pnlf2)

Construct.

inline NLHeader Header()

Provide NLHeader.

This method is called first.

NLHeader summarizes the model and provides some technical parameters, such as text/binary NL format.

inline bool WantNLComments() const

NL comments?

inline int OutputPrecision() const

The maximum number of significant digits written.

The default value requests full precision, which might be the shortest representation that, when converted to binary and properly rounded, will give exactly the binary value stored in the computer.

inline bool WantBoundsFirst() const

Write bounds first? The default is yes in AMPL, controlled by (the value of option nl_permute) & 32 (the bit is 0 for yes).

Changing this option is deprecated, see https://netlib.org/ampl/changes.

inline int WantColumnSizes() const

Want Jacobian column sizes? Required by some nonlinear solvers.

Options: 0 - none, 1 - cumulative, 2 - non-cumulative. This option controls how ColSizeWriter writes the provided sizes (which should be non-cumulative).

inline const char *ObjDescription(int i)

Description for objective function i (i in 0..num_objs-1).

With WantNLComments()==true, this is written to text-format NL as a comment.

inline int ObjType(int i)

Provide type of objective i.

0 - minimization; 1 - maximization.

template<class ObjGradWriterFactory>
inline void FeedObjGradient(int i, ObjGradWriterFactory &svwf)

Feed gradient for objective i.

Should include entries for all potentially nonzero elements (sparsity pattern).

Implementation skeleton: if (obj_grad[i].size()) { auto sv = svwf.MakeVectorWriter(obj_grad[i].size()); for (size_t j=0; j<obj_grad.size(); ++j) sv.Write(obj_grad[j].var_index, obj_grad[j].coef); }

template<class ObjExprWriter>
inline void FeedObjExpression(int i, ObjExprWriter &ew)

Feed nonlinear expression of objective i.

Implementation example: ew.EPut(obj_root_expr[i]);

Details of ObjExprWriter: see NLWriter2.

template<class DefVarWriterFactory>
inline void FeedDefinedVariables(int i, DefVarWriterFactory&)

Defined variables.

Classical NL writes first the defined variables which are used in several places (constraints and/or objectives). Defined variables used in a single place (1 constraint, or 1 objective), are written just before the expression tree of their usage.

For most solvers, this requirement can be ignored and this method can return all defined variables in the first group (for i=0).

The method is guaranteed to be called in the following order:

  1. For i=0;

  2. For i>0, increasing, before constraint (i-1)’s expression;

  3. For i<0, decreasing, before objective (-i-1)’s expression.

Implementation skeleton: // dvar_index in num_vars..num_vars+num_defvars-1. for (int dvar_index: dvar_indexes[i]) { auto dv = dvw.StartDefVar(dvar_index, lin_nnz, name_or_comment); /////////// Write the linear part: auto linw = dv.GetLinExprWriter(); for (int i=0; i<lin_nnz; ++i) linw.Write(linexp_var[i], linexp_coef[i]); /////////// Write the expression tree: auto ew = dv.GetExprWriter(); ew.EPut(root_expr); }

Parameters

i

  • For i=0, feed a sequence of defined variables used in several constraints and/or objectives.

  • For i>0, feed the defined variables used solely in constraint i-1.

  • For i<0, feed the defined variables used solely in objective -i-1.

template<class VarBoundsWriter>
inline void FeedVarBounds(VarBoundsWriter &vbw)

Bounds for variables (except defined variables).

Use +-inf for missing lower and/or upper bounds. Note that variable type is given by variable ordering, see NLHeader.

Implementation skeleton: for (int i = 0; i < hdr.num_vars; i++) vbw.WriteLbUb(lb[i], ub[i]);

template<class ConBoundsWriter>
inline void FeedConBounds(ConBoundsWriter &crw)

Bounds/complementarity for all algebraic constraints (num_algebraic_cons).

Implementation skeleton: for (int j=0; j<hdr.num_algebraic_cons; j++) { AlgConRange bnd; if (compl_var && compl_var[j]) { j = compl_var[j]-1; bnd.k = 0; if (vlb[j] > negInfinity) bnd.k = 1; if (vub[j] < Infinity) bnd.k |= 2; assert(bnd.k); bnd.cvar = j; } else { bnd.L = clb[j]; bnd.U = cub[j]; } cbw.WriteAlgConRange(bnd); }

inline const char *ConDescription(int i)

Description of constraint i (i in 0..num_algebraic_cons+num_logical_cons-1).

With WantNLComments()==true, this is written to text-format NL as a comment.

template<class ConLinearExprWriterFactory>
inline void FeedLinearConExpr(int i, ConLinearExprWriterFactory &clewf)

Feed the linear part of algebraic constraint i.

For smooth solvers, should contain entries for all potential nonzeros (Jacobian sparsity pattern).

Implementation skeleton: if (con_grad[i].size()) { auto sv = svw.MakeVectorWriter(con_grad[i].size()); for (size_t j=0; j<con_grad.size(); ++j) sv.Write(con_grad[j].var_index, con_grad[j].coef); }

template<class ConExprWriter>
inline void FeedConExpression(int i, ConExprWriter &ew)

Feed nonlinear expression of constraint i.

Algebraic constraints (num_algebraic_cons) come before logical (num_logical_cons). For linear constraints, the expression should be constant 0.

template<class ExprWriter>
inline void FeedExpr(Expr, ExprWriter&)
template<class PLSOSWriter>
inline void FeedPLSOS(PLSOSWriter&)
inline FuncDef Function(int)
template<class RandVarWriterFactory>
inline void FeedRandomVariables(RandVarWriterFactory&)
template<class ColSizeWriter>
inline void FeedColumnSizes(ColSizeWriter &csw)

Jacobian column sizes.

Should feed LP column sizes for all but the last variable.

Implementation skeleton: if (WantColumnSizes()) for (int i=0; i < num_vars+num_rand_vars-1; ++i) csw.Write(col_size[i]);

template<class IGWriter>
void FeedInitialGuesses(IGWriter&)

Initial primal guesses.

Implementation: if (ini_guess.size()) { auto ig = igw.MakeVectorWriter(ini_guess.size()); for (size_t i=0; i<ini_guess.size(); ++i) ig.Write(i, ini_guess[i]); }

template<class IDGWriter>
void FeedInitialDualGuesses(IDGWriter&)

Initial dual guesses.

template<class SuffixWriterFactory>
void FeedSuffixes(SuffixWriterFactory&)

Feed suffixes.

For constraints, assume ordering: first algebraic, then logical.

Implementation: while (….) { auto sw = swf.StartIntSuffix( // or …DblSuffix suf_name, kind, n_nonzeros); for (int i=0; i<n_nonzeros; ++i) sw.Write(index[i], value[i]); }

template<class RowObjNameWriter>
inline void FeedRowAndObjNames(RowObjNameWriter &wrt)

FeedRowAndObjNames: Provide constraint, then objective names.

Name information is optional.

Implementation: if ((output_desired) && wrt) for (i: ….) wrt << name[i].c_str();

template<class DelRowNameWriter>
inline void FeedDelRowNames(DelRowNameWriter &wrt)

Provide deleted row names.

template<class ColNameWriter>
inline void FeedColNames(ColNameWriter &wrt)

Provide variable names.

template<class UnusedVarNameWriter>
inline void FeedUnusedVarNames(UnusedVarNameWriter &wrt)

Provide unused variable names.

template<class FixedVarNameWriter>
inline void FeedFixedVarNames(FixedVarNameWriter &wrt)

Provide {fixed variable, extra info} pairs.

This includes defined eliminated variables.

Implementation: if ((output_desired) && wrt) for (….) wrt << typename Writer::StrStrValue { name[i].c_str(), comment[i].c_str() };

template<class ObjOffsetWriter>
inline void FeedObjAdj(ObjOffsetWriter &wrt)

Provide {obj name, constant term} pairs.

Implementation: if (wrt) for (….) wrt << typename Writer::StrDblValue { name[i].c_str(), (double)obj_offset[i] };

template<class IGWriter>
void FeedInitialDualGuesses(IGWriter &igw)

Initial dual guesses.

Protected Functions

inline const NLW2_NLFeeder_C &NLF() const

Private Members

const NLW2_NLFeeder_C nlf2_c_

Just store copy.

struct NLW2_NLModel_C
#include <nl-model-c.h>

extern “C” wrapper of mp::NLModel.

Intermediate representation for special model types: (MI)LP, (MI)QP. For full modeling capabilities use NLW2_NLFeeder_C, NLW2_SOLHandler_C.

See also

C API tests/examples.

Note

All model data pointers should stay valid until loading the model into NLW2_NLSolver_C.

Public Members

void *p_data_
struct NLW2_NLOptionsBasic_C

Basic NL options for NLModel.

Prefer to create by NLW2_MakeNLOptionsBasic_Default().

Public Members

int n_text_mode_

NL text mode?

int want_nl_comments_

NL comments in text mode?

int flags_

Flags (1== want output suffixes)

struct NLW2_NLSolution_C
#include <nl-model-c.h>

NL solution.

Public Members

int solve_result_

Solve result.

If >-2, solver interaction successful. Then:

  • -1 unknown - unexpected termination

  • 0- 99 solved - optimal solution found

  • 100-199 solved? - optimal solution indicated, but error likely

  • 200-299 infeasible - constraints cannot be satisfied

  • 300-399 unbounded - objective can be improved without limit

  • 400-499 limit - stopped by a limit that you set (such as on iterations)

  • 500-999 failure - stopped by an error condition in the solver

Note

NLSolution is feasible (not proven optimal) if unbounded or limit and x_ populated.

Note

Individual solvers may have more specific values, see https://ampl.com/products/solvers/solvers-we-sell/.

int nbs_

Number of solve_message’s initial characters already printed on the screen.

const char *solve_message_

Solve message.

double obj_val_

Objective value.

Only returned by NLW2_Solve_C(). Otherwise, after NLW2_ReadSolution…, should be manually computed, e.g., by NLW2_ComputeObjValue_C().

int n_primal_values_

N primal values.

const double *x_

Primals.

int n_dual_values_

N dual values.

const double *y_

Duals.

int nsuf_

Num suffixes.

const NLW2_NLSuffix_C *suffixes_

Suffixes.

struct NLW2_NLSolver_C
#include <nl-solver-c.h>

Manager for solving optimization models via NL files.

It performs zero-overhead model/solution transmission. In particular, it does not store any intermediate model/solution representation.

This wrapper offers both full NL functionality, as well as “easy” but limited interface via NLW2_NLModel_C.

See also

C API tests/examples.

Note

To manipulate, use NLW2_MakeNLSolver_C() / NLW2_DestroyNLSolver_C(), NLW2_LoadNLModel_C(), etc, see the below API.

Public Members

void *p_nlsol_

Internal data.

void *p_utl_
void *p_sol_
struct NLW2_NLSuffix_C
#include <nl-model-c.h>

NL suffix type.

Public Members

const char *name_

Name.

const char *table_

Suffix table.

int kind_

Kind.

VAR = 0, /**< Applies to variables. */ CON = 1, /**< Applies to constraints. */ OBJ = 2, /**< Applies to objectives. */ PROBLEM = 3 /**< Applies to problems. */

If the suffix should be delivered as real-valued, the kind_ should be bitwise-OR’ed with 0x4.

int numval_

Number of values.

Should correspond to the suffix kind.

const double *values_

Values. Always double precision.

struct NLW2_NLUtils_C

Wrap mp::NLUtils for C API.

NL writer and SOL reader utilities. It provides facilities for logging and error handling.

To fill default methods, call NLW2_MakeNLUtils_C_Default() / NLW2_Destroy…().

The default error handler exit()s.

Public Members

void *p_user_data_

Use this pointer if you need to store your data.

It is provided as the 1st argument to the methods.

void (*log_message)(void *p_user_data, const char *format, ...)

log message

void (*log_warning)(void *p_user_data, const char *format, ...)

log warning

void (*myexit)(void *p_user_data, const char *msg)

Override this to your error handler.

Not using exceptions by default. Only called on a wrong output format string (internal error.)

struct NLW2_SolCheckData_C

C “easy API” example using NLW2_NLModel_C to write NL file, execute solver, and read SOL file for a MILP model.

For full API, see documentation of NLW2 and related tests/examples. Solution checking data

Public Members

double *x_ref_
double obj_val_ref_
struct NLW2_SOLHandler_C
#include <sol-handler-c.h>

Wrap mp::SOLHandler for C API.

NLW2_SOLHandler_C: reads solution details on request via provided callback objects. See the examples folder.

To fill some default methods, call NLW2_MakeSOLHandler_C_Default() / NLW2_Destroy…().

Public Members

void *p_user_data_

User data, provided to the methods as the 1st arg.

NLHeader_C (*Header)(void *p_user_data)

The NLHeader used to write the NL file.

void (*OnSolveMessage)(void *p_user_data, const char *s, int nbs)

Receive solve message.

The message always ends with ‘

’.

Parameters

nbs – number of backspaces in the original solve message. So many characters should be skipped from the message if printed straightaway. AMPL solver drivers can supply the message with initial backspaces to indicate that so many characters should be skipped when printing. For example, if the driver prints MINOS 5.51: and exits, and the message starts with that again, this part should be skipped.

int (*OnAMPLOptions)(void *p_user_data, AMPLOptions_C)

Can be ignored by external systems.

Returns

non-zero to stop solution input.

void (*OnDualSolution)(void *p_user_data, int nvals, void *p_api_data)

Dual values for algebraic constraints, if provided in the solution.

Number of values <= NumAlgCons(). Implementation:

duals.reserve(nvals); while (nvals&#8212;) duals.push_back(NLW2_ReadSolVal(p_api_data));

void (*OnPrimalSolution)(void *p_user_data, int nvals, void *p_api_data)

Variable values, if provided.

Number of values <= NumVars().

void (*OnObjno)(void *p_user_data, int)

Receive notification of the objective index used by the driver (solver option ‘objno’-1).

void (*OnSolveCode)(void *p_user_data, int)

Receive notification of the solve code.

void (*OnIntSuffix)(void *p_user_data, NLW2_SuffixInfo_C si, void *p_api_data)

OnIntSuffix().

For constraints, can include values for logical constraints (after algebraic.) Sparse representation - can be empty (i.e., all values zero.)

int kind = si.kind_; int nmax = nitems_max[kind & 3]; // {vars, cons, objs, 1} const char* name = si.name_; const char* table = si.table_; int i; int v; while (NLW2_IntSuffixNNZ(p_api_data)) { NLW2_ReadIntSuffixEntry(p_api_data, &i, &v); if (i<0 || i>=nmax) { NLW2_ReportIntSuffixError( p_api_data, “bad suffix element index”); return; } suf[i] = v; } if (NLW2_IntSuffixReadOK(p_api_data)) // Can check RegisterSuffix(kind, name, table, suf);

void (*OnDblSuffix)(void *p_user_data, NLW2_SuffixInfo_C si, void *p_api_data)

Same as OnIntSuffix(), but use NLW2_ReadDblSuffixEntry() etc.

class mp::NLW2_SOLHandler_C_Impl : public mp::SOLHandler

Wrap NLW2_SOLHandler_C into a C++ class, in order to interface it for mp::SOLReader2.

Public Functions

inline NLW2_SOLHandler_C_Impl(NLW2_SOLHandler_C *psh2)

Construct.

inline NLHeader Header() const

The NLHeader used to write the NL file.

inline void OnSolveMessage(const char *s, int nbs)

Receive solve message.

The message always ends with ‘

’.

Parameters

nbs – number of backspaces in the original solve message. So many characters should be skipped from the message if printed straightaway. AMPL solver drivers can supply the message with initial backspaces to indicate that so many characters should be skipped when printing. For example, if the driver prints MINOS 5.51: and exits, and the message starts with that again, this part should be skipped.

inline int OnAMPLOptions(const AMPLOptions &ao)

Can be ignored by external systems.

Returns

non-zero to stop solution input.

template<class VecReader>
inline void OnDualSolution(VecReader &vr)

Dual values for algebraic constraints, if provided in the solution.

Number of values <= NumAlgCons(). Implementation:

duals.reserve(rd.Size()); while (rd.Size()) duals.push_back(rd.ReadNext());

template<class VecReader>
inline void OnPrimalSolution(VecReader &vr)

Variable values, if provided.

Number of values <= NumVars().

inline void OnObjno(int on)

Receive notification of the objective index used by the driver (solver option ‘objno’).

inline void OnSolveCode(int sc)

Receive notification of the solve code.

template<class SuffixReader>
inline void OnIntSuffix(SuffixReader &sr)

OnIntSuffix().

For constraints, can include values for logical constraints (after algebraic.) Sparse representation - can be empty (i.e., all values zero.)

const auto& si = sr.SufInfo(); int kind = si.Kind(); int nmax = nitems_max[kind & 3]; const std::string& name = si.Name(); const std::string& table = si.Table(); while (sr.Size()) { std::pair<int, int> val = sr.ReadNext(); if (val.first<0 || val.first>=nmax) { sr.SetError(mp::SOL_Read_Bad_Suffix, “bad suffix element index”); return; } suf[val.first] = val.second; } if (mp::SOL_Read_OK == sr.ReadResult()) // Can check RegisterSuffix(kind, name, table, suf);

template<class SuffixReader>
inline void OnDblSuffix(SuffixReader &sr)

Same as OnIntSuffix(), but sr.ReadNext() returns pair<int, double>

Protected Functions

inline const NLW2_SOLHandler_C &SH() const

Private Members

const NLW2_SOLHandler_C solh2_c_

Just store copy.

struct mp::NLW2_Solution_C_Data

Storage for NLSE_Solution_C data.

Public Members

mp::NLSolution sol_
std::vector<NLW2_NLSuffix_C> suffixes_
struct NLW2_SparseMatrix_C

Sparse matrix.

Public Members

int num_colrow_

Size of the start_ array: N cols (for colwise) / N rows (for rowwise), depending on format_.

NLW2_MatrixFormat format_

Format.

Only rowwise supported.

size_t num_nz_

Nonzeros.

const size_t *start_

Row / col starts.

const int *index_

Entry index.

const double *value_

Entry value.

struct NLW2_SparseVector_C

Sparse vector.

Public Members

int num_

Number of entries.

const int *index_

Entry index.

const double *value_

Entry value.

struct NLW2_SuffixInfo_C
#include <sol-handler-c.h>

Suffix information.

Public Members

int kind_

Suffix kind.

const char *name_

Name.

const char *table_

Suffix table, if provided.

struct NLW2_SuffixWriter_C

Public Members

std::function<void*(const char *suf_name, int kind, int nnz)> int_suf_starter_
std::function<void*(const char *suf_name, int kind, int nnz)> dbl_suf_starter_
struct NLWPY_ColData

Variables’ data.

Public Members

std::vector<double> lower_

lower bounds

std::vector<double> upper_

upper bounds

std::vector<int> type_

type: NLW2_VarType…

Set to NULL if all continuous.

class NLWPY_NLModel

NLWPY_NLModel.

Todo:

check array lengths etc.

Note

In contrast to C/C++, NLWPY copies all data so the provided arrays/views can be deleted straightaway.

Public Functions

inline NLWPY_NLModel(std::string nm = {})

Construct.

inline void SetCols(std::vector<double> lb, std::vector<double> ub, std::vector<int> ty)

Add variables (all at once.).

Todo:

ty can be None.

inline void SetColNames(std::vector<std::string> nm)

Add variable names.

inline void SetRows(std::vector<double> rlb, std::vector<double> rub, NLW2_MatrixFormat format, std::vector<size_t> st, std::vector<int> ind, std::vector<double> val)

Add linear constraints (all at once).

Only rowwise matrix supported.

Parameters
  • ind – Entry index

  • val – Entry value

inline void SetRowNames(std::vector<std::string> nm)

Add constraint names.

inline void SetLinearObjective(NLW2_ObjSense sense, double c0, std::vector<double> c)

Add linear objective (only single objective supported.) Sense: NLW2_ObjSenseM….

Coefficients: dense vector.

inline void SetHessian(NLW2_HessianFormat format, std::vector<size_t> st, std::vector<int> ind, std::vector<double> val)

Add Q for the objective quadratic part 0.5 @ x.T @ Q @ x.

Format: NLW2_HessianFormat…

Parameters
  • ind – Entry index

  • val – Entry value

inline void SetObjName(std::string nm)

Set obj name.

inline void SetWarmstart(std::vector<int> i, std::vector<double> v)

Set initial solution.

inline void SetDualWarmstart(std::vector<int> i, std::vector<double> v)

Set dual initial solution.

inline bool AddSuffix(mp::NLSuffix suf)

Add suffix.

Note

SOS constraints can be modeled as suffixes for some AMPL solvers.

Returns

true iff new suffix added (vs replaced.)

inline const mp::NLModel &GetModel() const

Get the model.

Private Members

std::string prob_name_ = {"NLWPY_Model"}

Store the strings/arrays to keep the memory.

mp::NLModel nlme_
int num_col_ = {}
NLWPY_ColData vars_ = {}
std::vector<std::string> var_names_ = {}
std::vector<const char*> var_names_c_ = {}
NLWPY_SparseMatrix A_ = {}
int num_row_ = {}
std::vector<double> row_lb_ = {}
std::vector<double> row_ub_ = {}
std::vector<std::string> row_names_ = {}
std::vector<const char*> row_names_c_ = {}
int obj_sense_ = {}
double obj_c0_ = {}
std::vector<double> obj_c_ = {}
NLW2_HessianFormat Q_format_ = {}
NLWPY_SparseMatrix Q_ = {}
std::string obj_name_ = {"obj[1]"}
std::vector<int> ini_x_i_
std::vector<double> ini_x_v_
std::vector<int> ini_y_i_
std::vector<double> ini_y_v_
struct NLWPY_SparseMatrix

Sparse matrix.

Size of the start_ array: N cols (for colwise) / N rows (for rowwise), depending on format_.

Public Members

NLW2_MatrixFormat format_

Format (NLW2_MatrixFormat…).

Only rowwise supported.

std::vector<size_t> start_

Row / col starts.

std::vector<int> index_

Entry index.

std::vector<double> value_

Entry value.

template<typename Params>
class mp::NLWriter2 : public Params::FormatterType
#include <nl-writer2.h>

NLWriter2.

mp::NLWriter2 is a zero-overhead NL model writer implemented with inline template code. In particular, it does not store any intermediate model representation.

Usage: recommended via mp::NLSOL class. If you need the NL writing part only, proceed as follows:

Write an NL file: WriteNLFile(filenamebase, feeder, utils);

where feeder is an object that provides information on model components. See NLFeeder for an interface of a feeder class.

See also NLReader and NLHandler classes.

Parameters

Params – a specialization of class NLWriter2Params<>.

Public Types

using FormatterType = typename Params::FormatterType
using FeederType = typename Params::FeederType

Public Functions

inline NLWriter2(FeederType &f, NLHeader h, NLUtils &utl)

Constructor.

WriteNLResult WriteFiles(const std::string &namebase)

Write to files with the given namebase.

Parameters

namebase – will be used for filenames namebase.nl, namebase.row, etc.

Returns

Write status.

inline WriteNLResult GetResult() const

Retrieve WriteNLResultCode and error message.

Protected Types

using SparseDblVecWriter = SparseVectorWriter<int, double>

Typedef SparseDblVecWriter.

using SparseIntVecWriter = SparseVectorWriter<int, int>

Typedef SparseIntVecWriter.

using SingleSparseDblVecWrtFactory = SingleSparseVecWrtFactory<int, double>

Typedef SingleSparseDblVecWrtFactory.

using SingleSparseIntVecWrtFactory = SingleSparseVecWrtFactory<int, int>

Typedef SingleSparseIntVecWrtFactory.

using SuffixIntWriter = SparseVectorWriter<int, int>
using SuffixDblWriter = SparseVectorWriter<int, double>

Protected Functions

void WriteAuxFiles(const std::string &namebase)

Write auxiliary files .row, .slc, .col, etc, if data provided by the corresp.

feeders (otherwise, any existing files are deleted).

void WriteNL(const std::string &namebase)

Write NL file, if any variables.

void WriteRowObjNames(const std::string &namebase)
void WriteRowDelNames(const std::string &namebase)
void WriteColNames(const std::string &namebase)
void WriteUnusedVarNames(const std::string &namebase)
void WriteFixedVars(const std::string &namebase)
void WriteObjAdj(const std::string &namebase)
void WriteNLHeader()
void WriteFunctions()
void WriteSuffixes()
void WritePLSOSConstraints()
void WriteVarBounds()
void WriteInitialGuesses()
void WriteConBounds()
void WriteDualInitialGuesses()
void WriteDefinedVariables(int i)

i=0: used in several places, i>0 increasing: used in 1 con, i<0 decreasing: used in 1 obj

void WriteConObjExpressions()
void WriteColumnSizes()
void WriteLinearConExpr()
void WriteObjGradients()
void WriteRandomVariables()
int WriteStringVec2File(const std::string &name, std::function<void(StringFileWriter&)>)

Write string vector calling the given feeder.

Returns

max string length.

template<class SparseVecFeeder>
void WriteSuffix(File &nm, int kind, const char *name, SparseVecFeeder &&sv)

Writes nothing if !sz.

void WriteSparseEntry(File &nm, int i, int v)
void WriteSparseEntry(File &nm, int i, double x)
void WriteBndRangeOrCompl(File &nm, double L, double U, int k = 0, int cvar = 0)
template<class ExprArgsFeeder>
void WriteExprArgs(File &nm, ExprArgsFeeder &&args)
inline FormatterType &Formatter()

Retrieve Writer.

inline FeederType &Feeder() const

Retrieve feeder.

inline const NLHeader &Hdr() const

Retrieve header.

double Infty() const

Infinity.

double NegInfty() const

Negative infinity.

Private Members

FeederType &feeder_
NLHeader header_
int num_vars_and_exprs_
int maxLen_ColName_ = {0}
int maxLen_UnvName_ = {0}
int maxLen_FixName_ = {0}
File nm
WriteNLResult result_ = {NLW2_WriteNL_Unset, ""}
template<class Formatter, class Feeder>
struct mp::NLWriter2Params
#include <nl-writer2-misc.h>

NLWriter2 parameters.

Parameters
  • Formatter – low-level writer: binary or text.

  • Feeder – a class implementing the NLFeeder concept that feeds model information on request.

  • Utils – writer utilities

Public Types

using FormatterType = Formatter
using FeederType = Feeder
class mp::pre::NodeRange
#include <valcvt-node.h>

Node range: range of node entries in a specific value node.

The node is specified as well

Public Functions

inline NodeRange(ValueNode *pvn = nullptr, NodeIndexRange ir = {})

Constructor.

inline bool IsValid() const

Valid?

inline void Invalidate()

invalidate

inline ValueNode *GetValueNode() const

Get pvn.

inline NodeIndexRange GetIndexRange() const

Get index range.

inline bool operator==(const NodeRange &nr) const

operator==

inline bool operator!=(const NodeRange &nr) const

operator!=

inline bool IsSingleIndex() const

check if the range represents just 1 index

inline int GetSingleIndex() const

Get the single index if range is just that.

inline explicit operator int() const

Get single index if it is.

inline bool ExtendableBy(NodeRange nr) const

Check extendability by given range.

inline bool TryExtendBy(NodeRange nr)

Try & extend the range by another one.

inline void ExtendBy(NodeRange nr)

Extend the range by another one.

Protected Functions

inline void Assign(ValueNode *pvn, NodeIndexRange ir)

Assign members, only accessible to ValueNode.

Private Members

ValueNode *pvn_ = nullptr
NodeIndexRange ir_

Friends

friend class ValueNode
template<class ModelConverter>
class mp::NotConverter_MIP : public mp::BasicFuncConstrCvt<NotConverter_MIP<ModelConverter>, ModelConverter>
#include <logical_not.h>

Converts NOT for MIP.

Public Types

using Base = BasicFuncConstrCvt<NotConverter_MIP<ModelConverter>, ModelConverter>

Base class.

using ItemType = NotConstraint

Converted item type.

Public Functions

inline NotConverter_MIP(ModelConverter &mc)

Constructor.

inline void Convert(const ItemType &nc, int)

Convert in both contexts (full reification)

inline void Convert(const ItemType &item, int i)

Generic Convert(), distinguishes context & result variable.

Distinguish positive and negative context because if only one of these is necessary, significant model reduction can be achieved in certain cases.

Responsible for adding presolve links, if any

The Impl can reimplement this

Parameters
  • item – the item to be converted

  • i – item index, used to create a presolve link

inline void ConvertCtxNeg(const ItemType &item, int)

Convert in negative context.

inline void ConvertCtxPos(const ItemType &item, int)

Convert in positive context.

inline const ModelConverter &GetMC() const

Reuse the stored ModelConverter.

inline ModelConverter &GetMC()

Reuse the stored ModelConverter.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

struct mp::internal::NullLinearExprHandler
#include <nl-reader.h>

Linear expression handler that ignores input.

Public Functions

inline void AddTerm(int, double)
template<typename ExprType>
class mp::NullNLHandler : public mp::NLHandler<NullNLHandler<ExprType>, ExprType>
#include <nl-reader.h>

An NL handler that ignores all input.

NullNLHandler can be used as a base class when only a subset of constructs needs to be handled. Unhandled constructs will be ignored, not reported.

ExprType is a return type of expression handler methods such as OnUnary useful for building expression objects. If not used it can be any default-constructible type.

Public Types

typedef ExprType Expr

An expression type.

typedef Expr NumericExpr

A numeric expression type. It is a typedef of Expr but subclasses may define it as a different type convertible to Expr.

typedef Expr LogicalExpr

A logical expression type. It is a typedef of Expr but subclasses may define it as a different type convertible to Expr.

typedef Expr CountExpr

A count expression type. It is a typedef of Expr but subclasses may define it as a different type convertible to NumericExpr.

typedef Expr Reference

A reference expression type. It is a typedef of Expr but subclasses may define it as a different type convertible to NumericExpr.

typedef LinearExprHandler LinearObjHandler

A typedef of a class that receives notifications of terms in the linear part of an objective expression.

typedef LinearExprHandler LinearConHandler

A typedef of a class that receives notifications of terms in the linear part of a constraint expression.

typedef ArgHandler NumericArgHandler

A typedef of a class that receives notifications of numeric arguments.

typedef ArgHandler VarArgHandler

A typedef of a class that receives notifications of vararg expression arguments.

typedef ArgHandler CallArgHandler

A typedef of a class that receives notifications of call expression arguments.

typedef ArgHandler NumberOfArgHandler

A typedef of a class that receives notifications of numberof expression arguments.

typedef ArgHandler CountArgHandler

A typedef of a class that receives notifications of count expression arguments.

typedef ArgHandler LogicalArgHandler

A typedef of a class that receives notifications of logical arguments.

typedef ArgHandler PairwiseArgHandler

A typedef of a class that receives notifications of pairwise expression arguments.

typedef ArgHandler SymbolicArgHandler

A typedef of a class that receives notifications of symbolic (numeric or string) arguments.

Public Functions

inline void OnUnhandled(const char*)

Receives notification of an unhandled construct and ignores it.

inline void OnHeader(const NLHeader &h)

Receives notification of an NL header.

inline bool NeedObj(int obj_index) const

Returns true if the objective with index obj_index should be handled.

inline int resulting_obj_index(int obj_index) const

Returns final objective index (e.g., returns 0 if objno>0 and multiobj=0)

inline void OnObj(int index, obj::Type type, NumericExpr expr)

Receives notification of an objective type and the nonlinear part of an objective expression.

inline void OnAlgebraicCon(int index, NumericExpr expr)

Receives notification of the nonlinear part of an algebraic constraint expression.

inline void OnLogicalCon(int index, LogicalExpr expr)

Receives notification of a logical constraint expression.

inline LinearExprHandler BeginCommonExpr(int index, int num_linear_terms)

Receives notification of the beginning of a common expression (defined variable).

inline void EndCommonExpr(int index, NumericExpr expr, int position)

Receives notification of the end of a common expression.

inline void OnComplementarity(int con_index, int var_index, ComplInfo info)

Receives notification of a complementarity relation var_lb <= x <= var_ub complements con_lb <= body <= con_ub, where x is the variable at index var_index and body is the constraint body. info gives the constraint bounds.

inline LinearObjHandler OnLinearObjExpr(int obj_index, int num_linear_terms)

Receives notification of the linear part of an objective expression.

inline LinearConHandler OnLinearConExpr(int con_index, int num_linear_terms)

Receives notification of the linear part of a constraint expression.

inline LinearExprHandler OnLinearCommonExpr(int expr_index, int num_linear_terms)

Receives notification of the linear part of a common expression.

inline void OnVarBounds(int index, double lb, double ub)

Receives notification of variable bounds.

inline void OnConBounds(int index, double lb, double ub)

Receives notification of constraint bounds (ranges).

inline void OnInitialValue(int var_index, double value)

Receives notification of the initial value for a variable.

inline void OnInitialDualValue(int con_index, double value)

Receives notification of the initial value for a dual variable.

inline ColumnSizeHandler OnColumnSizes()

Receives notification of Jacobian column sizes.

inline void OnFunction(int index, fmt::StringRef name, int num_args, func::Type type)

Receives notification of a function. The name argument is a function name and it is not null-terminated.

inline IntSuffixHandler OnIntSuffix(fmt::StringRef name, suf::Kind kind, int num_values)

Receives notification of an integer suffix. The name argument is a suffix name and it is not null-terminated. kind specifies the suffix kind.

inline DblSuffixHandler OnDblSuffix(fmt::StringRef name, suf::Kind kind, int num_values)

Receives notification of a double suffix. The name argument is a suffix name and it is not null-terminated. kind specifies the suffix kind.

inline NumericExpr OnNumber(double value)

Receives notification of a number in a nonlinear expression.

inline Reference OnVariableRef(int var_index)

Receives notification of a variable reference.

inline Reference OnCommonExprRef(int expr_index)

Receives notification of a common expression (defined variable) reference.

inline NumericExpr OnUnary(expr::Kind kind, NumericExpr arg)

Receives notification of a unary expression.

inline NumericExpr OnBinary(expr::Kind kind, NumericExpr lhs, NumericExpr rhs)

Receives notification of a binary expression.

inline NumericExpr OnIf(LogicalExpr condition, NumericExpr then_expr, NumericExpr else_expr)

Receives notification of an if expression.

inline PLTermHandler BeginPLTerm(int num_breakpoints)

Receives notification of the beginning of a piecewise-linear term.

inline NumericExpr EndPLTerm(PLTermHandler handler, Reference arg)

Receives notification of the end of a piecewise-linear term.

arg: argument that is a variable or a common expression reference.

inline CallArgHandler BeginCall(int func_index, int num_args)

Receives notification of the beginning of a call expression.

inline NumericExpr EndCall(CallArgHandler handler)

Receives notification of the end of a call expression.

inline VarArgHandler BeginVarArg(expr::Kind kind, int num_args)

Receives notification of the beginning of a vararg expression.

inline NumericExpr EndVarArg(VarArgHandler handler)

Receives notification of the end of a vararg expression.

inline NumericArgHandler BeginSum(int num_args)

Receives notification of the beginning of a summation.

inline NumericExpr EndSum(NumericArgHandler handler)

Receives notification of the end of a summation.

inline CountArgHandler BeginCount(int num_args)

Receives notification of the beginning of a count expression.

inline CountExpr EndCount(CountArgHandler handler)

Receives notification of the end of a count expression.

inline NumberOfArgHandler BeginNumberOf(int num_args, NumericExpr arg0)

Receives notification of the beginning of a numberof expression.

inline NumericExpr EndNumberOf(NumberOfArgHandler handler)

Receives notification of the end of a numberof expression.

inline SymbolicArgHandler BeginSymbolicNumberOf(int num_args, Expr arg0)

Receives notification of the beginning of a symbolic numberof expression.

inline NumericExpr EndSymbolicNumberOf(SymbolicArgHandler handler)

Receives notification of the end of a symbolic numberof expression.

inline LogicalExpr OnBool(bool value)

Receives notification of a Boolean value.

inline LogicalExpr OnNot(LogicalExpr arg)

Receives notification of a logical not.

inline LogicalExpr OnBinaryLogical(expr::Kind kind, LogicalExpr lhs, LogicalExpr rhs)

Receives notification of a binary logical expression.

inline LogicalExpr OnRelational(expr::Kind kind, NumericExpr lhs, NumericExpr rhs)

Receives notification of a relational expression.

inline LogicalExpr OnLogicalCount(expr::Kind kind, NumericExpr lhs, CountExpr rhs)

Receives notification of a logical count expression.

inline LogicalExpr OnImplication(LogicalExpr condition, LogicalExpr then_expr, LogicalExpr else_expr)

Receives notification of an implication expression.

inline LogicalArgHandler BeginIteratedLogical(expr::Kind kind, int num_args)

Receives notification of the beginning of an iterated logical expression.

inline LogicalExpr EndIteratedLogical(LogicalArgHandler handler)

Receives notification of the end of an iterated logical expression.

inline PairwiseArgHandler BeginPairwise(expr::Kind kind, int num_args)

Receives notification of the beginning of a pairwise expression.

inline LogicalExpr EndPairwise(PairwiseArgHandler handler)

Receives notification of the end of a pairwise expression.

inline Expr OnString(fmt::StringRef value)

Receives notification of a string. The value argument is a string value and it is not null-terminated.

inline Expr OnSymbolicIf(LogicalExpr condition, Expr then_expr, Expr else_expr)

Receives notification of a symbolic if expression.

inline void EndInput()

Receives notification of the end of the input.

template<class ModelConverter>
class mp::NumberofConstConverter_MIP : public mp::BasicFuncConstrCvt<NumberofConstConverter_MIP<ModelConverter>, ModelConverter>
#include <numberof_const.h>

Converts NOC for MIP.

Public Types

using Base = BasicFuncConstrCvt<NumberofConstConverter_MIP<ModelConverter>, ModelConverter>

Base class.

using ItemType = NumberofConstConstraint

Converted item type.

Public Functions

inline NumberofConstConverter_MIP(ModelConverter &mc)

Constructor.

inline void Convert(const ItemType &nocc, int)

Convert in any context.

inline void Convert(const ItemType &item, int i)

Generic Convert(), distinguishes context & result variable.

Distinguish positive and negative context because if only one of these is necessary, significant model reduction can be achieved in certain cases.

Responsible for adding presolve links, if any

The Impl can reimplement this

Parameters
  • item – the item to be converted

  • i – item index, used to create a presolve link

inline void ConvertCtxNeg(const ItemType &item, int)

Convert in negative context.

inline void ConvertCtxPos(const ItemType &item, int)

Convert in positive context.

inline const ModelConverter &GetMC() const

Reuse the stored ModelConverter.

inline ModelConverter &GetMC()

Reuse the stored ModelConverter.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

template<class ModelConverter>
class mp::NumberofVarConverter_MIP : public mp::BasicFuncConstrCvt<NumberofVarConverter_MIP<ModelConverter>, ModelConverter>
#include <numberof_var.h>

Converts NOV for MIP.

Public Types

using Base = BasicFuncConstrCvt<NumberofVarConverter_MIP<ModelConverter>, ModelConverter>

Base class.

using ItemType = NumberofVarConstraint

Converted item type.

Public Functions

inline NumberofVarConverter_MIP(ModelConverter &mc)

Constructor.

inline void Convert(const ItemType &novc, int)

Convert in any context.

Very basic, could be improved

inline void Convert(const ItemType &item, int i)

Generic Convert(), distinguishes context & result variable.

Distinguish positive and negative context because if only one of these is necessary, significant model reduction can be achieved in certain cases.

Responsible for adding presolve links, if any

The Impl can reimplement this

Parameters
  • item – the item to be converted

  • i – item index, used to create a presolve link

inline void ConvertCtxNeg(const ItemType &item, int)

Convert in negative context.

inline void ConvertCtxPos(const ItemType &item, int)

Convert in positive context.

inline const ModelConverter &GetMC() const

Reuse the stored ModelConverter.

inline ModelConverter &GetMC()

Reuse the stored ModelConverter.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

class mp::NumericConstant : public mp::BasicExpr<expr::NUMBER>
#include <expr.h>

A numeric constant.

Examples: 42, -1.23e-4

Public Types

enum [anonymous]

Values:

Public Functions

inline double value() const

Returns the value of this constant.

Protected Types

typedef ExprBase::Impl Impl

Reuse ExprBase::Impl.

typedef BasicExpr Base

Base = BasicExpr.

Private Functions

MP_EXPR(Base)
struct mp::internal::NLReader::NumericExprReader

Helper structs to provide a uniform interface to Read{Numeric,Logical}Expr since it is not possible to overload on expression type as NumericExpr and LogicalExpr can be the same type.

Public Types

typedef NumericExpr Expr

Public Functions

inline Expr Read(NLReader &r) const
class mp::NumericFunctionalConstraintTraits
#include <constr_base.h>

A base class for numerical functional constraint.

It provides default properties of such a constraint

Subclassed by mp::LinearFunctionalConstraint, mp::QuadraticFunctionalConstraint

Public Static Functions

static inline constexpr bool IsLogical()

Whether the constraint is logical.

static inline std::pair<double, double> GetAprioriBounds()

Apriori bounds on the result.

class mp::EasyModeler::NumExpr
#include <easy-modeler.h>

Wrap mp::NumericExpr to also keep the Builder.

Public Functions

inline NumExpr(Builder &bld, MP_NumExpr expr)
inline MP_NumExpr GetImpl()

The underlying mp::NumericExpr object.

inline Builder &GetBuilder()

The underlying builder.

Private Members

Builder &bld_

Operator definitions.

MP_NumExpr expr_
struct mp::internal::NLReader::ObjHandler : public mp::internal::NLReader<OBJ>::ItemHandler

Public Functions

inline explicit ObjHandler(NLReader &r)
inline int num_items() const
inline bool SkipExpr(int obj_index) const

Returns true if objective expression should be skipped.

inline Handler::LinearObjHandler OnLinearExpr(int index, int num_terms)

Public Static Attributes

static const ItemType TYPE = T

Protected Attributes

NLReader &reader_
class mp::pre::One2ManyLink : public mp::pre::Many2ManyLink
#include <valcvt-link.h>

A specialization of Many2ManyLink: each entry just copies from 1 source value into a range of values.

Useful to transfer values into expression subtree, in conversions, e.g., from 1 var / constraint / objective into several new ones

Public Types

using LinkEntry = std::pair<NodeRange, NodeRange>

Single link entry, stores src + dest ranges.

using CollectionOfEntries = std::deque<LinkEntry>

Collection of entries.

using ItemRangeList = std::vector<NodeRange>

Typedef item container.

Public Functions

inline One2ManyLink(ValuePresolver &pre)

Constructor.

inline virtual const char *GetTypeName() const override

Type name.

inline void AddEntry(LinkEntry be)

Add entry.

inline virtual void ExportEntryItems(EntryItems &ei, int i) const override

Get source/target nodes for a given link entry.

This is used for graph export

Protected Functions

template<class T>
inline void Distr(NodeRange nr1, NodeRange nr2)

Distribute values of type T from nr1 to nr2.

template<class T>
inline void Collect(NodeRange nr1, NodeRange nr2)

Collect values of type T from nr2 to nr1.

template<class T>
inline void DistributeFromSrc2Dest(LinkIndexRange ir)

Src -> dest for the entries index range ir.

template<class T>
inline void CollectFromDest2Src(LinkIndexRange ir)

Collect src <- dest for index range ir. Loop backwards.

inline void RegisterLinkIndex(int i)

Add a range of link entries to the Presolver’s list.

Every derived link should call either of the next two methods whenever adding a link entry. Version 1: add single link

inline void RegisterLinkIndexRange(LinkIndexRange)

Version 2: add a range of links.

Implement link range registration in global Presolver.

struct mp::nl::Opcode
#include <nl-opcodes.h>

Struct Opcode.

Public Members

int code
const char *name
class mp::internal::OpCodeInfo
#include <common.h>

Public Members

expr::Kind kind
expr::Kind first_kind

Private Static Attributes

static const OpCodeInfo INFO[MAX_OPCODE + 1]

Friends

friend const OpCodeInfo &GetOpCodeInfo(int opcode)
struct mp::Option
#include <option.h>

Command-line option.

Public Members

char name
const char *description
void *handler
bool (*on_option)(void*)
bool (*on_optionWithParam)(void*, const char*)
bool hasParam
template<class baseiterator>
class mp::SolverOptionManager::option_iterator_base
#include <solver-opt.h>

Base option iterator, to specialized for const/non-const.

Public Functions

inline option_iterator_base()
inline SolverOption &operator*() const
inline SolverOption *operator->() const
inline option_iterator_base &operator++()
inline option_iterator_base operator++(int)
inline bool operator==(option_iterator_base other) const
inline bool operator!=(option_iterator_base other) const

Private Types

using iterator_category = std::forward_iterator_tag
using difference_type = std::ptrdiff_t
using value_type = SolverOption
using pointer = value_type*
using reference = value_type&

Private Functions

inline explicit option_iterator_base(baseiterator it)

Private Members

baseiterator it_

Friends

friend class SolverOptionManager
class mp::OptionError : public mp::Error
#include <error.h>

An option error.

Subclassed by mp::InvalidOptionValue

Public Functions

inline explicit OptionError(fmt::CStringRef message)
inline int exit_code() const

The exit code.

Protected Functions

inline void SetMessage(const std::string &message)
inline void init(fmt::CStringRef format_str, fmt::ArgList args)
template<typename T>
struct OptionHelper

A helper class for implementing an option of type T.

template<>
struct mp::internal::OptionHelper<double>
#include <solver-opt.h>

Public Types

typedef double Arg

Public Static Functions

static inline void Write(fmt::Writer &w, double value)
static double Parse(const char *&s, bool splitString = false)
static inline double CastArg(double value)
template<>
struct mp::internal::OptionHelper<int>
#include <solver-opt.h>

Public Types

typedef int Arg

Public Static Functions

static inline void Write(fmt::Writer &w, Arg value)
static int Parse(const char *&s, bool splitString = false)
static inline int CastArg(fmt::LongLong value)
template<>
struct mp::internal::OptionHelper<std::string>
#include <solver-opt.h>

Public Types

typedef fmt::StringRef Arg

Public Static Functions

static inline void Write(fmt::Writer &w, const std::string &s)
static std::string Parse(const char *&s, bool splitString = false)
static inline fmt::StringRef CastArg(fmt::StringRef s)
class mp::OptionList
#include <option.h>

A list of command-line options.

Public Types

typedef OptionContainer::const_iterator iterator

Public Functions

inline OptionList()
inline iterator begin() const
inline iterator end() const
inline bool sorted() const
void Sort()

Sorts the option list.

const Option *Find(char name) const

Finds an option with the specified name in the list.

Requires list to be sorted.

Private Types

typedef std::vector<Option> OptionContainer

Private Functions

template<typename Handler, bool (Handler::* on_option)()>
inline void Add(char name, const char *description, Handler &h)
template<typename Handler, bool (Handler::* on_optionWithParam)(const char*)>
inline void AddWithParam(char name, const char *description, Handler &h)

Private Members

OptionContainer options_
bool sorted_

Private Static Functions

template<typename Handler, bool (Handler::* on_option)()>
static inline bool OnOption(void *handler)
template<typename Handler, bool (Handler::* on_optionWithParam)(const char *param)>
static inline bool OnOptionParam(void *handler, const char *param)
struct mp::SolverOptionManager::OptionNameLess

Public Functions

bool operator()(const SolverOption *lhs, const SolverOption *rhs) const

Options in the set are ordered lexicographically by name()

struct mp::FlatConverter::Options

Public Members

std::string file_graph_export_
int preprocessAnything_ = 1
int preprocessEqualityResultBounds_ = 1
int preprocessEqualityBvar_ = 1
int preproNestedAndOrs_ = 1
int passQuadObj_ = ModelAPIAcceptsQuadObj()
int passQuadCon_ = 1
int passSOCPCones_ = 0
int passSOCP2QC_ = 0
int passExpCones_ = 0
int accExpr_ = static_cast<std::underlying_type_t<ExpressionAcceptanceLevel>>(ModelAPI::ExpressionInterfaceAcceptanceLevel()) - 1
int relax_ = 0
int solcheckmode_ = 1 + 2 + 512
bool solcheckinfeas_ = false
bool solcheckfail_ = false
double solfeastol_ = 1e-6
double solfeastolrel_ = 1e-6
double solinttol_ = 1e-5
int sol_round_ = 100
int sol_prec_ = 100
int solchkoutlev_ = 0
struct mp::MIPBackend::Options

Public Members

int lazy_user_cuts_ = 3
int basis_ = 3
int warmstart_ = 1
int importPriorities_ = 1
int rays_ = 3
int exportIIS_ = 0
int returnMipGap_ = 0
int returnBestDualBound_ = 0
int solnSens_ = 0
int fixModel_ = 0
struct mp::MIPFlatConverter::Options

Public Members

double cmpEps_ = {1e-4}
double bigM_default_ = {-1}
double PLApproxRelTol_ = {1e-2}
double PLApproxDomain_ = {1e6}
double NoUEncPosCtxRatio_ = {0.0}
int NoUEncNegCtxMax_ = {1}
struct mp::ModelManagerWithProblemBuilder::Options

Public Members

int nNames_ = 1
struct mp::ProblemFlattener::Options

OPTIONS /////////////////////////.

Public Members

int sos_ = 1
int sos2_ = 1
struct mp::StdBackend::Options

Public Members

int exportKappa_ = 0
double lbpen_ = 1.0

feasrelax penalty options

double ubpen_ = 1.0
double rhspen_ = 1.0
int round_ = 0
double round_reptol_ = 1e-9
std::vector<std::string> export_files_

For write prob.

std::vector<std::string> just_export_files_
std::vector<std::string> export_sol_files_

For write sol.

struct mp::OptionValueInfo
#include <solver-opt.h>

Information about a possible option value.

Public Members

const char *value
const char *description
intptr_t data
template<class ModelConverter>
class mp::OrConverter_MIP : public mp::BasicFuncConstrCvt<OrConverter_MIP<ModelConverter>, ModelConverter>
#include <logical_or.h>

Converts Or/Exists for MIP.

Public Types

using Base = BasicFuncConstrCvt<OrConverter_MIP<ModelConverter>, ModelConverter>

Base class.

using ItemType = OrConstraint

Converted item type.

Public Functions

inline OrConverter_MIP(ModelConverter &mc)

Constructor.

inline void ConvertCtxPos(const ItemType &disj, int)

Convert in positive context.

inline void ConvertCtxNeg(const ItemType &disj, int)

Convert in negative context.

inline void Convert(const ItemType &item, int i)

Generic Convert(), distinguishes context & result variable.

Distinguish positive and negative context because if only one of these is necessary, significant model reduction can be achieved in certain cases.

Responsible for adding presolve links, if any

The Impl can reimplement this

Parameters
  • item – the item to be converted

  • i – item index, used to create a presolve link

inline void ConvertCtxNeg(const ItemType &item, int)

Convert in negative context.

inline void ConvertCtxPos(const ItemType &item, int)

Convert in positive context.

inline const ModelConverter &GetMC() const

Reuse the stored ModelConverter.

inline ModelConverter &GetMC()

Reuse the stored ModelConverter.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

class mp::OutputHandler
#include <solver-base.h>

A default interface for receiving solver output.

Subclassed by mp::BasicSolver

Public Functions

inline virtual ~OutputHandler()
inline virtual void HandleOutput(fmt::CStringRef output)

Public Members

bool has_output = false
size_t banner_size = 0
class mp::OverflowError : public std::exception
#include <safeint.h>

Public Functions

inline const char *what() const
class rst::Parser
#include <rstparser.h>

Public Functions

inline explicit Parser(ContentHandler *h)
void Parse(const char *s)

Private Functions

void SkipSpace()
std::string ParseDirectiveType()
void ParseParagraph()
void EnterBlock(rst::BlockType &prev_type, rst::BlockType type)
void ParseBlock(rst::BlockType type, rst::BlockType &prev_type, int indent)
void ParseLineBlock(rst::BlockType &prev_type, int indent)

Private Members

ContentHandler *handler_
const char *ptr_
class mp::path
#include <os.h>

Public Functions

inline path()
inline explicit path(const std::string &s)
inline path(const char *begin, const char *end)
inline const std::string &string() const
inline path filename() const
inline path &remove_filename()

Public Static Functions

static path temp_directory_path()

Public Static Attributes

static const char preferred_separator = '/'

Private Functions

inline std::size_t FindLastSep() const

Private Members

std::string str_
struct mp::PLApproxParams
#include <lin_approx_core.h>

Input and output for piecewise-linear approximation.

Public Members

FuncGraphDomain grDom

INPUT DATA ////////////// Graph domain for approximation.

bool is_x_int = {false}

Argument’s integrality.

double ubErr = 1e-5

Error upper bound (relative outside of +-1, absolute inside)

FuncGraphDomain grDomOut
PLPoints plPoints
bool fUsePeriod = {false}
double periodLength
Range periodicFactorRange
Range periodRemainderRange
class mp::PLConParams

Parameters of a PL constraint: keeps any or both of PLSlopes and PLPoints.

Public Functions

inline PLConParams(PLSlopes pls)

Construct from PLSlopes.

inline PLConParams(PLPoints plp)

Construct from PLPoints.

inline const PLPoints &GetPLPoints() const

Produce PLPoints, either stored or from PLSlopes.

Private Members

PLSlopes pls_
mutable PLPoints plp_
template<class ModelConverter>
class mp::PLConverter_MIP : public mp::BasicFuncConstrCvt<PLConverter_MIP<ModelConverter>, ModelConverter>
#include <piecewise_linear.h>

Convert PLConstraint into SOS2 + linear constraints.

Public Types

using Base = BasicFuncConstrCvt<PLConverter_MIP<ModelConverter>, ModelConverter>

Base class.

using ItemType = PLConstraint

Converted item type.

Public Functions

inline PLConverter_MIP(ModelConverter &mc)

Constructor.

inline void Convert(const ItemType &cc, int)

Convert in any context.

inline void Convert(const ItemType &item, int i)

Generic Convert(), distinguishes context & result variable.

Distinguish positive and negative context because if only one of these is necessary, significant model reduction can be achieved in certain cases.

Responsible for adding presolve links, if any

The Impl can reimplement this

Parameters
  • item – the item to be converted

  • i – item index, used to create a presolve link

inline void ConvertCtxNeg(const ItemType &item, int)

Convert in negative context.

inline void ConvertCtxPos(const ItemType &item, int)

Convert in positive context.

inline const ModelConverter &GetMC() const

Reuse the stored ModelConverter.

inline ModelConverter &GetMC()

Reuse the stored ModelConverter.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

Protected Functions

inline void ConsiderExtendingEndSegments()

See if we need to extend the end segments to cover larger domain.

inline void ConsiderShorteningPL()

See if we need to remove/shorten side segments.

inline bool ConsiderDegenerateCases()

See if we obtain a single point or segment.

Returns

true iff that (a corresponding simpler constraint is added)

inline bool ConsiderConvexity()

See if have a convex case.

inline void RedefineInSOS2()

Non-convex redefinition into SOS2 + linear.

inline double PLMaxVal() const

PLMaxVal, currently constant.

Default max abs value of the argument and of the result of a PL. Applied when the PL is defined on a smaller domain but the argument allows more.

inline void ExtendSegTo(size_t i0, size_t i1, double x0)

Extend segment (i0, i1) (if i0<i1, then to the left, otherwise to the right) in PLPoints to start/end in new x0.

Private Members

PLPoints points_
size_t i0 = {0}
size_t i1 = {0}
int x = {-1}
int y = {-1}
struct mp::PLPoints

Representing a PWL by points.

Public Functions

inline bool empty() const

Check if have information.

inline int size() const

size()

inline PLPoints()

Default construct.

inline PLPoints(std::vector<double> x, std::vector<double> y)

Construct from 2 vectors.

PLPoints(const PLSlopes &pls)

Construct from PLSlopes.

inline void AddPoint(double x, double y)

Add point.

inline void clear()

Clear out.

inline double PreSlope() const

Get preslope.

inline double PostSlope() const

Get postslope.

Public Members

std::vector<double> x_

The x, y coordinates of the PL function.

std::vector<double> y_
class mp::PLSlopes

AMPL represents PWL by a list of slopes and breakpoints between them, assuming (X0,Y0) is on the line.

Public Functions

inline PLSlopes()

Default constructor.

template<class Vec>
inline PLSlopes(Vec &&bp, Vec &&sl, double x, double y) noexcept

Construct from breakpoints, slopes, and a sample point.

inline const std::vector<double> &GetBP() const

Get breakpoints.

inline const std::vector<double> &GetSlopes() const

Get slopes.

inline double GetX0() const

Get sample point’s X.

inline double GetY0() const

Get sample poont’s Y.

inline int GetNBP() const

Get number of bp.

inline int GetNSlopes() const

Get number slopes.

inline bool check() const

Validate.

Private Members

std::vector<double> breakpoints_
std::vector<double> slopes_
double X0_
double Y0_
class mp::NLWriter2::PLSOSWriter
#include <nl-writer2.h>

PL-SOS constraints.

Public Functions

inline PLSOSWriter(NLWriter2 &nlw)

Construct.

SuffixIntWriter StartSOSVars(int nnz)

.sos for variables

SuffixIntWriter StartSOSCons(int nnz)

.sos for constraints

SuffixDblWriter StartSOSREFVars(int nnz)

.sosref for variables

Private Members

SuffixWriterFactory swf_
class mp::PLTerm : public mp::BasicExpr<expr::PLTERM>
#include <expr.h>

A piecewise-linear term.

Example: <<0; -1, 1>> x, where x is a variable.

Public Types

enum [anonymous]

Values:

Public Functions

inline int num_breakpoints() const

Returns the number of breakpoints in this term.

inline int num_slopes() const

Returns the number of slopes in this term.

inline double breakpoint(int index) const

Returns a breakpoint with the specified index.

inline double slope(int index) const

Returns a slope with the specified index.

inline Reference arg() const

Returns the argument (variable or common expression reference).

Protected Types

typedef ExprBase::Impl Impl

Reuse ExprBase::Impl.

typedef BasicExpr Base

Base = BasicExpr.

Private Functions

MP_EXPR(Base)
class mp::BasicExprFactory::PLTermBuilder
#include <expr.h>

A piecewise-linear term builder.

Public Functions

inline void AddSlope(double slope)
inline void AddBreakpoint(double breakpoint)

Private Functions

inline explicit PLTermBuilder(PLTerm::Impl *impl)

Private Members

PLTerm::Impl *impl_
int slope_index_
int breakpoint_index_

Friends

friend class BasicExprFactory
struct mp::ProblemBuilder::PLTermBuilder
#include <problem-builder.h>

Public Functions

inline void AddSlope(double slope)
inline void AddBreakpoint(double breakpoint)
struct mp::NLHandler::PLTermHandler
#include <nl-reader.h>

A class (struct) that receives notifications of slopes and breakpoints in a piecewise-linear term.

Public Functions

inline void AddSlope(double slope)

Receives notification of a slope.

inline void AddBreakpoint(double breakpoint)

Receives notification of a breakpoint.

template<class ModelConverter>
class mp::PowConstExponentConverter_MIP : public mp::FuncConConverter_MIP_CRTP<PowConstExponentConverter_MIP<ModelConverter>, ModelConverter, PowConstraint>
#include <power_const.h>

Converts PowConstraint (const exponent) for MIP.

Public Types

using Base = FuncConConverter_MIP_CRTP<PowConstExponentConverter_MIP<ModelConverter>, ModelConverter, PowConstraint>

Base class.

using ItemType = PowConstraint

Converted item type.

Public Functions

inline PowConstExponentConverter_MIP(ModelConverter &mc)

Constructor.

inline bool IfNeedsConversion(const ItemType&, int)

Check whether the constraint needs to be converted despite being accepted by ModelAPI.

This used to cover cases not accepted by GenConstrPow in Gurobi <=10: negative lower bound for x while positive integer exponent. But we did this even for all integer powers >=2 to avoid PL approximation in Gurobi. Cancelled in Gurobi 11. Note that ^2 has been quadratized in ProblemFlattener.

inline void Convert(const ItemType &con, int i)

Convert in any context.

template<class ItemType>
inline void Convert(const ItemType &item, int i)

Generic Convert(), distinguishes context & result variable.

Distinguish positive and negative context because if only one of these is necessary, significant model reduction can be achieved in certain cases.

Responsible for adding presolve links, if any

The Impl can reimplement this

Parameters
  • item – the item to be converted

  • i – item index, used to create a presolve link

template<class ItemType>
inline void ConvertCtxNeg(const ItemType &item, int)

Convert in negative context.

template<class ItemType>
inline void ConvertCtxPos(const ItemType &item, int)

Convert in positive context.

inline const ModelConverter &GetMC() const

Reuse the stored ModelConverter.

inline ModelConverter &GetMC()

Reuse the stored ModelConverter.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

Protected Functions

inline void Convert2Quadratics(const ItemType &con, int)

Convert into quadratics.

inline void Convert2PL(const ItemType &con, int i)

PL approximate.

struct mp::NLModel::PreprocessData
#include <nl-model.h>

Information exported by WriteNL()

Public Members

std::vector<int> vperm_

var permutation

std::vector<int> vperm_inv_

var inverse permutation

template<class FuncConstraint>
struct mp::PreprocessInfo
#include <preprocess.h>

Information about initial preprocessing of a constraint: bounds, result var type, result_var if known.

Public Functions

inline PreprocessInfo()
inline PreprocessInfo(double l, double u, var::Type t)
inline double lb() const
inline double ub() const
inline void narrow_result_bounds(double l, double u)
inline void NegateBounds()
inline var::Type get_result_type() const
inline var::Type type() const
inline void set_result_type(var::Type t)
inline bool is_constant() const
inline bool is_result_var_known() const
inline void set_result_var(int r)
inline int get_result_var() const

Public Members

double lb_ = -INFINITY
double ub_ = INFINITY
var::Type type_ = var::CONTINUOUS
int result_var_ = -1
template<typename Impl, typename ExprType>
class mp::ProblemBuilder : public mp::SuffixManager
#include <problem-builder.h>

A minimal implementation of the ProblemBuilder concept.

Public Types

typedef ExprType Expr
typedef Expr NumericExpr
typedef Expr LogicalExpr
typedef Expr CountExpr
typedef Expr Reference
typedef LinearExprBuilder LinearObjBuilder
typedef LinearExprBuilder LinearConBuilder
typedef SuffixHandler<int> IntSuffixHandler
typedef SuffixHandler<double> DblSuffixHandler
typedef ExprBuilder NumericExprBuilder
typedef ExprBuilder IteratedExprBuilder
typedef ExprBuilder CallExprBuilder
typedef ExprBuilder NumberOfExprBuilder
typedef ExprBuilder CountExprBuilder
typedef ExprBuilder IteratedLogicalExprBuilder
typedef ExprBuilder SymbolicNumberOfExprBuilder
typedef ExprBuilder PairwiseExprBuilder
typedef MutSuffix Suffix
typedef MutIntSuffix IntSuffix
typedef mp::SuffixSet SuffixSet

Public Functions

inline void SetInfo(const NLProblemInfo&)
inline void AddVar(double lb, double ub, var::Type type)

Adds a variable.

inline LinearObjBuilder AddObj(obj::Type type, NumericExpr expr, int num_linear_terms)

Adds an objective.

Returns a builder for the linear part of the objective expression.

inline LinearConBuilder AddCon(double lb, double ub, NumericExpr expr, int num_linear_terms)

Adds an algebraic constraint.

Returns a builder for the linear part of the constraint expression.

inline void AddCon(LogicalExpr expr)

Adds a logical constraint.

inline CommonExpr common_expr(int expr_index)
inline CommonExpr AddCommonExpr(NumericExpr expr)

Adds a common expression (defined variable).

inline void SetComplementarity(int con_index, int var_index, ComplInfo info)

Sets a complementarity relation.

inline Variable var(int index)
inline AlgebraicCon algebraic_con(int index)
inline void AddFunctions(int num_funcs)
inline Function DefineFunction(int index, fmt::StringRef name, int num_args, func::Type type)
inline Function AddFunction(fmt::StringRef name, int num_args, func::Type type)

Adds a function.

inline Function function(int index)
inline IntSuffixHandler AddIntSuffix(fmt::StringRef name, int kind, int num_values)

Adds a suffix.

inline DblSuffixHandler AddDblSuffix(fmt::StringRef name, int kind, int num_values)

Adds a suffix.

inline NumericExpr MakeNumericConstant(double value)
inline Reference MakeVariable(int var_index)
inline NumericExpr MakeUnary(expr::Kind kind, NumericExpr arg)
inline NumericExpr MakeBinary(expr::Kind kind, NumericExpr lhs, NumericExpr rhs)
inline NumericExpr MakeIf(LogicalExpr condition, NumericExpr then_expr, NumericExpr else_expr)
inline PLTermBuilder BeginPLTerm(int num_breakpoints)
inline NumericExpr EndPLTerm(PLTermBuilder builder, Reference arg)
inline CallExprBuilder BeginCall(Function func, int num_args)
inline NumericExpr EndCall(CallExprBuilder builder)
inline IteratedExprBuilder BeginIterated(expr::Kind kind, int num_args)
inline NumericExpr EndIterated(IteratedExprBuilder builder)
inline NumericExprBuilder BeginSum(int num_args)
inline NumericExpr EndSum(NumericExprBuilder builder)
inline NumberOfExprBuilder BeginNumberOf(int num_args, NumericExpr arg0)
inline NumericExpr EndNumberOf(NumberOfExprBuilder builder)
inline SymbolicNumberOfExprBuilder BeginSymbolicNumberOf(int num_args, Expr arg0)
inline NumericExpr EndSymbolicNumberOf(SymbolicNumberOfExprBuilder builder)
inline CountExprBuilder BeginCount(int num_args)
inline NumericExpr EndCount(CountExprBuilder builder)
inline LogicalExpr MakeLogicalConstant(bool value)
inline LogicalExpr MakeNot(LogicalExpr arg)
inline LogicalExpr MakeBinaryLogical(expr::Kind kind, LogicalExpr lhs, LogicalExpr rhs)
inline LogicalExpr MakeRelational(expr::Kind kind, NumericExpr lhs, NumericExpr rhs)
inline LogicalExpr MakeLogicalCount(expr::Kind kind, NumericExpr lhs, CountExpr rhs)
inline LogicalExpr MakeImplication(LogicalExpr condition, LogicalExpr then_expr, LogicalExpr else_expr)
inline IteratedLogicalExprBuilder BeginIteratedLogical(expr::Kind kind, int num_args)
inline LogicalExpr EndIteratedLogical(IteratedLogicalExprBuilder builder)
inline PairwiseExprBuilder BeginPairwise(expr::Kind kind, int num_args)
inline LogicalExpr EndPairwise(PairwiseExprBuilder builder)
inline Expr MakeStringLiteral(fmt::StringRef value)

Constructs a StringLiteral object.

value: string value which may not be null-terminated.

inline Expr MakeSymbolicIf(LogicalExpr condition, Expr then_expr, Expr else_expr)
inline SuffixSet &suffixes(suf::Kind kind)

Returns a set of suffixes.

inline const SuffixSet &suffixes(suf::Kind kind) const

Public Static Functions

static inline void ReportUnhandledConstruct(fmt::CStringRef name)
template<class Impl, class Problem, class FlatConverter>
class mp::ProblemFlattener : public mp::ExprConverter<Impl, EExpr>, public mp::BasicConverter<Problem>

ProblemFlattener: it walks and “flattens” most expressions by replacing them by a result variable and constraints.

Such replacement is performed by a FlatConverter object. Such constraints might need to be converted to others, which is handled by overloaded methods in descendants of FlatConverter.

Parameters
  • Impl – final CRTP class

  • Problem – the model class representing the input instance. Should implement the mp::BasicProblem interface.

  • FlatConverter – the FlatConverter type

Public Types

using ProblemType = Problem
using FlatConverterType = FlatConverter
using Var = typename FlatConverter::Var
using EExprType = EExpr
using VarArray = std::vector<Var>
using ModelType = Problem

The ProblemBuilder a.k.a. Model type.

Public Functions

inline ProblemFlattener(Env &e)
inline void InputVariables(int n, const double *lb, const double *ub, const var::Type *ty)

INCREMENTAL INTERFACE.

These guys used from outside to feed a model to be converted and forwarded to a backend Currently only used for testing

inline std::vector<int> AddVars(std::size_t nvars, double lb = -INFINITY, double ub = INFINITY, var::Type type = var::CONTINUOUS)

Add vector of variables. Type: var::CONTINUOUS by default.

inline void InputObjective(obj::Type t, int nnz, const double *c, const int *v, NumericExpr e = NumericExpr())
inline void InputAlgebraicCon(int nnz, const double *c, const int *v, double lb, double ub, NumericExpr e = NumericExpr())
inline virtual void ConvertModel() override

CONVERTERS OF STANDARD MP ITEMS //////////////////////////////.

Convert the whole model, e.g., after reading from NL

inline virtual void FillModelTraits(AMPLS_ModelTraits &mt) override

Fill model traits.

inline virtual bool HasUnfixedIntVars() const override

Solver-facing model info: has unfixed int vars?

inline EExpr VisitNumericConstant(NumericConstant n)

EXPRESSION VISITORS ////////////////////////////////////.

inline EExpr VisitVariable(Reference r)
inline EExpr VisitCommonExpr(Reference r)
inline EExpr VisitMinus(UnaryExpr e)
inline EExpr VisitAdd(BinaryExpr e)
inline EExpr VisitSub(BinaryExpr e)
inline EExpr VisitMul(BinaryExpr e)
inline EExpr VisitDiv(BinaryExpr e)
inline EExpr VisitSum(typename BaseExprVisitor::SumExpr expr)
inline EExpr VisitMax(typename BaseExprVisitor::VarArgExpr e)
inline EExpr VisitMin(typename BaseExprVisitor::VarArgExpr e)
inline EExpr VisitAbs(UnaryExpr e)
inline EExpr VisitLogicalConstant(LogicalConstant c)
inline EExpr VisitEQ(RelationalExpr e)
inline EExpr VisitNE(RelationalExpr e)
inline EExpr VisitLE(RelationalExpr e)
inline EExpr VisitLT(RelationalExpr e)
inline EExpr VisitGE(RelationalExpr e)
inline EExpr VisitGT(RelationalExpr e)
inline EExpr VisitNot(NotExpr e)
inline EExpr VisitAnd(BinaryLogicalExpr e)
inline EExpr VisitForAll(IteratedLogicalExpr e)
inline EExpr VisitOr(BinaryLogicalExpr e)
inline EExpr VisitExists(IteratedLogicalExpr e)
inline EExpr VisitIf(IfExpr e)
inline EExpr VisitImplication(ImplicationExpr e)
inline EExpr VisitIff(BinaryLogicalExpr e)
inline EExpr VisitAllDiff(PairwiseExpr e)
inline EExpr VisitNumberOf(typename BaseExprVisitor::NumberOfExpr e)

Numberof: const, var.

inline EExpr VisitCount(CountExpr ce)
inline EExpr VisitPLTerm(PLTerm e)
inline EExpr VisitPowConstExp(BinaryExpr e)
inline EExpr VisitPow2(UnaryExpr e)
inline EExpr VisitPow(BinaryExpr e)
inline EExpr VisitSqrt(UnaryExpr e)
inline EExpr VisitExp(UnaryExpr e)
inline EExpr VisitPowConstBase(BinaryExpr e)
inline EExpr VisitLog(UnaryExpr e)
inline EExpr VisitLog10(UnaryExpr e)
inline EExpr VisitSin(UnaryExpr e)
inline EExpr VisitCos(UnaryExpr e)
inline EExpr VisitTan(UnaryExpr e)
inline EExpr VisitAsin(UnaryExpr e)
inline EExpr VisitAcos(UnaryExpr e)
inline EExpr VisitAtan(UnaryExpr e)
inline EExpr VisitSinh(UnaryExpr e)
inline EExpr VisitCosh(UnaryExpr e)
inline EExpr VisitTanh(UnaryExpr e)
inline EExpr VisitAsinh(UnaryExpr e)
inline EExpr VisitAcosh(UnaryExpr e)
inline EExpr VisitAtanh(UnaryExpr e)
inline virtual void InitOptions() override

Init solver options.

inline virtual const ProblemType &GetModel() const override

The model as input from NL.

inline virtual ProblemType &GetModel() override

The model as input from NL.

inline const ProblemType &GetInputModel() const

The model as input from NL.

inline ProblemType &GetInputModel()

The model as input from NL.

inline const FlatConverter &GetFlatCvt() const
inline FlatConverter &GetFlatCvt()
inline EExpr VisitAtLeast(LogicalCountExpr e)
inline EExpr VisitAtMost(LogicalCountExpr e)
inline EExpr VisitExactly(LogicalCountExpr e)
inline EExpr VisitNotAtLeast(LogicalCountExpr e)
inline EExpr VisitNotAtMost(LogicalCountExpr e)
inline EExpr VisitNotExactly(LogicalCountExpr e)
MP_DEFINE_EXPR_TYPES(internal::ExprTypes)
Result Visit(Expr e)
inline Result VisitUnsupported(Expr e)
inline Result VisitNumeric(NumericExpr e)
inline Result VisitLogical(LogicalExpr e)
inline Result VisitVariable(Variable v)
inline Result VisitCommonExpr(CommonExpr e)
inline Result VisitUnary(UnaryExpr e)
inline Result VisitFloor(UnaryExpr e)
inline Result VisitCeil(UnaryExpr e)
inline Result VisitBinary(BinaryExpr e)

Visits a binary expression or a function taking two arguments.

inline Result VisitLess(BinaryExpr e)
inline Result VisitTruncDiv(BinaryExpr e)
inline Result VisitMod(BinaryExpr e)
inline Result VisitBinaryFunc(BinaryExpr e)
inline Result VisitAtan2(BinaryExpr e)
inline Result VisitPrecision(BinaryExpr e)
inline Result VisitRound(BinaryExpr e)
inline Result VisitTrunc(BinaryExpr e)
inline Result VisitCall(CallExpr e)
inline Result VisitVarArg(VarArgExpr e)
inline Result VisitMin(VarArgExpr e)
inline Result VisitMax(VarArgExpr e)
inline Result VisitSum(SumExpr e)
inline Result VisitNumberOf(NumberOfExpr e)
inline Result VisitNumberOfSym(SymbolicNumberOfExpr e)
inline Result VisitBinaryLogical(BinaryLogicalExpr e)
inline Result VisitRelational(RelationalExpr e)
inline Result VisitLogicalCount(LogicalCountExpr e)
inline Result VisitIteratedLogical(IteratedLogicalExpr e)
inline Result VisitNotAllDiff(PairwiseExpr e)
inline Result VisitStringLiteral(StringLiteral e)
inline Result VisitSymbolicIf(SymbolicIfExpr e)
inline const Env &GetEnv() const

GetEnv() const.

inline Env &GetEnv()

GetEnv()

Public Static Functions

static inline const char *GetTypeName()

Protected Types

using ClassName = ProblemFlattener
using BaseExprVisitor = ExprVisitor<Impl, EExpr>
using BaseConverter = BasicConverter<Problem>
using EExprArray = std::vector<EExpr>

Protected Functions

inline void ConvertStandardItems()

Convert problem items.

inline void ExportCommonExpr(int i)

Export common expression i.

inline void ExportObj(int i)

Export objective i.

inline void ExportAlgCon(int i)

Export algebraic constraint i.

inline void ExportLogCon(int i)

Export logical constraint i.

inline void ConvertVars()

Convert variables.

inline void Convert(typename ProblemType::MutCommonExpr)

Convert a common expr.

inline void Convert(typename ProblemType::MutObjective obj)

Convert an objective.

inline void ConvertAlgCon(int i)

Convert an algebraic constraint.

inline AlgConPrepare PrepareAlgConstraint(int i)

Prepare alg constraint for moving into FlatCvt.

inline void AddAlgebraicConstraint(AlgConPrepare &&pr)

Add algebraic constraint to FlatCvt.

inline void ConvertLogicalCon(int i)

Convert a logical constraint.

inline void CopyItemNames()
inline EExpr Convert2EExpr(Expr e)

Convert an expression to an EExpr.

inline int Convert2Var(Expr e)

From an expression: Adds a result variable r and constraint r == expr.

inline int Convert2Var(EExpr &&ee)
inline AffineExpr Convert2VarAsAffineExpr(EExpr &&ee)

Makes an affine expr representing just one variable.

inline AffineExpr Convert2AffineExpr(EExpr &&ee)
template<class FuncConstraint, class ExprArray = std::initializer_list<Expr>>
inline EExpr VisitFunctionalExpression(ExprArray ea)

Generic functional expression array visitor.

Assumes the arguments should be converted to variables. Can produce a new result variable/expression and specified constraints (normally, FuncConstraint) on it.

template<class ExprArray>
inline void Exprs2Vars(const ExprArray &ea, std::vector<int> &result)
template<class Expr>
inline void Exprs2Vars(const std::initializer_list<Expr> &ea, std::vector<int> &result)
template<class ExprArray, size_t N>
inline void Exprs2Vars(const ExprArray &ea, std::array<int, N> &result)
template<class FuncConstraint>
inline EExpr AssignResult2Args(FuncConstraint &&fc)
template<int comp_kind, class ExprArray = std::initializer_list<Expr>>
inline EExpr VisitRelationalExpression(ExprArray ea)

Generic relational expression visitor.

Can produce a new variable/expression and specified constraints on it. Produces a conditional linear/quadratic constraint b==1 <=/=> c’x [+ x’Qx] <=/= d.

Template Parameters

comp_kind – < (-2), <= (-1), == (0)

Parameters

ea – array of 2 expressions (comparison arguments lhs, rhs)

template<class ExprArray = std::initializer_list<Expr>>
inline EExpr VisitDisequality(ExprArray ea)

Disequality visitor.

Parameters

ea – array of 2 expressions (comparison arguments lhs, rhs)

template<class ExprArray, size_t N>
inline void Exprs2EExprs(const ExprArray &ea, std::array<EExpr, N> &result)

Convert array of Expr’s to array of EExpr’s.

inline void ConvertSOSConstraints()
inline void ConvertSOSCollection(ArrayRef<int> sosno, ArrayRef<double> ref, bool fAllSOS2)

fAllSOS2: if false, only groups with sosno<0 are treated as SOS2 Moreover if true, we assume they are for linearized PL

inline EExpr QuadratizeOrLinearize(EExpr &el, EExpr &er)

Depending on the target backend, can either convert to factor^2 (if el==er) or leave as quadratics.

Currently only quadratize higher-order products. Can change arguments (move out). They could point to the same expr. PERFORMANCE WARNING: allows &el==&er, needed from Pow2

inline EExpr Convert2Pow2(const LinTerms &ellt, const LinTerms &erlt)

(9*x) * x -> 9 x^2

inline EExpr Convert2Pow2(EExpr &&el)

aff_expr * aff_expr -> aff_expr^2

inline EExpr DontMultOut(EExpr &&el, EExpr &&er)

Create product without multiplying out.

Create a separate QC.

inline EExpr MultiplyOut(const EExpr &el, const EExpr &er)

Multiply out two EEXprs.

template<class Constraint>
inline pre::NodeRange AddConstraint_AS_ROOT(Constraint &&con)

Add constraint and propagate result into arguments.

Use this when any variables can be the result of an expression (flat constraint)

template<class Constraint>
inline pre::NodeRange AddConstraint(Constraint &&con)

Add constraint, do not propagate result into arguments.

inline pre::ValuePresolver &GetValuePresolver()

UTILITIES /////////////////////////////////.

inline bool IfFlatteningAConstraint() const

Whether flattening a constraint vs an objective.

inline int MakeFixedVar(double value)
inline pre::CopyLink &GetCopyLink()

Presolve link just copying values between model items.

inline int sos() const
inline int sos2_ampl_pl() const
inline int IfMultOutQPTerms() const

Distinguish between constraints and objectives.

What about common expressions?

inline bool IfQuadratizePow2() const

Quadratize Pow2 exactly when we pass QP terms.

Private Functions

inline void InitOwnOptions()

Private Members

std::vector<int> common_exprs_
int ifFltCon_ = -1
Options options_
ProblemType model_
FlatConverter flat_cvt_
template<template<typename, typename, typename> class ProblemFlt, class Problem, class FlatCvt>
class mp::ProblemFltImpl : public ProblemFlt<ProblemFltImpl<ProblemFlt, Problem, FlatCvt>, Problem, FlatCvt>

A ‘final’ ProblemFlattener in a hierarchy.

Public Functions

inline ProblemFltImpl(Env &e)

Construct.

Private Types

using Base = ProblemFlt<ProblemFltImpl<ProblemFlt, Problem, FlatCvt>, Problem, FlatCvt>

Typedef Base.

struct mp::internal::NLReader::ProblemHandler : public mp::internal::NLReader<PROB>::ItemHandler

Public Functions

inline explicit ProblemHandler(NLReader &r)
inline int num_items() const

An NL input always contains one problem.

Public Static Attributes

static const ItemType TYPE = T

Protected Attributes

NLReader &reader_
class mp::BasicSuffixSet::iterator::Proxy

A suffix proxy used for implementing operator->.

Public Functions

inline explicit Proxy(const SuffixImpl *impl)
inline const Suffix *operator->() const

Private Members

Suffix suffix_
class mp::internal::ExprIterator::Proxy

An expression proxy used for implementing operator->.

Public Functions

inline explicit Proxy(const ExprBase::Impl *e)
inline const ExprType *operator->() const

Private Members

ExprType expr_
template<class ModelConverter, int sens>
class mp::QCConverter_MIP : public mp::BasicItemConverter<ModelConverter>
#include <mul.h>

Convert all quadratic terms in the body of a QC.

This is the most universal way, in case some converter adds QC. An alternative would be, when flattening, to replace every multiplication by a special new constraint, and convert only these.

Public Types

using Base = BasicItemConverter<ModelConverter>

Base class.

using ItemType = QuadConRhs<sens>

Converted item type.

Public Functions

inline QCConverter_MIP(ModelConverter &mc)

Constructor.

inline bool IfNeedsConversion(const ItemType&, int)

Check whether the constraint needs to be converted despite being accepted by ModelAPI.

inline void Convert(const ItemType &qc, int)

Conversion.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

Protected Functions

inline void LinearizeQPTerms(const ItemType &qc)
inline LinTerms LinearizeQPTerm(double c, int x, int y)
inline LinTerms LinearizeProductWithBinaryVar(double c, int x, int y)
inline LinTerms LinearizeGeneralProduct(double c, int x, int y)

c*x*y -> 0.5*c((x+y)^2-x^2-y^2)

inline const ModelConverter &GetMC() const

Access const ModelConverter.

inline ModelConverter &GetMC()

Access ModelConverter.

template<class ModelConverter>
class mp::QConeConverter : public mp::BasicFuncConstrCvt<QConeConverter<ModelConverter>, ModelConverter>
#include <qcones2qc.h>

Converts QCone.

Public Types

using Base = BasicFuncConstrCvt<QConeConverter<ModelConverter>, ModelConverter>

Base class.

using ItemType = QuadraticConeConstraint

Converted item type.

Public Functions

inline QConeConverter(ModelConverter &mc)

Constructor.

inline bool IfNeedsConversion(const ItemType&, int)

Check whether the constraint needs to be converted despite being accepted by ModelAPI.

inline void Convert(const ItemType &ac, int)

Convert to (c[0]*x[0])^2 >= sum(i)((c[i]*x[i])^2) with x[0]>=0.

inline void Convert(const ItemType &item, int i)

Generic Convert(), distinguishes context & result variable.

Distinguish positive and negative context because if only one of these is necessary, significant model reduction can be achieved in certain cases.

Responsible for adding presolve links, if any

The Impl can reimplement this

Parameters
  • item – the item to be converted

  • i – item index, used to create a presolve link

inline void ConvertCtxNeg(const ItemType &item, int)

Convert in negative context.

inline void ConvertCtxPos(const ItemType &item, int)

Convert in positive context.

inline const ModelConverter &GetMC() const

Reuse the stored ModelConverter.

inline ModelConverter &GetMC()

Reuse the stored ModelConverter.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

struct mp::Convert1QC::QPTermsTraits
#include <cones.h>

Characteristics of QP terms.

Public Members

int nDiffVars = 0
int iDiffVars = -1
int x1 = -1
int x2 = -1
double coef12 = 0.0
int nSamePos = 0
int nSameNeg = 0
int iSamePos = -1
int iSameNeg = -1
class mp::QuadAndLinTerms : protected mp::LinTerms, protected mp::QuadTerms
#include <expr_quadratic.h>

Quadratic and linear terms.

Body of a quadratic constraint

Subclassed by mp::AlgebraicExpression< QuadAndLinTerms >

Public Functions

QuadAndLinTerms() = default

Default constructor.

inline QuadAndLinTerms(LinTerms lt, QuadTerms qt)

Construct from linear + QP terms.

inline const LinTerms &GetLinTerms() const

Get LinTerms, const.

inline LinTerms &GetLinTerms()

Get LinTerms.

inline const QuadTerms &GetQPTerms() const

Get QuadTerms, const.

inline QuadTerms &GetQPTerms()

Get QuadTerms.

inline bool empty() const

empty?

inline bool is_linear() const

is linear?

inline bool is_quadratic() const

Is quadratic?

inline bool is_variable() const

true when 1 linear variable with coef 1.0

inline int get_representing_variable() const

return the single variable assuming true==is_variable()

inline bool is_normalized() const

Is normalized? Assume sorted.

inline void negate()

Negate.

inline void add(const QuadAndLinTerms &qlt)

add body

template<class VarInfo>
inline long double ComputeValue(const VarInfo &x) const

Value at given variable vector.

inline void sort_terms()

Sort terms.

inline bool equals(const QuadAndLinTerms &qlc) const

Test equality.

inline bool operator==(const QuadAndLinTerms &qlc) const

Test equality.

inline void add_term(double c, int v)

add_term(c, v)

inline void add_term(double coef, int var1, int var2)

add_term(c, v1, v2)

Public Static Functions

static inline constexpr const char *GetTypeName()

Name.

Protected Functions

inline bool check() const

Validate.

inline size_t size() const

size()

inline double coef(size_t i) const

coef[i]

inline int var(size_t i) const

var[i]

inline const std::vector<double> &coefs() const

const vec& coefs()

inline const std::vector<int> &vars() const

const vec& vars()

inline const double *pcoefs() const

Ptr to coefs.

inline const int *pvars() const

Ptr to vars.

inline void set_coef(size_t i, double c)

Set coef.

inline void reserve(size_t s)

Reserve size.

inline void add_term(double c, int v)

Add linear term.

inline void add(const LinTerms &le)

Add another LinTerms.

template<class Vec>
inline void add_terms(const Vec &v2)

Add terms from a vector of pairs {c, v}.

inline void operator*=(double n)

Multiply by const.

inline void preprocess()

preprocess / canonicalize

void sort_terms(bool force_sort = false)

This a a NASTY one (when not used).

Use it before adding constraints / objectives. Add same variables, eliminate 0’s. Can be used by LinCon’s etc Gurobi complains when 0’s / repeated entries.

inline bool equals(const LinTerms &lt) const

Equality. Assumes being sorted.

inline bool operator==(const LinTerms &lt) const

operator== for hashing and testing

inline bool check() const

Validate.

inline int size() const

Size.

inline int capacity() const

Capacity.

inline const double *pcoefs() const
inline const int *pvars1() const
inline const int *pvars2() const
inline const std::vector<double> &coefs() const
inline const std::vector<int> &vars1() const
inline const std::vector<int> &vars2() const
inline double coef(int i) const
inline void set_coef(int i, double c)
inline int var1(size_t i) const
inline int var2(size_t i) const
inline void add_term(double coef, int var1, int var2)
inline void reserve(std::size_t num_terms)
inline void add(const QuadTerms &li)
inline void subtract(QuadTerms &&ae)
inline void operator*=(double n)
inline void clear()

Clear.

inline bool equals(const QuadTerms &qt) const

Test equality.

inline bool operator==(const QuadTerms &qt) const

Testing API.

Protected Static Functions

static inline constexpr bool is_linear()

Always linear.

class mp::QuadraticFunctionalConstraint : public mp::FunctionalConstraint, public mp::NumericFunctionalConstraintTraits

Quadratic Functional Constraint: r = quad_expr.

Public Types

using Arguments = QuadraticExpr

Typedef Arguments.

Public Functions

inline QuadraticFunctionalConstraint(QuadraticExpr &&qe) noexcept

A constructor ignoring result variable: use AssignResultToArguments() then.

Not sorting+merging

inline QuadraticFunctionalConstraint(int r, QuadraticExpr &&qe) noexcept

Constructor: known result var + body.

Not sorting+merging

inline const QuadraticExpr &GetQuadExpr() const

Getter: quad expr.

inline const Arguments &GetArguments() const

GetArguments(): get quad expr.

template<class Converter>
inline void AddQuadraticConstraint(Converter &cvt) const

add respective static constraint to a converter.

Use >=< depending on context.

inline int GetResultVar() const

using GetResultVar()

inline bool operator==(const FunctionalConstraint &dc) const

Basic operator==.

inline bool HasResultVar() const

Has result var (is functional)? We don’t store this info in the type (yet.)

inline int GetResultVar() const

Get result variable.

inline void SetResultVar(int v)

Set result variable.

inline Context GetContext() const

Get it.

inline void SetContext(Context c) const

Set it.

inline void AddContext(Context c)

Add context.

inline void AddContext(Context) const

Add (merge) context, if meaningful.

inline const char *GetName() const

Constraint name.

inline const char *name() const

Constraint name.

inline void SetName(std::string nm)

Set constraint name.

template<class VarInfo>
inline Violation ComputeViolation(const VarInfo&) const

Compute violation.

Public Static Functions

static inline const char *GetTypeName()

Constraint type name.

static inline constexpr bool UsesContext()

Whether context is meaningful.

static inline constexpr bool IsLogical()

Whether the constraint is logical.

static inline std::pair<double, double> GetAprioriBounds()

Apriori bounds on the result.

Private Members

QuadraticExpr quad_expr_
class mp::QuadraticObjective : public mp::LinearObjective
#include <obj_std.h>

Quadragtic objective.

Public Functions

inline QuadraticObjective(LinearObjective &&lc, QuadTerms &&qt)

Construct.

inline const QuadTerms &GetQPTerms() const

Get QP terms, const.

inline QuadTerms &GetQPTerms()

Get QP terms.

inline void sort_qp_terms()

Sort QP terms.

inline bool operator==(const QuadraticObjective &qc) const

Testing API.

inline obj::Type obj_sense() const

Get sense.

inline const LinTerms &GetLinTerms() const

Get lin terms, const.

inline LinTerms &GetLinTerms()

Get lin terms.

inline int num_terms() const

Get N terms.

inline bool check() const

Validate.

inline const std::vector<double> &coefs() const

Coefs vector.

inline const std::vector<int> &vars() const

Var vector.

inline const char *name() const

Name.

inline void set_name(std::string nm)

Set name.

inline bool operator==(const LinearObjective &lc) const

Testing API.

Private Members

QuadTerms qt_
class mp::QuadTerms
#include <expr_quadratic.h>

Quadratic terms x’Qx.

Subclassed by mp::QuadAndLinTerms

Public Functions

QuadTerms() = default

Default constructor.

inline QuadTerms(std::vector<double> c, std::vector<int> v1, std::vector<int> v2) noexcept

Construct from 3 vectors.

inline bool check() const

Validate.

inline bool empty() const

Empty?

inline int size() const

Size.

inline int capacity() const

Capacity.

inline const double *pcoefs() const
inline const int *pvars1() const
inline const int *pvars2() const
inline const std::vector<double> &coefs() const
inline const std::vector<int> &vars1() const
inline const std::vector<int> &vars2() const
inline double coef(int i) const
inline void set_coef(int i, double c)
inline int var1(size_t i) const
inline int var2(size_t i) const
template<class VarInfo>
inline long double ComputeValue(const VarInfo &x) const

Compute value given a dense vector of variable values.

inline void add_term(double coef, int var1, int var2)
inline void reserve(std::size_t num_terms)
inline bool is_normalized() const

Is normalized? Assume sorted.

inline void negate()

Arithmetic.

inline void add(const QuadTerms &li)
inline void subtract(QuadTerms &&ae)
inline void operator*=(double n)
void sort_terms()

Sort and eliminate duplicates.

inline void clear()

Clear.

inline bool equals(const QuadTerms &qt) const

Test equality.

inline bool operator==(const QuadTerms &qt) const

Testing API.

Public Static Functions

static inline constexpr const char *GetTypeName()

Name.

Private Members

std::vector<double> coefs_
std::vector<int> vars1_
std::vector<int> vars2_
class mp::NLWriter2::RandVarWriterFactory
#include <nl-writer2.h>

Write a sequence of random variables.

Public Functions

inline RandVarWriterFactory(NLWriter2 &nlw)

Construct.

ExprArgWriter StartRandVar(int index, const char *descr)

Start writing a random variable.

(To be finished by feeding the defining expression.)

Returns

A callback writing the defining expression.

Private Members

NLWriter2 &nlw_
template<typename T>
class mp::BasicProblem::Range
#include <problem.h>

A pair of iterators to problem elements.

Public Functions

inline iterator begin() const

Returns an iterator to the first element in the range.

inline iterator end() const

Returns an iterator to the element following the last element in the range.

An attempt to access this element will result in assertion failure if assertions are enabled and undefined behavior otherwise.

Private Functions

inline explicit Range(const BasicProblem *p)

Private Members

const BasicProblem *problem_

Friends

friend class BasicProblem
struct mp::Range
#include <lin_approx_core.h>

Range.

Public Functions

inline Range(double l = -1e100, double u = 1e100)

Construct.

Public Members

double lb

The bounds.

double ub
template<class ModelConverter, class RangeCon>
class mp::pre::RangeCon2Slack : public mp::pre::BasicStaticIndivEntryLink<RangeCon2Slack<ModelConverter, RangeCon>, 3, 3, 1>
#include <range_con.h>

Presolve link between RangeCon and either Con(LE/GE) or ConEQ+Slack.

Parameters of the base class: self, N value nodes (3), N indexes (3), N source nodes / indexes in the list (1).

Public Types

enum LinkEntryIndexes

Names for indexes in a Base::LinkEntry.

Values:

enumerator CON_SRC

Source range constraint index.

enumerator CON_TARGET

Target equality constraint index.

enumerator VAR_SLK

Target slack index.

using Base = BasicStaticIndivEntryLink<RangeCon2Slack<ModelConverter, RangeCon>, 3, 3, 1>

Base class.

using NodeList = std::array<ValueNode*, NNodes>

Typedef NodeList: list of ValueNode pointers.

A ValueNode is a node of the (structural) transformation graph and can store arrays of values for a list of model items

using LinkEntry = std::array<int, NIndexes>

Typedef: LinkEntry is just an array if node indexes.

using ItemRangeList = std::vector<NodeRange>

Typedef item container.

Public Functions

inline RangeCon2Slack(ModelConverter &cvt, const typename Base::NodeList &ndl)

Constructor.

Parameters
  • cvt – the model converter

  • ndl – list of 3 value nodes (orig ranges, new constraints, new slacks)

inline virtual const char *GetTypeName() const override

Type name.

inline void PresolveGenericDblEntry(const typename Base::LinkEntry &be)

Define pre- / postsolve methods for individual link entries.

Typedef LinkEntry is created in Base as std::array<int, 3> (3 is the base class template parameter) and means the following indexes: {range_con, lin_con, slack_index} PresolveGeneric double

inline void PostsolveGenericDblEntry(const typename Base::LinkEntry &be)

PostsolveGeneric double.

inline void PresolveGenericIntEntry(const typename Base::LinkEntry &be)

PresolveGeneric int.

inline void PostsolveGenericIntEntry(const typename Base::LinkEntry &be)

PostsolveGeneric int.

inline void PresolveSolutionEntry(const typename Base::LinkEntry &be)

Presolve solution (primal + dual).

Duals: just copy. Primals: compute slack. Slacks are probably only needed for Gurobi LP warmstart. Who does not need them, can use unpresolved primal solution.

inline void PostsolveSolutionEntry(const typename Base::LinkEntry &be)

Postsolve solution (primal + dual)

inline void PresolveBasisEntry(const typename Base::LinkEntry &be)

Presolve basis.

From a range constraint’s basis status, transfer it to the slack. Set the new constraint’s status to ‘equ’.

inline void PostsolveBasisEntry(const typename Base::LinkEntry &be)

Postsolve basis.

The reverse (forget solver’s constraint status)

inline void PresolveIISEntry(const typename Base::LinkEntry&)

Presolve IIS.

inline void PostsolveIISEntry(const typename Base::LinkEntry &be)

Postsolve IIS.

Take slack’s if set, otherwise the constraint’s

inline void PresolveLazyUserCutFlagsEntry(const typename Base::LinkEntry &be)

Mark Lazy/user cut: copy flag.

inline void PostsolveLazyUserCutFlagsEntry(const typename Base::LinkEntry&)
inline void PresolveNamesEntry(const typename Base::LinkEntry &be)

Presolve names.

inline void PostsolveNamesEntry(const typename Base::LinkEntry&)

Postsolve names: none.

inline void FillEntryItems(typename Base::EntryItems &ei, const LinkEntry &en) const

Get source/target nodes for a given link entry.

This is used for graph export

inline void AddEntry(LinkEntry be)

Add entry.

inline virtual void ExportEntryItems(EntryItems &ei, int i) const override

Get source/target nodes for a given link entry.

This is used for graph export

Protected Functions

inline ModelConverter &GetMC()

Get the model converter.

inline const ValueNode &GetNode(size_t i) const

Access whole node at specific index, const.

inline ValueNode &GetNode(size_t i)

Access whole node at specific index.

inline int GetInt(const LinkEntry &be, size_t pos) const

Access int value at the node pos at the index stored in be[pos].

Parameters
  • be – a LinkEntry

  • pos – node number from 0..NNodes-1

inline void SetInt(const LinkEntry &be, size_t pos, int i)

SetInt.

inline double GetDbl(const LinkEntry &be, size_t pos) const

Access double value at the node pos at the index stored in be[pos].

Parameters
  • be – a LinkEntry

  • pos – node number from 0..NNodes-1

inline void SetDbl(const LinkEntry &be, size_t pos, double i)

SetDbl.

inline const VCString &GetStr(const LinkEntry &be, size_t pos) const

Access string value at the node pos at the index stored in be[pos].

Parameters
  • be – a LinkEntry

  • pos – node number from 0..NNodes-1

inline void SetStr(const LinkEntry &be, size_t pos, VCString v)

SetStr.

inline void RegisterLinkIndex(int i)

Add a range of link entries to the Presolver’s list.

Every derived link should call either of the next two methods whenever adding a link entry. Version 1: add single link

inline void RegisterLinkIndexRange(LinkIndexRange)

Version 2: add a range of links.

Implement link range registration in global Presolver.

Protected Static Functions

static inline int ReverseBasisLowUpp(int stt)

Reverse low/upp basis statuses.

Private Members

ModelConverter &cvt_
template<class ModelConverter, class AlgConBody>
class mp::RangeConstraintConverter : public mp::BasicItemConverter<ModelConverter>
#include <range_con.h>

Converts proper range constraints to body+slack=ub, otherwise to body </=/> rhs.

Parameters
  • ModelConverter – the main converter class

  • AlgConBody – The Body argument of the AlgebraicConstraint

Public Types

using Base = BasicItemConverter<ModelConverter>

Base class.

using ItemType = AlgebraicConstraint<AlgConBody, AlgConRange>

Converted item type.

using AlgConLE = AlgebraicConstraint<AlgConBody, AlgConRhs<-1>>

Resulting constraint type: LE.

using AlgConEQ = AlgebraicConstraint<AlgConBody, AlgConRhs<0>>

Resulting constraint type: equality.

using AlgConGE = AlgebraicConstraint<AlgConBody, AlgConRhs<1>>

Resulting constraint type: GE.

Public Functions

inline RangeConstraintConverter(ModelConverter &mc)

Constructor.

inline void Convert(const ItemType &item, int i)

Conversion.

Responsible for adding presolve links

Parameters
  • item – the item to be converted

  • i – item index, used to create a presolve link

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

Protected Types

using RangeRelations = std::array<bool, 3>
using SlackLink = pre::RangeLinCon2Slack<ModelConverter>

Protected Functions

inline RangeRelations Relate(double lb, double ub)
inline void ConvertRange(const ItemType &item, int i)
inline void ConvertWithRhs(const ItemType &item, RangeRelations rr)
inline SlackLink &GetSlackLink()
inline const ModelConverter &GetMC() const

Access const ModelConverter.

inline ModelConverter &GetMC()

Access ModelConverter.

Private Members

class mp::internal::ReaderBase
#include <nl-reader.h>

Subclassed by mp::internal::BinaryReaderBase, mp::internal::TextReader< Locale >

Public Functions

ReaderBase(NLStringRef data, fmt::CStringRef name)
inline char ReadChar()
inline const char *ptr() const
inline void set_ptr(const char *ptr)
inline bool IsEOF(const char *ptr) const
inline bool IsEOF() const

Protected Functions

inline ~ReaderBase()

Protected Attributes

const char *ptr_
const char *start_
const char *end_
const char *token_
std::string name_
class mp::ReadError : public mp::Error
#include <nl-reader.h>

A read error with location information.

Public Functions

inline ReadError(fmt::CStringRef filename, int line, int column, fmt::CStringRef format_str, fmt::ArgList args)

Constructs the exception object.

inline ~ReadError()

Destructs the exception object.

inline const std::string &filename() const

Returns the name of the file where error occurred.

inline int line() const

Returns the line number where error occurred, starting from 1.

inline int column() const

Returns the column number where error occurred, starting from 1.

inline int exit_code() const

The exit code.

Protected Functions

inline void SetMessage(const std::string &message)
inline void init(fmt::CStringRef format_str, fmt::ArgList args)

Private Functions

void init(fmt::CStringRef filename, int line, int column, fmt::CStringRef format_str, fmt::ArgList args)

Private Members

std::string filename_
int line_
int column_
class mp::Reference : public mp::BasicExpr<expr::FIRST_REFERENCE, expr::LAST_REFERENCE>
#include <expr.h>

A reference to a variable or a common expression.

Example: x

Public Types

enum [anonymous]

Values:

Public Functions

inline int index() const

Returns the index of the referenced object.

Protected Types

typedef ExprBase::Impl Impl

Reuse ExprBase::Impl.

typedef BasicExpr Base

Base = BasicExpr.

Private Functions

MP_EXPR(Base)
class mp::SolveResultRegistry::RegEntry
#include <solver-base.h>

Registry entry.

This is a pair<int, int>, meaning a range (first-last) of result codes. Plus a description.

Public Functions

inline RegEntry(int a, int b, std::string d)

Construct from a range.

inline RegEntry(int a, std::string d)

Construct from a single code.

inline bool isSingle() const

Is signle code?

inline int first() const

First.

inline int last() const

Last.

inline const std::string &descr() const

Descr.

inline bool operator<(const RegEntry &k) const

operator<: We need range 100-199 to come before range 100-149 before single code 100, etc.

Private Members

int first_
int last_
std::string descr_
template<class ModelConverter>
class mp::RQConeConverter : public mp::BasicFuncConstrCvt<RQConeConverter<ModelConverter>, ModelConverter>
#include <qcones2qc.h>

Converts RQCone.

Public Types

using Base = BasicFuncConstrCvt<RQConeConverter<ModelConverter>, ModelConverter>

Base class.

using ItemType = RotatedQuadraticConeConstraint

Converted item type.

Public Functions

inline RQConeConverter(ModelConverter &mc)

Constructor.

inline bool IfNeedsConversion(const ItemType&, int)

Check whether the constraint needs to be converted despite being accepted by ModelAPI.

inline void Convert(const ItemType &ac, int)

Convert to 2(c[0]*x[0]*c[1]*x[1]) >= sum(i>=2)((c[i]*x[i])^2).

inline void Convert(const ItemType &item, int i)

Generic Convert(), distinguishes context & result variable.

Distinguish positive and negative context because if only one of these is necessary, significant model reduction can be achieved in certain cases.

Responsible for adding presolve links, if any

The Impl can reimplement this

Parameters
  • item – the item to be converted

  • i – item index, used to create a presolve link

inline void ConvertCtxNeg(const ItemType &item, int)

Convert in negative context.

inline void ConvertCtxPos(const ItemType &item, int)

Convert in positive context.

inline const ModelConverter &GetMC() const

Reuse the stored ModelConverter.

inline ModelConverter &GetMC()

Reuse the stored ModelConverter.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

template<typename T>
class mp::SafeInt
#include <safeint.h>

Public Functions

inline SafeInt(T value)
template<typename U>
inline explicit SafeInt(U value)

Private Members

T value_

Friends

inline friend T val(SafeInt<T> n)
struct mp::SensRanges
#include <backend-mip.h>

Sensitivity ranges (postsolved)

Public Members

std::vector<double> varlblo
std::vector<double> varlbhi
std::vector<double> varublo
std::vector<double> varubhi
std::vector<double> varobjlo
std::vector<double> varobjhi
std::vector<double> conrhslo
std::vector<double> conrhshi
std::vector<double> conlblo
std::vector<double> conlbhi
std::vector<double> conublo
std::vector<double> conubhi
struct mp::SensRangesPresolved
#include <backend_flat.h>

Store presolved sensitivities.

Public Members

pre::ModelValuesDbl varlblo
pre::ModelValuesDbl varlbhi
pre::ModelValuesDbl varublo
pre::ModelValuesDbl varubhi
pre::ModelValuesDbl varobjlo
pre::ModelValuesDbl varobjhi
pre::ModelValuesDbl conrhslo
pre::ModelValuesDbl conrhshi
pre::ModelValuesDbl conlblo
pre::ModelValuesDbl conlbhi
pre::ModelValuesDbl conublo
pre::ModelValuesDbl conubhi
class mp::internal::SignalHandler : public mp::Interrupter
#include <solver-app-base.h>

Public Functions

explicit SignalHandler(BasicSolver &s)
~SignalHandler()
inline virtual bool Stop() const

Returns true if the solution process should be stopped.

virtual void SetHandler(InterruptHandler handler, void *data)

Sets a handler function.

The handler function must be safe to call from a signal handler. In particular, it must only call async-signal-safe library functions.

Private Members

BasicSolver &solver_
std::string message_
SignalRepeater repeater_

Private Static Functions

static void HandleSigInt(int sig)

Private Static Attributes

static std::sig_atomic_t stop_
static atomic<const char*> signal_message_ptr_
static atomic<unsigned> signal_message_size_
static atomic<InterruptHandler> handler_
static atomic<void*> data_
struct mp::internal::SignalRepeater
#include <solver-app-base.h>

Public Functions

inline explicit SignalRepeater(const char*)
template<class Index, class Value>
class mp::NLWriter2::SingleSparseVecWrtFactory
#include <nl-writer2.h>

Single sparse vector writer factory.

Can be used once to produce a SparseVectorWriter. At first it writes the number of nonzeros using the given format string.

Public Functions

inline SingleSparseVecWrtFactory(NLWriter2 &nlw, const char *fmt)

Construct.

Parameters

fmt – format string for printf()

containing d for the number of sparse elements and finishing with ‘

’, e.g., “x%d\t# initial guess\n”

inline SingleSparseVecWrtFactory(NLWriter2 &nlw, std::function<void(int)> hdr_prn)

Construct.

More general.

Parameters

hdr_prn – a lambda printing something given N nonzeros.

inline SparseVectorWriter<Index, Value> MakeVectorWriter(size_t nnz)

Create a vector writer.

Private Members

NLWriter2 &nlw_
const char *fmt_ = nullptr
std::function<void(int)> hdr_prn_
int nInst_ = 0
struct mp::SolCheck
#include <constr_keeper.h>

Solution check data.

Public Functions

inline SolCheck(ArrayRef<double> x, const pre::ValueMapDbl&, ArrayRef<double> obj, ArrayRef<double> x_raw, ArrayRef<var::Type> vtype, ArrayRef<double> lb, ArrayRef<double> ub, double feastol, double feastolrel, int sol_rnd, int sol_prec, bool recomp_vals, int chk_mode)

Construct.

Parameters

chk_mode – can be subset of 1+2+4+8+16

inline bool HasAnyViols() const

Any violations?

inline bool HasAnyConViols() const

Any constraint violations?

inline bool HasAnyObjViols() const

Any objective value violations?

inline const std::string &GetReport() const

Summary.

inline const VarInfoStatic &x_ext() const

VarInfo, can be used like x() for templates.

inline double x(int i) const

x[i]

inline const ArrayRef<double> &obj_vals() const

objective values

inline double GetFeasTol() const

Absolute feasibility tolerance.

inline double GetFeasTolRel() const

Relative feasibility tolerance.

inline bool if_recomputed() const

Using recomputed aux vars?

inline int check_mode() const

Check mode.

inline ViolSummArray<2> &VarViolBnds()

Var bnd violations.

inline ViolSummArray<2> &VarViolIntty()

Var int-ty violations.

inline std::map<std::string, ViolSummArray<3>> &ConViolAlg()

Constraints: algebraic.

Map by constraint type. Values: for original, intermediate, and solver-side constraints.

inline std::map<std::string, ViolSummArray<3>> &ConViolLog()

Constraints: logical.

inline ViolSummary &ObjViols()

Obj viols.

inline void SetReport(std::string rep)

Set report.

Private Members

VarInfoStatic x_
ArrayRef<double> obj_
double feastol_
double feastolrel_
bool fRecomputedVals_
int check_mode_
std::string report_
ViolSummArray<2> viol_var_bnds_

Variable bounds: orig, aux.

ViolSummArray<2> viol_var_int_

Variable integrality: orig, aux.

std::map<std::string, ViolSummArray<3>> viol_cons_alg_

Constraints: algebraic.

std::map<std::string, ViolSummArray<3>> viol_cons_log_

Constraints: logical.

ViolSummary viol_obj_

Objectives.

class mp::SolFileWriter
#include <solver-io.h>

The default .sol file writer.

Subclassed by mp::SolutionWriterImpl< Solver, ProblemBuilder, SolFileWriter >, mp::SolutionWriterImpl< Solver, ProblemBuilder, Writer >

Public Functions

template<typename Solution>
inline void Write(fmt::CStringRef filename, const Solution &sol)
class mp::SOLHandler
#include <sol-handler.h>

SOLHandler: reads solution details on request via provided callback objects. See the examples folder.

SOLHandler can be used as a base class for other handlers, or just be an interface prototype.

Subclassed by ExampleSOLHandler, mp::NLW2_SOLHandler_C_Impl, mp::SOLHandler_Easy

Public Functions

inline NLHeader Header() const

The NLHeader used to write the NL file.

inline void OnSolveMessage(const char *s, int nbs)

Receive solve message.

The message always ends with ‘

’.

Parameters

nbs – number of backspaces in the original solve message. So many characters should be skipped from the message if printed straightaway. AMPL solver drivers can supply the message with initial backspaces to indicate that so many characters should be skipped when printing. For example, if the driver prints MINOS 5.51: and exits, and the message starts with that again, this part should be skipped.

inline int OnAMPLOptions(const AMPLOptions&)

Can be ignored by external systems.

Returns

non-zero to stop solution input.

template<class VecReader>
inline void OnDualSolution(VecReader &rd)

Dual values for algebraic constraints, if provided in the solution.

Number of values <= NumAlgCons(). Implementation:

duals.reserve(rd.Size()); while (rd.Size()) duals.push_back(rd.ReadNext());

template<class VecReader>
inline void OnPrimalSolution(VecReader &rd)

Variable values, if provided.

Number of values <= NumVars().

inline void OnObjno(int)

Receive notification of the objective index used by the driver (solver option ‘objno’-1).

inline void OnSolveCode(int)

Receive notification of the solve code.

Solve result codes docu: https://mp.ampl.com/features-guide.html#solve-result-codes

template<class SuffixReader>
inline void OnIntSuffix(SuffixReader &sr)

OnIntSuffix().

For constraints, can include values for logical constraints (after algebraic.) Sparse representation - can be empty (i.e., all values zero.)

const auto& si = sr.SufInfo(); int kind = si.Kind(); int nmax = nitems_max[kind & 3]; const std::string& name = si.Name(); const std::string& table = si.Table(); while (sr.Size()) { std::pair<int, int> val = sr.ReadNext(); if (val.first<0 || val.first>=nmax) { sr.SetError(NLW2_SOLRead_Bad_Suffix, “bad suffix element index”); return; } suf[val.first] = val.second; } if (NLW2_SOLRead_OK == sr.ReadResult()) // Can check RegisterSuffix(kind, name, table, suf);

template<class SuffixReader>
inline void OnDblSuffix(SuffixReader &sr)

Same as OnIntSuffix(), but sr.ReadNext() returns pair<int, double>

class mp::SOLHandler_Easy : public mp::SOLHandler

Specialize SOLHandler for NLModel.

Public Functions

inline SOLHandler_Easy(const NLHeader &h, const NLModel::PreprocessData &pd, NLSolution &sol)

Construct.

inline NLHeader Header() const

The NLHeader used to write the NL file.

inline void OnSolveMessage(const char *s, int nbs)

Receive solve message.

The message always ends with ‘

’.

Parameters

nbs – number of backspaces in the original solve message. So many characters should be skipped from the message if printed straightaway. AMPL solver drivers can supply the message with initial backspaces to indicate that so many characters should be skipped when printing. For example, if the driver prints MINOS 5.51: and exits, and the message starts with that again, this part should be skipped.

template<class VecReader>
inline void OnDualSolution(VecReader &rd)

Dual values for algebraic constraints, if provided in the solution.

Number of values <= NumAlgCons(). Implementation:

duals.reserve(rd.Size()); while (rd.Size()) duals.push_back(rd.ReadNext());

template<class VecReader>
inline void OnPrimalSolution(VecReader &rd)

Variable values, if provided.

Number of values <= NumVars().

inline void OnSolveCode(int c)

Receive notification of the solve code.

Solve result codes docu: https://mp.ampl.com/features-guide.html#solve-result-codes

template<class SuffixReader>
inline void OnIntSuffix(SuffixReader &sr)

OnIntSuffix().

For constraints, can include values for logical constraints (after algebraic.) Sparse representation - can be empty (i.e., all values zero.)

const auto& si = sr.SufInfo(); int kind = si.Kind(); int nmax = nitems_max[kind & 3]; const std::string& name = si.Name(); const std::string& table = si.Table(); while (sr.Size()) { std::pair<int, int> val = sr.ReadNext(); if (val.first<0 || val.first>=nmax) { sr.SetError(mp::SOL_Read_Bad_Suffix, “bad suffix element index”); return; } suf[val.first] = val.second; } if (mp::SOL_Read_OK == sr.ReadResult()) // Can check RegisterSuffix(kind, name, table, suf);

template<class SuffixReader>
inline void OnDblSuffix(SuffixReader &sr)

Same as OnIntSuffix(), but sr.ReadNext() returns pair<int, double>

inline int OnAMPLOptions(const AMPLOptions&)

Can be ignored by external systems.

Returns

non-zero to stop solution input.

inline void OnObjno(int)

Receive notification of the objective index used by the driver (solver option ‘objno’-1).

Protected Functions

inline int NItemsMax(int kind) const
template<class SuffixReader>
inline void OnSuffix(SuffixReader &sr)

Private Members

NLHeader header_
const NLModel::PreprocessData &pd_
NLSolution &sol_
template<typename SOLHandler>
class mp::SOLReader2
#include <sol-reader2.h>

SOL reader.

AMPL SOL is a format for representing solutions of optimization problems such as linear, quadratic, nonlinear, complementarity and constraint programming problems in discrete or continuous variables, used by AMPL. It is not documented yet.

Usage: recommended via mp::NLSOL class. If you need to read solutions separately, proceed as follows:

MySOLHandler handler; mp::NLUtils utils;

auto status = ReadSOLFile(name, handler, utils); if (status.first) { printf(“Error: %s\n”, status.second.c_str()); exit(EXIT_FAILURE); }

Parameters

SOLHandler – class that receives information on solution components.

Public Functions

inline SOLReader2(SOLHandler &sh, NLUtils &utl)

Constructor.

NLW2_SOLReadResultCode ReadSOLFile(const std::string &name)

Read .sol file.

Some refurbished old code.

inline const std::string &ErrorMessage(NLW2_SOLReadResultCode) const

Error message, if any.

Warnings are printed independently via NLUtils::log_warning().

inline int internal_rv() const

Internal AMPL result code.

Protected Types

using Long = int
using uLong = unsigned int
using uiolen = uLong

cfront screws up when we use typedef Long uiolen;

It renders Long as long rather than Long.

using real = double
typedef uLong integer

Protected Functions

inline const SOLHandler &Handler() const

Get const handler&.

inline SOLHandler &Handler()

Get handler&.

inline const NLUtils &Utils() const

Get const utils&.

inline NLUtils &Utils()

Get utils&.

inline const NLHeader &Header() const

Get const NLHeader&.

inline int NumVars() const

NumVars.

inline int NumAlgCons() const

NumAlgCons.

inline int NumLogCons() const

NumLogCons.

template<class Reader>
inline bool CheckReader(const Reader &rd, NLW2_SOLReadResultCode &rr)

Check result of a [vector] reader.

NLW2_SOLReadResultCode bsufread(FILE *f)

Read suffixes, binary.

NLW2_SOLReadResultCode gsufread(FILE *f)

Read suffixes, text.

int sufheadcheck(SufRead *sr)

Suffix head check.

NLW2_SOLReadResultCode ReportEarlyEof()

Report Early Eof.

NLW2_SOLReadResultCode ReportBadFormat()

Report bad format.

NLW2_SOLReadResultCode ReportBadLine(const std::string &line)

Report bad line.

void serror(const char *format, ...)

Save error message.

Private Members

SOLHandler &solh_
NLUtils &utils_
NLHeader hdr_
std::string solve_msg_
std::string err_msg_
int internal_rv_ = {0}
NLW2_SOLReadResultCode readresult_ = {NLW2_SOLRead_Result_Not_Set}
const char *stub_ = {nullptr}
const char *bkind[2] = {"ASCII", "binary"}
char *b1
char buf[512]
char *from_solve
char *s
char *se
Long Objno[2] = {-2, -2}
Long nOpts
Long Lt
Long Options[14]
Long *z
uiolen L
uiolen L1
uiolen L2
int binary
int bs
int c
int have_options
int hs
int i
int j
int j1
int je
int need_vbtol
int newsufs
int nsv
int objno = -2
int presolved
int rv
int slin
int solmsg
double vbtol
double x
size_t len
size_t n
size_t n1
size_t nbs
size_t ui
int ndebug
int sstatus_seen
struct mp::Solution
#include <backend-std.h>

Solution (postsolved)

Public Members

std::vector<double> primal

primal

std::vector<double> dual

dual

std::vector<double> objvals

objective values

ArrayRef<int> spars_primal

Sparsity, if solver wants it.

template<typename ProblemBuilder>
class mp::SolutionAdapter
#include <solver-io.h>

Adapts a solution for WriteSol.

Public Functions

inline SolutionAdapter(int status, ProblemBuilder *pb, const char *message, mp::ArrayRef<long> options, mp::ArrayRef<double> values, mp::ArrayRef<double> dual_values, int on)
inline int status() const
inline const char *message() const
inline int num_options() const
inline long option(int index) const
inline int num_values() const
inline double value(int index) const
inline int num_dual_values() const
inline double dual_value(int index) const
inline int objno() const
inline int num_vars() const
inline int num_algebraic_cons() const
inline const ProblemBuilder::SuffixSet *suffixes(suf::Kind kind) const

Private Members

int status_
ProblemBuilder *builder_
const char *message_
mp::ArrayRef<long> options_
mp::ArrayRef<double> values_
mp::ArrayRef<double> dual_values_
int objno_
struct mp::SolutionBasis
#include <backend-mip.h>

Basis status values of a solution (postsolved)

Public Functions

inline operator bool() const

Check if has both vars and cons’ statuses.

Public Members

std::vector<int> varstt

Var and con statuses.

std::vector<int> constt
template<class Impl>
class mp::SolutionChecker
#include <sol_check.h>

A mix-in base class for solution checking.

Subclassed by mp::FlatConverter< Impl, ModelAPI, FlatModel< > >, mp::FlatConverter< Impl, ModelAPI, FlatModel >

Public Functions

inline bool CheckSolution(ArrayRef<double> x, const pre::ValueMapDbl &duals, ArrayRef<double> obj, void *p_extra)

Check postsolved & unpostsolved solutions in various ways.

Parameters

p_extra – !=0 means known infeas solution

inline ArrayRef<double> RecomputeAuxVars(ArrayRef<double> x)

Recompute auxiliary variables.

inline std::string DoCheckSol(ArrayRef<double> x, const pre::ValueMapDbl &duals, ArrayRef<double> obj, ArrayRef<double> x_raw, std::vector<double> &x_back, bool if_recomp_vals)

Check single unpostsolved solution.

Parameters

x_back – solution vector from realistic mode. It can be changed by the :round and :prec options. Its auxiliary vars are compared with recomputed expression values.

inline void CheckVars(SolCheck &chk)
inline void CheckCons(SolCheck &chk)

Includes logical constraints.

inline void CheckObjs(SolCheck &chk)
inline void GenerateViolationsReport(SolCheck &chk, bool)
inline void Gen1Viol(const ViolSummary &vs, fmt::MemoryWriter &wrt, bool f_max, const std::string &type)

Generate message about 1 violation.

Parameters

f_max – whether we need to print the maximal violations.

inline std::string Gen1ViolMax(bool f_max, double viol, const char *nm)

Stringify 1 maximal violation.

inline void GenConViol(const std::map<std::string, ViolSummArray<3>> &cvmap, fmt::MemoryWriter &wrt, int alg_log)

std::string classnm = alg_log ? “Logical” : “Algebraic”; wrt.write(classnm + ” expression violations:\n”);

Public Members

VarsRecomputeFn recomp_fn = [this](int i, const VarInfoRecomp& x) {if (MPCD( HasInitExpression(i) )) {const auto& iexpr =MPCD( GetInitExpression(i) );auto pCK = iexpr.GetCK();if (!pCK->IsUnused(iexpr.GetIndex()))return pCK->ComputeValue(iexpr.GetIndex(), x);}return x.get_x().get_x()[i];}

Functor to recompute auxiliary var i.

class mp::SolutionHandler
#include <solver-base.h>

An interface for receiving solutions.

Subclassed by mp::SolutionWriterImpl< Solver, ProblemBuilder, SolFileWriter >, mp::BasicSolutionHandler, mp::SolutionWriterImpl< Solver, ProblemBuilder, Writer >

Public Functions

inline virtual ~SolutionHandler()
virtual void HandleFeasibleSolution(int solve_code, fmt::CStringRef message, const double *values, const double *dual_values, double obj_value) = 0

Receives a feasible solution.

inline virtual void HandleFeasibleSolution(fmt::CStringRef message, const double *values, const double *dual_values, double obj_value)

Receives a feasible solution, no solve code.

Deprecated.

virtual void HandleSolution(int status, fmt::CStringRef message, const double *values, const double *dual_values, double obj_value) = 0

Receives the final solution or a notification that the problem is infeasible or unbounded.

inline virtual void OverrideSolutionFileName(const std::string&)

Override solution output file stub.

template<typename Solver, typename ProblemBuilder, typename Writer = SolFileWriter>
class mp::SolutionWriterImpl : private mp::SolFileWriter, public mp::SolutionHandler
#include <solver-io.h>

A solution writer.

Parameters
  • Solver – optimization solver class

  • ProblemBuilder – suffix handler

  • Writer – .sol writer

Public Functions

inline SolutionWriterImpl(fmt::StringRef stub, Solver &s, ProblemBuilder &b, ArrayRef<long> options = mp::ArrayRef<long>(0, 0))
inline Writer &sol_writer()

Returns the .sol writer.

virtual void HandleFeasibleSolution(int status, fmt::CStringRef message, const double *values, const double *dual_values, double)

Writes an intermediate solution to a .sol file.

inline virtual void HandleFeasibleSolution(fmt::CStringRef message, const double *values, const double *dual_values, double obj)

Deprecated: no status.

virtual void HandleSolution(int status, fmt::CStringRef message, const double *values, const double *dual_values, double)

Writes the solution to a .sol file.

inline virtual void OverrideSolutionFileName(const std::string &fileName)

Override solution output file stub.

Protected Functions

inline Solver &solver()
inline ProblemBuilder &builder()
inline const std::string &stub() const

Private Members

std::string stub_
std::string overrideStub_
Solver &solver_
ProblemBuilder &builder_
ArrayRef<long> options_
int num_solutions_

The number of feasible solutions found.

class mp::Solver : public mp::BasicSolver
#include <solver.h>

DEPRECATED.

An old base class for solver drivers.

Subclassed by mp::SolverImpl< ProblemBuilderT >

Public Types

typedef std::vector<SuffixInfo> SuffixList
enum [anonymous]

Possible values for the wantsol option (can be combined with bitwise OR).

Values:

enumerator WRITE_SOL_FILE
enumerator PRINT_SOLUTION
enumerator PRINT_DUAL_SOLUTION
enumerator SUPPRESS_SOLVER_MSG
enum [anonymous]

The default precision used in FormatObjValue if the objective_precision env variable is not specified or 0.

Values:

enumerator DEFAULT_PRECISION
enum [anonymous]

Solver flags.

Values:

enumerator MULTIPLE_SOL

Multiple solutions support.

Makes Solver register “countsolutions” and “solutionstub” options and write every solution passed to HandleFeastibleSolution to a file solutionstub & i & “.sol” where i is a solution number.

enumerator MULTIPLE_OBJ

Multiple objectives support.

Makes Solver register the “multiobj” option

using WarningsMap = std::map<std::string, std::pair<int, std::string>>

Map to count warnings by types.

Stores just 1 message for each type.

enum [anonymous]

Flags for ParseOptions.

Values:

enumerator NO_OPTION_ECHO

Don’t echo options during parsing.

enumerator FROM_COMMAND_LINE

When options are passed from command line (not via environment var) the quotes are automatically removed and the input string split in substrings (accessible via argv)

typedef std::unique_ptr<SolverOption> OptionPtr

Smart ptr to an option.

using set_option_iterator = option_iterator_base<OptionSet::iterator>

Alias for writeable option iterator.

using option_iterator = option_iterator_base<OptionSet::const_iterator>

Alias for const option iterator.

using SRRegMap = std::set<RegEntry>

Registry map.

Public Functions

inline Solver(fmt::CStringRef name, fmt::CStringRef long_name, long date, int flags)

Constructs a Solver object.

date: The solver date in YYYYMMDD format. flags: Bitwise OR of zero or more of the following values MULTIPLE_SOL MULTIPLE_OBJ

inline void AddSuffix(const char *name, const char *table, int kind, int nextra = 0)

Adds a suffix.

inline const SuffixList &suffixes() const
inline std::string GetOptionFile(const SolverOption&) const

Name of the file with option settings, provided by tech:optionfile.

void UseOptionFile(const SolverOption&, fmt::StringRef value)

Read otpions from option file.

inline int GetWantSol(const SolverOption&) const

wantsol value

inline void SetWantSol(const SolverOption&, int value)

set wantsol

inline std::string GetSolutionStub(const SolverOption&) const

solution output filename stub

inline void SetSolutionStub(const SolverOption&, fmt::StringRef value)

Set sol stub.

inline int GetObjNo(const SolverOption&) const

Obj number.

inline void SetObjNo(const SolverOption &opt, int value)

Set obj number.

inline int GetTiming(const SolverOption&) const
inline void SetTiming(const SolverOption &opt, int value)
inline const char *name() const

Returns the solver name.

This is used to extract solver options from the env variable (solver_name)_options.

inline const char *long_name() const

Returns the long solver name.

This name is used in startup “banner”.

inline const char *exe_path() const

Returns the executable path.

inline void set_exe_path(const char *p)
inline const char *version() const

Returns the solver version.

inline long date() const

Returns the solver date in YYYYMMDD format.

inline int wantsol() const

Returns the value of the wantsol option which specifies what solution information to write in a stand-alone invocation (no -AMPL on the command line).

inline void set_wantsol(int value)
inline bool ampl_flag()
inline void set_ampl_flag(bool value = true)
inline bool verbose_mode() const

True if verbose mode.

Should be set by the implementation, otherwise it’s true

inline void set_verbose_mode(bool f)

Set verbosity, by the impl.

inline bool debug_mode() const

True if need to debug.

Outputs test infos etc

inline int objno_used() const

Returns the index of the objective to optimize starting from 1, 0 to not use objective.

inline int objno_specified() const

objno_specified(): actually even if not specified, it returns the objno to use (0 - feasibility, otherwise obj index).

Both multiobj() and objno_specified() are used in NLReader to select the objective(s), solvers should not use these accessors.

inline bool is_objno_specified() const

Whether user specified the option objno.

inline void notify_obj_added()

Notify Solver if an objective is added.

inline void notify_start_opts()

Notify Solver we start reading options.

inline void notify_end_opts()

Notify we are done.

inline bool multiobj() const

Returns true if multiobjective optimization is enabled.

Both multiobj and objno are used in NLReader to select the objective(s), solvers should not use these options.

inline int timing() const

>0 if the timing is enabled

inline ErrorHandler *error_handler()

Return error handler.

inline void set_error_handler(ErrorHandler *eh)

Set the error handler.

inline OutputHandler *output_handler()

Return output handler.

inline OutputHandler &get_output_handler()

Return output handler.

inline void set_output_handler(OutputHandler *oh)

Sets the output handler.

inline const Interrupter *interrupter() const

Interrupter, const.

inline Interrupter *interrupter()

Interrupter.

inline void set_interrupter(Interrupter *interrupter)

Set interrupter.

inline const char *solution_stub() const

Sol stub as char*.

inline bool need_multiple_solutions() const

Need mutiple solutions.

inline virtual void HandleOutput(fmt::CStringRef output) override

Override methods from base service classes.

inline virtual void HandleError(fmt::CStringRef message) override

Handle error.

inline virtual bool Stop() const override

The default implementation of Interrupter does nothing.

inline virtual void SetHandler(InterruptHandler, void*) override

Set interrupt handler.

inline virtual void HandleUnknownOption(const char *name)

Handle unknown option.

inline void ReportError(fmt::CStringRef format, const fmt::ArgList &args)

Reports an error by throwing it.

Usage: ReportError(“File not found: {}”) << filename;

inline void Print(fmt::CStringRef format, const fmt::ArgList &args)

Variadic overload of ReportError()

Formats a string and prints it to stdout or, if an output handler is registered, sends it to the output handler.

const char *GetSolCheckWarningKey(bool f_recomp) const

Variadic overload of Print()

Get solution check warnings key name.

Parameters

f_recomp – whether with recomputed auxiliaries.

void AddWarning(std::string key, std::string msg, bool replace = false)

Add a warning.

Parameters
  • key – warning category

  • msg – detailed message

const std::pair<int, std::string> &GetWarning(const std::string &key)

Get a warning type.

void ClearWarning(const std::string &key)

Clear a warning type.

std::string GetWarnings() const

Get warnings as string.

void PrintWarnings()

Print warnings.

bool ShowVersion()

Prints version information.

DoubleFormatter FormatObjValue(double value)

Returns a formatter that writes value using objective precision.

Usage: Print(“objective {}”, FormatObjValue(obj_value));

virtual bool ParseOptions(char **argv, unsigned flags = 0, const ASLProblem *p = 0)

Parses solver options from the (solver)_options env variable and/or strings in argv.

For example, solver_options=’timelim=300’ solver /tmp/diet.nl -AMPL “basis=0”.

Returns

true if there were no errors and false otherwise. It accepts a pointer to the problem because some options may depend on problem features.

void ParseOptionString(const char *s, unsigned flags)

Parses a solver option string.

inline const WarningsMap &GetWarningsMap() const

Get warnings map.

inline WarningsMap &GetWarningsMap()
inline void SetConstraintListHeader(std::string clh)

Set constraint list header (printed at the start of -c)

inline void AddConstraintDescr(std::string cn, std::string cdescr)

Add constraint type description.

bool ShowConstraintDescriptions()

Show constraint descriptions.

inline virtual void RecordOutputTime()
inline virtual void RecordSetupTime()

Record setup time.

inline void SetReadTime(double read_time)
inline void SetConversionTime(double conv_time)
inline virtual void RecordSolveTime()

Record solve time.

inline int num_options() const

Returns the number of options.

inline SolverOption *GetOption(const char *name) const

Returns the option with specified name.

inline void set_option_header(const char *header)

Sets a text to be displayed before option descriptions.

inline void add_to_option_header(const char *header_more)

Add more text to be displayed before option descriptions.

void AddOption(OptionPtr opt)

Add an option.

template<class Value>
inline void AddOption(const char *name, const char *description, Value &value, Value lb, Value ub)

Same: stored option referencing a variable; min, max values.

Note

description “HIDDEN” means the option is not printed

SolverOption *FindOption(const char *name, bool wildcardvalues = false) const

Finds an option and returns a pointer to it if found or null otherwise.

If wildcardvalues==true, wildcarded options should have values (i.e., parsing real input)

inline const char *option_header() const

Returns the option header.

inline fmt::LongLong GetIntOption(const char *name) const

Returns the value of an integer option.

Throws OptionError if there is no such option or it has a different type.

inline void SetIntOption(const char *name, fmt::LongLong value)
inline double GetDblOption(const char *name) const
inline void SetDblOption(const char *name, double value)
inline std::string GetStrOption(const char *name) const
inline void SetStrOption(const char *name, fmt::StringRef value)
template<class Value>
inline void AddStoredOption(const char *name, const char *description, Value &value, ValueArrayRef values = ValueArrayRef())

Simple stored option referencing a variable.

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddStoredOption(const char *name, const char *description, Value &value, Value, Value)

Simple stored option referencing a variable; min, max values (they are unused but to deduce type; we are too lazy to maintain correct min/max between solver versions.)

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddListOption(const char *name, const char *description, Value &value, ValueArrayRef values = ValueArrayRef())

Add list option referencing a container.

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddListOption(const char *name, const char *description, Value &value, typename Value::value_type, typename Value::value_type)

Add list option referencing a container; min, max values (they are unused but to deduce type; we aree too lazy to maintain correct min/max between solver versions.)

Note

description “HIDDEN” means the option is not printed

inline void ReplaceOptionDescription(const char *name, const char *desc)

Replace option descr.

inline void AddToOptionDescription(const char *name, const char *desc_add)

Add to option descr.

void AddOptionSynonyms_Inline_Front(const char *names_list, const char *realName)

Add “inline” option synonyms.

The _Front version puts them in the front of the synonyms list and the 1st of them is used in the -a output for sorting.

void AddOptionSynonyms_Inline_Back(const char *names_list, const char *realName)

Add “inline” option synonyms.

The _Back version.

void AddOptionSynonyms_OutOfLine(const char *name, const char *realName)

Add an “out-of-line” synonym.

Creates extra entry under -=

template<typename Handler, typename Int>
inline void AddIntOption(const char *name, const char *description, Int (Handler::* get)(const SolverOption&) const, void (Handler::* set)(const SolverOption&, Int))

Adds an integer option.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddIntOption(const char *name, const char *description, int (Handler::* get)(const SolverOption&, const Info&) const, void (Handler::* set)(const SolverOption&, int, const Info&), const Info &info)

Adds an integer option with additional information.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddIntOption(const char *name_list, const char *description, int (Handler::* get)(const SolverOption&, Info) const, void (Handler::* set)(const SolverOption&, int, Info), Info info)

The same as above but with Info argument passed by value.

Note

description “HIDDEN” means the option is not printed

template<typename Handler>
inline void AddDblOption(const char *name, const char *description, double (Handler::* get)(const SolverOption&) const, void (Handler::* set)(const SolverOption&, double))

Adds a double option.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddDblOption(const char *name, const char *description, double (Handler::* get)(const SolverOption&, const Info&) const, void (Handler::* set)(const SolverOption&, double, const Info&), const Info &info)

Adds a double option with additional information.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddDblOption(const char *name, const char *description, double (Handler::* get)(const SolverOption&, Info) const, void (Handler::* set)(const SolverOption&, double, Info), Info info)

The same as above but with Info argument passed by value.

Note

description “HIDDEN” means the option is not printed

template<typename Handler>
inline void AddStrOption(const char *name, const char *description, std::string (Handler::* get)(const SolverOption&) const, void (Handler::* set)(const SolverOption&, fmt::StringRef), ValueArrayRef values = ValueArrayRef())

Adds a string option.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddStrOption(const char *name, const char *description, std::string (Handler::* get)(const SolverOption&, const Info&) const, void (Handler::* set)(const SolverOption&, fmt::StringRef, const Info&), const Info &info, ValueArrayRef values = ValueArrayRef())

Adds a string option with additional information.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddStrOption(const char *name, const char *description, std::string (Handler::* get)(const SolverOption&, Info) const, void (Handler::* set)(const SolverOption&, fmt::StringRef, Info), Info info, ValueArrayRef values = ValueArrayRef())

The same as above but with Info argument passed by value.

Note

description “HIDDEN” means the option is not printed

inline option_iterator option_begin() const

Get the start const-iterator.

inline option_iterator option_end() const

Get the end const-iterator.

inline set_option_iterator set_option_begin() const

Get the start writeable iterator.

inline set_option_iterator set_option_end() const

Get the end writeable iterator.

void AddSolveResults(const SRRegMap &sm, bool ifCanReplace = false)

Add a map with result descriptions.

inline const SRRegMap &GetSolveResultRegistry() const

Get the registry.

Public Static Functions

static std::string ToString(const WarningsMap::value_type &wrn)

Stringify a WarningsMap entry.

Protected Functions

void InitMetaInfoAndOptions(fmt::CStringRef name, fmt::CStringRef long_name, long date, int flags)

InitMetaInfoAndOptions.

Derived classes which want to provide the info after construction can use the default constructor and call this.

Parameters
  • date – The solver date in YYYYMMDD format.

  • flags – Bitwise OR of zero or more of the following values MULTIPLE_SOL MULTIPLE_OBJ

inline void set_long_name(fmt::StringRef name)
inline void add_to_long_name(fmt::StringRef name)
inline void set_version(fmt::StringRef version)
inline void add_to_version(fmt::StringRef version)
inline void set_license_info(fmt::StringRef license_info)
inline virtual std::string set_external_libs()
inline void set_read_flags(unsigned flags)

Sets the flags for Problem::Read.

inline Stats &stats()

Private Members

SuffixList suffixes_
template<typename Solver, typename Reader = internal::NLFileReader<>>
class mp::SolverApp : private mp::internal::NLFileReader<>
#include <solver-app.h>

DEPRECATED.

A solver application with built-in NL file input. Solver: optimization solver class; normally a subclass of SolverImpl Reader: .nl reader

Public Functions

inline SolverApp()
inline OptionList &options()
inline Solver &solver()
inline Reader &reader()
inline CCallbacks &GetCallbacks()
int Run(char **argv, int nl_reader_flags = 0)

Protected Functions

inline int GetResultCode() const
inline Solver &GetSolver()
inline ProblemBuilder &GetProblemBuilder()
bool Init(char **argv, int nl_reader_flags)
void ReadNL(int nl_reader_flags)
void Solve()
void Resolve()

Methods for incremental interface.

Protected Attributes

CCallbacks callbacks_ = {}

Private Types

typedef Solver::ProblemBuilder ProblemBuilder

Private Members

int result_code_ = 0
unsigned banner_size = 0
Solver solver_
std::string nl_filename
std::string filename_no_ext
std::unique_ptr<ProblemBuilder> builder_
std::unique_ptr<internal::SolverNLHandler<Solver>> handler_
internal::SignalHandler sig_handler
internal::SolverAppOptionParser option_parser_
AppOutputHandler output_handler_
class mp::internal::SolverAppOptionParser
#include <solver-app-base.h>

Command-line option parser for a solver application.

Not to be mistaken with solver option parser built into the Solver class.

Public Functions

explicit SolverAppOptionParser(BasicSolver &s)
inline OptionList &options()
inline bool echo_solver_options() const

Retruns true if assignments of solver options should be echoed.

const char *Parse(char **&argv)

Parses command-line options.

Private Functions

bool ShowUsage()

Prints usage information and stops processing options.

bool ShowSolverOptions(const char*)

Prints information about solver options.

bool ShowSolverOptionsASL()
bool ShowSolveResults()
inline bool WantSol()
inline bool DontEchoSolverOptions()
inline bool EndOptions()

Stops processing options.

Private Members

std::string currentOptionString
BasicSolver &solver_
OptionList options_

Command-line options.

bool echo_solver_options_
class mp::SolveResultRegistry
#include <solver-base.h>

Solve result registry.

Subclassed by mp::BasicSolver

Public Types

using SRRegMap = std::set<RegEntry>

Registry map.

Public Functions

SolveResultRegistry()

Construct.

inline virtual ~SolveResultRegistry()

Destroy.

void AddSolveResults(const SRRegMap &sm, bool ifCanReplace = false)

Add a map with result descriptions.

inline const SRRegMap &GetSolveResultRegistry() const

Get the registry.

Private Members

SRRegMap registry_
template<typename ProblemBuilderT>
class mp::SolverImpl : public mp::Solver
#include <solver.h>

DEPRECATED.

Convenience template used by some APIs to provide [NL]ProblemBuilderType

Public Types

typedef ProblemBuilderT ProblemBuilder
typedef internal::NLProblemBuilder<ProblemBuilder> NLProblemBuilder
typedef std::vector<SuffixInfo> SuffixList
enum [anonymous]

Possible values for the wantsol option (can be combined with bitwise OR).

Values:

enumerator WRITE_SOL_FILE
enumerator PRINT_SOLUTION
enumerator PRINT_DUAL_SOLUTION
enumerator SUPPRESS_SOLVER_MSG
enum [anonymous]

The default precision used in FormatObjValue if the objective_precision env variable is not specified or 0.

Values:

enumerator DEFAULT_PRECISION
enum [anonymous]

Solver flags.

Values:

enumerator MULTIPLE_SOL

Multiple solutions support.

Makes Solver register “countsolutions” and “solutionstub” options and write every solution passed to HandleFeastibleSolution to a file solutionstub & i & “.sol” where i is a solution number.

enumerator MULTIPLE_OBJ

Multiple objectives support.

Makes Solver register the “multiobj” option

using WarningsMap = std::map<std::string, std::pair<int, std::string>>

Map to count warnings by types.

Stores just 1 message for each type.

enum [anonymous]

Flags for ParseOptions.

Values:

enumerator NO_OPTION_ECHO

Don’t echo options during parsing.

enumerator FROM_COMMAND_LINE

When options are passed from command line (not via environment var) the quotes are automatically removed and the input string split in substrings (accessible via argv)

typedef std::unique_ptr<SolverOption> OptionPtr

Smart ptr to an option.

using set_option_iterator = option_iterator_base<OptionSet::iterator>

Alias for writeable option iterator.

using option_iterator = option_iterator_base<OptionSet::const_iterator>

Alias for const option iterator.

using SRRegMap = std::set<RegEntry>

Registry map.

Public Functions

inline SolverImpl(fmt::CStringRef name, fmt::CStringRef long_name = 0, long date = 0, int flags = 0)
inline void AddSuffix(const char *name, const char *table, int kind, int nextra = 0)

Adds a suffix.

inline const SuffixList &suffixes() const
inline std::string GetOptionFile(const SolverOption&) const

Name of the file with option settings, provided by tech:optionfile.

void UseOptionFile(const SolverOption&, fmt::StringRef value)

Read otpions from option file.

inline int GetWantSol(const SolverOption&) const

wantsol value

inline void SetWantSol(const SolverOption&, int value)

set wantsol

inline std::string GetSolutionStub(const SolverOption&) const

solution output filename stub

inline void SetSolutionStub(const SolverOption&, fmt::StringRef value)

Set sol stub.

inline int GetObjNo(const SolverOption&) const

Obj number.

inline void SetObjNo(const SolverOption &opt, int value)

Set obj number.

inline int GetTiming(const SolverOption&) const
inline void SetTiming(const SolverOption &opt, int value)
inline const char *name() const

Returns the solver name.

This is used to extract solver options from the env variable (solver_name)_options.

inline const char *long_name() const

Returns the long solver name.

This name is used in startup “banner”.

inline const char *exe_path() const

Returns the executable path.

inline void set_exe_path(const char *p)
inline const char *version() const

Returns the solver version.

inline long date() const

Returns the solver date in YYYYMMDD format.

inline int wantsol() const

Returns the value of the wantsol option which specifies what solution information to write in a stand-alone invocation (no -AMPL on the command line).

inline void set_wantsol(int value)
inline bool ampl_flag()
inline void set_ampl_flag(bool value = true)
inline bool verbose_mode() const

True if verbose mode.

Should be set by the implementation, otherwise it’s true

inline void set_verbose_mode(bool f)

Set verbosity, by the impl.

inline bool debug_mode() const

True if need to debug.

Outputs test infos etc

inline int objno_used() const

Returns the index of the objective to optimize starting from 1, 0 to not use objective.

inline int objno_specified() const

objno_specified(): actually even if not specified, it returns the objno to use (0 - feasibility, otherwise obj index).

Both multiobj() and objno_specified() are used in NLReader to select the objective(s), solvers should not use these accessors.

inline bool is_objno_specified() const

Whether user specified the option objno.

inline void notify_obj_added()

Notify Solver if an objective is added.

inline void notify_start_opts()

Notify Solver we start reading options.

inline void notify_end_opts()

Notify we are done.

inline bool multiobj() const

Returns true if multiobjective optimization is enabled.

Both multiobj and objno are used in NLReader to select the objective(s), solvers should not use these options.

inline int timing() const

>0 if the timing is enabled

inline ErrorHandler *error_handler()

Return error handler.

inline void set_error_handler(ErrorHandler *eh)

Set the error handler.

inline OutputHandler *output_handler()

Return output handler.

inline OutputHandler &get_output_handler()

Return output handler.

inline void set_output_handler(OutputHandler *oh)

Sets the output handler.

inline const Interrupter *interrupter() const

Interrupter, const.

inline Interrupter *interrupter()

Interrupter.

inline void set_interrupter(Interrupter *interrupter)

Set interrupter.

inline const char *solution_stub() const

Sol stub as char*.

inline bool need_multiple_solutions() const

Need mutiple solutions.

inline virtual void HandleOutput(fmt::CStringRef output) override

Override methods from base service classes.

inline virtual void HandleError(fmt::CStringRef message) override

Handle error.

inline virtual bool Stop() const override

The default implementation of Interrupter does nothing.

inline virtual void SetHandler(InterruptHandler, void*) override

Set interrupt handler.

inline virtual void HandleUnknownOption(const char *name)

Handle unknown option.

inline void ReportError(fmt::CStringRef format, const fmt::ArgList &args)

Reports an error by throwing it.

Usage: ReportError(“File not found: {}”) << filename;

inline void Print(fmt::CStringRef format, const fmt::ArgList &args)

Variadic overload of ReportError()

Formats a string and prints it to stdout or, if an output handler is registered, sends it to the output handler.

const char *GetSolCheckWarningKey(bool f_recomp) const

Variadic overload of Print()

Get solution check warnings key name.

Parameters

f_recomp – whether with recomputed auxiliaries.

void AddWarning(std::string key, std::string msg, bool replace = false)

Add a warning.

Parameters
  • key – warning category

  • msg – detailed message

const std::pair<int, std::string> &GetWarning(const std::string &key)

Get a warning type.

void ClearWarning(const std::string &key)

Clear a warning type.

std::string GetWarnings() const

Get warnings as string.

void PrintWarnings()

Print warnings.

bool ShowVersion()

Prints version information.

DoubleFormatter FormatObjValue(double value)

Returns a formatter that writes value using objective precision.

Usage: Print(“objective {}”, FormatObjValue(obj_value));

virtual bool ParseOptions(char **argv, unsigned flags = 0, const ASLProblem *p = 0)

Parses solver options from the (solver)_options env variable and/or strings in argv.

For example, solver_options=’timelim=300’ solver /tmp/diet.nl -AMPL “basis=0”.

Returns

true if there were no errors and false otherwise. It accepts a pointer to the problem because some options may depend on problem features.

void ParseOptionString(const char *s, unsigned flags)

Parses a solver option string.

inline const WarningsMap &GetWarningsMap() const

Get warnings map.

inline WarningsMap &GetWarningsMap()
inline void SetConstraintListHeader(std::string clh)

Set constraint list header (printed at the start of -c)

inline void AddConstraintDescr(std::string cn, std::string cdescr)

Add constraint type description.

bool ShowConstraintDescriptions()

Show constraint descriptions.

inline virtual void RecordOutputTime()
inline virtual void RecordSetupTime()

Record setup time.

inline void SetReadTime(double read_time)
inline void SetConversionTime(double conv_time)
inline virtual void RecordSolveTime()

Record solve time.

inline int num_options() const

Returns the number of options.

inline SolverOption *GetOption(const char *name) const

Returns the option with specified name.

inline void set_option_header(const char *header)

Sets a text to be displayed before option descriptions.

inline void add_to_option_header(const char *header_more)

Add more text to be displayed before option descriptions.

void AddOption(OptionPtr opt)

Add an option.

template<class Value>
inline void AddOption(const char *name, const char *description, Value &value, Value lb, Value ub)

Same: stored option referencing a variable; min, max values.

Note

description “HIDDEN” means the option is not printed

SolverOption *FindOption(const char *name, bool wildcardvalues = false) const

Finds an option and returns a pointer to it if found or null otherwise.

If wildcardvalues==true, wildcarded options should have values (i.e., parsing real input)

inline const char *option_header() const

Returns the option header.

inline fmt::LongLong GetIntOption(const char *name) const

Returns the value of an integer option.

Throws OptionError if there is no such option or it has a different type.

inline void SetIntOption(const char *name, fmt::LongLong value)
inline double GetDblOption(const char *name) const
inline void SetDblOption(const char *name, double value)
inline std::string GetStrOption(const char *name) const
inline void SetStrOption(const char *name, fmt::StringRef value)
template<class Value>
inline void AddStoredOption(const char *name, const char *description, Value &value, ValueArrayRef values = ValueArrayRef())

Simple stored option referencing a variable.

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddStoredOption(const char *name, const char *description, Value &value, Value, Value)

Simple stored option referencing a variable; min, max values (they are unused but to deduce type; we are too lazy to maintain correct min/max between solver versions.)

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddListOption(const char *name, const char *description, Value &value, ValueArrayRef values = ValueArrayRef())

Add list option referencing a container.

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddListOption(const char *name, const char *description, Value &value, typename Value::value_type, typename Value::value_type)

Add list option referencing a container; min, max values (they are unused but to deduce type; we aree too lazy to maintain correct min/max between solver versions.)

Note

description “HIDDEN” means the option is not printed

inline void ReplaceOptionDescription(const char *name, const char *desc)

Replace option descr.

inline void AddToOptionDescription(const char *name, const char *desc_add)

Add to option descr.

void AddOptionSynonyms_Inline_Front(const char *names_list, const char *realName)

Add “inline” option synonyms.

The _Front version puts them in the front of the synonyms list and the 1st of them is used in the -a output for sorting.

void AddOptionSynonyms_Inline_Back(const char *names_list, const char *realName)

Add “inline” option synonyms.

The _Back version.

void AddOptionSynonyms_OutOfLine(const char *name, const char *realName)

Add an “out-of-line” synonym.

Creates extra entry under -=

template<typename Handler, typename Int>
inline void AddIntOption(const char *name, const char *description, Int (Handler::* get)(const SolverOption&) const, void (Handler::* set)(const SolverOption&, Int))

Adds an integer option.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddIntOption(const char *name, const char *description, int (Handler::* get)(const SolverOption&, const Info&) const, void (Handler::* set)(const SolverOption&, int, const Info&), const Info &info)

Adds an integer option with additional information.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddIntOption(const char *name_list, const char *description, int (Handler::* get)(const SolverOption&, Info) const, void (Handler::* set)(const SolverOption&, int, Info), Info info)

The same as above but with Info argument passed by value.

Note

description “HIDDEN” means the option is not printed

template<typename Handler>
inline void AddDblOption(const char *name, const char *description, double (Handler::* get)(const SolverOption&) const, void (Handler::* set)(const SolverOption&, double))

Adds a double option.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddDblOption(const char *name, const char *description, double (Handler::* get)(const SolverOption&, const Info&) const, void (Handler::* set)(const SolverOption&, double, const Info&), const Info &info)

Adds a double option with additional information.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddDblOption(const char *name, const char *description, double (Handler::* get)(const SolverOption&, Info) const, void (Handler::* set)(const SolverOption&, double, Info), Info info)

The same as above but with Info argument passed by value.

Note

description “HIDDEN” means the option is not printed

template<typename Handler>
inline void AddStrOption(const char *name, const char *description, std::string (Handler::* get)(const SolverOption&) const, void (Handler::* set)(const SolverOption&, fmt::StringRef), ValueArrayRef values = ValueArrayRef())

Adds a string option.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddStrOption(const char *name, const char *description, std::string (Handler::* get)(const SolverOption&, const Info&) const, void (Handler::* set)(const SolverOption&, fmt::StringRef, const Info&), const Info &info, ValueArrayRef values = ValueArrayRef())

Adds a string option with additional information.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddStrOption(const char *name, const char *description, std::string (Handler::* get)(const SolverOption&, Info) const, void (Handler::* set)(const SolverOption&, fmt::StringRef, Info), Info info, ValueArrayRef values = ValueArrayRef())

The same as above but with Info argument passed by value.

Note

description “HIDDEN” means the option is not printed

inline option_iterator option_begin() const

Get the start const-iterator.

inline option_iterator option_end() const

Get the end const-iterator.

inline set_option_iterator set_option_begin() const

Get the start writeable iterator.

inline set_option_iterator set_option_end() const

Get the end writeable iterator.

void AddSolveResults(const SRRegMap &sm, bool ifCanReplace = false)

Add a map with result descriptions.

inline const SRRegMap &GetSolveResultRegistry() const

Get the registry.

Public Static Functions

static std::string ToString(const WarningsMap::value_type &wrn)

Stringify a WarningsMap entry.

Protected Functions

void InitMetaInfoAndOptions(fmt::CStringRef name, fmt::CStringRef long_name, long date, int flags)

InitMetaInfoAndOptions.

Derived classes which want to provide the info after construction can use the default constructor and call this.

Parameters
  • date – The solver date in YYYYMMDD format.

  • flags – Bitwise OR of zero or more of the following values MULTIPLE_SOL MULTIPLE_OBJ

inline void set_long_name(fmt::StringRef name)
inline void add_to_long_name(fmt::StringRef name)
inline void set_version(fmt::StringRef version)
inline void add_to_version(fmt::StringRef version)
inline void set_license_info(fmt::StringRef license_info)
inline virtual std::string set_external_libs()
inline void set_read_flags(unsigned flags)

Sets the flags for Problem::Read.

inline Stats &stats()
template<class Solver, class ProblemBuilder, class NLProblemBuilder>
class mp::internal::SolverNLHandlerImpl : public mp::internal::NLProblemBuilder<ProblemBuilder>
#include <solver-io.h>

An .nl handler for an application using BasicSolver.

The full definition separates parameters Solver, ProblemBuilder, and NLProblemBuilder.

Public Types

typedef ProblemBuilder::Function Function
typedef ProblemBuilder::Expr Expr
typedef ProblemBuilder::NumericExpr NumericExpr
typedef ProblemBuilder::LogicalExpr LogicalExpr
typedef ProblemBuilder::CountExpr CountExpr
typedef ProblemBuilder::Reference Reference
typedef ProblemBuilder::LinearObjBuilder LinearObjHandler
typedef ProblemBuilder::LinearConBuilder LinearConHandler
typedef ProblemBuilder::LinearExprBuilder LinearExprHandler
typedef ProblemBuilder::IntSuffixHandler IntSuffixHandler
typedef ProblemBuilder::DblSuffixHandler DblSuffixHandler
typedef ProblemBuilder::PLTermBuilder PLTermHandler
typedef ProblemBuilder::CallExprBuilder CallArgHandler
typedef ProblemBuilder::IteratedExprBuilder VarArgHandler
typedef ProblemBuilder::IteratedExprBuilder NumericArgHandler
typedef ProblemBuilder::NumberOfExprBuilder NumberOfArgHandler
typedef ProblemBuilder::SymbolicNumberOfExprBuilder SymbolicArgHandler
typedef ProblemBuilder::CountExprBuilder CountArgHandler
typedef ProblemBuilder::IteratedLogicalExprBuilder LogicalArgHandler
typedef ProblemBuilder::PairwiseExprBuilder PairwiseArgHandler

Public Functions

inline SolverNLHandlerImpl(ProblemBuilder &pb, Solver &s, std::function<void()> after_h = {})
inline int num_options() const
inline const long *options() const
inline virtual int objno() const override

objno(). virtual, so that SolverNLHandler can override

inline virtual bool multiobj() const override

multiobj(). virtual, so that SolverNLHandler can override

inline virtual void notify_obj_added() const override

notify_obj_added(). virtual, so that SolverNLHandler can override

void OnHeader(const NLHeader &h)
inline ProblemBuilder &builder()

Get builder.

inline void AddVariables(const NLHeader &h)

Add variables.

inline void DoAddVars(int n, var::Type t, int &k)

DoAddVars: update counter k.

inline int resulting_nobj(int nobj_header) const

Actual N objectives.

inline bool NeedObj(int obj_index) const

Whether need this objective.

inline int resulting_obj_index(int index) const

Final obj index for a given original index.

For multiobj, it’s the same. Otherwise it’s 0 (1st objective).

inline void OnObj(int index, obj::Type type, NumericExpr expr)
inline void OnAlgebraicCon(int index, NumericExpr expr)
inline void OnLogicalCon(int index, LogicalExpr expr)
inline void OnComplementarity(int con_index, int var_index, ComplInfo info)
inline LinearObjHandler OnLinearObjExpr(int obj_index, int num_linear_terms)
inline LinearConHandler OnLinearConExpr(int con_index, int num_linear_terms)
inline LinearExprHandler BeginCommonExpr(int index, int num_linear_terms)
inline void EndCommonExpr(int index, NumericExpr expr, int position)
inline void OnVarBounds(int index, double lb, double ub)
inline void OnConBounds(int index, double lb, double ub)
inline void OnInitialValue(int var_index, double value)
inline void OnInitialDualValue(int con_index, double value)
inline ColumnSizeHandler OnColumnSizes()
inline void OnFunction(int index, fmt::StringRef name, int num_args, func::Type type)
inline IntSuffixHandler OnIntSuffix(fmt::StringRef name, suf::Kind kind, int num_values)
inline DblSuffixHandler OnDblSuffix(fmt::StringRef name, suf::Kind kind, int num_values)
inline NumericExpr OnNumber(double value)
inline Reference OnVariableRef(int var_index)
inline Reference OnCommonExprRef(int expr_index)
inline NumericExpr OnUnary(expr::Kind kind, NumericExpr arg)
inline NumericExpr OnBinary(expr::Kind kind, NumericExpr lhs, NumericExpr rhs)
inline NumericExpr OnIf(LogicalExpr condition, NumericExpr then_expr, NumericExpr else_expr)
inline PLTermHandler BeginPLTerm(int num_breakpoints)
inline NumericExpr EndPLTerm(PLTermHandler handler, Reference arg)
inline CallArgHandler BeginCall(int func_index, int num_args)
inline NumericExpr EndCall(CallArgHandler handler)
inline VarArgHandler BeginVarArg(expr::Kind kind, int num_args)
inline NumericExpr EndVarArg(VarArgHandler handler)
inline NumericArgHandler BeginSum(int num_args)
inline NumericExpr EndSum(NumericArgHandler handler)
inline NumberOfArgHandler BeginNumberOf(int num_args, NumericExpr arg0)
inline NumericExpr EndNumberOf(NumberOfArgHandler handler)
inline SymbolicArgHandler BeginSymbolicNumberOf(int num_args, Expr arg0)
inline NumericExpr EndSymbolicNumberOf(SymbolicArgHandler handler)
inline CountArgHandler BeginCount(int num_args)
inline CountExpr EndCount(CountArgHandler handler)
inline LogicalExpr OnBool(bool value)
inline LogicalExpr OnNot(LogicalExpr arg)
inline LogicalExpr OnBinaryLogical(expr::Kind kind, LogicalExpr lhs, LogicalExpr rhs)
inline LogicalExpr OnRelational(expr::Kind kind, NumericExpr lhs, NumericExpr rhs)
inline LogicalExpr OnLogicalCount(expr::Kind kind, NumericExpr lhs, CountExpr rhs)
inline LogicalExpr OnImplication(LogicalExpr condition, LogicalExpr then_expr, LogicalExpr else_expr)
inline LogicalArgHandler BeginIteratedLogical(expr::Kind kind, int num_args)
inline LogicalExpr EndIteratedLogical(LogicalArgHandler handler)
inline PairwiseArgHandler BeginPairwise(expr::Kind kind, int num_args)
inline LogicalExpr EndPairwise(PairwiseArgHandler handler)
inline Expr OnString(fmt::StringRef value)
inline Expr OnSymbolicIf(LogicalExpr condition, Expr then_expr, Expr else_expr)
inline void EndInput()

Private Types

typedef NLProblemBuilder Base

Private Members

Solver &solver_
int num_options_
long options_[MAX_AMPL_OPTIONS]
std::function<void()> after_header_
class mp::SolverOption
#include <solver-opt.h>

A solver option.

Note

description “HIDDEN” means the option is not printed

Subclassed by mp::TypedSolverOption< Container::value_type >, mp::TypedSolverOption< int >, mp::TypedSolverOption< Value >, mp::TypedSolverOption< T >

Public Types

enum Option_Type

Option type classifier, used in AMPLS.

Values:

enumerator BOOL
enumerator INT
enumerator DBL
enumerator STRING

Public Functions

SolverOption(const char *names_list, const char *description, ValueArrayRef values = ValueArrayRef(), bool is_flag = false)

Constructs a SolverOption object.

The solver option stores pointers to the passed name(s) and description and copies the strings for the names only. Normally the description is a string literal and has static storage duration but if this is not the case make sure that the string’s lifetime is longer than that of the option object.

The description should be written in a subset of reStructuredText (RST). Currently the following RST constructs are supported:

  • paragraphs

  • bullet lists

  • literal blocks

  • line blocks

  • the value-table directive (.. value-table::) which is replaced by a table of option values as given by the values array

names_list: option names list names can be wildcarded, e.g., “obj:*:method” then setter/getter can use wildcard_ accessors description: option description values: information about possible option values

inline virtual ~SolverOption()
inline const char *name() const

Return the option name.

const char *name_ASL() const

Return the ASL (not qualified) name as the first inline synonym - or the name itself if no synonyms are defined.

inline const std::vector<std::string> &inline_synonyms() const

Returns the “inline” synonyms.

void add_synonyms_front(const char *names_list)

Add additional “inline” synonyms.

void add_synonyms_back(const char *names_list)
inline bool is_hidden() const

Is hidden?

inline bool is_wildcard() const

Wildcards.

bool wc_match(const std::string &key)

Checks if matches, then saves key & body.

inline const std::string &wc_head() const
inline const std::string &wc_tail() const
inline const std::string &wc_key_last() const
inline const std::string &wc_keybody_last() const
inline std::string wc_key_last__std_form() const

Printing last parsed wc key in std form.

inline const char *description() const

Return/set the option description.

inline void set_description(const char *d)
inline void add_to_description(const char *d)
inline void format_description(fmt::MemoryWriter &writer, int indent = 0) const

Append the formatted description to the writer.

inline std::string format_description(int indent = 0) const

Get the formatted option description.

inline ValueArrayRef values() const

Returns the information about possible values.

inline virtual bool is_flag() const

Returns true if this option is a flag, i.e. it doesn’t take a value.

inline virtual void GetValue(fmt::LongLong&) const

Returns the option value.

inline virtual void GetValue(double&) const
inline virtual void GetValue(std::string&) const
inline virtual void GetValue(int &int_value) const
template<typename T>
inline T GetValue() const
inline virtual void SetValue(fmt::LongLong)

Sets the option value or throws InvalidOptionValue if the value is invalid.

inline virtual void SetValue(double)
inline virtual void SetValue(fmt::StringRef)
inline virtual void SetValue(int value)
inline virtual std::string echo_with_value()

Echo option name(s) [= value].

virtual void Write(fmt::Writer &w) = 0

Formats the option value.

Throws OptionError in case of error. Not called for flags.

virtual void Parse(const char *&s, bool splitString = false) = 0

Parses a string and sets the option value.

Throws InvalidOptionValue if the value is invalid or OptionError in case of another error.

inline virtual std::string echo()

Echo option name(s).

virtual Option_Type type() = 0

Return type classifier.

Private Types

using WCHeadTail = std::pair<std::string, std::string>

Wildcard info Standard name’s head/tail.

Private Members

std::string name_ = {}
std::vector<std::string> inline_synonyms_ = {}
std::string description_
std::vector<WCHeadTail> wc_headtails_
std::string wc_key_last_

Last actual key parsed and it’s ‘*’ body.

std::string wc_body_last_
ValueArrayRef values_
bool is_flag_

Private Static Functions

static WCHeadTail wc_split(const std::string &name)

Assumes name constains ‘*’.

template<class Value, class Index>
class mp::StdBackend::SolverOptionAccessor
#include <backend-std.h>

Solver options accessor, facilitates calling backend_.Get/SetSolverOption()

Public Types

using value_type = Value
using index_type = Index

Public Functions

inline SolverOptionAccessor(Impl &b)
inline Value get(const SolverOption&, Index i) const

Options setup.

inline void set(const SolverOption&, typename internal::OptionHelper<Value>::Arg v, Index i)

Private Members

Impl &backend_
class mp::SolverOptionManager
#include <solver-opt.h>

A collection of solver options.

Subclassed by mp::BasicSolver

Public Types

enum [anonymous]

Flags for ParseOptions.

Values:

enumerator NO_OPTION_ECHO

Don’t echo options during parsing.

enumerator FROM_COMMAND_LINE

When options are passed from command line (not via environment var) the quotes are automatically removed and the input string split in substrings (accessible via argv)

typedef std::unique_ptr<SolverOption> OptionPtr

Smart ptr to an option.

using set_option_iterator = option_iterator_base<OptionSet::iterator>

Alias for writeable option iterator.

using option_iterator = option_iterator_base<OptionSet::const_iterator>

Alias for const option iterator.

Public Functions

inline int num_options() const

Returns the number of options.

inline SolverOption *GetOption(const char *name) const

Returns the option with specified name.

inline void set_option_header(const char *header)

Sets a text to be displayed before option descriptions.

inline void add_to_option_header(const char *header_more)

Add more text to be displayed before option descriptions.

void AddOption(OptionPtr opt)

Add an option.

SolverOption *FindOption(const char *name, bool wildcardvalues = false) const

Finds an option and returns a pointer to it if found or null otherwise.

If wildcardvalues==true, wildcarded options should have values (i.e., parsing real input)

inline const char *option_header() const

Returns the option header.

inline fmt::LongLong GetIntOption(const char *name) const

Returns the value of an integer option.

Throws OptionError if there is no such option or it has a different type.

inline void SetIntOption(const char *name, fmt::LongLong value)
inline double GetDblOption(const char *name) const
inline void SetDblOption(const char *name, double value)
inline std::string GetStrOption(const char *name) const
inline void SetStrOption(const char *name, fmt::StringRef value)
template<class Value>
inline void AddStoredOption(const char *name, const char *description, Value &value, ValueArrayRef values = ValueArrayRef())

Simple stored option referencing a variable.

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddStoredOption(const char *name, const char *description, Value &value, Value, Value)

Simple stored option referencing a variable; min, max values (they are unused but to deduce type; we are too lazy to maintain correct min/max between solver versions.)

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddOption(const char *name, const char *description, Value &value, Value lb, Value ub)

Same: stored option referencing a variable; min, max values.

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddListOption(const char *name, const char *description, Value &value, ValueArrayRef values = ValueArrayRef())

Add list option referencing a container.

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddListOption(const char *name, const char *description, Value &value, typename Value::value_type, typename Value::value_type)

Add list option referencing a container; min, max values (they are unused but to deduce type; we aree too lazy to maintain correct min/max between solver versions.)

Note

description “HIDDEN” means the option is not printed

inline void ReplaceOptionDescription(const char *name, const char *desc)

Replace option descr.

inline void AddToOptionDescription(const char *name, const char *desc_add)

Add to option descr.

void AddOptionSynonyms_Inline_Front(const char *names_list, const char *realName)

Add “inline” option synonyms.

The _Front version puts them in the front of the synonyms list and the 1st of them is used in the -a output for sorting.

void AddOptionSynonyms_Inline_Back(const char *names_list, const char *realName)

Add “inline” option synonyms.

The _Back version.

void AddOptionSynonyms_OutOfLine(const char *name, const char *realName)

Add an “out-of-line” synonym.

Creates extra entry under -=

template<typename Handler, typename Int>
inline void AddIntOption(const char *name, const char *description, Int (Handler::* get)(const SolverOption&) const, void (Handler::* set)(const SolverOption&, Int))

Adds an integer option.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddIntOption(const char *name, const char *description, int (Handler::* get)(const SolverOption&, const Info&) const, void (Handler::* set)(const SolverOption&, int, const Info&), const Info &info)

Adds an integer option with additional information.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddIntOption(const char *name_list, const char *description, int (Handler::* get)(const SolverOption&, Info) const, void (Handler::* set)(const SolverOption&, int, Info), Info info)

The same as above but with Info argument passed by value.

Note

description “HIDDEN” means the option is not printed

template<typename Handler>
inline void AddDblOption(const char *name, const char *description, double (Handler::* get)(const SolverOption&) const, void (Handler::* set)(const SolverOption&, double))

Adds a double option.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddDblOption(const char *name, const char *description, double (Handler::* get)(const SolverOption&, const Info&) const, void (Handler::* set)(const SolverOption&, double, const Info&), const Info &info)

Adds a double option with additional information.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddDblOption(const char *name, const char *description, double (Handler::* get)(const SolverOption&, Info) const, void (Handler::* set)(const SolverOption&, double, Info), Info info)

The same as above but with Info argument passed by value.

Note

description “HIDDEN” means the option is not printed

template<typename Handler>
inline void AddStrOption(const char *name, const char *description, std::string (Handler::* get)(const SolverOption&) const, void (Handler::* set)(const SolverOption&, fmt::StringRef), ValueArrayRef values = ValueArrayRef())

Adds a string option.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddStrOption(const char *name, const char *description, std::string (Handler::* get)(const SolverOption&, const Info&) const, void (Handler::* set)(const SolverOption&, fmt::StringRef, const Info&), const Info &info, ValueArrayRef values = ValueArrayRef())

Adds a string option with additional information.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddStrOption(const char *name, const char *description, std::string (Handler::* get)(const SolverOption&, Info) const, void (Handler::* set)(const SolverOption&, fmt::StringRef, Info), Info info, ValueArrayRef values = ValueArrayRef())

The same as above but with Info argument passed by value.

Note

description “HIDDEN” means the option is not printed

inline option_iterator option_begin() const

Get the start const-iterator.

inline option_iterator option_end() const

Get the end const-iterator.

inline set_option_iterator set_option_begin() const

Get the start writeable iterator.

inline set_option_iterator set_option_end() const

Get the end writeable iterator.

virtual ~SolverOptionManager()

Private Types

typedef std::set<SolverOption*, OptionNameLess> OptionSet

Private Members

std::string option_header_
OptionSet options_
template<class ModelConverter>
class mp::SOS2Converter_MIP : public mp::BasicFuncConstrCvt<SOS2Converter_MIP<ModelConverter>, ModelConverter>
#include <sos2.h>

Converts SOS2 for MIP.

Public Types

using Base = BasicFuncConstrCvt<SOS2Converter_MIP<ModelConverter>, ModelConverter>

Base class.

using ItemType = SOS2Constraint

Converted item type.

Public Functions

inline SOS2Converter_MIP(ModelConverter &mc)

Constructor.

inline void Convert(const ItemType &cc, int)

Convert in any context.

inline void Convert(const ItemType &item, int i)

Generic Convert(), distinguishes context & result variable.

Distinguish positive and negative context because if only one of these is necessary, significant model reduction can be achieved in certain cases.

Responsible for adding presolve links, if any

The Impl can reimplement this

Parameters
  • item – the item to be converted

  • i – item index, used to create a presolve link

inline void ConvertCtxNeg(const ItemType &item, int)

Convert in negative context.

inline void ConvertCtxPos(const ItemType &item, int)

Convert in positive context.

inline const ModelConverter &GetMC() const

Reuse the stored ModelConverter.

inline ModelConverter &GetMC()

Reuse the stored ModelConverter.

inline const ModelConverter &GetMC() const

Access const ModelConverter.

template<class ItemType>
inline bool IfNeedsConversion(const ItemType&, int)

Generic check whether the constraint needs to be converted despite being recommended for acceptance by ModelAPI.

Example: PowConstraint(x, …) with lb(x)<0. Default: false.

Protected Functions

inline void ConvertGeneralSOS2(const ItemType&)
inline void ConvertSOS2FromPL(const ItemType &cc)
template<int type>
class mp::SOS_1or2_Constraint : public mp::BasicConstraint
#include <constr_general.h>

SOS1, SOS2 constraints.

Public Functions

inline int get_sos_type() const
inline int size() const
inline const std::vector<int> &get_vars() const

Returns vector of variables, sorted by weights.

inline const std::vector<int> &GetArguments() const

vars via GetArguments()

inline const std::vector<double> &get_weights() const

Returns weights, sorted.

inline const SOSExtraInfo &get_extra_info() const

SOS2 extra info.

inline SOSExtraInfo::Bounds get_sum_of_vars_range() const

Sum of vars range, extra info if supplied.

template<class VV = std::vector<int>, class WV = std::vector<double>>
inline SOS_1or2_Constraint(VV v, WV w, SOSExtraInfo ei, std::string nm = {})

Constructor.

template<class VV = std::vector<int>, class WV = std::vector<double>>
inline SOS_1or2_Constraint(VV v, WV w, std::string nm = {})

Constructor.

inline bool check() const

Check data.

template<class VarInfo>
inline Violation ComputeViolation(const VarInfo &x) const

Compute violation.

template<class VarInfo>
inline Violation ComputeViolationSOS1(const VarInfo &x) const

Compute violation.

template<class VarInfo>
inline Violation ComputeViolationSOS2(const VarInfo &x) const

Compute violation.

inline const char *GetName() const

Constraint name.

inline const char *name() const

Constraint name.

inline void SetName(std::string nm)

Set constraint name.

inline Context GetContext() const

Get context, if meaningful.

inline void SetContext(Context) const

Set context, if meaningful.

inline void AddContext(Context) const

Add (merge) context, if meaningful.

inline bool HasResultVar() const

Has result var (is functional)?

inline int GetResultVar() const

For functional constraints, result variable index.

Public Static Functions

static inline const char *GetTypeName()

Constraint type name.

static inline bool IsLogical()

Is logical?

static inline constexpr bool UsesContext()

Whether context is meaningful here.

Protected Functions

inline void sort()

Sort by weights.

Private Members

std::vector<int> v_
std::vector<double> w_
const SOSExtraInfo extra_info_

Private Static Attributes

static constexpr const char *name1_ = "SOS1Constraint"
static constexpr const char *name2_ = "SOS2Constraint"
struct mp::SOSExtraInfo
#include <constr_general.h>

SOS1, SOS2.

SOS constraint extra info, supplied for better conversion

Public Functions

inline SOSExtraInfo(Bounds b = {})

Constructor.

inline bool operator==(const SOSExtraInfo &ei) const

operator==

Public Members

struct mp::SOSExtraInfo::Bounds bounds_
struct SparseEntry
#include <nlsol_ex_c_model.h>

Typedef SparseEntry.

Public Members

int index_
double value_
template<class Index, class Value>
class mp::NLWriter2::SparseVectorWriter
#include <nl-writer2.h>

Writer callbacks.

The callbacks are employed by user-specialized feeder when asked to feed something. Sparse vector writer. Is constructed knowing the number of nozeros to be written.

Public Functions

inline SparseVectorWriter()

Construct.

SparseVectorWriter(const SparseVectorWriter&) = delete

Not construct(const&)

inline SparseVectorWriter(SparseVectorWriter &&other)

Construct(&&)

SparseVectorWriter(NLWriter2 &nlw, size_t n)

Constructor.

inline ~SparseVectorWriter()

Destructor.

SparseVectorWriter &operator=(const SparseVectorWriter &vw) = delete

No operator=(const&)

inline SparseVectorWriter &operator=(SparseVectorWriter &&other)

operator=(&&)

void Write(Index, Value)

Write next entry.

inline int NLeft() const

Number of outstanding elements.

Private Members

NLWriter2 *p_nlw_ = nullptr
size_t n_entries_ = 0
struct mp::BasicSolver::Stats
#include <solver-base.h>

Public Members

std::chrono::steady_clock::time_point time = std::chrono::steady_clock::now()
double setup_time = 0.0
double solution_time = 0.0
double read_time = 0.0
double conversion_time = 0.0
double output_time = 0.0
int n_altern_sol_checks_failed_ = 0
template<class Impl>
class mp::StdBackend : public mp::BackendWithModelManager
#include <backend-std.h>

StdBackend: the standard solver API wrapper.

The standard wrapper provides common functionality: standard option handling and placeholders for solver API

Subclassed by mp::MIPBackend< Impl, BaseBackend >

Public Types

using MPSolverBase = BackendWithModelManager
using MPUtils = MPSolverBase
using Callbacks = CCallbacks

Callbacks typedef.

enum [anonymous]

Possible values for the wantsol option (can be combined with bitwise OR).

Values:

enumerator WRITE_SOL_FILE
enumerator PRINT_SOLUTION
enumerator PRINT_DUAL_SOLUTION
enumerator SUPPRESS_SOLVER_MSG
enum [anonymous]

The default precision used in FormatObjValue if the objective_precision env variable is not specified or 0.

Values:

enumerator DEFAULT_PRECISION
enum [anonymous]

Solver flags.

Values:

enumerator MULTIPLE_SOL

Multiple solutions support.

Makes Solver register “countsolutions” and “solutionstub” options and write every solution passed to HandleFeastibleSolution to a file solutionstub & i & “.sol” where i is a solution number.

enumerator MULTIPLE_OBJ

Multiple objectives support.

Makes Solver register the “multiobj” option

using WarningsMap = std::map<std::string, std::pair<int, std::string>>

Map to count warnings by types.

Stores just 1 message for each type.

enum [anonymous]

Flags for ParseOptions.

Values:

enumerator NO_OPTION_ECHO

Don’t echo options during parsing.

enumerator FROM_COMMAND_LINE

When options are passed from command line (not via environment var) the quotes are automatically removed and the input string split in substrings (accessible via argv)

typedef std::unique_ptr<SolverOption> OptionPtr

Smart ptr to an option.

using set_option_iterator = option_iterator_base<OptionSet::iterator>

Alias for writeable option iterator.

using option_iterator = option_iterator_base<OptionSet::const_iterator>

Alias for const option iterator.

using SRRegMap = std::set<RegEntry>

Registry map.

Public Functions

virtual Solution GetSolution() = 0

Further, using virtual methods for convenience (CRTP not essential)

Placeholder for solution getter (postsolved, final solution)

virtual ArrayRef<double> GetObjectiveValues() = 0

Placeholder for objective values getter (postsolved, final solution) Used only if we don’t want the solution values, otherwise GetSolution() provides this.

inline virtual void RunFromNLFile(const std::string &nl_filename, const std::string &filename_no_ext) override

FeasRelax No API to overload, Impl should check:

  • feasrelax() returns feasrelax mode

  • feasrelax().(methods) give the API MIP solution rounding Nothing to do for the Impl, enabled by default Model export. Redefine to true and implement the method. Redefine this if you want some extensions to be written after solving instead. This is for compatibility wiht ASL drivers where ‘writeprob’ was used for native-format model and solution output #218. Solution export. Redefine to true and implement the method. Runs Solver given the NL file name. This is called from BackendApp.

inline virtual void ReadNL(const std::string &nl_filename, const std::string &filename_no_ext, char **opts) override

Detailed steps for AMPLS C API.

Read NL.

Parameters

opts – extra options (to be read after the [solver]_options env var). All model-related options should be here (obj:…/objno/multiobj, cvt:…, acc:…).

inline virtual void InputExtras() override

Input warm start, suffixes, and all that can modify the model.

This is used by the AMPLS C API

inline void SetSolutionFileName(const std::string &filename)
inline virtual void ReportResults() override

Report results.

inline virtual void InitMetaInfoAndOptions() override

Deriving backends can use this.

inline virtual void InitNamesAndVersion()
inline const MPUtils &GetMPUtils() const
inline MPUtils &GetMPUtils()
inline virtual void ReportSolutionViaSolver()

Write solution result in solver native format via solver’s output.

inline virtual void ExportModel(const std::vector<std::string> &filenames)

Write model.

inline virtual ~StdBackend()

Virtual destructor.

inline void Print(fmt::CStringRef format, const fmt::ArgList &args)

Variadic overload of ReportError()

Formats a string and prints it to stdout or, if an output handler is registered, sends it to the output handler.

inline void add_to_long_name(fmt::StringRef name)
inline void add_to_version(fmt::StringRef version)
inline virtual void Init(char **argv) override

Initialize backend, incl.

solver options

Parameters

argv – the command-line arguments, NULL-terminated

inline virtual void ReportError(int solve_result, fmt::CStringRef msg) override

Can be overridden.

For example, if we know the output name, this should write .sol file with the solve_result and msg.

inline void ReportError(fmt::CStringRef format, const fmt::ArgList &args)

Reports an error by throwing it.

Usage: ReportError(“File not found: {}”) << filename;

inline virtual void SetOptionData(char **argv, int f)

Provide cmdline solver options list and flags.

inline virtual bool ParseSolverOptions(char **argv, unsigned flags = 0)

Parse solver options such as “outlev=1” from env and argv.

Parameters
  • argv – (remaining part of) vector of cmdline strings

  • flags – 0 or Solver::NO_OPTION_ECHO

inline virtual void InitOptionParsing()

Chance for the Backend to init solver environment, etc.

inline virtual void FinishOptionParsing()

Chance to consider options immediately (open cloud, etc)

inline Callbacks &GetCallbacks()

Obtain callbacks.

inline void OverrideSolutionFile(const std::string &solFile)
inline std::string GetOverridenSolutionFile()
inline std::string GetOptionFile(const SolverOption&) const

Name of the file with option settings, provided by tech:optionfile.

void UseOptionFile(const SolverOption&, fmt::StringRef value)

Read otpions from option file.

inline int GetWantSol(const SolverOption&) const

wantsol value

inline void SetWantSol(const SolverOption&, int value)

set wantsol

inline std::string GetSolutionStub(const SolverOption&) const

solution output filename stub

inline void SetSolutionStub(const SolverOption&, fmt::StringRef value)

Set sol stub.

inline int GetObjNo(const SolverOption&) const

Obj number.

inline void SetObjNo(const SolverOption &opt, int value)

Set obj number.

inline int GetTiming(const SolverOption&) const
inline void SetTiming(const SolverOption &opt, int value)
inline const char *name() const

Returns the solver name.

This is used to extract solver options from the env variable (solver_name)_options.

inline const char *long_name() const

Returns the long solver name.

This name is used in startup “banner”.

inline const char *exe_path() const

Returns the executable path.

inline void set_exe_path(const char *p)
inline const char *version() const

Returns the solver version.

inline long date() const

Returns the solver date in YYYYMMDD format.

inline int wantsol() const

Returns the value of the wantsol option which specifies what solution information to write in a stand-alone invocation (no -AMPL on the command line).

inline void set_wantsol(int value)
inline bool ampl_flag()
inline void set_ampl_flag(bool value = true)
inline bool verbose_mode() const

True if verbose mode.

Should be set by the implementation, otherwise it’s true

inline void set_verbose_mode(bool f)

Set verbosity, by the impl.

inline bool debug_mode() const

True if need to debug.

Outputs test infos etc

inline int objno_used() const

Returns the index of the objective to optimize starting from 1, 0 to not use objective.

inline int objno_specified() const

objno_specified(): actually even if not specified, it returns the objno to use (0 - feasibility, otherwise obj index).

Both multiobj() and objno_specified() are used in NLReader to select the objective(s), solvers should not use these accessors.

inline bool is_objno_specified() const

Whether user specified the option objno.

inline void notify_obj_added()

Notify Solver if an objective is added.

inline void notify_start_opts()

Notify Solver we start reading options.

inline void notify_end_opts()

Notify we are done.

inline bool multiobj() const

Returns true if multiobjective optimization is enabled.

Both multiobj and objno are used in NLReader to select the objective(s), solvers should not use these options.

inline int timing() const

>0 if the timing is enabled

inline ErrorHandler *error_handler()

Return error handler.

inline void set_error_handler(ErrorHandler *eh)

Set the error handler.

inline OutputHandler *output_handler()

Return output handler.

inline OutputHandler &get_output_handler()

Return output handler.

inline void set_output_handler(OutputHandler *oh)

Sets the output handler.

inline const Interrupter *interrupter() const

Interrupter, const.

inline Interrupter *interrupter()

Interrupter.

inline void set_interrupter(Interrupter *interrupter)

Set interrupter.

inline const char *solution_stub() const

Sol stub as char*.

inline bool need_multiple_solutions() const

Need mutiple solutions.

inline virtual void HandleOutput(fmt::CStringRef output) override

Override methods from base service classes.

inline virtual void HandleError(fmt::CStringRef message) override

Handle error.

inline virtual bool Stop() const override

The default implementation of Interrupter does nothing.

inline virtual void SetHandler(InterruptHandler, void*) override

Set interrupt handler.

inline virtual void HandleUnknownOption(const char *name)

Handle unknown option.

inline void Print(fmt::CStringRef format, const fmt::ArgList &args)

Variadic overload of ReportError()

Formats a string and prints it to stdout or, if an output handler is registered, sends it to the output handler.

const char *GetSolCheckWarningKey(bool f_recomp) const

Variadic overload of Print()

Get solution check warnings key name.

Parameters

f_recomp – whether with recomputed auxiliaries.

void AddWarning(std::string key, std::string msg, bool replace = false)

Add a warning.

Parameters
  • key – warning category

  • msg – detailed message

const std::pair<int, std::string> &GetWarning(const std::string &key)

Get a warning type.

void ClearWarning(const std::string &key)

Clear a warning type.

std::string GetWarnings() const

Get warnings as string.

void PrintWarnings()

Print warnings.

bool ShowVersion()

Prints version information.

DoubleFormatter FormatObjValue(double value)

Returns a formatter that writes value using objective precision.

Usage: Print(“objective {}”, FormatObjValue(obj_value));

virtual bool ParseOptions(char **argv, unsigned flags = 0, const ASLProblem *p = 0)

Parses solver options from the (solver)_options env variable and/or strings in argv.

For example, solver_options=’timelim=300’ solver /tmp/diet.nl -AMPL “basis=0”.

Returns

true if there were no errors and false otherwise. It accepts a pointer to the problem because some options may depend on problem features.

void ParseOptionString(const char *s, unsigned flags)

Parses a solver option string.

inline const WarningsMap &GetWarningsMap() const

Get warnings map.

inline WarningsMap &GetWarningsMap()
inline void SetConstraintListHeader(std::string clh)

Set constraint list header (printed at the start of -c)

inline void AddConstraintDescr(std::string cn, std::string cdescr)

Add constraint type description.

bool ShowConstraintDescriptions()

Show constraint descriptions.

inline virtual void RecordOutputTime()
inline virtual void RecordSetupTime()

Record setup time.

inline void SetReadTime(double read_time)
inline void SetConversionTime(double conv_time)
inline virtual void RecordSolveTime()

Record solve time.

inline int num_options() const

Returns the number of options.

inline SolverOption *GetOption(const char *name) const

Returns the option with specified name.

inline void set_option_header(const char *header)

Sets a text to be displayed before option descriptions.

inline void add_to_option_header(const char *header_more)

Add more text to be displayed before option descriptions.

void AddOption(OptionPtr opt)

Add an option.

template<class Value>
inline void AddOption(const char *name, const char *description, Value &value, Value lb, Value ub)

Same: stored option referencing a variable; min, max values.

Note

description “HIDDEN” means the option is not printed

SolverOption *FindOption(const char *name, bool wildcardvalues = false) const

Finds an option and returns a pointer to it if found or null otherwise.

If wildcardvalues==true, wildcarded options should have values (i.e., parsing real input)

inline const char *option_header() const

Returns the option header.

inline fmt::LongLong GetIntOption(const char *name) const

Returns the value of an integer option.

Throws OptionError if there is no such option or it has a different type.

inline void SetIntOption(const char *name, fmt::LongLong value)
inline double GetDblOption(const char *name) const
inline void SetDblOption(const char *name, double value)
inline std::string GetStrOption(const char *name) const
inline void SetStrOption(const char *name, fmt::StringRef value)
template<class Value>
inline void AddStoredOption(const char *name, const char *description, Value &value, ValueArrayRef values = ValueArrayRef())

Simple stored option referencing a variable.

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddStoredOption(const char *name, const char *description, Value &value, Value, Value)

Simple stored option referencing a variable; min, max values (they are unused but to deduce type; we are too lazy to maintain correct min/max between solver versions.)

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddListOption(const char *name, const char *description, Value &value, ValueArrayRef values = ValueArrayRef())

Add list option referencing a container.

Note

description “HIDDEN” means the option is not printed

template<class Value>
inline void AddListOption(const char *name, const char *description, Value &value, typename Value::value_type, typename Value::value_type)

Add list option referencing a container; min, max values (they are unused but to deduce type; we aree too lazy to maintain correct min/max between solver versions.)

Note

description “HIDDEN” means the option is not printed

inline void ReplaceOptionDescription(const char *name, const char *desc)

Replace option descr.

inline void AddToOptionDescription(const char *name, const char *desc_add)

Add to option descr.

void AddOptionSynonyms_Inline_Front(const char *names_list, const char *realName)

Add “inline” option synonyms.

The _Front version puts them in the front of the synonyms list and the 1st of them is used in the -a output for sorting.

void AddOptionSynonyms_Inline_Back(const char *names_list, const char *realName)

Add “inline” option synonyms.

The _Back version.

void AddOptionSynonyms_OutOfLine(const char *name, const char *realName)

Add an “out-of-line” synonym.

Creates extra entry under -=

template<typename Handler, typename Int>
inline void AddIntOption(const char *name, const char *description, Int (Handler::* get)(const SolverOption&) const, void (Handler::* set)(const SolverOption&, Int))

Adds an integer option.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddIntOption(const char *name, const char *description, int (Handler::* get)(const SolverOption&, const Info&) const, void (Handler::* set)(const SolverOption&, int, const Info&), const Info &info)

Adds an integer option with additional information.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddIntOption(const char *name_list, const char *description, int (Handler::* get)(const SolverOption&, Info) const, void (Handler::* set)(const SolverOption&, int, Info), Info info)

The same as above but with Info argument passed by value.

Note

description “HIDDEN” means the option is not printed

template<typename Handler>
inline void AddDblOption(const char *name, const char *description, double (Handler::* get)(const SolverOption&) const, void (Handler::* set)(const SolverOption&, double))

Adds a double option.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddDblOption(const char *name, const char *description, double (Handler::* get)(const SolverOption&, const Info&) const, void (Handler::* set)(const SolverOption&, double, const Info&), const Info &info)

Adds a double option with additional information.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddDblOption(const char *name, const char *description, double (Handler::* get)(const SolverOption&, Info) const, void (Handler::* set)(const SolverOption&, double, Info), Info info)

The same as above but with Info argument passed by value.

Note

description “HIDDEN” means the option is not printed

template<typename Handler>
inline void AddStrOption(const char *name, const char *description, std::string (Handler::* get)(const SolverOption&) const, void (Handler::* set)(const SolverOption&, fmt::StringRef), ValueArrayRef values = ValueArrayRef())

Adds a string option.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddStrOption(const char *name, const char *description, std::string (Handler::* get)(const SolverOption&, const Info&) const, void (Handler::* set)(const SolverOption&, fmt::StringRef, const Info&), const Info &info, ValueArrayRef values = ValueArrayRef())

Adds a string option with additional information.

The option stores pointers to the name and the description so make sure that these strings have sufficient lifetimes (normally these are string literals). The arguments get and set should be pointers to member functions in the solver class. They are used to get and set an option value respectively.

Note

description “HIDDEN” means the option is not printed

template<typename Handler, typename Info>
inline void AddStrOption(const char *name, const char *description, std::string (Handler::* get)(const SolverOption&, Info) const, void (Handler::* set)(const SolverOption&, fmt::StringRef, Info), Info info, ValueArrayRef values = ValueArrayRef())

The same as above but with Info argument passed by value.

Note

description “HIDDEN” means the option is not printed

inline option_iterator option_begin() const

Get the start const-iterator.

inline option_iterator option_end() const

Get the end const-iterator.

inline set_option_iterator set_option_begin() const

Get the start writeable iterator.

inline set_option_iterator set_option_end() const

Get the end writeable iterator.

void AddSolveResults(const SRRegMap &sm, bool ifCanReplace = false)

Add a map with result descriptions.

inline const SRRegMap &GetSolveResultRegistry() const

Get the registry.

Public Static Functions

static inline const char *GetSolverName()

Name displayed in messages.

static inline std::string GetSolverVersion()

And version.

static inline const char *GetAMPLSolverName()

AMPL solver name is used to parse solver options for the [name]_options environment variable.

This is only done if the [executable_name]_options variable is not provided.

static inline const char *GetAMPLSolverLongName()

Unused.

static inline long Date()

Unused.

static inline int Flags()

Default mp::Solver flags, used there to implement multiobj and .nsol.

static std::string ToString(const WarningsMap::value_type &wrn)

Stringify a WarningsMap entry.

Protected Types

using PMM = std::unique_ptr<BasicModelManager>

Protected Functions

inline virtual void ObjPriorities(ArrayRef<int>)

MULTIOBJ support.

Placeholder: set objective priorities

inline virtual void ObjWeights(ArrayRef<double>)

Placeholder: set objective weights.

Presolve the values if needed

inline virtual void ObjAbsTol(ArrayRef<double>)

Placeholder: set objective abs tol Presolve the values if needed.

inline virtual void ObjRelTol(ArrayRef<double>)

Placeholder: set objective rel tol Presolve the values if needed.

inline virtual double Kappa()

MULTISOL support No API to overload, Impl should check need_multiple_solutions() and call ReportIntermediateSolution({x, pi, objvals}) for each (postsolve the values if needed)

Kappa estimate Placeholder: retrieve Kappa

virtual void Solve() override = 0

Solve, no model modification any more.

Can report intermediate results via ReportIntermediateSolution() during this, otherwise in ReportResults()

inline virtual void Report()

Report.

inline virtual void InputStdExtras()

Standard extras.

inline virtual void SetupTimerAndInterrupter()

Timer, interrupter.

inline virtual void SetupInterrupter()

Call SetInterrupter() which can be defined in Impl.

virtual void SetInterrupter(mp::Interrupter*) = 0

Placeholder for interrupt notifier in Impl.

inline virtual void ReportTimes()
inline virtual void InputFeasrelaxData()

Input feasrelax data Impl should presolve it if needed.

inline virtual void ReportSuffixes()

Report suffixes.

inline virtual void ReportStandardSuffixes()

Report standard suffixes.

inline virtual void ReportKappa()

Report Kappa.

inline virtual void ReportCustomSuffixes()

Placeholder: report custom suffixes.

inline void ReportIntermediateSolution(Solution sol)

Callback.

Parameters

sol – postsolved solution. Normally report all alternative solutions, including the final one, before reporting the final solution via standard way (ReportSolution).

inline virtual void ReportSolution()

Report final solution.

inline virtual void ReportSolution2AMPL()

to AMPL via SOL file

inline virtual void Abort(int solve_code_now, std::string msg)

Abort.

inline void RoundSolution(std::vector<double> &sol, fmt::MemoryWriter &writer)

MIP solution rounding. Better use solver’s capabilities.

inline std::pair<int, double> DoRound(std::vector<double> &sol)
inline void ModifySolveCodeAndMessageAfterRounding(std::pair<int, double> rndres, fmt::MemoryWriter &writer)
inline virtual int SolveCode() const

Solve result number.

inline const char *SolveStatus() const

Solver result message.

inline void SetStatus(std::pair<int, std::string> stt)

Set solve result.

inline virtual bool IsProblemSolved() const

Following the taxonomy of the enum sol, returns true if we have an optimal solution or a feasible solution for a satisfaction problem.

inline virtual bool IsProblemSolvedOrFeasible() const

Solved or feasible.

inline virtual bool IsProblemIndiffInfOrUnb() const

Undecidedly infeas or unbnd.

inline virtual bool IsProblemInfOrUnb() const

Infeasible or unbounded.

inline virtual bool IsProblemInfeasible() const
inline virtual bool IsProblemUnbounded() const
inline virtual bool IsSolStatusRetrieved() const
inline bool IsFinite(double n) const

Use the solver’ inf.

inline void AddToSolverMessage(const std::string &msg)
inline bool onlyRecordOptions()
inline void RecordSolverOption(SlvOptionRecord sor)
inline void ReplaySolverOptions()
template<class KeyType, class ValueType = std::string>
inline void AddSolverOption(const char *name_list, const char *description, KeyType k, ValueType, ValueType)

Adding solver options of types int/double/string/…

The type is deduced from the two last parameters min, max (currently unused otherwise.) If min/max omitted, assume ValueType=std::string Assumes existence of Impl::Get/SetSolverOption(KeyType, ValueType(&))

template<class KeyType, class ValueType = std::string>
inline void AddSolverOption(const char *name_list, const char *description, KeyType k)

String-valued option.

template<class KeyType, class ValueType = std::string>
inline void AddSolverOption(const char *name_list, const char *description, KeyType k, ValueArrayRef values, ValueType defaultValue)

With value table.

Type deduced from defaultValue

template<class KeyType>
inline void AddSolverOption(const char *name_list, const char *description, KeyType k, ValueArrayRef values, const char *defaultValue)

With value table: specialize for const char*.

inline int exportKappa() const
inline FeasrelaxIO &feasrelax()

Feasrelax I/O data.

inline double lbpen() const
inline double ubpen() const
inline double rhspen() const
inline int round() const

Whether to round MIP solution and modify messages.

inline double round_reptol() const

MIP solution rounding reporting tolerance.

inline int exportFileMode() const

Return 2 if we only need to write the problem, 1 if solution and export are wanted, 0 if no export is needed or supported.

inline const std::vector<std::string> &export_file_names() const
inline virtual void InitStandardOptions()
inline virtual void InitCustomOptions()
inline std::vector<double> FillFeasrelaxPenalty(ArrayRef<double> suf_pen, double pen, int n)

Returns {} if these penalties are +inf.

inline bool need_multiple_solutions() const

For Impl to check if user wants multiple solutions reported.

void InitMetaInfoAndOptions(fmt::CStringRef name, fmt::CStringRef long_name, long date, int flags)

InitMetaInfoAndOptions.

Derived classes which want to provide the info after construction can use the default constructor and call this.

Parameters
  • date – The solver date in YYYYMMDD format.

  • flags – Bitwise OR of zero or more of the following values MULTIPLE_SOL MULTIPLE_OBJ

inline const BasicModelManager &GetMM() const
inline BasicModelManager &GetMM()
inline void SetMM(PMM pmm)
inline virtual void HandleSolution(int status, fmt::CStringRef msg, const double *x, const double *y, double obj)

Access to ModelManager’s interface.

inline virtual void HandleFeasibleSolution(int solve_code, fmt::CStringRef msg, const double *x, const double *y, double obj)
inline virtual ArrayRef<double> InitialValues()

Variables’ initial values.

inline virtual ArrayRef<int> InitialValuesSparsity()

Variables’ initial values: sparsity.

inline virtual ArrayRef<double> InitialDualValues()

Initial dual values.

inline virtual ArrayRef<int> InitialDualValuesSparsity()

Initial dual values.

template<class N>
inline ArrayRef<N> ReadSuffix(const SuffixDef<N> &suf)

Read unpresolved suffix.

inline virtual ArrayRef<int> ReadIntSuffix(const SuffixDef<int> &suf)
inline virtual ArrayRef<double> ReadDblSuffix(const SuffixDef<double> &suf)
inline virtual size_t GetSuffixSize(int kind)
inline virtual void ReportSuffix(const SuffixDef<int> &suf, ArrayRef<int> values)

Record suffix values which are written into .sol by HandleSolution() Does nothing if vector empty.

inline virtual void ReportSuffix(const SuffixDef<double> &suf, ArrayRef<double> values)
inline virtual void ReportIntSuffix(const SuffixDef<int> &suf, ArrayRef<int> values)
inline virtual void ReportDblSuffix(const SuffixDef<double> &suf, ArrayRef<double> values)
template<class N>
inline void ReportSingleSuffix(const SuffixDef<N> &suf, N value)

Report single value for all elements of the suffix.

inline const std::vector<bool> &IsVarInt() const

Access original (NL) model instance: integrality flags.

Used in solution rounding.

inline bool HasUnfixedIntVars() const

Solver-facing instance info: has unfixed integer variables?

inline char **GetArgvOptions() const

0-terminated list of custom options

inline int GetOptionFlags() const

option parser flags

inline void set_long_name(fmt::StringRef name)
inline void add_to_long_name(fmt::StringRef name)
inline void set_version(fmt::StringRef version)
inline void add_to_version(fmt::StringRef version)
inline void set_license_info(fmt::StringRef license_info)
inline virtual std::string set_external_libs()
inline void set_read_flags(unsigned flags)

Sets the flags for Problem::Read.

inline Stats &stats()

Protected Attributes

bool onlyRecordOptions_ = false

Protected Static Functions

static inline constexpr double AMPLInf()

AMPL’s inf.

static inline constexpr double AMPLMinusInf()

AMPL’s -inf.

Private Types

using SlvOptionRecord = std::function<void(void)>

Recorded solver options.

Private Members

std::pair<int, std::string> status_ = {sol::NOT_SET, "status not set"}
int kIntermSol_ = 0
std::pair<double, double> objIntermSol_ = {-1e100, 1e100}
std::string solver_msg_extra_
std::vector<SlvOptionRecord> slvOptionRecords_
struct mp::StdBackend::Options storedOptions_
class mp::StdBackend::FeasrelaxIO feasRelaxIO_
const SuffixDef<int> suf_objpriority = {"objpriority", suf::OBJ | suf::INPUT}
const SuffixDef<double> suf_objweight = {"objweight", suf::OBJ | suf::INPUT}
const SuffixDef<double> suf_objabstol = {"objabstol", suf::OBJ | suf::INPUT}
const SuffixDef<double> suf_objreltol = {"objreltol", suf::OBJ | suf::INPUT}
const SuffixDef<double> suf_objkappa = {"kappa", suf::OBJ | suf::OUTONLY}
const SuffixDef<double> suf_probkappa = {"kappa", suf::PROBLEM | suf::OUTONLY}
template<class Value>
class mp::SolverOptionManager::StoredOption : public mp::TypedSolverOption<Value>
#include <solver-opt.h>

Stored option: references a variable.

StoredOption<bool> is specialized.

Public Types

using value_type = Value
enum Option_Type

Option type classifier, used in AMPLS.

Values:

enumerator BOOL
enumerator INT
enumerator DBL
enumerator STRING

Public Functions

inline StoredOption(const char *name_list, const char *description, Value &v, ValueArrayRef values = ValueArrayRef())
inline void GetValue(Value &v) const override
inline void SetValue(typename internal::OptionHelper<Value>::Arg v) override
inline virtual void Write(fmt::Writer &w) override

Formats the option value.

Throws OptionError in case of error. Not called for flags.

inline virtual void Parse(const char *&s, bool splitString = false) override

Parses the string for an option value, throws an exception if the value is invalid.

Parameters
  • s – string to be parsed

  • splitString – set to true to identify that the options string has already been pre-parsed (by the command line interpreter) so it is now in the format of null terminated substrings. If parsed from the environment variable, the string is monolithic, space separated and quotes have to be considered.

inline virtual Option_Type type() override

Return type classifier.

inline const char *name() const

Return the option name.

const char *name_ASL() const

Return the ASL (not qualified) name as the first inline synonym - or the name itself if no synonyms are defined.

inline const std::vector<std::string> &inline_synonyms() const

Returns the “inline” synonyms.

void add_synonyms_front(const char *names_list)

Add additional “inline” synonyms.

void add_synonyms_back(const char *names_list)
inline bool is_hidden() const

Is hidden?

inline bool is_wildcard() const

Wildcards.

bool wc_match(const std::string &key)

Checks if matches, then saves key & body.

inline const std::string &wc_head() const
inline const std::string &wc_tail() const
inline const std::string &wc_key_last() const
inline const std::string &wc_keybody_last() const
inline std::string wc_key_last__std_form() const

Printing last parsed wc key in std form.

inline const char *description() const

Return/set the option description.

inline void set_description(const char *d)
inline void add_to_description(const char *d)
inline void format_description(fmt::MemoryWriter &writer, int indent = 0) const

Append the formatted description to the writer.

inline std::string format_description(int indent = 0) const

Get the formatted option description.

inline ValueArrayRef values() const

Returns the information about possible values.

inline virtual bool is_flag() const

Returns true if this option is a flag, i.e. it doesn’t take a value.

inline virtual void GetValue(fmt::LongLong&) const

Returns the option value.

inline virtual void GetValue(double&) const
inline virtual void GetValue(std::string&) const
inline virtual void GetValue(int &int_value) const
template<typename T>
inline T GetValue() const
inline virtual void SetValue(fmt::LongLong)

Sets the option value or throws InvalidOptionValue if the value is invalid.

inline virtual void SetValue(double)
inline virtual void SetValue(fmt::StringRef)
inline virtual void SetValue(int value)
inline virtual std::string echo_with_value()

Echo option name(s) [= value].

inline virtual std::string echo()

Echo option name(s).

Private Members

Value &value_
template<>
class mp::SolverOptionManager::StoredOption<bool> : public mp::TypedSolverOption<int>
#include <solver-opt.h>

Stored option <bool>.

Can only be set to True.

Public Types

using value_type = bool
enum Option_Type

Option type classifier, used in AMPLS.

Values:

enumerator BOOL
enumerator INT
enumerator DBL
enumerator STRING

Public Functions

inline StoredOption(const char *name_list, const char *description, bool &v, ValueArrayRef values = ValueArrayRef())
inline virtual bool is_flag() const override

We are a flag.

inline virtual void Parse(const char*&, bool = false) override

Parse: only set to True.

inline virtual void GetValue(int &v) const override

Dummy.

inline virtual void SetValue(int v) override
inline virtual void Write(fmt::Writer &w) override

Formats the option value.

Throws OptionError in case of error. Not called for flags.

inline virtual Option_Type type() override

Return type classifier.

inline const char *name() const

Return the option name.

const char *name_ASL() const

Return the ASL (not qualified) name as the first inline synonym - or the name itself if no synonyms are defined.

inline const std::vector<std::string> &inline_synonyms() const

Returns the “inline” synonyms.

void add_synonyms_front(const char *names_list)

Add additional “inline” synonyms.

void add_synonyms_back(const char *names_list)
inline bool is_hidden() const

Is hidden?

inline bool is_wildcard() const

Wildcards.

bool wc_match(const std::string &key)

Checks if matches, then saves key & body.

inline const std::string &wc_head() const
inline const std::string &wc_tail() const
inline const std::string &wc_key_last() const
inline const std::string &wc_keybody_last() const
inline std::string wc_key_last__std_form() const

Printing last parsed wc key in std form.

inline const char *description() const

Return/set the option description.

inline void set_description(const char *d)
inline void add_to_description(const char *d)
inline void format_description(fmt::MemoryWriter &writer, int indent = 0) const

Append the formatted description to the writer.

inline std::string format_description(int indent = 0) const

Get the formatted option description.

inline ValueArrayRef values() const

Returns the information about possible values.

inline virtual void GetValue(fmt::LongLong&) const

Returns the option value.

inline virtual void GetValue(double&) const
inline virtual void GetValue(std::string&) const
template<typename T>
inline T GetValue() const
inline virtual void SetValue(fmt::LongLong)

Sets the option value or throws InvalidOptionValue if the value is invalid.

inline virtual void SetValue(double)
inline virtual void SetValue(fmt::StringRef)
inline virtual std::string echo_with_value()

Echo option name(s) [= value].

inline virtual std::string echo()

Echo option name(s).

Private Members

bool &value_
class mp::StringFileWriter
#include <nl-writer2.hpp>

Write strings to a file.

The file is only opened when the user calls operator bool() or upon 1st write. If nothing written, the file is removed (if exists).

Public Types

using TOpener = std::function<File(bool)>

bool: true if should remove the file

using StrStrValue = std::pair<const char*, const char*>

Typedef StrStrValue.

using StrDblValue = std::pair<const char*, double>

Typedef StrDblValue.

Public Functions

inline StringFileWriter(int &lmax, TOpener opener)

Construct.

StringFileWriter(const StringFileWriter&) = delete

No copy.

inline ~StringFileWriter()

Destroy.

void operator=(const StringFileWriter&) = delete

No assign.

inline operator bool()

oper bool()

template<class Value>
inline void Write(Value s)

Write const char*, StrStrValue, StrDblValue.

Protected Functions

inline bool Open()
inline int Print_ReturnLen1(const char *s)
inline int Print_ReturnLen1(StrStrValue p)
inline int Print_ReturnLen1(StrDblValue p)

Private Members

int &len_max_
TOpener opener_
File nm
bool fTriedOpen_ = {false}
int cnt_ = {0}
class mp::StringLiteral : public mp::BasicExpr<expr::STRING>
#include <expr.h>

String Literal.

Public Types

enum [anonymous]

Values:

Public Functions

inline const char *value() const

String literal value.

Protected Types

typedef ExprBase::Impl Impl

Reuse ExprBase::Impl.

typedef BasicExpr Base

Base = BasicExpr.

Private Functions

MP_EXPR(Base)
template<int N>
struct mp::Convert1ExpC::SubexprTraits
#include <cones.h>

Characterize target subexpression.

Public Functions

inline SubexprTraits(std::array<double, N> c = {}, std::array<int, N> v = {}, std::vector<int> v2d = {})

Construct.

inline operator bool() const

Valid?

Public Members

std::array<double, N> coefs_

Variables to use.

Coefs

std::array<int, N> vars_

-1 means ‘use constant 1’.

std::vector<int> vars2del_

Vars to delete.

bool valid_ = {false}

Valid?

struct ExampleModel::Suffix
#include <nlsol_ex_mdl.h>

Suffixes.

Public Members

const char *name_
int kind_
std::vector<double> values_
class mp::Suffix : private mp::internal::SuffixBase
#include <suffix.h>

A suffix.

Suffixes are data that can be attached to variables, objectives, constraints and problems.

Subclassed by mp::MutSuffix

Public Functions

inline Suffix()
template<typename T>
inline Suffix(BasicSuffix<T> other)
template<typename Visitor>
inline void VisitValues(Visitor &v) const

Iterates over nonzero suffix values and sends them to the visitor.

Private Functions

inline explicit Suffix(const Impl *impl)

Friends

friend class internal::SuffixBase
friend class MutSuffix
friend class BasicSuffixSet
struct Suffix
#include <nlsol_ex_c_model.h>

Suffix.

Public Members

const char *name_
int kind_
int n_val_
const SparseEntry *values_
class mp::internal::SuffixBase
#include <suffix.h>

Subclassed by mp::BasicSuffix< T >, mp::Suffix

Public Functions

inline SuffixBase()

Constructs a Suffix object representing a null reference to a suffix.

The only operation permitted for such object is copying, assignment and check whether it is null using operator SafeBool.

inline const char *name() const

Returns the suffix name.

inline int kind_pure() const

Returns the suffix pure kind (var/con/prob/obj).

inline int kind() const

Returns the suffix kind.

inline void or_kind(int flg)

Or’s the kind with a given int argument.

inline int num_values() const
template<class T>
inline ArrayRef<T> get_values() const

Don’t use.

inline const SuffixTable &table() const
inline operator SafeBool() const

Returns a value convertible to bool that can be used in conditions but not in comparisons and evaluates to “true” if this suffix is not null and “false” otherwise.

Example: if (s) { // Do something if s is not null. }

template<>
inline ArrayRef<int> get_values() const
template<>
inline ArrayRef<double> get_values() const

Protected Types

typedef void (SuffixBase::* SafeBool)() const

Protected Functions

template<typename SuffixType>
inline explicit SuffixBase(SuffixType s)
inline void get_value(int index, int &value) const
inline void set_value(int index, int value)
inline void get_value(int index, double &value) const
inline void set_value(int index, double value)
inline const Impl *impl() const
inline explicit SuffixBase(const Impl *impl)

Private Functions

inline void True() const

Private Members

const Impl *impl_
template<class T>
class mp::SuffixDef
#include <suffix.h>

High-level suffix description.

This is a suffix of a specific kind - var/con/obj/prob.

Public Types

using value_type = T

Public Functions

inline SuffixDef(fmt::StringRef nm, int ki, const SuffixTable &st = {})
inline fmt::StringRef name() const
inline int kind() const
inline const SuffixTable &table() const
template<class T2>
inline SuffixDef<T2> to_type() const

Convert type.

Private Members

fmt::StringRef name_
int kind_
SuffixTable tab_
template<typename T>
class mp::BasicProblem::SuffixHandler
#include <problem.h>

Suffixes.

Public Types

typedef void (internal::SuffixBase::* SafeBool)() const

Safe bool type.

Public Functions

inline explicit SuffixHandler(BasicMutSuffix<T> s)
inline operator SafeBool() const
inline void SetValue(int index, T value)

Sets the suffix value.

Private Members

BasicMutSuffix<T> suffix_
template<typename T>
struct mp::ProblemBuilder::SuffixHandler

Public Functions

inline void SetValue(int index, T value)
template<typename T>
struct mp::internal::SuffixInfo
#include <suffix.h>

Public Types

enum [anonymous]

Values:

enumerator KIND
class mp::Solver::SuffixInfo
#include <solver.h>

Public Functions

inline SuffixInfo(const char *name, const char *table, int kind, int nextra)
inline const char *name() const
inline const char *table() const
inline int kind() const
inline int nextra() const

Private Members

const char *name_
const char *table_
int kind_
int nextra_
class mp::SuffixInfo
#include <sol-reader2.h>

Suffix info.

Public Functions

inline SuffixInfo(int k, std::string n, std::string t)

Construct.

inline int Kind() const

Suffix kind.

inline const std::string &Name() const

Suffix name.

inline const std::string &Table() const

Suffix table.

Private Members

int kind_
std::string name_
std::string table_
template<>
struct mp::internal::SuffixInfo<double>
#include <suffix.h>

Public Types

enum [anonymous]

Values:

enumerator KIND
class mp::SuffixManager
#include <suffix.h>

SuffixManager.

Stores SuffixSet’s for the 4 suffix kinds.

Subclassed by mp::BasicProblem< ProblemParams >, mp::ProblemBuilder< Impl, ExprType >

Public Types

typedef MutSuffix Suffix
typedef MutIntSuffix IntSuffix
typedef mp::SuffixSet SuffixSet

Public Functions

inline virtual ~SuffixManager()

Virtual destructor.

inline SuffixSet &suffixes(suf::Kind kind)

Returns a set of suffixes.

inline const SuffixSet &suffixes(suf::Kind kind) const

Private Members

mp::SuffixSet suffixes_[internal::NUM_SUFFIX_KINDS]

Private Static Functions

static inline void Check(suf::Kind kind)
struct mp::BasicSuffixSet::SuffixNameLess

Public Functions

inline bool operator()(const SuffixImpl &lhs, const SuffixImpl &rhs) const
template<class Element>
class mp::SuffixReader : public mp::VecReader<Element>
#include <sol-reader2.h>

Class SuffixReader<>

Public Types

using value_type = Value

Typedef value_type.

Public Functions

inline SuffixReader(SuffixInfo si, FILE *f, int b, int n)

Construct.

inline const SuffixInfo &SufInfo() const

Suffix info.

inline int Size() const

Size remaining to read.

Value ReadNext()

Read next value.

inline void SetError(NLW2_SOLReadResultCode res, std::string msg)

Set error status.

inline NLW2_SOLReadResultCode ReadResult() const

status

inline const std::string &ErrorMessage() const

error message

Private Members

SuffixInfo si_
class mp::internal::SuffixValueCounter
#include <sol.h>

Suffix value visitor that counts values.

Public Functions

inline SuffixValueCounter()
inline int num_values() const
template<typename T>
inline void Visit(int, T)

Private Members

int num_values_
class mp::internal::SuffixValueWriter
#include <sol.h>

Suffix value visitor that writes values to a file.

Public Functions

inline explicit SuffixValueWriter(fmt::BufferedFile &file)
template<typename T>
inline void Visit(int index, T value)
inline void Visit(int index, double value)

Private Members

fmt::BufferedFile &file_
class mp::NLWriter2::SuffixWriterFactory
#include <nl-writer2.h>

Suffixes.

Public Functions

inline SuffixWriterFactory(NLWriter2 &nlw)

Construct.

SuffixIntWriter StartIntSuffix(const char *name, int kind, int nnz)

Start writing an int-valued suffix.

SuffixDblWriter StartDblSuffix(const char *name, int kind, int nnz)

Start writing an dbl-valued suffix.

Private Members

NLWriter2 &nlw_
struct mp::SufHead
#include <sol-reader2.hpp>

Suffix head.

Public Members

char sufid[8]
int kind
int n
int namelen
int tablen
struct mp::SufRead
#include <sol-reader2.hpp>

Suffix read data.

Public Members

SufHead h
char *name
char *tabname
char *table
std::vector<char> xp
int tablines
struct mp::internal::NLReader::SymbolicExprReader

Public Types

typedef Handler::Expr Expr

Public Functions

inline Expr Read(NLReader &r) const
class mp::LinearExpr::Term

Public Functions

inline int var_index() const
inline double coef() const
inline void set_coef(double c)
inline void operator*=(double n)

Private Functions

inline Term(int var_index, double coef)

Private Members

int var_index_
double coef_

Friends

friend class LinearExpr
class mp::TextFormatter
#include <nl-writer2-misc.h>

Text formatter.

Public Functions

inline TextFormatter(NLUtils &u, bool nlc, int outprec = 0)

Construct.

inline NLHeader::Format Mode() const

Mode query.

int apr(File&, const char*, ...)

Text printf.

For printing to .nl or auxiliary files.

void nput(File&, double)

Text nput.

inline NLUtils &Utils()

Retrieve utils.

Private Members

NLUtils &utils_
const bool nl_comments = {false}
const int output_prec = {0}
template<typename Locale = Locale>
class mp::internal::TextReader : public mp::internal::ReaderBase
#include <nl-reader.h>

Public Functions

TextReader(NLStringRef data, fmt::CStringRef name)
inline Locale &locale()
inline void ReportError(fmt::CStringRef format_str, const fmt::ArgList &args)
inline void ReadTillEndOfLine()
template<typename Int>
inline Int ReadInt()
inline int ReadUInt()
inline double ReadDouble()
fmt::StringRef ReadString()
fmt::StringRef ReadName()

Reads a function or suffix name.

void ReadHeader(NLHeader &header)

Reads an .nl file header.

The header is always in text format, so this function doesn’t have a counterpart in BinaryReader.

inline char ReadChar()
inline const char *ptr() const
inline void set_ptr(const char *ptr)
inline bool IsEOF(const char *ptr) const
inline bool IsEOF() const

Protected Attributes

const char *ptr_
const char *start_
const char *end_
const char *token_
std::string name_

Private Functions

template<typename Int>
inline bool ReadIntWithoutSign(Int &value)

Reads an integer without a sign.

Int: signed or unsigned integer type.

template<typename Int>
inline bool DoReadOptionalInt(Int &value)
inline int ReadUInt(int &accumulator)

Reads a nonnegative integer and checks that adding it to accumulator doesn’t overflow.

template<typename Int>
inline Int ReadUInt()
inline bool ReadOptionalInt(int &value)
inline bool ReadOptionalUInt(int &value)
bool ReadOptionalDouble(double &value)
void DoReportError(const char *loc, fmt::CStringRef format_str, const fmt::ArgList &args = fmt::ArgList())
inline void SkipSpace()

Private Members

const char *line_start_
int line_
CopyableLocale locale_
struct ThInfo

Public Members

Bigint *Freelist[Kmax + 1]
Bigint *P5s
template<typename T>
class mp::TypedSolverOption : public mp::SolverOption
#include <solver-opt.h>

Subclassed by mp::SolverOptionManager::ConcreteOptionWithInfo< SolverOptionAccessor< ValueType, KeyType >, ValueType, KeyType >, mp::SolverOptionManager::ConcreteOption< Handler, T, AccessorT >, mp::SolverOptionManager::ConcreteOptionWithInfo< Handler, T, Info, InfoArg, AccessorT >

Public Types

enum Option_Type

Option type classifier, used in AMPLS.

Values:

enumerator BOOL
enumerator INT
enumerator DBL
enumerator STRING

Public Functions

inline TypedSolverOption(const char *name, const char *description, ValueArrayRef values = ValueArrayRef())
inline virtual void Write(fmt::Writer &w) override

Formats the option value.

Throws OptionError in case of error. Not called for flags.

inline virtual void Parse(const char *&s, bool splitString = false) override

Parses the string for an option value, throws an exception if the value is invalid.

Parameters
  • s – string to be parsed

  • splitString – set to true to identify that the options string has already been pre-parsed (by the command line interpreter) so it is now in the format of null terminated substrings. If parsed from the environment variable, the string is monolithic, space separated and quotes have to be considered.

inline virtual Option_Type type() override

Return type classifier.

inline const char *name() const

Return the option name.

const char *name_ASL() const

Return the ASL (not qualified) name as the first inline synonym - or the name itself if no synonyms are defined.

inline const std::vector<std::string> &inline_synonyms() const

Returns the “inline” synonyms.

void add_synonyms_front(const char *names_list)

Add additional “inline” synonyms.

void add_synonyms_back(const char *names_list)
inline bool is_hidden() const

Is hidden?

inline bool is_wildcard() const

Wildcards.

bool wc_match(const std::string &key)

Checks if matches, then saves key & body.

inline const std::string &wc_head() const
inline const std::string &wc_tail() const
inline const std::string &wc_key_last() const
inline const std::string &wc_keybody_last() const
inline std::string wc_key_last__std_form() const

Printing last parsed wc key in std form.

inline const char *description() const

Return/set the option description.

inline void set_description(const char *d)
inline void add_to_description(const char *d)
inline void format_description(fmt::MemoryWriter &writer, int indent = 0) const

Append the formatted description to the writer.

inline std::string format_description(int indent = 0) const

Get the formatted option description.

inline ValueArrayRef values() const

Returns the information about possible values.

inline virtual bool is_flag() const

Returns true if this option is a flag, i.e. it doesn’t take a value.

inline virtual void GetValue(fmt::LongLong&) const

Returns the option value.

inline virtual void GetValue(double&) const
inline virtual void GetValue(std::string&) const
inline virtual void GetValue(int &int_value) const
template<typename T>
inline T GetValue() const
inline virtual void SetValue(fmt::LongLong)

Sets the option value or throws InvalidOptionValue if the value is invalid.

inline virtual void SetValue(double)
inline virtual void SetValue(fmt::StringRef)
inline virtual void SetValue(int value)
inline virtual std::string echo_with_value()

Echo option name(s) [= value].

inline virtual std::string echo()

Echo option name(s).

struct mp::FlatModelInfoImpl::TypeInfoRefEqualTo
#include <model_info.hpp>

TypeInfoRef ==.

Public Functions

inline bool operator()(TypeInfoRef lhs, TypeInfoRef rhs) const
struct mp::FlatModelInfoImpl::TypeInfoRefHasher
#include <model_info.hpp>

TypeInfoRefHasher.

Public Functions

inline std::size_t operator()(TypeInfoRef code) const
union U

Public Members

double d
ULong L[2]
ULLong LL
class mp::UnsupportedError : public mp::Error
#include <error.h>

The operation is not supported by the object.

Public Functions

inline int exit_code() const

The exit code.

Protected Functions

inline void SetMessage(const std::string &message)
inline void init(fmt::CStringRef format_str, fmt::ArgList args)
class mp::ValueArrayRef
#include <solver-opt.h>

A reference to an array of OptionValueInfo objects.

Public Types

typedef const OptionValueInfo *iterator

Public Functions

inline ValueArrayRef()
template<int SIZE>
inline ValueArrayRef(const OptionValueInfo (&values)[SIZE], int offset = 0)
inline int size() const
inline iterator begin() const
inline iterator end() const

Private Members

const OptionValueInfo *values_
int size_
template<class Array, class Param = int>
class mp::pre::ValueMap
#include <valcvt-base.h>

Value(Node) map.

Contains a map of either:

  • concrete arrays of int’s and/or double’s (ValueMapInt/Dbl), or

  • ValueNode’s (conversion graph nodes) which manage such arrays.

The data in a single map corresponds to either variables, constraints, or objectives, and map keys correspond to different item subcategories (e.g., linear vs quadratic constraints). When IsSingleKey(), the map only has a single array (at key 0), accessible via ().

Parameters
  • Array – the type of array stored (std::vector(int) / (double)), or ValueNode.

  • Param – type of parameter to call CreateArray < Array > (Param) when we need to create a mapped value.

Public Types

using ParamType = Param

Typedef ParamType.

using MapType = std::map<int, Array>

Typedef to map item type number to value array For example, distinguish values for linear constraints etc.

Public Functions

inline ValueMap(Param p = {})

Constructor.

template<class SomeArray>
inline ValueMap(const SomeArray &r)

Construct from a single SomeArray.

inline ValueMap(MapType m)

Construct from the low-level MapType.

template<class Array2>
inline ValueMap(const std::map<int, Array2> &llm)

Construct from a low-level map<AnotherArray>

template<class Array2, class Param2>
inline ValueMap(const ValueMap<Array2, Param2> &m)

Construct from another map.

template<class Array2>
inline ValueMap &operator=(const ValueMap<Array2> &m)

Assign from another map.

inline bool Empty() const

Empty() if no values or all values empty()

inline bool IsSingleKey() const

Check if we have only the single key.

inline Array &MakeSingleKey()

Make single key, or check one, and return.

inline const Array &operator()() const &

Retrieve the single array, const.

inline Array operator()() &&

Move out the single array, rvalue.

inline Array &operator()() &

Retrieve the single array (creating if need)

inline const Array &operator()(int i) const &

Retrieve the array with key i, const.

inline Array operator()(int i) &&

Move out the array with key i, rvalue.

inline Array &operator()(int i) &

Retrieve the array with key i (creating if need)

inline Array MoveOut()

Move out the single array.

inline Array MoveOut(int i)

Move out array i.

inline const MapType &GetMap() const

Retrieve the whole map.

inline void SetName(std::string s)

Set map name.

Private Members

Param prm_
std::string name_ = {"VMapName__unset"}
MapType map_
class mp::pre::ValueNode
#include <valcvt-node.h>

Value node, a node of the conversion graph.

Stores arrays of int’s, double’s, and VCString’s corresponding to variables, or a constraint type, or objectives. The data is stored temporarily during a conversion run.

Public Functions

inline ~ValueNode()

Destructor.

inline ValueNode(BasicValuePresolver &pre, std::string nm = {})

Constructor.

Need ValuePresolver to register itself.

inline ValueNode(ValueNode &&vn)

Move constructor.

inline ValueNode(const ValueNode &vn)

Copy constructor.

inline bool Empty() const

bool Empty(). True when Size()==0

inline bool empty() const

bool empty().

True when actual values are empty or 0. Has STL syntax.

inline size_t Size() const

Declared size (what is being used by links)

inline NodeRange Add(int n = 1)

Create entry (range) pointer: add n elements.

inline NodeRange Select(int pos, int n = 1)

Create entry (range) pointer: select n elements at certain pos pos=-1 means last.

inline ValueNode &operator=(std::vector<int> ai)

Assign from ArrayRef<int>.

Always copy the values. Some (target) node assignments can be longer vectors: e.g., Gurobi adds variables for FeasRelax.

inline ValueNode &operator=(std::vector<double> ad)

Assign from vector. Always copy.

inline ValueNode &operator=(std::vector<VCString> as)

Assign from vector. Always copy.

inline operator ArrayRef<int>() const

Retrieve whole ArrayRef<int>

inline operator ArrayRef<double>() const

Retrieve whole ArrayRef<double>

inline operator ArrayRef<VCString>() const

Retrieve whole ArrayRef<str>

template<class T>
inline std::vector<T> &GetValVec()

Retrieve vec<T>& - dummy version.

inline operator const std::vector<int>&() const

Retrieve whole const vector<int>&.

inline operator const std::vector<double>&() const

Retrieve whole vector<double>&.

inline operator const std::vector<VCString>&() const

Retrieve whole vector<VCString&>&.

inline const std::vector<VCString> &GetStrVec() const

Retrieve whole const vector<VCString&>&.

inline std::vector<VCString> &GetStrVec()

Retrieve whole vector<VCString&>&.

template<class T>
inline const T &GetVal(size_t) const

Retrieve T, dummy version.

template<class T>
inline void SetVal(size_t i, T)

Set T, dummy version.

inline int GetInt(size_t i) const

Retrieve int[i].

inline const int &GetIntRef(size_t i) const

Retrieve int[i].

inline void SetInt(size_t i, int v)

Set int[i].

If existing value non-0, only allow larger value.

inline double GetDbl(size_t i) const

Retrieve double[i].

inline const double &GetDblRef(size_t i) const

Retrieve double[i].

inline void SetDbl(size_t i, double v)

Set double[i].

CONFLICT RESOLUTION: If existing value non-0, only allow larger value.

inline const VCString &GetStr(size_t i) const

Retrieve string[i].

inline void SetStr(size_t i, VCString v)

Set string[i].

CONFLICT RESOLUTION: If existing value non-0, only allow larger value???

inline const std::string &GetName() const

GetName.

inline void SetName(std::string s)

SetName.

inline void CleanUpAndRealloc()

Clean up and realloc with current size, fill by 0’s.

Numeric arrays only.

inline void CleanUpAndRealloc_Names()

Clean up and realloc names.

template<>
inline std::vector<double> &GetValVec()
template<>
inline std::vector<int> &GetValVec()
template<>
inline std::vector<VCString> &GetValVec()
template<>
inline const double &GetVal(size_t i) const
template<>
inline const int &GetVal(size_t i) const
template<>
inline const VCString &GetVal(size_t i) const
template<>
inline void SetVal(size_t i, double v)
template<>
inline void SetVal(size_t i, int v)
template<>
inline void SetVal(size_t i, VCString v)

Protected Functions

template<class Vec>
inline void SetNum(Vec &vec, size_t i, typename Vec::value_type v)

Set int[i] or dbl[i].

If existing value non-0, only allow larger value, BUT only if that is non-0 too. This way, the order of propagations is irrelevant.

inline void RegisterMe()

Register with the ValuePresolver.

inline void DeregisterMe()

Deregister with the ValuePresolver.

Protected Static Functions

template<class T>
static inline bool EmptyOr0(const std::vector<T> &v)

EmptyOr0 for a vector.

static inline bool EmptyOr0(const std::vector<VCString> &v)

EmptyOr0 for a vector<str>

Private Members

BasicValuePresolver &pre_
std::vector<int> vi_
std::vector<double> vd_
std::vector<VCString> vStr_
size_t sz_ = 0
std::string name_ = "default_value_node"
class mp::pre::ValuePresolver : public mp::pre::ValuePresolverImpl
#include <valcvt.h>

Final ValuePresolver.

It specializes PresolveSolution() to update fixed variables

Public Functions

inline ValuePresolver(BasicFlatModel &m, Env &env, BasicLogger &bts, SolCheckerType sc = {})
inline MVOverEl<double> PresolveSolution(const MVOverEl<double> &mv) override

Override PresolveSolution().

Move warm start values into the bounds.

inline MVOverEl<double> PostsolveSolution(const MVOverEl<double> &mv) override

Override PostsolveSolution().

Check solution if checker provided. mv’s ExtraData() is passed to the checker.

inline const ModelValuesTerminal &GetSourceNodes() const

Source nodes of the conversion graph, const.

inline ModelValuesTerminal &GetSourceNodes()

Source nodes of the conversion graph.

inline const ModelValuesTerminal &GetTargetNodes() const

Target nodes of the conversion graph, const.

inline ModelValuesTerminal &GetTargetNodes()

Target nodes of the conversion graph.

inline void Add(LinkRange br)

Add (register) a link range.

This is normally called automatically from a link when an entry is added. Exports previous entries if exporter provided.

inline bool GetExport() const

Want Export?

inline void FinishExportingLinkEntries()

Finish exporting entries, if exporting=ON.

This should be called after model conversions are finished, because the exports are lazy.

inline bool AllEntriesExported() const

Check that the whole entries list has been exported.

inline virtual LIST_PRESOLVE_METHODS void Register (ValueNode *pvn) override

Register a ValueNode*.

inline virtual void Deregister(ValueNode *pvn) override

Deregister a ValueNode*.

inline void CleanUpValueNodes() const

Clean up value nodes for new propagation.

Numeric arrays only.

inline void CleanUpNameNodes() const

Clean up name nodes for new propagation.

inline const Env &GetEnv() const

GetEnv() const.

inline Env &GetEnv()

GetEnv()

Protected Types

using LinkFn = void (BasicLink::*)(LinkIndexRange)

Helper type: virtual member function pointer.

Protected Functions

template<class ModelValues>
inline ModelValues RunPresolve(LinkFn fn, const ModelValues &mv) const

Generic value presolve loop: forward.

template<class ModelValues>
inline ModelValues RunPostsolve(LinkFn fn, const ModelValues &mv) const

Generic value postsolve loop: backward.

inline void ExportRemainingEntries()

Export unexported entries, if exporter provided.

inline void ExportLinkEntry(const BasicLink &ln, int i_entry)

Export certain link entry.

template<class JSON>
inline void WriteNodes(JSON jw, const std::vector<NodeRange> &nodes)

Write a vector of nodes.

Private Members

BasicFlatModel &model_
SolCheckerType solchk_
class mp::pre::ValuePresolverImpl : public mp::pre::BasicValuePresolver
#include <valcvt.h>

Value presolver intermediate implementation.

A ValuePresolver converts solutions and suffixes between the original model and the presolved one.

Subclassed by mp::pre::ValuePresolver

Public Functions

inline ValuePresolverImpl(Env &env, BasicLogger &bts)

Constructor.

inline const ModelValuesTerminal &GetSourceNodes() const

Source nodes of the conversion graph, const.

inline ModelValuesTerminal &GetSourceNodes()

Source nodes of the conversion graph.

inline const ModelValuesTerminal &GetTargetNodes() const

Target nodes of the conversion graph, const.

inline ModelValuesTerminal &GetTargetNodes()

Target nodes of the conversion graph.

inline void Add(LinkRange br)

Add (register) a link range.

This is normally called automatically from a link when an entry is added. Exports previous entries if exporter provided.

inline bool GetExport() const

Want Export?

inline void FinishExportingLinkEntries()

Finish exporting entries, if exporting=ON.

This should be called after model conversions are finished, because the exports are lazy.

inline bool AllEntriesExported() const

Check that the whole entries list has been exported.

inline virtual LIST_PRESOLVE_METHODS void Register (ValueNode *pvn) override

Register a ValueNode*.

inline virtual void Deregister(ValueNode *pvn) override

Deregister a ValueNode*.

inline void CleanUpValueNodes() const

Clean up value nodes for new propagation.

Numeric arrays only.

inline void CleanUpNameNodes() const

Clean up name nodes for new propagation.

inline const Env &GetEnv() const

GetEnv() const.

inline Env &GetEnv()

GetEnv()

Protected Types

using LinkFn = void (BasicLink::*)(LinkIndexRange)

Helper type: virtual member function pointer.

Protected Functions

template<class ModelValues>
inline ModelValues RunPresolve(LinkFn fn, const ModelValues &mv) const

Generic value presolve loop: forward.

template<class ModelValues>
inline ModelValues RunPostsolve(LinkFn fn, const ModelValues &mv) const

Generic value postsolve loop: backward.

inline void ExportRemainingEntries()

Export unexported entries, if exporter provided.

inline void ExportLinkEntry(const BasicLink &ln, int i_entry)

Export certain link entry.

template<class JSON>
inline void WriteNodes(JSON jw, const std::vector<NodeRange> &nodes)

Write a vector of nodes.

Private Members

std::unordered_set<ValueNode*> val_nodes_

val_nodes_ should be before src_ / dest_

mutable ModelValuesTerminal src_ = {*this, "src"}

val_nodes_ should be before src_ / dest_

ModelValuesTerminal dest_ = {*this, "dest"}
LinkRangeList brl_

The link ranges.

BasicLogger &bts_

Exporter functor.

int i_exported_ = 0

1-after-last exported entry

BasicLink::EntryItems entry_items_

Link entry items temporary storage for exporting.

struct mp::BasicProblem::Var

A variable.

Public Functions

inline Var(double lb, double ub)

Public Members

double lb
double ub
class mp::VarArrayDef
#include <model_api_base.h>

Define an array of variables.

Public Functions

VarArrayDef() = default
template<class BndVec, class TypeVec, class NameVec = ArrayRef<const char*>>
inline VarArrayDef(BndVec &&lbs, BndVec &&ubs, TypeVec &&tys, NameVec &&nms = {})
inline VarArrayDef(std::initializer_list<double> lbs, std::initializer_list<double> ubs, std::initializer_list<var::Type> tys, std::initializer_list<const char*> nms = {})
inline int size() const
inline const double *plb() const
inline const double *pub() const
inline const var::Type *ptype() const
inline void set_lb_ub_types(ArrayRef<double> lbs, ArrayRef<double> ubs, ArrayRef<var::Type> types)
inline const char *const *pnames() const
inline bool check() const

Private Members

ArrayRef<double> lbs_
ArrayRef<double> ubs_
ArrayRef<var::Type> types_
ArrayRef<const char*> names_
class mp::NLWriter2::VarBndWriter
#include <nl-writer2.h>

Write num_vars variable bounds (all except defined variables).

Public Functions

inline VarBndWriter(NLWriter2 &nlw)

Construct.

void WriteLbUb(double lb, double ub)

Write range for the next variable.

inline int GetNWritten() const

Get N written.

Private Members

NLWriter2 &nlw_
int nWrt_ = 0
template<typename Handler>
class mp::internal::VarBoundHandler : public mp::NullNLHandler<Handler::Expr>
#include <nl-reader.h>

An NLHandler that forwards notification of variable bounds to another handler and ignores all other notifications.

Public Types

typedef ExprType Expr

An expression type.

typedef Expr NumericExpr

A numeric expression type. It is a typedef of Expr but subclasses may define it as a different type convertible to Expr.

typedef Expr LogicalExpr

A logical expression type. It is a typedef of Expr but subclasses may define it as a different type convertible to Expr.

typedef Expr CountExpr

A count expression type. It is a typedef of Expr but subclasses may define it as a different type convertible to NumericExpr.

typedef Expr Reference

A reference expression type. It is a typedef of Expr but subclasses may define it as a different type convertible to NumericExpr.

typedef LinearExprHandler LinearObjHandler

A typedef of a class that receives notifications of terms in the linear part of an objective expression.

typedef LinearExprHandler LinearConHandler

A typedef of a class that receives notifications of terms in the linear part of a constraint expression.

typedef ArgHandler NumericArgHandler

A typedef of a class that receives notifications of numeric arguments.

typedef ArgHandler VarArgHandler

A typedef of a class that receives notifications of vararg expression arguments.

typedef ArgHandler CallArgHandler

A typedef of a class that receives notifications of call expression arguments.

typedef ArgHandler NumberOfArgHandler

A typedef of a class that receives notifications of numberof expression arguments.

typedef ArgHandler CountArgHandler

A typedef of a class that receives notifications of count expression arguments.

typedef ArgHandler LogicalArgHandler

A typedef of a class that receives notifications of logical arguments.

typedef ArgHandler PairwiseArgHandler

A typedef of a class that receives notifications of pairwise expression arguments.

typedef ArgHandler SymbolicArgHandler

A typedef of a class that receives notifications of symbolic (numeric or string) arguments.

Public Functions

inline explicit VarBoundHandler(Handler &h)
inline void OnVarBounds(int index, double lb, double ub)
inline void OnUnhandled(const char*)

Receives notification of an unhandled construct and ignores it.

inline void OnHeader(const NLHeader &h)

Receives notification of an NL header.

inline bool NeedObj(int obj_index) const

Returns true if the objective with index obj_index should be handled.

inline int resulting_obj_index(int obj_index) const

Returns final objective index (e.g., returns 0 if objno>0 and multiobj=0)

inline void OnObj(int index, obj::Type type, NumericExpr expr)

Receives notification of an objective type and the nonlinear part of an objective expression.

inline void OnAlgebraicCon(int index, NumericExpr expr)

Receives notification of the nonlinear part of an algebraic constraint expression.

inline void OnLogicalCon(int index, LogicalExpr expr)

Receives notification of a logical constraint expression.

inline LinearExprHandler BeginCommonExpr(int index, int num_linear_terms)

Receives notification of the beginning of a common expression (defined variable).

inline void EndCommonExpr(int index, NumericExpr expr, int position)

Receives notification of the end of a common expression.

inline void OnComplementarity(int con_index, int var_index, ComplInfo info)

Receives notification of a complementarity relation var_lb <= x <= var_ub complements con_lb <= body <= con_ub, where x is the variable at index var_index and body is the constraint body. info gives the constraint bounds.

inline LinearObjHandler OnLinearObjExpr(int obj_index, int num_linear_terms)

Receives notification of the linear part of an objective expression.

inline LinearConHandler OnLinearConExpr(int con_index, int num_linear_terms)

Receives notification of the linear part of a constraint expression.

inline LinearExprHandler OnLinearCommonExpr(int expr_index, int num_linear_terms)

Receives notification of the linear part of a common expression.

inline void OnConBounds(int index, double lb, double ub)

Receives notification of constraint bounds (ranges).

inline void OnInitialValue(int var_index, double value)

Receives notification of the initial value for a variable.

inline void OnInitialDualValue(int con_index, double value)

Receives notification of the initial value for a dual variable.

inline ColumnSizeHandler OnColumnSizes()

Receives notification of Jacobian column sizes.

inline void OnFunction(int index, fmt::StringRef name, int num_args, func::Type type)

Receives notification of a function. The name argument is a function name and it is not null-terminated.

inline IntSuffixHandler OnIntSuffix(fmt::StringRef name, suf::Kind kind, int num_values)

Receives notification of an integer suffix. The name argument is a suffix name and it is not null-terminated. kind specifies the suffix kind.

inline DblSuffixHandler OnDblSuffix(fmt::StringRef name, suf::Kind kind, int num_values)

Receives notification of a double suffix. The name argument is a suffix name and it is not null-terminated. kind specifies the suffix kind.

inline NumericExpr OnNumber(double value)

Receives notification of a number in a nonlinear expression.

inline Reference OnVariableRef(int var_index)

Receives notification of a variable reference.

inline Reference OnCommonExprRef(int expr_index)

Receives notification of a common expression (defined variable) reference.

inline NumericExpr OnUnary(expr::Kind kind, NumericExpr arg)

Receives notification of a unary expression.

inline NumericExpr OnBinary(expr::Kind kind, NumericExpr lhs, NumericExpr rhs)

Receives notification of a binary expression.

inline NumericExpr OnIf(LogicalExpr condition, NumericExpr then_expr, NumericExpr else_expr)

Receives notification of an if expression.

inline PLTermHandler BeginPLTerm(int num_breakpoints)

Receives notification of the beginning of a piecewise-linear term.

inline NumericExpr EndPLTerm(PLTermHandler handler, Reference arg)

Receives notification of the end of a piecewise-linear term.

arg: argument that is a variable or a common expression reference.

inline CallArgHandler BeginCall(int func_index, int num_args)

Receives notification of the beginning of a call expression.

inline NumericExpr EndCall(CallArgHandler handler)

Receives notification of the end of a call expression.

inline VarArgHandler BeginVarArg(expr::Kind kind, int num_args)

Receives notification of the beginning of a vararg expression.

inline NumericExpr EndVarArg(VarArgHandler handler)

Receives notification of the end of a vararg expression.

inline NumericArgHandler BeginSum(int num_args)

Receives notification of the beginning of a summation.

inline NumericExpr EndSum(NumericArgHandler handler)

Receives notification of the end of a summation.

inline CountArgHandler BeginCount(int num_args)

Receives notification of the beginning of a count expression.

inline CountExpr EndCount(CountArgHandler handler)

Receives notification of the end of a count expression.

inline NumberOfArgHandler BeginNumberOf(int num_args, NumericExpr arg0)

Receives notification of the beginning of a numberof expression.

inline NumericExpr EndNumberOf(NumberOfArgHandler handler)

Receives notification of the end of a numberof expression.

inline SymbolicArgHandler BeginSymbolicNumberOf(int num_args, Expr arg0)

Receives notification of the beginning of a symbolic numberof expression.

inline NumericExpr EndSymbolicNumberOf(SymbolicArgHandler handler)

Receives notification of the end of a symbolic numberof expression.

inline LogicalExpr OnBool(bool value)

Receives notification of a Boolean value.

inline LogicalExpr OnNot(LogicalExpr arg)

Receives notification of a logical not.

inline LogicalExpr OnBinaryLogical(expr::Kind kind, LogicalExpr lhs, LogicalExpr rhs)

Receives notification of a binary logical expression.

inline LogicalExpr OnRelational(expr::Kind kind, NumericExpr lhs, NumericExpr rhs)

Receives notification of a relational expression.

inline LogicalExpr OnLogicalCount(expr::Kind kind, NumericExpr lhs, CountExpr rhs)

Receives notification of a logical count expression.

inline LogicalExpr OnImplication(LogicalExpr condition, LogicalExpr then_expr, LogicalExpr else_expr)

Receives notification of an implication expression.

inline LogicalArgHandler BeginIteratedLogical(expr::Kind kind, int num_args)

Receives notification of the beginning of an iterated logical expression.

inline LogicalExpr EndIteratedLogical(LogicalArgHandler handler)

Receives notification of the end of an iterated logical expression.

inline PairwiseArgHandler BeginPairwise(expr::Kind kind, int num_args)

Receives notification of the beginning of a pairwise expression.

inline LogicalExpr EndPairwise(PairwiseArgHandler handler)

Receives notification of the end of a pairwise expression.

inline Expr OnString(fmt::StringRef value)

Receives notification of a string. The value argument is a string value and it is not null-terminated.

inline Expr OnSymbolicIf(LogicalExpr condition, Expr then_expr, Expr else_expr)

Receives notification of a symbolic if expression.

inline void EndInput()

Receives notification of the end of the input.

Private Members

Handler &handler_
struct mp::internal::NLReader::VarHandler : public mp::internal::NLReader<VAR>::ItemHandler

Public Functions

inline explicit VarHandler(NLReader &r)
inline int num_items() const
inline void SetBounds(int index, double lb, double ub)
inline void SetInitialValue(int index, double value)

Public Static Attributes

static const ItemType TYPE = T

Protected Attributes

NLReader &reader_
struct mp::ProblemBuilder::Variable
#include <problem-builder.h>

Public Functions

inline void set_value(double value)
template<class VarVec>
class mp::VarInfoImpl
#include <constr_keeper.h>

Variable information used by solution check.

Subclassed by mp::VarInfoRecomp

Public Functions

inline VarInfoImpl(double ft, bool recomp_vals, VarVec x, ArrayRef<double> x_raw, ArrayRef<var::Type> type, ArrayRef<double> lb, ArrayRef<double> ub, int sol_rnd, int sol_prec)

Constructor.

inline int size() const

Number of vars.

inline double operator[](int i) const

Access variable value.

inline const VarVec &get_x() const

Access VarVec.

inline double raw(int i) const

Access raw variables.

inline bool is_var_int(int i) const

Access integrality condition.

inline bool is_nonzero(int i) const

Variable value nonzero?

inline bool is_positive(int i) const

Variable value positive?

inline bool is_at_lb(int i) const

Is at lb?

inline bool is_at_ub(int i) const

Is at ub?

inline double bounds_viol(int i) const

Bounds violation.

inline double feastol() const

Feasibility tolerance.

inline bool recomp_vals() const

Using recomputed auxiliary vars?

inline bool idealistic() const

Using idealistic checking of solution (without tolerances)?

inline std::string solution_round() const

sol_rnd as string

inline std::string solution_precision() const

sol_rnd as string

Protected Functions

inline void apply_precision_options(int sol_rnd, int sol_prec)

Private Members

double feastol_
bool recomp_vals_
VarVec x_
ArrayRef<double> x_raw_
const ArrayRef<var::Type> type_
const ArrayRef<double> lb_
const ArrayRef<double> ub_
int sol_rnd_ = 100
int sol_prec_ = 100
class mp::VarInfoRecomp : public mp::VarInfoImpl<VarVecRecomp>
#include <constr_keeper.h>

Define VarInfoRecomp.

Public Functions

inline int size() const

Number of vars.

inline double operator[](int i) const

Access variable value.

inline const VarVec &get_x() const

Access VarVec.

inline double raw(int i) const

Access raw variables.

inline bool is_var_int(int i) const

Access integrality condition.

inline bool is_nonzero(int i) const

Variable value nonzero?

inline bool is_positive(int i) const

Variable value positive?

inline bool is_at_lb(int i) const

Is at lb?

inline bool is_at_ub(int i) const

Is at ub?

inline double bounds_viol(int i) const

Bounds violation.

inline double feastol() const

Feasibility tolerance.

inline bool recomp_vals() const

Using recomputed auxiliary vars?

inline bool idealistic() const

Using idealistic checking of solution (without tolerances)?

inline std::string solution_round() const

sol_rnd as string

inline std::string solution_precision() const

sol_rnd as string

Protected Functions

inline void apply_precision_options(int sol_rnd, int sol_prec)
class mp::BasicProblem::VarNamer
#include <problem.h>

Variable namer.

Public Functions

inline VarNamer(BasicProblem &p)

Construct.

inline const std::string &vname(int i) const

Normal var name.

inline const std::string &dvname(int i) const

Defined var name.

Private Members

BasicProblem &p_
class mp::BasicFCC::VarOrConst

Holder for the conversion result of an expression.

Public Functions

inline bool is_var() const
inline bool is_const() const
inline double get_const() const
inline Var get_var() const

Public Members

double c_
Var var_

Public Static Functions

static inline VarOrConst MakeVar(Var v)
static inline VarOrConst MakeConst(double c)

Private Functions

inline VarOrConst(bool isv, Var v)
inline VarOrConst(bool isv, double c)

Private Members

const bool is_v_
union mp::BasicFCC::VarOrConst::[anonymous] [anonymous]
class mp::VarVecRecomp
#include <constr_keeper.h>

Var vector managing recomputation.

Public Functions

inline VarVecRecomp(std::vector<double> x, VarsRecomputeFn rec_fn)

Construct.

inline void set_p_var_info(const VarInfoRecomp *p) const

Set p_var_info_recomp_.

inline int size() const

Number of vars.

inline double operator[](int i) const

Access variable value.

Recompute if not yet.

inline std::vector<double>::iterator begin()

Expose begin()

inline std::vector<double>::iterator end()

Expose end()

inline std::vector<double> &get_x() const

Move out x.

Private Members

mutable std::vector<double> x_
mutable std::vector<bool> is_recomp_
VarsRecomputeFn recomp_fn_
mutable const VarInfoRecomp *p_var_info_recomp_ = {nullptr}
class mp::pre::VCString
#include <valcvt-base.h>

Typedef VCString.

This class stores node names and counts references to a given name and allows numbering derived items ‘Con01_1_’, …

Public Functions

VCString() = default

Construct default.

inline VCString(std::string s)

Construct from string.

inline VCString(const VCString &vcs)

Copy from VCString.

Updates its counter, but inits own counter to 0.

inline VCString &operator=(const VCString &vcs)

Assign VCString.

Only if empty (then copy.)

inline const std::string &MakeCurrentName() const

Return current name, unmodified.

inline std::string MakeCountedName() const

Produce name s + ‘_<counter>_’ if n_>0.

Post-increment counter.

inline operator std::string() const

Use MakeCountedName().

template<class T>
inline VCString operator+(const T &arg) const

Produce another VCString with an added string or char.

Does not change own counter, we assume the caller cares for name uniqueness.

inline bool empty() const

empty?

Private Members

std::string s_
mutable std::size_t n_ = 0
template<class Value>
class mp::VecReader
#include <sol-reader2.h>

Declare VecReader<>

Vector reader.

Subclassed by mp::SuffixReader< Element >

Public Types

using value_type = Value

Typedef value_type.

Public Functions

inline VecReader(FILE *f, int b, int n)

Construct.

inline ~VecReader()

Destruct.

inline int Size() const

Size remaining to read.

Value ReadNext()

Read next value.

inline void SetError(NLW2_SOLReadResultCode res, std::string msg)

Set error status.

inline NLW2_SOLReadResultCode ReadResult() const

status

inline const std::string &ErrorMessage() const

error message

Private Members

FILE *f_
int binary_
int n_
NLW2_SOLReadResultCode rr_ = {NLW2_SOLRead_OK}
std::string err_msg_
struct mp::Violation
#include <constr_base.h>

Constraint/obj violation.

Public Functions

inline std::pair<bool, double> Check(double epsabs, double epsrel) const

Compute whether violated + relative violation.

Both absolute and relative should be violated (relative only if refvar!=0.)

Public Members

double viol_
double valX_
struct mp::ViolSummary
#include <constr_keeper.h>

Violation summary for a class of vars/cons/objs.

Public Functions

inline void CheckViol(Violation viol, double epsabs, double epsrel, const char *nm)

Check if this violation should be counted.

inline void CountViol(Violation viol, double violRel, const char *nm)

Count violation.

Public Members

int N_ = {0}
double epsAbsMax_ = {0.0}
const char *nameAbs_ = {nullptr}
double epsRelMax_ = {0.0}
const char *nameRel_ = {nullptr}
namespace [anonymous]
namespace [anonymous]
namespace _nlwpy
namespace Base
namespace conf

Variables

list extensions = ["sphinx.ext.autodoc","sphinx.ext.intersphinx","sphinx.ext.autosummary","sphinx.ext.napoleon",]
bool autosummary_generate = True
list templates_path = ["_templates"]
string source_suffix = ".rst"
string master_doc = "index"
string project = "nlwpy"
string copyright = "2024, AMPL Optimization Inc."
string author = "Gleb Belov"
string version = "0.0.1"
string release = "0.0.1"
language   =  None
list exclude_patterns = ["_build"]
string pygments_style = "sphinx"
bool todo_include_todos = False
string html_theme = "alabaster"
list html_static_path = ["_static"]
string htmlhelp_basename = "nlwpydoc"
dictionary latex_elements  =  {# The paper size ('letterpaper' or 'a4paper').#'papersize': 'letterpaper',# The font size ('10pt', '11pt' or '12pt').#'pointsize': '10pt',# Additional stuff for the LaTeX preamble.#'preamble': '',# Latex figure (float) alignment#'figure_align': 'htbp',}
list latex_documents = [(master_doc,"nlwpy.tex","nlwpy Documentation","Gleb Belov","manual",),]
list man_pages = [(master_doc, "nlwpy", "nlwpy Documentation", [author], 1)]
list texinfo_documents = [(master_doc,"nlwpy","nlwpy Documentation",author,"nlwpy","One line description of project.","Miscellaneous",),]
dictionary intersphinx_mapping   =  {"https://docs.python.org/": None}
namespace DAVID_GAY_GFMT

Typedefs

typedef int Long

Functions

char *gfmt(double x, int prec)
int g_fmt(char *b, double x, int prec)

Adjusts precision of floating point numbers.

Variables

char Bf[400]
namespace fmt

Typedefs

typedef BasicWriter<char> Writer
typedef BasicWriter<wchar_t> WWriter
typedef BasicStringRef<char> StringRef
typedef BasicStringRef<wchar_t> WStringRef
typedef BasicCStringRef<char> CStringRef
typedef BasicCStringRef<wchar_t> WCStringRef
typedef BasicMemoryWriter<char> MemoryWriter
typedef BasicMemoryWriter<wchar_t> WMemoryWriter
typedef BasicArrayWriter<char> ArrayWriter
typedef BasicArrayWriter<wchar_t> WArrayWriter

Enums

enum Alignment

Values:

enumerator ALIGN_DEFAULT
enumerator ALIGN_LEFT
enumerator ALIGN_RIGHT
enumerator ALIGN_CENTER
enumerator ALIGN_NUMERIC
enum [anonymous]

Values:

enumerator SIGN_FLAG
enumerator PLUS_FLAG
enumerator MINUS_FLAG
enumerator HASH_FLAG
enumerator CHAR_FLAG
enum Color

Values:

enumerator BLACK
enumerator RED
enumerator GREEN
enumerator YELLOW
enumerator BLUE
enumerator MAGENTA
enumerator CYAN
enumerator WHITE

Functions

IntFormatSpec<int, TypeSpec<'b'>> bin(int value)

Returns an integer format specifier to format the value in base 2.

IntFormatSpec<int, TypeSpec<'o'>> oct(int value)

Returns an integer format specifier to format the value in base 8.

IntFormatSpec<int, TypeSpec<'x'>> hex(int value)

Returns an integer format specifier to format the value in base 16 using lower-case letters for the digits above 9.

IntFormatSpec<int, TypeSpec<'X'>> hexu(int value)

Returns an integer formatter format specifier to format in base 16 using upper-case letters for the digits above 9.

template<char TYPE_CODE, typename Char>
IntFormatSpec<int, AlignTypeSpec<TYPE_CODE>, Char> pad(int value, unsigned width, Char fill = ' ')

Returns an integer format specifier to pad the formatted argument with the fill character to the specified width using the default (right) numeric alignment.

Example:

MemoryWriter out;
out << pad(hex(0xcafe), 8, '0');
// out.str() == "0000cafe"

template<typename Char>
inline StrFormatSpec<Char> pad(const Char *str, unsigned width, Char fill = ' ')

Returns a string formatter that pads the formatted argument with the fill character to the specified width using the default (left) string alignment.

Example:

std::string s = str(MemoryWriter() << pad("abc", 8));
// s == "abc     "

inline StrFormatSpec<wchar_t> pad(const wchar_t *str, unsigned width, char fill = ' ')
FMT_API void report_system_error (int error_code, StringRef message) FMT_NOEXCEPT
FMT_API void print_colored (Color c, CStringRef format, ArgList args)

Formats a string and prints it to stdout using ANSI escape sequences to specify color (experimental).

Example: print_colored(fmt::RED, “Elapsed time: {0:.2f} seconds”, 1.23);

inline std::string format(CStringRef format_str, ArgList args)

Formats arguments and returns the result as a string.

Example:

std::string message = format("The answer is {}", 42);

inline std::wstring format(WCStringRef format_str, ArgList args)
FMT_API void print (std::FILE *f, CStringRef format_str, ArgList args)

Prints formatted data to the file f.

Example:

print(stderr, "Don't {}!", "panic");

FMT_API void print (CStringRef format_str, ArgList args)

Prints formatted data to stdout.

Example:

print("Elapsed time: {0:.2f} seconds", 1.23);

template<typename Char>
void printf(BasicWriter<Char> &w, BasicCStringRef<Char> format, ArgList args)
inline std::string sprintf(CStringRef format, ArgList args)

Formats arguments and returns the result as a string.

Example:

std::string message = fmt::sprintf("The answer is %d", 42);

inline std::wstring sprintf(WCStringRef format, ArgList args)
FMT_API int fprintf (std::FILE *f, CStringRef format, ArgList args)

Prints formatted data to the file f.

Example:

fmt::fprintf(stderr, "Don't %s!", "panic");

inline int printf(CStringRef format, ArgList args)

Prints formatted data to stdout.

Example:

fmt::printf("Elapsed time: %.2f seconds", 1.23);

template<typename T>
inline void format_decimal(char *&buffer, T value)
template<typename T>
inline internal::NamedArg<char> arg(StringRef name, const T &arg)

Returns a named argument for formatting functions.

Example:

print("Elapsed time: {s:.2f} seconds", arg("s", 1.23));

template<typename T>
inline internal::NamedArg<wchar_t> arg(WStringRef name, const T &arg)
template<typename Char> void arg (StringRef, const internal::NamedArg< Char > &) FMT_DELETED_OR_UNDEFINED
template<typename Char> void arg (WStringRef, const internal::NamedArg< Char > &) FMT_DELETED_OR_UNDEFINED
long getpagesize()

Variables

FMT_GCC_EXTENSION typedef long long LongLong
FMT_GCC_EXTENSION typedef unsigned long long ULongLong
namespace mp

Backend with a Model Manager.

Just for checking compilation.

Implementation of value presolver.

Value presolver: namespace mp::pre.

Wrappers implementing a HashStreamer interface.

Support for .nl/.sol/console I/O requiring a (Basic)Solver.

Namespace mp.

Generate ModelManagerWithPB<mp::Problem>

Generate ModelManagerWithPB<mp::Problem>, header file.

This is an abstract interface to a Model Manager which provides model IO, solution handling and suffixes, etc.

Redefinition of smooth nonlinear functions via piecewise-linear approximation.

Convert quadratic indicators for MIP.

Redefinition for MIP of (cond) ==> (constr1) [ else (constr2) ].

Converter-independent linear approximation routines.

Implementation of flat model info.

Public interface for flat model info.

Bounds and type computation for various expressions.

A template algebraic expression: Body (variable_terms) + constant_term.

The mp namespace.

Backends using ValuePresolver should derive from here.

Separates compiling NLHandler from Converter

Separate compiling NLHandler from Converter to improve compilation speed

Include this in a separate .cc

HashStreamer can

  1. Compute hash for a given array in 1 go;

  2. ”Accumulate” new values / arrays to an intermediate “hash state”.

Various implementations are possible, one is typedef’d as HashStreamer.

Typedefs

using Env = BasicSolver

Typedef Env to access solver options, output handler, etc.

typedef BasicExpr<expr::FIRST_EXPR, expr::LAST_EXPR> Expr

Typedef Expr.

typedef BasicExpr<expr::FIRST_NUMERIC, expr::LAST_NUMERIC> NumericExpr

A numeric expression.

typedef BasicExpr<expr::FIRST_LOGICAL, expr::LAST_LOGICAL> LogicalExpr

A logical expression.

typedef BasicUnaryExpr<NumericExpr, expr::FIRST_UNARY, expr::LAST_UNARY> UnaryExpr

A unary numeric expression.

Examples: -x, sin(x), where x is a variable.

typedef BasicBinaryExpr<NumericExpr, expr::FIRST_BINARY, expr::LAST_BINARY> BinaryExpr

A binary numeric expression.

Examples: x / y, atan2(x, y), where x and y are variables.

typedef BasicIfExpr<NumericExpr, expr::IF> IfExpr

An if-then-else expression.

Example: if x != 0 then y else z, where x, y and z are variables.

typedef BasicIteratedExpr<NumericExpr, expr::FIRST_ITERATED, expr::LAST_ITERATED> IteratedExpr

A numeric iterated expression such as min, max, sum or numberof.

Examples: min{i in I} x[i], sum{i in I} x[i], numberof 42 in ({i in I} x[i]), where I is a set and x is a variable.

typedef BasicIteratedExpr<Expr, expr::NUMBEROF_SYM> SymbolicNumberOfExpr

A symbolic numberof expression.

Example: numberof (if x then ‘a’ else ‘b’) in (‘a’, ‘b’, ‘c’), where x is a variable.

typedef BasicIteratedExpr<LogicalExpr, expr::COUNT> CountExpr

A count expression.

Example: count{i in I} (x[i] >= 0), where I is a set and x is a variable.

typedef BasicUnaryExpr<LogicalExpr, expr::NOT> NotExpr

A logical NOT expression.

Example: not a, where a is a logical expression.

typedef BasicBinaryExpr<LogicalExpr, expr::FIRST_BINARY_LOGICAL, expr::LAST_BINARY_LOGICAL> BinaryLogicalExpr

A binary logical expression.

Examples: a || b, a && b, where a and b are logical expressions.

typedef BasicBinaryExpr<NumericExpr, expr::FIRST_RELATIONAL, expr::LAST_RELATIONAL> RelationalExpr

A relational expression.

Examples: x < y, x != y, where x and y are variables.

typedef BasicIfExpr<LogicalExpr, expr::IMPLICATION> ImplicationExpr

An implication expression.

Example: a ==> b else c, where a, b and c are logical expressions.

typedef BasicIteratedExpr<LogicalExpr, expr::FIRST_ITERATED_LOGICAL, expr::LAST_ITERATED_LOGICAL> IteratedLogicalExpr

An iterated logical expression.

Example: exists{i in I} x[i] >= 0, where I is a set and x is a variable.

typedef BasicIteratedExpr<NumericExpr, expr::FIRST_PAIRWISE, expr::LAST_PAIRWISE> PairwiseExpr

A pairwise expression (alldiff or !alldiff).

Example: alldiff{i in I} x[i], where I is a set and x is a variable.

typedef BasicIfExpr<Expr, expr::IFSYM> SymbolicIfExpr

A symbolic if-then-else expression.

Example: if x != 0 then ‘a’ else 0, where x is a variable.

typedef BasicExprFactory<std::allocator<char>> ExprFactory
using LinConRange = AlgebraicConstraint<LinTerms, AlgConRange>

Linear range constraint.

template<int sens>
using LinConRhs = AlgebraicConstraint<LinTerms, AlgConRhs<sens>>

Convenience typedef.

using LinConLT = LinConRhs<-2>

Linear constraint c’x < d.

using LinConLE = LinConRhs<-1>

Linear constraint c’x <= d.

using LinConEQ = LinConRhs<0>

Linear constraint c’x == d.

using LinConGE = LinConRhs<1>

Linear constraint c’x >= d.

using LinConGT = LinConRhs<2>

Linear constraint c’x > d.

using QuadConRange = AlgebraicConstraint<QuadAndLinTerms, AlgConRange>

Quadratic range constraint.

template<int sens>
using QuadConRhs = AlgebraicConstraint<QuadAndLinTerms, AlgConRhs<sens>>

Convenience typedef.

using QuadConLT = QuadConRhs<-2>

Quadratic constraint c’x+x’Qx < d.

using QuadConLE = QuadConRhs<-1>

Quadratic constraint c’x+x’Qx <= d.

using QuadConEQ = QuadConRhs<0>

Quadratic constraint c’x+x`Qx == d.

using QuadConGE = QuadConRhs<1>

Quadratic constraint c’x+x`Qx >= d.

using QuadConGT = QuadConRhs<2>

Quadratic constraint c’x+x`Qx > d.

using VarArray1 = std::array<int, 1>

Possible argument arrays for CustomFunctionalConstraint.

Fixed argument array of 1 element

using VarArray2 = std::array<int, 2>

Fixed argument array of 2 elements.

using VarArray3 = std::array<int, 3>

Fixed argument array of 3 elements.

template<int N>
using VarArrayN = std::array<int, N>

Fixed argument array of N elements.

using VarArray = std::vector<int>

Variable-size argument array.

template<class Num, size_t N>
using ParamArrayN = std::array<Num, N>

Possible parameter arrays.

Fixed parameter array of N elements

using ParamArray0 = ParamArrayN<int, 0>

Empty parameter array.

using DblParamArray1 = ParamArrayN<double, 1>

Fixed parameter array of 1 double.

using DblParamArray2 = ParamArrayN<double, 2>

Fixed parameter array of 2 double.

using DblParamArray3 = ParamArrayN<double, 3>

Fixed parameter array of 3 double.

using DblParamArray = std::vector<double>

Variable-length parameter array.

using CondLinConLT = CondLinLTConstraint
using CondLinConLE = CondLinLEConstraint
using CondLinConEQ = CondLinEQConstraint
using CondLinConGE = CondLinGEConstraint
using CondLinConGT = CondLinGTConstraint
using CondQuadConLT = CondQuadLTConstraint
using CondQuadConLE = CondQuadLEConstraint
using CondQuadConEQ = CondQuadEQConstraint
using CondQuadConGE = CondQuadGEConstraint
using CondQuadConGT = CondQuadGTConstraint
using LinExpression = ExprWrapper<LinearFunctionalConstraint>

Typedef LinExpression.

using QuadExpression = ExprWrapper<QuadraticFunctionalConstraint>

Typedef LinExpression.

using IndicatorConstraintLinLE = IndicatorConstraint<LinConLE>

Typedef indicator<LinConLE>

using IndicatorConstraintLinEQ = IndicatorConstraint<LinConEQ>

Typedef indicator<LinConEQ>

using IndicatorConstraintLinGE = IndicatorConstraint<LinConGE>

Typedef indicator<LinConGE>

using IndicatorConstraintQuadLE = IndicatorConstraint<QuadConLE>

Typedef indicator<QuadConLE>

using IndicatorConstraintQuadEQ = IndicatorConstraint<QuadConEQ>

Typedef indicator<QuadConEQ>

using IndicatorConstraintQuadGE = IndicatorConstraint<QuadConGE>

Typedef indicator<QuadConGE>

using SOS1Constraint = SOS_1or2_Constraint<1>

Typedef SOS1Constraint.

using SOS2Constraint = SOS_1or2_Constraint<2>

Typedef SOS2Constraint.

using ComplementarityLinear = ComplementarityConstraint<AffineExpr>

Typedef ComplementarityLinRange.

using ComplementarityQuadratic = ComplementarityConstraint<QuadraticExpr>

Typedef ComplementarityQuadRange.

template<int Nkinds>
using ViolSummArray = std::array<ViolSummary, Nkinds>

Array of violation summaries.

For different kinds, e.g., original / aux vars.

using VarsRecomputeFn = std::function<double(int i, const VarInfoRecomp &x)>

Function prototype to recompute variable at index i.

using VarVecStatic = std::vector<double>

Static var vector.

using VarInfoRecompTypedef = VarInfoImpl<VarVecRecomp>

VarInfoRecompTypedef.

using VarInfoStatic = VarInfoImpl<VarVecStatic>

VarInfoStatic.

using AbstractConstraintLocation = ConstraintLocationHelper<BasicConstraintKeeper>

Without constraint type.

template<class Constraint>
using ConstraintMap = std::unordered_map<std::reference_wrapper<const Constraint>, int>

Subexpression map.

Indexes constraint location

using AffineExpr = AlgebraicExpression<LinTerms>

Typedef AffineExpr.

using JSONW = MiniJSONWriter<fmt::MemoryWriter>

Specialize our JSON writer.

using QuadraticExpr = AlgebraicExpression<QuadAndLinTerms>

Typedef QuadraticExpr.

using PreprocessInfoStd = PreprocessInfo<int>

Typical preprocess info.

using P_ZZI_Encoding = std::shared_ptr<ZZI_Encoding>

Obtain an object of ZII_Encoding.

template<class MC>
using ComplCvtLin_MIP = ComplementarityConverter_MIP<MC, ComplementarityLinear>

Typedef linear compl cvt.

template<class MC>
using ComplCvtQuad_MIP = ComplementarityConverter_MIP<MC, ComplementarityQuadratic>

Typedef quadratic compl cvt.

template<class MC>
using CondLinEQConverter_MIP = CondEQConverter_MIP<MC, LinTerms>

Specialize for linear constraint.

template<class MC>
using CondQuadEQConverter_MIP = CondEQConverter_MIP<MC, QuadAndLinTerms>

Specialize for quadratic constraint.

template<class MC>
using CondLinLEConverter_MIP = Cond_LE_LT_GT_GE_Converter_MIP<MC, LinConLE>

Specialize for linear constraint.

template<class MC>
using CondQuadLEConverter_MIP = Cond_LE_LT_GT_GE_Converter_MIP<MC, QuadConLE>

Specialize for quadratic constraint.

template<class MC>
using CondLinGEConverter_MIP = Cond_LE_LT_GT_GE_Converter_MIP<MC, LinConGE>

Specialize for linear constraint.

template<class MC>
using CondQuadGEConverter_MIP = Cond_LE_LT_GT_GE_Converter_MIP<MC, QuadConGE>

Specialize for quadratic constraint.

template<class MC>
using CondLinLTConverter_MIP = Cond_LE_LT_GT_GE_Converter_MIP<MC, LinConLT>

Specialize for linear constraint.

template<class MC>
using CondQuadLTConverter_MIP = Cond_LE_LT_GT_GE_Converter_MIP<MC, QuadConLT>

Specialize for quadratic constraint.

template<class MC>
using CondLinGTConverter_MIP = Cond_LE_LT_GT_GE_Converter_MIP<MC, LinConGT>

Specialize for linear constraint.

template<class MC>
using CondQuadGTConverter_MIP = Cond_LE_LT_GT_GE_Converter_MIP<MC, QuadConGT>

Specialize for quadratic constraint.

template<class MC>
using IndicatorQuadLEConverter_MIP = IndicatorQuadConverter_MIP<MC, -1>

Typedef IndicatorQuadLEConverter_MIP.

template<class MC>
using IndicatorQuadEQConverter_MIP = IndicatorQuadConverter_MIP<MC, 0>

Typedef IndicatorQuadEQConverter_MIP.

template<class MC>
using IndicatorQuadGEConverter_MIP = IndicatorQuadConverter_MIP<MC, 1>

Typedef IndicatorQuadGEConverter_MIP.

template<class MC>
using FuncConConverter_MIP_Exp = FuncConConverter_MIP<MC, ExpConstraint>

Typedef FuncConConverter_MIP_Exp.

template<class MC>
using FuncConConverter_MIP_Log = FuncConConverter_MIP<MC, LogConstraint>

Typedef FuncConConverter_MIP_Log.

template<class MC>
using FuncConConverter_MIP_LogA = FuncConConverter_MIP<MC, LogAConstraint>

Typedef FuncConConverter_MIP_LogA.

template<class MC>
using FuncConConverter_MIP_ExpA = FuncConConverter_MIP<MC, ExpAConstraint>

Typedef FuncConConverter_MIP_ExpA.

template<class MC>
using FuncConConverter_MIP_Sin = FuncConConverter_MIP<MC, SinConstraint>

Typedef FuncConConverter_MIP_Sin.

template<class MC>
using FuncConConverter_MIP_Cos = FuncConConverter_MIP<MC, CosConstraint>

Typedef FuncConConverter_MIP_Cos.

template<class MC>
using FuncConConverter_MIP_Tan = FuncConConverter_MIP<MC, TanConstraint>

Typedef FuncConConverter_MIP_Tan.

template<class MC>
using FuncConConverter_MIP_Asin = FuncConConverter_MIP<MC, AsinConstraint>

Typedef FuncConConverter_MIP_ASin.

template<class MC>
using FuncConConverter_MIP_Acos = FuncConConverter_MIP<MC, AcosConstraint>

Typedef FuncConConverter_MIP_ACos.

template<class MC>
using FuncConConverter_MIP_Atan = FuncConConverter_MIP<MC, AtanConstraint>

Typedef FuncConConverter_MIP_ATan.

template<class MC>
using FuncConConverter_MIP_Sinh = FuncConConverter_MIP<MC, SinhConstraint>

Typedef FuncConConverter_MIP_Sinh.

template<class MC>
using FuncConConverter_MIP_Cosh = FuncConConverter_MIP<MC, CoshConstraint>

Typedef FuncConConverter_MIP_Cosh.

template<class MC>
using FuncConConverter_MIP_Tanh = FuncConConverter_MIP<MC, TanhConstraint>

Typedef FuncConConverter_MIP_Tanh.

template<class MC>
using FuncConConverter_MIP_Asinh = FuncConConverter_MIP<MC, AsinhConstraint>

Typedef FuncConConverter_MIP_ASinh.

template<class MC>
using FuncConConverter_MIP_Acosh = FuncConConverter_MIP<MC, AcoshConstraint>

Typedef FuncConConverter_MIP_ACosh.

template<class MC>
using FuncConConverter_MIP_Atanh = FuncConConverter_MIP<MC, AtanhConstraint>

Typedef FuncConConverter_MIP_ATanh.

template<class ModelConverter>
using MinConverter_MIP = MinOrMaxConverter_MIP<ModelConverter, -1>

Typedef of MinConverter.

template<class ModelConverter>
using MaxConverter_MIP = MinOrMaxConverter_MIP<ModelConverter, 1>

Typedef of MaxConverter.

template<class MC>
using MulCvtLE_MIP = QCConverter_MIP<MC, -1>

Typedef MulCvt<QuadConLE>

template<class MC>
using MulCvtEQ_MIP = QCConverter_MIP<MC, 0>

Typedef MulCvt<QuadConEQ>

template<class MC>
using MulCvtGE_MIP = QCConverter_MIP<MC, 1>

Typedef MulCvt<QuadConGE>

template<class MC>
using RangeLinearConstraintConverter = RangeConstraintConverter<MC, LinTerms>

Typedef RangeLinearConstraintConverter.

template<class MC>
using RangeQuadraticConstraintConverter = RangeConstraintConverter<MC, QuadAndLinTerms>

Typedef RangeQuadraticConstraintConverter.

using ModelMgrWithStdPB = ModelManagerWithProblemBuilder<BasicConverter<mp::Problem>>
typedef BasicProblem<> Problem

A BasicProblem<> with default parameters.

typedef bool (*InterruptHandler)(void*)

Interrupt handler.

Returns true if the solver was interrupted, false if it is not running.

template<class Solver, class Writer = SolFileWriter>
using SolutionWriter = SolutionWriterImpl<Solver, typename Solver::ProblemBuilder, Writer>

Convenience typedef for APIs using SolverImpl<> or similar.

typedef std::auto_ptr<Solver> SolverPtr
using SuffixTable = std::string

Suffix table is a newline-separated string.

typedef BasicSuffix<int> IntSuffix
typedef BasicSuffix<double> DoubleSuffix
typedef BasicMutSuffix<int> MutIntSuffix
typedef BasicMutSuffix<double> MutDoubleSuffix
typedef BasicSuffixSet<std::allocator<char>> SuffixSet

Typedef SuffixSet.

template<class T>
using ModelSuffixDef = SuffixDef<T>

Description of a suffix that can exist for several itme types (vars, cons, objs, problem).

The kind parameter should be a bitwise OR of suf::Kind::…_BIT’s.

using HashStreamer = HashStreamerCombine

Selecting one particular implementation as HashStreamer.

using WriteNLResult = std::pair<NLW2_WriteNLResultCode, std::string>

Typedef WriteNLResult: result code and error message.

template<class Element>
using SparseVecReader = VecReader<std::pair<int, Element>>

Typedef SparseVecReader.

using NLSOL_C_Impl = mp::NLSolver

Typedef our specialization of NLSOL.

Enums

enum class IISStatus

.iis suffix values

Values:

enumerator non
enumerator low
enumerator fix
enumerator upp
enumerator mem
enumerator pmem
enumerator plow
enumerator pupp
enumerator bug
enum class BasicStatus

Basic status values (suffix .sstatus)

Values:

enumerator none
enumerator bas
enumerator sup
enumerator low
enumerator upp
enumerator equ
enumerator btw
enum class ConstraintAcceptanceLevel

Level of acceptance of a constraint by a backend.

Values:

enumerator NotAccepted
enumerator AcceptedButNotRecommended
enumerator Recommended
enum class ExpressionAcceptanceLevel

Level of acceptance of an expression by a backend.

Values:

enumerator NotAccepted
enumerator AcceptedButNotRecommended
enumerator Recommended
enum ConstraintGroup

Constraint groups.

This is used to access constraint attributes (basis status, duals, …) Convenient, when the solver accesses constraint attributes in groups. For example, Gurobi 9.5 has linear, quadratic, SOS, and general

Todo:

Keep consistent with congroup_names

Values:

enumerator CG_Default
enumerator CG_All
enumerator CG_Algebraic
enumerator CG_Linear
enumerator CG_Quadratic
enumerator CG_Conic
enumerator CG_General
enumerator CG_Piecewiselinear
enumerator CG_SOS
enumerator CG_SOS1
enumerator CG_SOS2
enumerator CG_Logical
enumerator CG_END_
enum [anonymous]

Values:

enumerator MAX_AMPL_OPTIONS

Maximum number of options reserved for AMPL use in NL and SOL formats.

enum [anonymous]

Values:

enumerator VBTOL_OPTION_INDEX

internal constant

enumerator USE_VBTOL_FLAG

internal constant

enum [anonymous]

Flags for ReadNLFile and ReadNLString.

Values:

enumerator READ_BOUNDS_FIRST

Read variable bounds before anything else.

enum [anonymous]

Values:

enumerator BUFFER_SIZE
enum [anonymous]

Values:

enumerator MAX_AMPL_OPTIONS

Maximum number of options reserved for AMPL use in NL and SOL formats.

enum [anonymous]

Values:

enumerator VBTOL_OPTION_INDEX

internal constant

enumerator USE_VBTOL_FLAG

internal constant

Functions

template<typename T>
inline ArrayRef<T> MakeArrayRef(const T *data, std::size_t size) noexcept
template<class Vec>
inline auto data_or_null(const Vec &v) -> decltype(v.data())

std::vector::data() might not return nullptr when empty

inline int RunBackendApp(char **argv, std::function<std::unique_ptr<mp::BasicBackend>()> be_creator, BasicBackend::Callbacks callbacks = {})

Create and run a backend.

Parameters
  • argv – command-line arguments, null-terminated vector

  • be_creator – backend factory

  • callbacks – special callbacks

Returns

application exit value

template<class ProblemBuilder>
EasyModeler<ProblemBuilder> MakeEasyModeler(ProblemBuilder &bld)
inline UnsupportedError MakeUnsupportedError(fmt::CStringRef format_str, fmt::ArgList args)

Makes UnsupportedError with prefix “unsupported: “.

Use via macro MP_UNSUPPORTED

template<typename ExprType>
inline ExprType Cast(Expr e)

Casts an expression to type ExprType which must be a valid expression type.

Returns a null expression if e is not convertible to ExprType.

void format(fmt::BasicFormatter<char> &f, const char*&, NumericExpr e)
inline bool IsZero(NumericExpr e)

Returns true iff e is a zero constant.

bool Equal(Expr e1, Expr e2)

Recursively compares two expressions and returns true if they are equal.

void WriteModelItem(fmt::MemoryWriter &wrt, const LinTerms &lt, const std::vector<std::string> &vnam)
void WriteModelItem(fmt::MemoryWriter &wrt, const QuadTerms &qt, const std::vector<std::string> &vnam)
void WriteModelItem(fmt::MemoryWriter &wrt, const QuadAndLinTerms &qlt, const std::vector<std::string> &vnam)
template<class Writer, class Body>
inline void WriteModelItem(Writer &wrt, const AlgebraicConstraint<Body, AlgConRange> &algc, const std::vector<std::string> &vnam)

Write RangeCon without name.

template<class Writer, class Body, int kind>
inline void WriteModelItem(Writer &wrt, const AlgebraicConstraint<Body, AlgConRhs<kind>> &algc, const std::vector<std::string> &vnam)

Write RhsCon without name.

template<class Body, class RhsOrRange>
inline void WriteJSON(JSONW jw, const AlgebraicConstraint<Body, RhsOrRange> &algc)

Write an algebraic constraint.

inline void WriteJSON(JSONW jw, const AlgConRange &acr)

Write alg con range.

template<int kind>
inline void WriteJSON(JSONW jw, const AlgConRhs<kind> &acrhs)

Write alg con rhs.

template<class Writer, class Vec, typename T = std::decay_t<decltype(*begin(std::declval<Vec>()))>>
inline void WriteModelItem(Writer &wrt, const Vec &v, const std::vector<std::string> &vnam)

Write flat expr/obj/con variables: vector/array.

template<class Writer, class Vec, typename T = std::decay_t<decltype(*begin(std::declval<Vec>()))>>
void WriteModelItemParameters(Writer &wrt, const Vec &v)

Write flat expr/obj/con parameters: vector/array.

template<class Writer, class A, class P, class N, class I>
inline void WriteModelItem(Writer &wrt, const CustomFunctionalConstraint<A, P, N, I> &cfc, const std::vector<std::string> &vnam)

Specialize WriteModelItem() for CustomFuncCon<>

template<class Writer, class Con>
inline void WriteFlatCon(Writer &wrt, const Con &c, const std::vector<std::string> &vnam)

Very general template to write any flat constraint with name.

template<class JW, class A, class P, class N, class I>
inline void WriteJSON(JW jw, const CustomFunctionalConstraint<A, P, N, I> &cfc)

Write a CustomFunctionalConstraint<>

template<size_t N>
inline void VisitArguments(const std::array<int, N> &cnt, std::function<void(int)> argv)

Argument container visitor: VarArrayN.

template<class Item>
inline void VisitArguments(const Item &item, std::function<void(int)> argv)

Generic constraint/objective argument visitor.

template<>
inline void VisitArguments(const std::vector<int> &cnt, std::function<void(int)> argv)

Argument container visitor: VarArray.

template<class Con, class VarVec>
double ComputeValue(const Con&, const VarVec&)

Dummy template: compute result of functional constraint.

Should be implemented for proper functional specializations, but has no sense for conic constraints, for example.

template<class Args, class Params, class NumOrLogic, class Id, class VarVec>
Violation ComputeViolation(const CustomFunctionalConstraint<Args, Params, NumOrLogic, Id> &c, const VarVec &x)

Compute violation of functional constraint.

Can only be used for proper functional constraints, should be redefined for cones.

template<class Writer, class Con>
inline void WriteModelItem(Writer &wrt, const ConditionalConstraint<Con> &condc, const std::vector<std::string> &vnam)

Write ConditionalCon without name.

template<class Writer>
void WriteVar(Writer &pr, const char *name, double lb, double ub, var::Type ty)

Write a readable variable definition.

template<class JW, class Con>
inline void WriteJSON(JW jw, const ConditionalConstraint<Con> &condc)

Write a CondCon.

template<class VarVec>
double ComputeValue(const MaxConstraint &con, const VarVec &x)

Compute result of the max constraint.

template<class VarVec>
double ComputeValue(const MinConstraint &con, const VarVec &x)

Compute result of the min constraint.

template<class VarVec>
double ComputeValue(const AbsConstraint &con, const VarVec &x)

Compute result of the abs constraint.

template<class VarVec>
double ComputeValue(const AndConstraint &con, const VarVec &x)

Compute result of the and constraint.

template<class VarVec>
double ComputeValue(const OrConstraint &con, const VarVec &x)

Compute result of the or constraint.

template<class VarVec>
double ComputeValue(const NotConstraint &con, const VarVec &x)

Compute result of the not constraint.

template<class VarVec>
double ComputeValue(const DivConstraint &con, const VarVec &x)

Compute result of the div constraint.

template<class VarVec>
double ComputeValue(const IfThenConstraint &con, const VarVec &x)

Compute result of the IfThen constraint.

template<class VarVec>
double ComputeValue(const ImplicationConstraint &con, const VarVec &x)

Compute result of the Implication constraint.

template<class VarVec>
double ComputeValue(const AllDiffConstraint &con, const VarVec &x)

Compute result of the AllDiff constraint.

template<class VarInfo>
double ComputeValue(const NumberofConstConstraint &con, const VarInfo &x)

Compute result of the NumberofConst constraint.

template<class VarVec>
double ComputeValue(const NumberofVarConstraint &con, const VarVec &x)

Compute result of the NumberofVar constraint.

template<class VarVec>
double ComputeValue(const CountConstraint &con, const VarVec &x)

Compute result of the count constraint.

template<class VarVec>
double ComputeValue(const ExpConstraint &con, const VarVec &x)

Compute result of the exp constraint.

template<class VarVec>
double ComputeValue(const ExpAConstraint &con, const VarVec &x)

Compute result of the expA constraint.

template<class VarVec>
double ComputeValue(const LogConstraint &con, const VarVec &x)

Compute result of the log constraint.

template<class VarVec>
double ComputeValue(const LogAConstraint &con, const VarVec &x)

Compute result of the logA constraint.

template<class VarVec>
double ComputeValue(const PowConstraint &con, const VarVec &x)

Compute result of the pow constraint.

template<class VarVec>
double ComputeValue(const SinConstraint &con, const VarVec &x)

Compute result of the sin constraint.

template<class VarVec>
double ComputeValue(const CosConstraint &con, const VarVec &x)

Compute result of the cos constraint.

template<class VarVec>
double ComputeValue(const TanConstraint &con, const VarVec &x)

Compute result of the tan constraint.

template<class VarVec>
double ComputeValue(const AsinConstraint &con, const VarVec &x)

Compute result of the asin constraint.

template<class VarVec>
double ComputeValue(const AcosConstraint &con, const VarVec &x)

Compute result of the acos constraint.

template<class VarVec>
double ComputeValue(const AtanConstraint &con, const VarVec &x)

Compute result of the atan constraint.

template<class VarVec>
double ComputeValue(const SinhConstraint &con, const VarVec &x)

Compute result of the sinh constraint.

template<class VarVec>
double ComputeValue(const CoshConstraint &con, const VarVec &x)

Compute result of the cosh constraint.

template<class VarVec>
double ComputeValue(const TanhConstraint &con, const VarVec &x)

Compute result of the tanh constraint.

template<class VarVec>
double ComputeValue(const AsinhConstraint &con, const VarVec &x)

Compute result of the asinh constraint.

template<class VarVec>
double ComputeValue(const AcoshConstraint &con, const VarVec &x)

Compute result of the acosh constraint.

template<class VarVec>
double ComputeValue(const AtanhConstraint &con, const VarVec &x)

Compute result of the atanh constraint.

template<class VarVec>
double ComputeValue(const LinearFunctionalConstraint &con, const VarVec &x)

Compute result of the LinearFuncCon constraint.

template<class VarVec>
double ComputeValue(const QuadraticFunctionalConstraint &con, const VarVec &x)

Compute result of the QuadrFuncCon constraint.

template<class Con, class VarVec>
double ComputeValue(const ConditionalConstraint<Con> &con, const VarVec &x)

Compute result of a conditional constraint.

Just return bool(viol(subcon) <= 0). This is not used to compute violation.

template<class VarVec>
Violation ComputeViolation(const QuadraticConeConstraint &con, const VarVec &x)

Compute violation of the QuadraticCone constraint.

template<class VarVec>
Violation ComputeViolation(const RotatedQuadraticConeConstraint &con, const VarVec &x)

Compute violation of the RotatedQuadraticCone constraint.

template<class VarVec>
Violation ComputeViolation(const ExponentialConeConstraint &con, const VarVec &x)

Compute violation of the ExponentialCone constraint.

template<class VarVec>
double ComputeValue(const PLConstraint &con, const VarVec &x)

Compute result of the PL constraint.

DEF_NUMERIC_FUNC_CONSTR (Max, VarArray, "r = max(v1, v2, ..., vn)")
DEF_NUMERIC_FUNC_CONSTR (Min, VarArray, "r = min(v1, v2, ..., vn)")
DEF_NUMERIC_FUNC_CONSTR (Abs, VarArray1, "r = abs(v)")
DEF_LOGICAL_FUNC_CONSTR (And, VarArray, "r = forall({vi})")
DEF_LOGICAL_FUNC_CONSTR (Or, VarArray, "r = exists({vi})")
DEF_LOGICAL_FUNC_CONSTR (Not, VarArray1, "r = !v")
DEF_NUMERIC_FUNC_CONSTR (Div, VarArray2, "r = v1 / v2 and v2!=0")

DivConstraint and DivExpression.

DEF_NUMERIC_FUNC_CONSTR (IfThen, VarArrayN< 3 >, "Expr-valued: if (cond) then (expr1) else (expr2)")
DEF_LOGICAL_FUNC_CONSTR (Implication, VarArrayN< 3 >, "Logic-valued: if (cond) then (con1) else (con2)")
DEF_LOGICAL_FUNC_CONSTR (AllDiff, VarArray, "alldiff({})")
DEF_NUMERIC_FUNC_CONSTR_WITH_PRM (NumberofConst, VarArray, DblParamArray1, "numberof_const(k, {x0...xn})")
DEF_NUMERIC_FUNC_CONSTR (NumberofVar, VarArray, "numberof_var(x0, {x1...xn})")
DEF_NUMERIC_FUNC_CONSTR (Count, VarArray, "count({x0...xn})")
DEF_NUMERIC_FUNC_CONSTR (Exp, VarArray1, "r = exp(v)")
DEF_NUMERIC_FUNC_CONSTR_WITH_PRM (ExpA, VarArray1, DblParamArray1, "r = a**v")
DEF_NUMERIC_FUNC_CONSTR (Log, VarArray1, "r = log(v)")
DEF_NUMERIC_FUNC_CONSTR_WITH_PRM (LogA, VarArray1, DblParamArray1, "r = log(v)/log(a)")
DEF_NUMERIC_FUNC_CONSTR_WITH_PRM (Pow, VarArray1, DblParamArray1, "r = v ** a")
DEF_NUMERIC_FUNC_CONSTR (Sin, VarArray1, "r = sin(v)")
DEF_NUMERIC_FUNC_CONSTR (Cos, VarArray1, "r = cos(v)")
DEF_NUMERIC_FUNC_CONSTR (Tan, VarArray1, "r = tan(v)")
DEF_NUMERIC_FUNC_CONSTR (Asin, VarArray1, "r = asin(v)")
DEF_NUMERIC_FUNC_CONSTR (Acos, VarArray1, "r = acos(v)")
DEF_NUMERIC_FUNC_CONSTR (Atan, VarArray1, "r = atan(v)")
DEF_NUMERIC_FUNC_CONSTR (Sinh, VarArray1, "r = sinh(v)")
DEF_NUMERIC_FUNC_CONSTR (Cosh, VarArray1, "r = cosh(v)")
DEF_NUMERIC_FUNC_CONSTR (Tanh, VarArray1, "r = tanh(v)")
DEF_NUMERIC_FUNC_CONSTR (Asinh, VarArray1, "r = asinh(v)")
DEF_NUMERIC_FUNC_CONSTR (Acosh, VarArray1, "r = acosh(v)")
DEF_NUMERIC_FUNC_CONSTR (Atanh, VarArray1, "r = atanh(v)")
DEF_CONDITIONAL_CONSTRAINT_WRAPPER(CondLinLT, LinConLT)

Not using: var1 != var2.

Represented by Not { Eq0Constraint… }

DEF_CONDITIONAL_CONSTRAINT_WRAPPER(CondLinLE, LinConLE)
DEF_CONDITIONAL_CONSTRAINT_WRAPPER(CondLinEQ, LinConEQ)
DEF_CONDITIONAL_CONSTRAINT_WRAPPER(CondLinGE, LinConGE)
DEF_CONDITIONAL_CONSTRAINT_WRAPPER(CondLinGT, LinConGT)
DEF_CONDITIONAL_CONSTRAINT_WRAPPER(CondQuadLT, QuadConLT)
DEF_CONDITIONAL_CONSTRAINT_WRAPPER(CondQuadLE, QuadConLE)
DEF_CONDITIONAL_CONSTRAINT_WRAPPER(CondQuadEQ, QuadConEQ)
DEF_CONDITIONAL_CONSTRAINT_WRAPPER(CondQuadGE, QuadConGE)
DEF_CONDITIONAL_CONSTRAINT_WRAPPER(CondQuadGT, QuadConGT)
template<class Writer>
inline void WriteModelItem(Writer &wrt, const LinearFunctionalConstraint &lfc, const std::vector<std::string> &vnam)

Write LFC without name.

inline void WriteJSON(JSONW jw, const LinearFunctionalConstraint &lfc)

Write a LinFuncCon.

template<class Writer>
inline void WriteModelItem(Writer &wrt, const QuadraticFunctionalConstraint &qfc, const std::vector<std::string> &vnam)

Write LFC without name.

inline void WriteJSON(JSONW jw, const QuadraticFunctionalConstraint &qfc)

Write a QuadrFuncCon.

DEF_NUMERIC_FUNC_CONSTR_WITH_PRM (PL, VarArray1, PLConParams, "r = piecewise_linear(x)")

Define PLConstraint.

template<class Writer>
void WriteModelItemParameters(Writer &wrt, const PLConParams &plp)

Write flat expr/obj/con parameters: PLConParams.

inline void WriteJSON(JSONW jw, const PLConParams &plp)

Write PLConParams.

template<class Writer, class Con>
inline void WriteModelItem(Writer &wrt, const IndicatorConstraint<Con> &ic, const std::vector<std::string> &vnam)

Write indicator without name.

template<class Con>
inline void WriteJSON(JSONW jw, const IndicatorConstraint<Con> &ic)

Export indicator constraint.

template<class Con>
inline void VisitArguments(const IndicatorConstraint<Con> &ic, std::function<void(int)> argv)

Specialize.

DEF_STATIC_CONSTR (UnaryEncoding, VarArray1, "Unary encoding of an integer bounded variable")

Unary encoding.

Currently a dummy constraint just to build the reformulation graph.

template<class Writer, int type>
inline void WriteModelItem(Writer &wrt, const SOS_1or2_Constraint<type> &sos, const std::vector<std::string> &vnam)

Write SOS without name.

template<int type>
inline void WriteJSON(JSONW jw, const SOS_1or2_Constraint<type> &sos)

Export a SOS1, SOS2 constraint.

template<class Writer, class Expr>
inline void WriteModelItem(Writer &wrt, const ComplementarityConstraint<Expr> &cc, const std::vector<std::string> &vnam)

Write ComplCon without name.

template<class Expr>
inline void WriteJSON(JSONW jw, const ComplementarityConstraint<Expr> &cc)

Write a ComplementarityCon.

template<class Expr>
inline void VisitArguments(const ComplementarityConstraint<Expr> &cc, std::function<void(int)> argv)

Specialize.

DEF_STATIC_CONSTR_WITH_PRM (QuadraticCone, VarArray, DblParamArray, "Quadratic cone p1*x1 >= sqrt((p2*x2)^2 + ...))," " with factors p1..pn")

Quadratic cone.

DEF_STATIC_CONSTR_WITH_PRM (RotatedQuadraticCone, VarArray, DblParamArray, "Rotated quadratic cone " "2 * p1*x1*p2*x2 >= (p3*x3)^2 + ...)," " x1, x2 >= 0 or x1, x2 <= 0, with factors p1..pn")

Rotated quadratic cone.

DEF_STATIC_CONSTR_WITH_PRM (ExponentialCone, VarArray3, DblParamArray3, "Exponential cone ax >= by exp(cz / (by))," " where ax, by >= 0, with factors a,b,c")

Exponential cone.

DEF_STATIC_CONSTR_WITH_PRM (PowerCone, VarArray, DblParamArray, "Power cone with factors")

Power cone.

DEF_STATIC_CONSTR_WITH_PRM (GeometricCone, VarArray, DblParamArray, "Geometric with factors")

Geometric cone.

template<class Args, class Params, class NumOrLogic, class Id>
inline bool operator==(std::reference_wrapper<const CustomFunctionalConstraint<Args, Params, NumOrLogic, Id>> c1, std::reference_wrapper<const CustomFunctionalConstraint<Args, Params, NumOrLogic, Id>> c2)

Subexpression maps for an expression require operator==(refwrap<expr>, refwrap<expr>).

The below one is for CustomFunctionalConstraint<>

template<class Con>
inline bool operator==(std::reference_wrapper<const ConditionalConstraint<Con>> c1, std::reference_wrapper<const ConditionalConstraint<Con>> c2)

operator==(refwrap<ConditionalConstraint<> >)

inline bool operator==(std::reference_wrapper<const LinearFunctionalConstraint> c1, std::reference_wrapper<const LinearFunctionalConstraint> c2)

operator==(LFC)

inline bool operator==(std::reference_wrapper<const QuadraticFunctionalConstraint> c1, std::reference_wrapper<const QuadraticFunctionalConstraint> c2)

operator==(QFC)

template<class Converter, class Constraint, class Converter2>
FCC<Converter, Constraint> MakeFuncConstrConverter(Converter2 &cvt, Constraint &&fc)
template<>
void WriteJSON(JSONW jw, const LinTerms &qt)

Specialize.

void VisitArguments(const LinTerms &lt, std::function<void(int)> argv)

Specialize.

template<class Writer, class Terms>
inline void WriteModelItem(Writer &wrt, const AlgebraicExpression<Terms> &ale, const std::vector<std::string> &vnam)

Write algebraic expr.

template<class Writer, class Obj>
void WriteJSON(Writer w, const Obj &o)

Very general template to write a JSON-like representation of anything.

template<class Terms>
inline void WriteJSON(JSONW jw, const AlgebraicExpression<Terms> &ale)

Write an AlgebraicExpression.

template<>
void WriteJSON(JSONW jw, const QuadTerms &qt)

Specialize.

template<>
void WriteJSON(JSONW jw, const QuadAndLinTerms &qt)

Specialize.

void VisitArguments(const QuadTerms &lt, std::function<void(int)> argv)

Specialize.

void VisitArguments(const QuadAndLinTerms &lt, std::function<void(int)> argv)

Specialize.

inline AffineExpr MoveOutAffineExpr(QuadraticExpr &&qe)

Extract (move out) affine expr.

const char *ConGroupName(int cg)

Constraint group names.

Todo:

Keep consistent with the ConstraintGroups enum.

template<class ModelAPI, template<typename, typename, typename> class FlatConverter, class Backend>
std::unique_ptr<BasicModelManager> CreateModelMgrWithFlatConverter(Backend &gc, Env &e, pre::BasicValuePresolver *&pPre)

A template to create a ModelManager with a FlatConverter for a specific solver.

Currently is uses mp::Problem as intermediate storage of the NL model.

Template Parameters
  • Backend – the Backend class

  • ModelAPI – the ModelAPI class to be created and used by the ModelManager

  • FlatConverter – the FlatConverter to be used

Parameters
  • gc – Backend object

  • e – the MP environment

  • pPre – return ValuePresolver for Backends that use it

std::unique_ptr<FlatModelInfo> CreateFlatModelInfo()

FlatModelInfo factory.

void WriteModelItem(fmt::MemoryWriter &wrt, const QuadraticObjective &obj, const std::vector<std::string> &vnam)

Write objective.

template<class VarVec>
double ComputeValue(const QuadraticObjective &obj, const VarVec &x)

Compute value of an objective.

template<class Num>
bool is_integer(Num n)

Short check for integrality.

inline LinTerms ToLinTerms(const LinearExpr &e)

Convert mp::LinearExpr to LinTerms.

template<typename ExprTypes, typename LinearExpr, typename NumericExpr, typename Namer>
void WriteExpr(fmt::Writer &w, const LinearExpr &linear, NumericExpr nonlinear, Namer)

Write algebraic expression (linear + non-linear.)

template<typename ExprTypes, typename LogicalExpr, class VN>
void WriteExpr(fmt::Writer &w, LogicalExpr expr, VN)

Write logical expression.

template<class ExprTypes, class AlgCon, class VN>
void WriteAlgCon(fmt::Writer &w, const AlgCon &con, VN)

Write algebraic constraint.

P_ZZI_Encoding MakeZZIEncoding()
std::vector<double> GetExtendedColumn(ZZI_Encoding&, int r, int k, int v0, int v1)

Obtain column k of the encoding matrix C^r prepended by 0 and postpended by line v1-1 if v1-1 == 2^r.

template<class FuncCon>
void PLApproximate(const FuncCon &con, PLApproxParams &laPrm)

Do the approximation by calling the function-specific approximator.

Parameters

laPrm – in-out parameter

std::pair<std::string, std::string> GetWarningKeyAndText(const char *conName, double tol)

A function to add warning about PL approximation.

std::unique_ptr<BasicModelManager> CreateModelManagerWithStdBuilder(std::unique_ptr<BasicConverter<mp::Problem>> pcvt)

Declare a ModelManager factory.

fmt::Writer &operator<<(fmt::Writer &w, const NLHeader &h)

Writes NLHeader in the NL format.

template<typename Handler>
void ReadNLString(NLStringRef str, Handler &handler, fmt::CStringRef name, int flags)

Reads an optimization problem in the NL format from the string str and sends notifications of the problem components to the handler object. See mp::ReadNLFile() for description of handler and flags. Both str and name can be C strings or std::string objects. The name argument is used as the name of the input when reporting errors.

template<typename Handler>
inline void ReadNLFile(fmt::CStringRef filename, Handler &handler, int flags)

Reads an optimization problem in the NL format from the file filename and sends notifications of the problem components to the handler object. The handler class can be one of the following

The filename argument can be a C string or an std::string object. flags can be either 0, which is the default, to read all constructs in the order they appear in the input, or mp::READ_BOUNDS_FIRST to read variable bounds after the NL header and before other constructs such as nonlinear expressions.

Example:

// Count the number of variable references in all nonlinear expressions.
struct VarCounter : mp::NullNLHandler<int> {
  int num_vars;
  VarCounter() : num_vars(0) {}
  Reference OnVariableRef(int) {
    ++num_vars;
    return Reference();
  }
};
VarCounter counter;
mp::ReadNLFile("test.nl", counter);
fmt::print("The number of variable references is {}.", counter.num_vars);

char ParseOptions(char **&args, OptionList &options)

Parses command-line options until the first argument that doesn’t start with ‘-’.

Returns the option that terminated parsing or 0 if parsing continued till the end.

path GetExecutablePath()
template<typename T>
inline MakeUnsigned<T>::Type SafeAbs(T value)
template<typename T>
inline SafeInt<T> operator+(SafeInt<T> a, SafeInt<T> b)
template<typename T1, typename T2>
inline SafeInt<T1> operator+(SafeInt<T1> a, T2 b)
template<typename T1, typename T2>
inline SafeInt<T2> operator+(T1 a, SafeInt<T2> b)
template<typename T>
inline SafeInt<T> operator-(SafeInt<T> a, SafeInt<T> b)
template<typename T1, typename T2>
inline SafeInt<T1> operator-(SafeInt<T1> a, T2 b)
template<typename T1, typename T2>
inline SafeInt<T2> operator-(T1 a, SafeInt<T2> b)
template<typename T>
inline SafeInt<T> operator*(SafeInt<T> a, SafeInt<T> b)
template<typename T1, typename T2>
inline SafeInt<T1> operator*(SafeInt<T1> a, T2 b)
template<typename T1, typename T2>
inline SafeInt<T2> operator*(T1 a, SafeInt<T2> b)
template<typename Solution>
void WriteSolFile(fmt::CStringRef filename, const Solution &sol)

Writes a solution to a .sol file.

inline SolverPtr move(SolverPtr p)
template<typename SuffixType>
inline SuffixType Cast(Suffix s)

“inline” is used here instead of the definition to suppress bogus C4396 warnings in MSVC.

Casts a suffix to type SuffixType which must be a valid suffix type.

Returns a null suffix if s is not convertible to SuffixType.

template<typename SuffixType>
inline SuffixType Cast(MutSuffix s)
double GetTimeAndReset(std::chrono::steady_clock::time_point &t)
std::unique_ptr<BasicFileAppender> MakeFileAppender()

FileAppender maker.

template<class F>
F round_to_digits(F value, int digits)

https://stackoverflow.com/questions/13094224/a-c-routine-to-round-a-float-to-n-significant-digits

std::vector<std::string> split_string(const char*)

Split string.

template<class Str>
inline std::vector<std::string> split_string(const Str &str)

Split string.

template<class NLFeeder>
inline WriteNLResult WriteNLFile(const std::string &namebase, NLFeeder &nlf, NLUtils &utl)

Write NL file and any necessary auxiliary files.

Parameters

namebase – name without extension, to be augmented by .nl, .col, …etc.

Returns

Write status. Note that warnings are reported via utl.

template<class Value>
StringFileWriter &operator<<(StringFileWriter &wrt, Value s)

operator<< (StringFileWriter&, Value)

template<class SOLHandler>
inline std::pair<NLW2_SOLReadResultCode, std::string> ReadSOLFile(const std::string &name, SOLHandler &solh, NLUtils &utl, int *p_internal_rv = nullptr)

Read SOL file.

inline int decstring(const char *buf, double *val)

Parse double.

inline NLW2_SOLReadResultCode Read(FILE *f, int binary, double &v, std::string &err)

Read a double from text or binary file.

template<class El>
inline NLW2_SOLReadResultCode Read(FILE *f, int binary, std::pair<int, El> &v, std::string &err)

Read a pair<int, El> from text or binary file.

inline int Lget(char **sp, int *Lp)

Parse int.

NLHeader_C MakeNLHeader_C_Default(void)

Variables

static constexpr char gl_1__short[] = "%c%d"
static constexpr char gl_2a[] = " %d %d %d %d %d"
static constexpr char gl_1a []  = "\t# problem %s" EOL
static constexpr char gl_2 []  = "\t# vars, algcons, objs, ranges, eqns%s" EOL
static constexpr char gl_3 []  = " %d %d\t# nonlinear cons, objs" EOL
static constexpr char gl_3c []  = "\t# nonlinear cons, objs; compl: lin, nonlin, range, nzlb%s" EOL
static constexpr char gl_4 []  = "\t# network cons: nonlinear, linear" EOL
static constexpr char gl_4r []  = " %d\t# network cons: nonlinear, linear; stages" EOL
static constexpr char gl_5 []  = " %d %d %d\t# nonlinear vars in cons, objs, both" EOL
static constexpr char gl_6 []  = " %d %d\t# linear network vars; funcs" EOL
static constexpr char gl_6x []  = " %d %d %d %d\t# linear network vars; funcs; arith, flags" EOL
static constexpr char gl_6y []  = " %d %d %d %d %d\t# linear network vars; funcs; arith, flags; randcalls" EOL
static constexpr char gl_7 []  = " %d %d %d %d %d\t# discrete vars: binary, integer, nonlinear (b,c,o)" EOL
static constexpr char gl_8 []  = " %zd %zd\t# nonzeros in Jacobian, gradients" EOL
static constexpr char gl_9 []  = " %d %d\t# max name lengths: cons/objs, vars" EOL
static constexpr char gl_10 []  = "\t# common exprs: b,c,o,c1,o1%s" EOL
namespace [anonymous]
namespace mp::arith

Namespace arith.

Enums

enum Kind

Floating-point arithmetic kind.

Values:

enumerator UNKNOWN

Unknown floating-point arithmetic.

enumerator IEEE_LITTLE_ENDIAN

Standard IEEE-754 floating point - little endian.

enumerator IEEE_BIG_ENDIAN

Standard IEEE-754 floating point - big endian.

enumerator IBM

IBM floating point.

enumerator VAX

VAX floating point (legacy).

enumerator CRAY

Cray floating point.

enumerator LAST

Last floating point.

enumerator UNKNOWN

Unknown floating-point arithmetic.

enumerator IEEE_LITTLE_ENDIAN

Standard IEEE-754 floating point - little endian.

enumerator IEEE_BIG_ENDIAN

Standard IEEE-754 floating point - big endian.

enumerator IBM

IBM floating point.

enumerator VAX

VAX floating point (legacy).

enumerator CRAY

Cray floating point.

enumerator LAST

Last floating point.

enum Kind

Floating-point arithmetic kind.

Values:

enumerator UNKNOWN

Unknown floating-point arithmetic.

enumerator IEEE_LITTLE_ENDIAN

Standard IEEE-754 floating point - little endian.

enumerator IEEE_BIG_ENDIAN

Standard IEEE-754 floating point - big endian.

enumerator IBM

IBM floating point.

enumerator VAX

VAX floating point (legacy).

enumerator CRAY

Cray floating point.

enumerator LAST

Last floating point.

enumerator UNKNOWN

Unknown floating-point arithmetic.

enumerator IEEE_LITTLE_ENDIAN

Standard IEEE-754 floating point - little endian.

enumerator IEEE_BIG_ENDIAN

Standard IEEE-754 floating point - big endian.

enumerator IBM

IBM floating point.

enumerator VAX

VAX floating point (legacy).

enumerator CRAY

Cray floating point.

enumerator LAST

Last floating point.

Functions

Kind GetKind()

Returns floating-point arithmetic kind used on the current system.

inline bool IsIEEE(arith::Kind k)

IsIEEE.

namespace mp::expr

Expression information.

Enums

enum Kind

Expression kind. Both AMPL-like and mathematical notation is given for each expression in the descriptions below as in \(\mathrm{abs}(x) = |x|\), unless they are identical such as \(\mathrm{sin}(x)\) or there is no standard mathematical notation.

Values:

enumerator UNKNOWN

An unknown expression.

enumerator FIRST_EXPR

The first expression kind other than the unknown expression kind.

enumerator FIRST_NUMERIC

The first numeric expression kind. Numeric expression kinds are in the range [FIRST_NUMERIC, LAST_NUMERIC].

enumerator NUMBER

A number such as 42 or -1.23e-4.

enumerator FIRST_REFERENCE

The first reference expression kind. Reference expression kinds are in the range [FIRST_REFERENCE, LAST_REFERENCE].

enumerator VARIABLE

A reference to a variable.

enumerator COMMON_EXPR

A reference to a common expression.

enumerator LAST_REFERENCE

The last reference expression kind.

enumerator FIRST_UNARY

The first unary numeric expression kind. Unary numeric expression kinds are in the range [FIRST_UNARY, LAST_UNARY].

enumerator MINUS

A unary minus, \(-x\).

enumerator ABS

The absolute value function, \(\mathrm{abs}(x) = |x|\).

enumerator FLOOR

The floor function, \(\mathrm{floor}(x) = \lfloor x \rfloor\).

enumerator CEIL

The ceiling function, \(\mathrm{ceil}(x) = \lceil x \rceil\).

enumerator SQRT

The square root function, \(\mathrm{sqrt}(x) = \sqrt{x}\).

enumerator POW2

Squaring: \(x \mathop{\verb!^!} 2 = x^2\).

enumerator EXP

The natural exponential function, \(\mathrm{exp}(x) = e^x\).

enumerator LOG

The natural logarithmic function, \(\mathrm{log}(x) = \mathrm{ln}(x)\).

enumerator LOG10

The base 10 logarithmic function, \(\mathrm{log10}(x) = \mathrm{log}_{10}(x)\).

enumerator SIN

Sine, \(\mathrm{sin}(x)\).

enumerator SINH

Hyperbolic sine, \(\mathrm{sinh}(x)\).

enumerator COS

Cosine, \(\mathrm{cos}(x)\).

enumerator COSH

Hyperbolic cosine, \(\mathrm{cosh}(x)\).

enumerator TAN

Tangent, \(\mathrm{tan}(x)\).

enumerator TANH

Hyperbolic tangent, \(\mathrm{tan}(x)\).

enumerator ASIN

Inverse sine, \(\mathrm{asin}(x) = \mathrm{sin}^{-1}(x)\).

enumerator ASINH

Inverse hyperbolic sine, \(\mathrm{asinh}(x) = \mathrm{sinh}^{-1}(x)\).

enumerator ACOS

Inverse cosine, \(\mathrm{acos}(x) = \mathrm{cos}^{-1}(x)\).

enumerator ACOSH

Inverse hyperbolic cosine, \(\mathrm{acosh}(x) = \mathrm{cosh}^{-1}(x)\).

enumerator ATAN

Inverse tangent, \(\mathrm{atan}(x) = \mathrm{tan}^{-1}(x)\).

enumerator ATANH

Inverse hyperbolic tangent, \(\mathrm{atanh}(x) = \mathrm{tanh}^{-1}(x)\).

enumerator LAST_UNARY

The last unary numeric expression kind.

enumerator FIRST_BINARY

The first binary expression kind. Binary expression kinds are in the range [FIRST_BINARY, LAST_BINARY].

enumerator ADD

Addition, \(x + y\).

enumerator SUB

Subtraction, \(x - y\).

enumerator LESS

The \(\mathrm{less}\) operation, \(x \mathop{\rm less} y = \mathrm{max}(x - y, 0)\).

enumerator MUL

Multiplication, \(x * y = x y\).

enumerator DIV

Division, \(x / y\).

enumerator TRUNC_DIV

Truncated division, \(x \mathop{\rm div} y = \mathrm{trunc}(x / y)\).

enumerator MOD

The modulo operation, \(x \mathop{\rm mod} y\).

enumerator POW

Exponentiation, \(x \mathop{\verb!^!} y = x^y\).

enumerator POW_CONST_BASE

Exponentiation with a constant base, \(a^x\).

enumerator POW_CONST_EXP

Exponentiation with a constant exponent \(x^a\).

enumerator ATAN2

Inverse tangent, \(\mathrm{atan2}(y, x) = \mathrm{tan}^{-1}(y/x)\).

enumerator PRECISION

The function \(\mathrm{precision}(x, n)\) which returns \(x\) rounded to \(n\) significant decimal digits.

enumerator ROUND

The function \(\mathrm{round}(x, n)\) which returns \(x\) rounded to \(n\) digits past decimal point.

enumerator TRUNC

The function \(\mathrm{trunc}(x, n)\) which returns \(x\) truncated to \(n\) digits past decimal point.

enumerator LAST_BINARY

The last binary numeric expression kind.

enumerator IF

An if-then-else expression, \(\mathrm{if}\;c\;\mathrm{then}\;e_1\;[\mathrm{else}\;e_2]\), where \(c\) is a logical expression representing condition, while \(e_1\) and \(e_2\) are numeric expressions. The expression evaluates to \(e_1\) if \(c\) is true and to \(e_2\) otherwise. If the else clause is omitted, \(e_2\) is assumed to be zero.

enumerator PLTERM

A piecewise-linear term, \(\verb|<<|b_1, ..., b_n; s_1, ..., s_{n + 1}\verb|>> | r\), where \(b_i\) are breakpoints, \(s_i\) are slopes and \(r\) is a reference.

enumerator CALL

A function call, \(f(e_1, ..., e_n)\), where \(f\) is a function name and \(e_i\) are numeric or string expressions.

enumerator FIRST_ITERATED

The first iterated expression kind. Iterated expression kinds are in the range [FIRST_ITERATED, LAST_ITERATED].

The term “iterated” in the context of operators and expressions comes from the article AMPL: A Mathematical Programming Language and is used to denote operators indexed over sets.

enumerator FIRST_VARARG

A vararg expression, \(\mathrm{min}\) or \(\mathrm{max}\). Vararg expression kinds are in the range [FIRST_VARARG, LAST_VARARG].

enumerator MIN

Minimum, \(\mathrm{min}(e_1, ..., e_n) = \min_{i=1,...,n} e_i\).

enumerator MAX

Maximum, \(\mathrm{max}(e_1, ..., e_n) = \max_{i=1,...,n} e_i\).

enumerator LAST_VARARG

The last vararg expression kind.

enumerator SUM

Summation, \(\mathrm{sum}(e_1, ..., e_n) = \sum_{i=1}^n e_i\).

enumerator NUMBEROF

A \(\mathrm{numberof}\) expression, \(\mathrm{numberof}\;e_0\;\mathrm{in}\;(e_1, ..., e_n)\), which evaluates to the number of times the value of \(e_0\) appears among the values of \(e_1, ..., e_n\).

enumerator LAST_ITERATED

The last iterated expression kind.

enumerator NUMBEROF_SYM

A symbolic \(\mathrm{numberof}\) expression. \(\mathrm{numberof}\;s_0\;\mathrm{in}\;(s_1, ..., s_n)\), which evaluates to the number of times the value of \(s_0\) appears among the values of \(s_1, ..., s_n\).

enumerator COUNT

A \(\mathrm{count}\) expression, \(\mathrm{count}(l_1, ..., l_n)\), where \(l_i\) are logical expressions. This expression evaluates to the number of \(l_i\) whose values are true.

enumerator LAST_NUMERIC

The last numeric expression kind.

enumerator FIRST_LOGICAL

The first logical expression kind. Logical expression kinds are in the range [FIRST_LOGICAL, LAST_LOGICAL].

enumerator BOOL

A Boolean (logical) constant, true or false.

enumerator NOT

A logical not, \(!l\), where \(l\) is a logical expression.

enumerator FIRST_BINARY_LOGICAL

The first binary logical expression kind. Binary logical expression kinds are in the range [FIRST_BINARY_LOGICAL, LAST_BINARY_LOGICAL].

enumerator OR

Logical or, \(l_1\) || \(l_2\).

enumerator AND

Logical and, \(l_1\) && \(l_2\).

enumerator IFF

If and only if, \(l_1\) <==> \(l_2\).

enumerator LAST_BINARY_LOGICAL

The last binary logical expression kind.

enumerator FIRST_RELATIONAL

The first relational expression kind. Relational expression kinds are in the range [FIRST_RELATIONAL, LAST_RELATIONAL].

enumerator LT

Less than, \(e_1\) < \(e_2\).

enumerator LE

Less or equal to, \(e_1\) <= \(e_2\).

enumerator EQ

Equal to, \(e_1\) = \(e_2\).

enumerator GE

Greater or equal to, \(e_1\) >= \(e_2\).

enumerator GT

Greater than, \(e_1\) > \(e_2\).

enumerator NE

Not equal to, \(e_1\) != \(e_2\).

enumerator LAST_RELATIONAL

The last relational expression kind.

enumerator FIRST_LOGICAL_COUNT

The first logical count expression kind. Logical count expression kinds are in the range [FIRST_LOGICAL_COUNT, LAST_LOGICAL_COUNT].

enumerator ATLEAST

An \(\mathrm{atleast}\) expression, \(\mathrm{atleast}\;e\;(l_1, ..., l_n)\), where \(e\) is a numeric expression and \(l_i\) are logical expressions. It evaluates to true if at least \(e\) expressions \(l_i\) are true.

enumerator ATMOST

An \(\mathrm{atmost}\) expression, \(\mathrm{atmost}\;e\;(l_1, ..., l_n)\), where \(e\) is a numeric expression and \(l_i\) are logical expressions. It evaluates to true if at most \(e\) expressions \(l_i\) are true.

enumerator EXACTLY

An \(\mathrm{exactly}\) expression, \(\mathrm{exactly}\;e\;(l_1, ..., l_n)\), where \(e\) is a numeric expression and \(l_i\) are logical expressions. It evaluates to true if exactly \(e\) expressions \(l_i\) are true.

enumerator NOT_ATLEAST

The negation of an \(\mathrm{atleast}\) expression, \(!\mathrm{atleast}\;e\;(l_1, ..., l_n)\).

enumerator NOT_ATMOST

The negation of an \(\mathrm{atmost}\) expression, \(!\mathrm{atmost}\;e\;(l_1, ..., l_n)\).

enumerator NOT_EXACTLY

The negation of an \(\mathrm{exactly}\) expression, \(!\mathrm{exactly}\;e\;(l_1, ..., l_n)\).

enumerator LAST_LOGICAL_COUNT

The last logical count expression kind.

enumerator IMPLICATION

An implication expression, \(c\;\verb|==>|\;l_1\;[\mathrm{else}\;l_2]\), where \(c\) is a logical expression representing condition, while \(l_1\) and \(l_2\) are logical expressions. The expression evaluates to \(l_1\) if \(c\) is true and to \(l_2\) otherwise. If the else clause is omitted, \(l_2\) is assumed to be true.

enumerator FIRST_ITERATED_LOGICAL

The first iterated logical expression kind. Iterated logical expression kinds are in the range [FIRST_ITERATED_LOGICAL, LAST_ITERATED_LOGICAL].

enumerator EXISTS

An \(\mathrm{exists}\) expression, \(\mathrm{exists}(l_1, ..., l_n)\), where \(l_i\) are logical expressions. It evaluates to true if at least one \(l_i\) is true.

enumerator FORALL

A \(\mathrm{forall}\) expression, \(\mathrm{forall}(l_1, ..., l_n)\), where \(l_i\) are logical expressions. It evaluates to true if all \(l_i\) are true.

enumerator LAST_ITERATED_LOGICAL

The last iterated logical expression kind.

enumerator FIRST_PAIRWISE

The first pairwise expression kind. Pairwise expression kinds are in the range [FIRST_PAIRWISE, LAST_PAIRWISE].

enumerator ALLDIFF

An alldifferent expression, \(\mathrm{alldiff}(e_1, ..., e_n)\), where \(e_i\) are numeric expressions. It evaluates to true if all \(e_i\) take different values.

enumerator NOT_ALLDIFF

The negation of an alldifferent expression, \(!\mathrm{alldiff}(e_1, ..., e_n)\).

enumerator LAST_PAIRWISE

The last pairwise expression kind.

enumerator LAST_LOGICAL

The last logical expression kind.

enumerator STRING

A string such as “abc”.

enumerator IFSYM

A symbolic if-then-else expression. \(\mathrm{if}\;c\;\mathrm{then}\;e_1\;[\mathrm{else}\;e_2]\), where \(c\) is a logical expression representing condition, while \(e_1\) and \(e_2\) are numeric or string expressions. The expression evaluates to \(e_1\) if \(c\) is true and to \(e_2\) otherwise. If \(e_2\) is omitted, it is assumed to be zero.

enumerator LAST_EXPR

The last expression kind.

Functions

inline const char *str(expr::Kind kind)

Returns the string representation of the given expression kind. Expressions of different kinds can have identical strings. For example, POW, POW_CONST_BASE and POW_CONST_EXP all have the same representation “^”.

inline int nl_opcode(expr::Kind kind)

Returns the NL opcode for the given expression kind.

namespace mp::func

Function information.

Enums

enum Type

Function type.

Values:

enumerator NUMERIC

A numeric function.

enumerator SYMBOLIC

A symbolic function accepting numeric and string arguments.

namespace mp::internal

MP low-level stuff.

Typedefs

template<class Solver>
using SolverNLHandler = SolverNLHandlerImpl<Solver, typename Solver::ProblemBuilder, typename Solver::NLProblemBuilder>

A shorthand typedef for APIs using SolverImpl or similar.

template<class Solver, class Writer = SolFileWriter>
using AppSolutionHandler = AppSolutionHandlerImpl<Solver, typename Solver::ProblemBuilder, Writer>

Convenience typedef for APIs using SolverImpl<> or similar.

Enums

enum [anonymous]

Values:

enumerator SUFFIX_KIND_MASK
enumerator NUM_SUFFIX_KINDS
enum [anonymous]

Maximum NL opcode.

Values:

enumerator MAX_OPCODE

Functions

inline void Unused(...)
template<typename ExprType>
inline bool Is(expr::Kind k)
inline bool IsValid(expr::Kind kind)
inline const OpCodeInfo &GetOpCodeInfo(int opcode)
template<typename ExprType>
inline ExprType UncheckedCast(Expr e)

Casts an expression to type ExprType which must be a valid expression type.

If assertions are enabled, it generates an assertion failure when e is not convertible to ExprType. Otherwise no runtime check is performed.

inline void CheckIndex(int index, std::size_t size)

Checks if index is in the range [0, size).

template<typename InputConverter, typename Handler>
void ReadBinary(TextReader<> &reader, const NLHeader &header, Handler &handler, int flags)
template<typename NameHandler>
void ReadNames(fmt::CStringRef filename, fmt::StringRef data, NameHandler &handler)

Reads names from the string data sending the names to the handler object by calling handler.OnName(name).

The name argument to OnName is a fmt::StringRef

object and the string it refers to is not null-terminated. Each name in the input string/file should be on a separate line ended with a newline character (’

’) or “\r\n” (on Windows).

inline std::size_t ConvertFileToMmapSize(fmt::LongLong file_size, fmt::CStringRef filename)
void WriteMessage(fmt::BufferedFile &file, const char *message)

Write message into a fmt::BufferedFile.

template<typename SuffixMap>
void WriteSuffixes(fmt::BufferedFile &file, const SuffixMap *suffixes)

Write suffixes to a file.

template<typename Solver>
inline void SetBasename(Solver &s, const std::string *basename, Check<void (Solver::*)(fmt::StringRef), &Solver::set_basename> = 0)
template<typename Solver>
inline void SetBasename(Solver&, ...)
void CheckDemoVersion(const NLHeader &h)

Perform demo version checks if necessary.

void PrintSolution(const double *values, int num_values, const char *name_col, const char *value_col, NameProvider &np)

Prints a solution to stdout.

void FormatRST(fmt::Writer &w, fmt::CStringRef s, int indent = 0, ValueArrayRef values = ValueArrayRef())

Formats the string s containing the reStructuredText (RST) markup and writes it to w.

Parameters
  • w – stream writer used for output

  • indent – indentation to use for the formatted text

  • s – string containing reStructuredText to format

  • values – information about possible option values to be formatted by the value-table directive

inline OptionError OptionTypeError(fmt::StringRef name, fmt::StringRef type)

Raise OptionError.

template<typename SuffixType>
inline bool Is(Suffix s)

Returns true if s is of type SuffixType.

template<class T>
inline std::size_t HashCombine(std::size_t seed, const T &v)

HashCombine template, 32-bit.

namespace mp::nl

Namespace nl.

Defines NL opcodes to be used, e.g., by the NL writer.

Variables

const Opcode ADD = {0, "+"}
const Opcode SUB = {1, "-"}
const Opcode MUL = {2, "*"}
const Opcode DIV = {3, "/"}
const Opcode MOD = {4, "mod"}
const Opcode POW = {5, "^"}
const Opcode LESS = {6, "less"}
const Opcode MIN = {11, "min"}
const Opcode MAX = {12, "max"}
const Opcode FLOOR = {13, "floor"}
const Opcode CEIL = {14, "ceil"}
const Opcode ABS = {15, "abs"}
const Opcode MINUS = {16, "unary -"}
const Opcode OR = {20, "||"}
const Opcode AND = {21, "&&"}
const Opcode LT = {22, "<"}
const Opcode LE = {23, "<="}
const Opcode EQ = {24, "="}
const Opcode GE = {28, ">="}
const Opcode GT = {29, ">"}
const Opcode NE = {30, "!="}
const Opcode NOT = {34, "!"}
const Opcode IF = {35, "if"}
const Opcode TANH = {37, "tanh"}
const Opcode TAN = {38, "tan"}
const Opcode SQRT = {39, "sqrt"}
const Opcode SINH = {40, "sinh"}
const Opcode SIN = {41, "sin"}
const Opcode LOG10 = {42, "log10"}
const Opcode LOG = {43, "log"}
const Opcode EXP = {44, "exp"}
const Opcode COSH = {45, "cosh"}
const Opcode COS = {46, "cos"}
const Opcode ATANH = {47, "atanh"}
const Opcode ATAN2 = {48, "atan2"}
const Opcode ATAN = {49, "atan"}
const Opcode ASINH = {50, "asinh"}
const Opcode ASIN = {51, "asin"}
const Opcode ACOSH = {52, "acosh"}
const Opcode ACOS = {53, "acos"}
const Opcode SUM = {54, "sum"}
const Opcode TRUNC_DIV = {55, "div"}
const Opcode PRECISION = {56, "precision"}
const Opcode ROUND = {57, "round"}
const Opcode TRUNC = {58, "trunc"}
const Opcode COUNT = {59, "count"}
const Opcode NUMBEROF = {60, "numberof"}
const Opcode NUMBEROF_SYM = {61, "symbolic numberof"}
const Opcode ATLEAST = {62, "atleast"}
const Opcode ATMOST = {63, "atmost"}
const Opcode PLTERM = {64, "piecewise-linear term"}
const Opcode IFSYM = {65, "symbolic if"}
const Opcode EXACTLY = {66, "exactly"}
const Opcode NOT_ATLEAST = {67, "!atleast"}
const Opcode NOT_ATMOST = {68, "!atmost"}
const Opcode NOT_EXACTLY = {69, "!exactly"}
const Opcode FORALL = {70, "forall"}
const Opcode EXISTS = {71, "exists"}
const Opcode IMPLICATION = {72, "==>"}
const Opcode IFF = {73, "<==>"}
const Opcode ALLDIFF = {74, "alldiff"}
const Opcode NOT_ALLDIFF = {75, "!alldiff"}
const Opcode POW_CONST_EXP = {76, "^"}
const Opcode POW2 = {77, "^2"}
const Opcode POW_CONST_BASE = {78, "^"}
namespace mp::obj

Objective information.

Enums

enum Type

Objective type.

Values:

enumerator MIN

A minimization objective.

enumerator MAX

A maximization objective.

namespace mp::pre

Namespace mp::pre: value presolve methods.

They transform solutions, etc., between the original and presolved models

Typedefs

template<class MC>
using RangeLinCon2Slack = RangeCon2Slack<MC, LinConRange>

Typedef RangeLinCon2Slack.

template<class MC>
using RangeQuadCon2Slack = RangeCon2Slack<MC, QuadConRange>

Typedef RangeQuadCon2Slack.

template<class El>
using VMapOverElement = ValueMap<std::vector<El>>

ValueMap typedef template over the element type.

using ValueMapInt = VMapOverElement<int>

Specialize ValueMap storing int’s.

using ValueMapDbl = VMapOverElement<double>

Specialize ValueMap storing double’s.

using ValueMapStr = VMapOverElement<std::string>

Specialize ValueMap storing strings.

template<class El>
using MVOverEl = ModelValues<VMapOverElement<El>>

ModelValues typedef template over vectors of given element type.

using ModelValuesInt = MVOverEl<int>

Specialize ModelValues<> for concrete int data.

using ModelValuesDbl = MVOverEl<double>

Specialize ModelValues<> for concrete double data.

using ModelValuesStr = MVOverEl<std::string>

Specialize ModelValues<> for concrete string data.

using LinkIndexRange = IndexRange

Index range in a link.

using NodeIndexRange = IndexRange

Index range for a single node.

using BasicValuePresolverRef = BasicValuePresolver&

Typedef BasicValuePresolverRef.

using NodeMap = ValueMap<ValueNode, BasicValuePresolverRef>

Typedef map of nodes.

using ModelValuesTerminal = ModelValues<NodeMap>

Terminal nodes of a conversion graph.

using SolCheckerCall = bool(ArrayRef<double> x, const ValueMapDbl &y, ArrayRef<double> obj, void *p_extra)

How to call a solution checker.

using SolCheckerType = std::function<SolCheckerCall>

Function wrapper.

Functions

template<class Any>
void SetValueNodeName(Any&, std::string)

Default SetValueNodeName().

For std::vector<> it does nothing.

template<class Array, class Param>
Array CreateArray(Param)

Default CreateArray().

For std::vector<> it does not use the Param.

inline void SetValueNodeName(ValueNode &vn, std::string nm)

Specialize SetValueNodeName() for ValueNode.

template<>
inline ValueNode CreateArray(BasicValuePresolver &vp)

Specialize CreateArray() for ValueNode.

template<class Vec>
inline bool CopyRange(Vec &src, Vec &dest, NodeIndexRange ir, int i1)

Copy int or double range only.

Returns

always true currently

template<class T>
inline void Copy(NodeRange ir1, NodeRange ir2)

Copy range of node entries to another node.

namespace mp::sol

Enums

enum Status

Solution status.

For printing solve result codes with the -! command-line switch, every solution driver should register its solve_result codes via BasicSolver::AddSolveResults(). Only non-major codes should normally be registered (those with _LAST defined are pre-registered automatically.)

The meaning ideally should be the same for existing codes (use description from the comment.) For extra codes, use passing ranges (e.g., for stopping with a feasible solution on a limit, use 400-449), otherwise SPECIFIC+ codes.

Values:

enumerator NOT_SET

If not touched.

Don’t register this code.

enumerator UNKNOWN

Unknown status.

Don’t register this code.

enumerator SOLVED

Solved.

An optimal solution found for an optimization problem or a feasible solution found for a satisfaction problem. Codes 0-99.

enumerator SOLVED_LAST

End of the ‘solved’ range.

enumerator UNCERTAIN

Solved? Solution candidate returned but error likely.

Codes 100-199.

enumerator UNCERTAIN_LAST

End of the ‘uncertain’ range.

enumerator MP_SOLUTION_CHECK

MP Solution check failed.

Codes 150-159.

enumerator MP_SOLUTION_CHECK_LAST

End of the ‘mp-solution-check’ range.

enumerator INFEASIBLE

Problem is infeasible.

Codes 200-299.

enumerator INFEASIBLE_LAST

End of the ‘infeasible’ range.

enumerator INFEASIBLE_NO_IIS

Problem is infeasible, IIS computation not attempted.

enumerator INFEASIBLE_IIS

Problem is infeasible, IIS returned.

enumerator INFEASIBLE_IIS_FAILED

Problem is infeasible, IIS finder failed.

enumerator UNBOUNDED_FEAS

Problem is unbounded, feasible solution returned.

Codes 300-349.

enumerator UNBOUNDED_FEAS_LAST

End of the ‘unbounded-feas’ range.

enumerator UNBOUNDED

Deprecated.

enumerator UNBOUNDED_NO_FEAS

Problem is unbounded, no feasible solution returned.

Codes 350-399. For undecidedly inf/unb, use LIMIT_INF_UNB.

enumerator UNBOUNDED_NO_FEAS_LAST

End of the ‘unbounded-no-feas’ range.

enumerator LIMIT_FEAS

Limit.

Feasible solution, stopped by a limit, e.g., on iterations or Ctrl-C. Codes 400-449. For new custom codes, use LIMIT_FEAS_CUSTOM, LIMIT_NO_FEAS_CUSTOM.

enumerator LIMIT_FEAS_NEW

Start of custom LIMIT_FEAS codes.

enumerator LIMIT_FEAS_LAST

End of the ‘limit_feas’ range.

enumerator LIMIT

Deprecated.

enumerator LIMIT_FEAS_INTERRUPT

User interrupt, feasible solution.

enumerator LIMIT_FEAS_TIME

Time limit, feasible solution.

enumerator LIMIT_FEAS_ITER

Iteration limit, feasible solution.

enumerator LIMIT_FEAS_NODES

Node limit, feasible solution.

enumerator LIMIT_FEAS_BESTOBJ_BESTBND

Best obj/bound reached, feasible solution.

enumerator LIMIT_FEAS_GAP

Gap reached, feasible solution.

enumerator LIMIT_FEAS_BESTOBJ

Best obj reached, feasible solution.

enumerator LIMIT_FEAS_BESTBND

Best bound reached, feasible solution.

enumerator LIMIT_FEAS_NUMSOLS

Solution number bound reached.

enumerator LIMIT_FEAS_WORK

Work limit reached, feasible solution.

enumerator LIMIT_FEAS_SOFTMEM

Soft memory limit reached, feasible solution.

enumerator LIMIT_FEAS_FAILURE

Unrecoverable failure, feasible solution found.

enumerator LIMIT_INF_UNB

Limit.

Problem is infeasible or unbounded. Codes 450-469.

enumerator LIMIT_INF_UNB_LAST

End of the ‘limit inf/unb’ range.

enumerator INF_OR_UNB

Deprecated.

enumerator LIMIT_NO_FEAS

Limit.

No feasible solution returned. Codes 470-499.

enumerator LIMIT_NO_FEAS_NEW

Start of custom LIMIT_FEAS codes.

enumerator LIMIT_NO_FEAS_LAST

End of the ‘limit-no-feas’ range.

enumerator LIMIT_NO_FEAS_INTERRUPT

User interrupt, no feasible solution.

enumerator LIMIT_NO_FEAS_TIME

Time limit, no feasible solution.

enumerator LIMIT_NO_FEAS_ITER

Iteration limit, no feasible solution.

enumerator LIMIT_NO_FEAS_NODES

Node limit, no feasible solution.

enumerator LIMIT_NO_FEAS_CUTOFF

Objective cutoff, no feasible solution.

enumerator LIMIT_NO_FEAS_BESTBND

Best bound reached, no feasible solution.

enumerator LIMIT_NO_FEAS_WORK

Work limit reached, no feasible solution.

enumerator LIMIT_NO_FEAS_SOFTMEM

Soft memory limit reached, no feasible solution.

enumerator FAILURE

Failure, without a feasible solution.

Codes 500-999. With a feasible solution, use LIMIT_FEAS_FAILURE.

enumerator FAILURE_LAST

End of the ‘failure’ range.

enumerator NUMERIC

Failure.

A numeric issue without a feasible solution. With a feasible solution, use UNCERTAIN.

enumerator SPECIFIC

Specific.

Use for specific codes not fitting in above categories.

enumerator INTERRUPTED

Deprecated.

Use LIMIT_FEAS_INTERRUPT, LIMIT_NOFEAS_INTERRUPT instead.

namespace mp::suf

Suffix information.

Enums

enum Kind

Suffix kind.

Values:

enumerator VAR

Applies to variables.

enumerator CON

Applies to constraints.

enumerator OBJ

Applies to objectives.

enumerator PROBLEM

Applies to problems.

enumerator VAR_BIT
enumerator CON_BIT
enumerator OBJ_BIT
enumerator PROB_BIT
enum [anonymous]

Values:

enumerator FLOAT

Suffix values are floating-point numbers.

enumerator IODECL

Declare an INOUT suffix.

enumerator OUTPUT

Output suffix: return values from a solver.

enumerator INPUT

Input suffix: values were passed to a solver.

enumerator OUTONLY

Output only: reject as an input value.

Variables

constexpr int KIND_MASK = Kind::VAR | Kind::CON | Kind::OBJ | Kind::PROBLEM
namespace mp::var

Variable information.

Enums

enum Type

Variable type.

Values:

enumerator CONTINUOUS

A continuous variable.

enumerator INTEGER

An integer variable.

namespace NL_LIB_GFMT

Functions

void gfmt(char *b, size_t sz, double x, int prec)

Adjusts precision of floating point numbers.

If too slow, should be replaced by fmt::format or std::to_chars (C++ 17).

namespace nlwpy
namespace test
namespace __main__
namespace nlwpy::test::test_solve

Functions

def solve_and_check(solver, sopts, binary, stub)
def find_solver()
def test_binary_nl()
def test_text_nl()
namespace Params
namespace rst

Enums

enum BlockType

Values:

enumerator PARAGRAPH
enumerator LINE_BLOCK
enumerator BLOCK_QUOTE
enumerator BULLET_LIST
enumerator LIST_ITEM
enumerator LITERAL_BLOCK
namespace setup

Functions

def compile_args()
def ls_dir(base_dir)
def package_content()

Variables

string __version__ = "0.0.1b0"
namespace std

Functions

inline fmt::BufferedFile &move(fmt::BufferedFile &f)
inline fmt::File &move(fmt::File &f)
file ampls-c-api.h
#include <>
#include “mp/ampls-ccallbacks.h

Defines

AMPLS_C_EXPORT
DECLARE_SOLVER_API_FUNCTIONS(name)

Typedefs

typedef struct AMPLS_MP_Solver_T AMPLS_MP_Solver

An AMPLS solver instance.

typedef struct AMPLSCOption_T AMPLS_C_Option

Functions

AMPLS_C_EXPORT int AMPLSLoadNLModel (AMPLS_MP_Solver *slv, const char *nl_filename, char **options)

Load model incl.

suffixes. The method assumes that slv has been initialized by a solver-specific API using functions of ampls-cpp-api.h.

Returns

0 on success

AMPLS_C_EXPORT void AMPLSReadExtras (AMPLS_MP_Solver *slv)

Load suffixes and other option-dependent info.

AMPLS_C_EXPORT void AMPLSSolve (AMPLS_MP_Solver *slv)
AMPLS_C_EXPORT int AMPLSReportResults (AMPLS_MP_Solver *slv, const char *solFileName)

Report results.

The kind of results reported is influenced by solver option wantsol.

Returns

0 on success

AMPLS_C_EXPORT void AMPLSAddMessage (AMPLS_MP_Solver *slv, const char *msg)

Add message.

AMPLS_C_EXPORT const char *const  * AMPLSGetMessages (AMPLS_MP_Solver *slv)

Retrieve messages, 0-terminated array.

AMPLS_C_EXPORT AMPLS_C_Option * AMPLSGetOptions (AMPLS_MP_Solver *slv)
AMPLS_C_EXPORT int AMPLSSetIntOption (AMPLS_MP_Solver *, const char *name, int value)

Return 0 on success.

AMPLS_C_EXPORT int AMPLSGetIntOption (AMPLS_MP_Solver *, const char *name, int *value)
AMPLS_C_EXPORT int AMPLSSetDblOption (AMPLS_MP_Solver *slv, const char *name, double value)
AMPLS_C_EXPORT int AMPLSGetDblOption (AMPLS_MP_Solver *slv, const char *name, double *value)
AMPLS_C_EXPORT int AMPLSSetStrOption (AMPLS_MP_Solver *slv, const char *name, const char *value)
AMPLS_C_EXPORT int AMPLSGetStrOption (AMPLS_MP_Solver *slv, const char *name, const char **value)
file ampls-ccallbacks.h

Typedefs

typedef struct AMPLS_ModelTraits_T AMPLS_ModelTraits

Model traits for license check.

typedef void (*Checker_AMPLS_ModeltTraits)(const AMPLS_ModelTraits*)
typedef struct CCallbacks_T CCallbacks

Set of callbacks provided to a driver for licensing issues.

file ampls-cpp-api.h
#include <>
#include “mp/backend-base.h
#include “mp/ampls-c-api.h

Functions

AMPLS_MP_Solver *AMPLS__internal__Open(std::unique_ptr<mp::BasicBackend> p_be, CCallbacks cb)

AMPLS internal initialize.

To be used by Init<Gurobi>(AMPLS_MP_Solver*, char*) etc. This function is not for the user.

Parameters

p_be – GurobiBackend etc.

Returns

slv on success, otherwise NULL and use AMPLSGetMessages() (well they can contain warnings in any case).

void AMPLS__internal__Close(AMPLS_MP_Solver *slv)

Shut down solver instance.

Internal only. Deallocate the mp-related info and the structure itself. Before calling this function, a solver-specific implementation should delete solver_info_ and user_info_ if allocated.

mp::BasicBackend *AMPLSGetBackend(AMPLS_MP_Solver *slv)

Retrieve the Backend.

template<class Fn>
inline int AMPLS__internal__TryCatchWrapper(AMPLS_MP_Solver *slv, Fn fn)

Wrapper for try/catch.

Can be used from C++ functions returning int for C API.

Returns

0 if success

file arrayref.h
#include <>
#include <>
file backend-app.h
#include <>
#include <>
#include <>
#include “mp/solver-app-base.h
#include “mp/backend-base.h
#include “mp/common.h
#include “mp/error.h
file backend-base.h
#include <>
#include “mp/ampls-c-api.h
#include “mp/solver-base.h
file backend-mip.h
#include “mp/common.h
#include “mp/backend-std.h
file backend-std.h
#include <>
#include <>
#include <>
#include “mp/backend-with-mm.h

Defines

USING_STD_FEATURES

Issue this if you redefine std feature switches.

DEFAULT_STD_FEATURES_TO(val)

Default switch for unmentioned std features, can be used to override base class’ settings.

DEFINE_STD_FEATURE(name)

And default them.

ALLOW_STD_FEATURE(name, val)
IMPL_HAS_STD_FEATURE(name)
STD_FEATURE_QUERY_FN
STD_FEATURE_STRUCT_NM(name)
FEATURE_API_TO_IMPLEMENT(name, functionsignature)
DRIVER_DATE
file backend-to-model-api.h
#include <>
file backend-with-mm.h
#include <>
#include <>
#include “mp/backend-base.h
#include “mp/model-mgr-base.h
file backend-with-valcvt.h
#include “mp/valcvt-base.h
file basic-expr-visitor.h
#include “mp/common.h
#include “mp/error.h

Defines

MP_DEFINE_EXPR_TYPES(ExprTypes)
file common.h
#include <>
#include <>
#include “mp/error.h
#include “”

Defines

MP_CONST_DISPATCH(call)
MPCD(call)
MP_DISPATCH(call)
MPD(call)
MP_DISPATCH_STATIC(call)
MPDS(call)
file converter-base.h
#include “mp/env.h
#include “mp/ampls-ccallbacks.h
file easy-modeler.h
#include <>
#include “mp/expr.h

Defines

EXPORT_BINARY_OPERATOR(symbol, NAMEvv, NAMEvc, NAMEcv)

inject operator* etc directly into the out-of-class namespace

EXPORT_COMMUTATIVE_BINARY_OPERATOR(symbol, NAME)
file env.h
#include “mp/solver-base.h
file error.h
#include <>
#include “mp/format.h

Defines

MP_ASSERT(condition, message)

Debug assert.

MP_ASSERT_ALWAYS(condition, message)

Assert even for Release.

MP_UNSUPPORTED(name)

Use this to raise UnsupportedError.

MP_RAISE(msg)

Raise error.

MP_RAISE_WITH_CODE(exit_code, msg)

Raise with exit code.

MP_INFEAS(msg)

Raise infeasibility.

MP_UNUSED(x)

Silence unused parameter warnings.

file expr-visitor.h
#include “mp/basic-expr-visitor.h
#include “mp/expr.h
file expr.h
#include <>
#include <>
#include <>
#include “mp/common.h
#include “mp/error.h
#include “mp/format.h
#include “mp/safeint.h
#include “mp/utils-hash.h

Defines

MP_EXPR(ExprType)
file backend_flat.h
#include “mp/common.h
#include “mp/backend-with-valcvt.h
#include “mp/backend-mip.h
#include “mp/suffix.h
file constr_2_expr.h
#include <>
#include “mp/flat/constr_keeper.h
file constr_algebraic.h
#include <>
#include <>
#include <>
#include “mp/flat/constr_base.h
#include “mp/flat/expr_quadratic.h
file constr_base.h
#include <>
#include <>
#include <>
#include <>
#include <>
#include <>
#include <>
#include “mp/format.h
#include “mp/error.h
#include “mp/common.h
#include “mp/flat/context.h

Defines

DEF_CUSTOM_FUNC_CONSTR_WITH_PRM(Name, Args, Params, NumLogic, Descr)

Args is the argument type, e.g., array of variables, or an expression.

Params is the parameter type, e.g., array of numbers. Can be empty.

DEF_NUMERIC_FUNC_CONSTR(Name, Args, Descr)

Custom numeric constraint without fixed parameters.

DEF_LOGICAL_FUNC_CONSTR(Name, Args, Descr)

Custom logical constraint without fixed parameters.

DEF_NUMERIC_FUNC_CONSTR_WITH_PRM(Name, Args, Params, Descr)

Custom numeric constraint with parameter data.

DEF_LOGICAL_FUNC_CONSTR_WITH_PRM(Name, Args, Params, Descr)

Custom logical constraint with parameter data.

DEF_CONDITIONAL_CONSTRAINT_WRAPPER(Name, StaticConName)

A wrapper on a static constraint making it conditional.

DEF_STATIC_CONSTR(Name, Args, Descr)

STATIC CONSTRAINTS Workaround: defining as functional constraint (result unused) Could be solved by a mix-in parent.

DEF_STATIC_CONSTR_WITH_PRM(Name, Args, Params, Descr)
file constr_eval.h
#include <>
#include “constr_functional.h
#include “constr_general.h
file constr_functional.h
#include “mp/error.h
#include “mp/flat/constr_static.h
file constr_general.h
#include <>
#include <>
#include <>
#include “mp/error.h
file constr_hash.h
#include <>
#include <>
#include <>
#include “mp/utils-hash-stream.h
#include “mp/flat/constr_std.h
#include “mp/flat/expr_affine.h
file constr_keeper.h
#include <>
#include <>
#include <>
#include <>
#include “mp/common.h
#include “mp/format.h
#include “mp/env.h
#include “mp/utils-math.h
#include “mp/utils-file.h
#include “mp/util-json-write.hpp
#include “mp/flat/model_api_base.h
#include “mp/flat/constr_hash.h
#include “mp/valcvt-node.h
#include “mp/flat/constr_eval.h

Defines

USE_BASE_CONSTRAINT_CONVERTERS(BaseConverter)

Derived converter classes have to tell C++ to use default handlers if they need them when they overload Convert() etc, due to C++ name hiding.

USE_BASE_MAP_FINDERS(BaseConverter)

Similarly to Convert(), need to ‘using’ base class’ map accessors in the Converter.

GET_CONST_CONSTRAINT_KEEPER(Constraint)

Macros to define / access constraint keepers Assume ConstraintManager as public parent.

Use this to obtain a certain keeper, const

GET_CONSTRAINT_KEEPER(Constraint)

Use this to obtain a certain keeper.

GET_CONST_CONSTRAINT_MAP(Constraint)

Use this to obtain a certain map, const.

GET_CONSTRAINT_MAP(Constraint)

Use this to obtain a certain map.

STORE_CONSTRAINT_TYPE__INTERNAL(Constraint, optionNames)

Define a constraint keeper without a subexpression map.

Parameters
  • optionNames – name (or a few, space-separated) of the solver option(s) for acceptance of this constraint

STORE_CONSTRAINT_TYPE__NO_MAP(Constraint, optionNames)

Define a constraint keeper without a subexpression map.

Provide empty MapFind (returns -1) / MapInsert

STORE_CONSTRAINT_TYPE__WITH_MAP(Constraint, optionNames)

Define a constraint keeper with a subexpression map.

The Converter storing the Constraint should define MapFind / MapInsert accessing the GET_(CONST_)CONSTRAINT_MAP(Constraint)

CONSTRAINT_KEEPER_VAR(Constraint)

Internal use. Name of the constraint container.

STORE_CONSTRAINT_MAP(Constraint)

Create constraint map. Normally internal use.

CONSTRAINT_MAP_VAR(Constraint)

Internal use. Name of the constraint map.

file constr_prepro.h
#include <>
#include <>
#include “mp/flat/preprocess.h
#include “mp/flat/constr_std.h
file constr_prop_down.h
#include “mp/common.h
#include “mp/flat/constr_std.h
file constr_static.h
#include “mp/flat/constr_general.h
file constr_std.h
#include “mp/flat/constr_static.h
file context.h
file convert_functional.h
#include <>
#include <>
#include “mp/flat/preprocess.h
file converter.h
#include <>
#include <>
#include <>
#include <>
#include <>
#include “mp/env.h
#include “mp/format.h
#include “mp/solver-base.h
#include “mp/flat/constr_keeper.h
#include “mp/flat/constr_std.h
#include “mp/flat/expr_bounds.h
#include “mp/flat/constr_prepro.h
#include “mp/flat/constr_2_expr.h
#include “mp/flat/sol_check.h
#include “mp/valcvt.h
#include “mp/ampls-ccallbacks.h
file converter_model.h
#include <>
#include <>
#include <>
#include <>
#include <>
#include “mp/flat/obj_std.h
#include “mp/flat/constr_std.h
#include “mp/flat/constr_keeper.h
#include “mp/flat/model_info.h
file converter_model_base.h
#include <>
file eexpr.h
#include <>
#include “mp/flat/expr_quadratic.h
file model_api_base.h
#include “mp/flat/model_api_base.h

Defines

ACCEPT_EXPRESSION_INTERFACE(val)

A ModelAPI accepting NL trees should declare this.

  • NotAccepted: not compiled

  • AcceptedButNotRecommended: compiled but off by default (option acc:_expr)

  • Recommended: on by default

file model_api_base.h
#include <>
#include “mp/arrayref.h
#include “mp/common.h
#include “mp/flat/constr_base.h
#include “mp/flat/obj_std.h
#include “mp/flat/model_info.h

Defines

ACCEPT_CONSTRAINT(ConstrType, level, con_grp)

… then for a certain constraint it can be specified

ACCEPT_EXPRESSION(FlatExprType, level)

… and/or for expressions, e.g., AbsExpression:

USE_BASE_CONSTRAINT_HANDLERS(BaseBackend)

Derived backends have to tell C++ to use default handlers if they are needed when they overload AddConstraint(), due to C++ name hiding.

file expr_affine.h
#include <>
#include <>
#include <>
#include <>
#include <>
#include <>
#include <>
#include “mp/arrayref.h
#include “mp/flat/expr_algebraic.h
file expr_algebraic.h
#include <>
#include <>
#include “mp/util-json-write.hpp
#include “mp/arrayref.h
file expr_bounds.h
#include “mp/flat/preprocess.h
#include “mp/flat/expr_quadratic.h
file expr_quadratic.h
#include <>
#include “mp/flat/expr_affine.h
file model_api_connect.h
#include <>
#include “mp/env.h
#include “mp/flat/converter.h
file model_info.h
#include <>
#include <>
file model_info.hpp
#include <>
#include <>
#include “mp/flat/model_info.h
file obj_std.h
#include <>
#include <>
#include “mp/common.h
#include “mp/flat/expr_quadratic.h
#include “mp/flat/constr_eval.h
file preprocess.h
#include <>
#include <>
#include “mp/common.h
file problem_flattener.h
#include <>
#include <>
#include <>
#include <>
#include “mp/problem.h
#include “mp/converter-base.h
#include “mp/expr-visitor.h
#include “mp/flat/eexpr.h
#include “mp/flat/constr_std.h
#include “mp/flat/obj_std.h
#include “mp/valcvt.h
file cones.h
#include <>
#include <>
#include <>
#include “mp/flat/constr_keeper.h
#include “mp/valcvt-link.h
file qcones2qc.h
#include “mp/flat/constr_std.h
file encodings.h
#include <>
#include <>
file abs.h
#include “mp/common.h
#include “mp/flat/constr_std.h
file alldiff.h
#include “mp/flat/constr_std.h
file complement.h
#include <>
#include “mp/flat/constr_std.h
file cond_eq.h
#include “mp/common.h
#include “mp/flat/constr_std.h
file cond_ineq.h
#include “mp/flat/constr_std.h
file converter_mip.h
#include <>
#include “mp/flat/converter.h
file lin_approx_core.h
#include “mp/flat/constr_std.h
file count.h
#include “mp/flat/constr_std.h
file div.h
#include “mp/flat/constr_std.h
file ifthenelse.h
#include “mp/flat/constr_std.h
file impl.h
#include “mp/flat/constr_std.h
file indicator_eq.h
file indicator_ge.h
#include “mp/flat/constr_std.h
file indicator_le.h
#include “mp/flat/constr_std.h
file indicator_quad.h
#include “mp/flat/constr_std.h
file lin_approx.h
#include “mp/common.h
#include “mp/flat/constr_std.h
file logical_and.h
#include “mp/flat/constr_std.h
file logical_not.h
#include “mp/flat/constr_std.h
file logical_or.h
#include “mp/flat/constr_std.h
file min_max.h
#include “mp/flat/constr_std.h
file mul.h
#include “mp/error.h
#include “mp/flat/constr_std.h
file numberof_const.h
#include “mp/flat/constr_std.h
file numberof_var.h
#include “mp/flat/constr_std.h
file piecewise_linear.h
#include <>
#include <>
#include “mp/flat/constr_std.h
file power_const.h
#include <>
#include <>
file redefs_mip_std.h
#include “mp/flat/redef/MIP/abs.h
#include “mp/flat/redef/MIP/div.h
#include “mp/flat/redef/MIP/impl.h
#include “mp/flat/redef/MIP/mul.h
#include “mp/flat/redef/MIP/sos2.h
file sos2.h
#include <>
#include “mp/flat/constr_std.h
#include “mp/common.h
file redef_base.h
#include “mp/format.h

Defines

GET_CONSTRAINT_VALUE_NODE(con_type)

To be used by descendants of BasicConverter.

INSTALL_ITEM_CONVERTER(item_cvt_type)

In the ModelConverter: to use a specific item_cvt_type<> Assumes Impl is the final ModelConverter type.

file range_con.h
#include “mp/valcvt-link.h
#include “mp/flat/constr_std.h
#include “mp/common.h
file sol_check.h
#include <>
#include <>
#include “mp/flat/constr_std.h
#include “mp/flat/constr_keeper.h
#include “mp/common.h
#include “mp/valcvt.h
file format.h
#include <>
#include <>
#include <>
#include <>
#include <>
#include <>
#include <>
#include <>
#include <>
#include <>
#include <>
#include <>

Defines

FMT_SECURE_SCL
FMT_MSC_VER
FMT_API
FMT_GCC_EXTENSION
FMT_HAS_FEATURE(x)
FMT_HAS_BUILTIN(x)
FMT_HAS_CPP_ATTRIBUTE(x)
FMT_USE_VARIADIC_TEMPLATES
FMT_USE_RVALUE_REFERENCES
FMT_EXCEPTIONS
FMT_THROW(x)
FMT_USE_NOEXCEPT
FMT_NOEXCEPT
FMT_OVERRIDE
FMT_USE_DELETED_FUNCTIONS
FMT_DELETED_OR_UNDEFINED
FMT_DISALLOW_COPY_AND_ASSIGN(TypeName)
FMT_USE_USER_DEFINED_LITERALS
FMT_ASSERT(condition, message)
FMT_SPECIALIZE_MAKE_UNSIGNED(T, U)
FMT_USE_EXTERN_TEMPLATES
FMT_USE_WINDOWS_H
FMT_DISABLE_CONVERSION_TO_INT(Type)
FMT_MAKE_VALUE_(Type, field, TYPE, rhs)
FMT_MAKE_VALUE(Type, field, TYPE)
FMT_MAKE_STR_VALUE(Type, TYPE)
FMT_MAKE_WSTR_VALUE(Type, TYPE)
FMT_DISPATCH(call)
FMT_DEFINE_INT_FORMATTERS(TYPE)
FMT_GEN(n, f)
FMT_GEN1(f)
FMT_GEN2(f)
FMT_GEN3(f)
FMT_GEN4(f)
FMT_GEN5(f)
FMT_GEN6(f)
FMT_GEN7(f)
FMT_GEN8(f)
FMT_GEN9(f)
FMT_GEN10(f)
FMT_GEN11(f)
FMT_GEN12(f)
FMT_GEN13(f)
FMT_GEN14(f)
FMT_GEN15(f)
FMT_ARG_TYPE_DEFAULT(n)
FMT_MAKE_TEMPLATE_ARG(n)
FMT_MAKE_ARG_TYPE(n)
FMT_MAKE_ARG(n)
FMT_ASSIGN_char(n)
FMT_ASSIGN_wchar_t(n)
FMT_MAKE_REF(n)
FMT_MAKE_REF2(n)
FMT_WRAP1(func, arg_type, n)
FMT_VARIADIC_VOID(func, arg_type)
FMT_CTOR(ctor, func, arg0_type, arg1_type, n)
FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type)
FMT_FOR_EACH1(f, x0)
FMT_FOR_EACH2(f, x0, x1)
FMT_FOR_EACH3(f, x0, x1, x2)
FMT_FOR_EACH4(f, x0, x1, x2, x3)
FMT_FOR_EACH5(f, x0, x1, x2, x3, x4)
FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5)
FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6)
FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7)
FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8)
FMT_FOR_EACH10(f, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9)
FMT_EXPAND(args)
FMT_NARG(...)
FMT_NARG_(...)
FMT_ARG_N(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...)
FMT_RSEQ_N()
FMT_CONCAT(a, b)
FMT_FOR_EACH_(N, f, ...)
FMT_FOR_EACH(f, ...)
FMT_ADD_ARG_NAME(type, index)
FMT_GET_ARG_NAME(type, index)
FMT_WRAP(Char, ReturnType, func, call, n, ...)
FMT_VARIADIC_(Char, ReturnType, func, call, ...)
FMT_VARIADIC(ReturnType, func, ...)

Defines a variadic function with the specified return type, function name and argument types passed as variable arguments to this macro.

Example:

void print_error(const char *file, int line, const char *format,
                 fmt::ArgList args) {
  fmt::print("{}: {}: ", file, line);
  fmt::print(format, args);
}
FMT_VARIADIC(void, print_error, const char *, int, const char *)

FMT_VARIADIC is used for compatibility with legacy C++ compilers that don’t implement variadic templates. You don’t have to use this macro if you don’t need legacy compiler support and can use variadic templates directly:

template <typename... Args>
void print_error(const char *file, int line, const char *format,
                 const Args & ... args) {
  fmt::print("{}: {}: ", file, line);
  fmt::print(format, args...);
}

FMT_VARIADIC_W(ReturnType, func, ...)
FMT_CAPTURE_ARG_(id, index)
FMT_CAPTURE_ARG_W_(id, index)
FMT_CAPTURE(...)

Convenient macro to capture the arguments’ names and values into several fmt::arg(name, value).

Example:

int x = 1, y = 2;
print("point: ({x}, {y})", FMT_CAPTURE(x, y));
// same as:
// print("point: ({x}, {y})", arg("x", x), arg("y", y));

FMT_CAPTURE_W(...)
FMT_FUNC
file model-mgr-base.h
#include <>
#include “mp/ampls-ccallbacks.h
#include “mp/arrayref.h
#include “mp/solver-base.h
#include “mp/suffix.h
file model-mgr-with-pb.h
#include <>
#include <>
#include “mp/env.h
#include “mp/utils-clock.h
#include “mp/model-mgr-base.h
#include “mp/solver-io.h
file model-mgr-with-std-pb.h
#include <>
#include “mp/model-mgr-base.h
#include “mp/problem.h
#include “mp/converter-base.h
file model-mgr-with-std-pb.hpp
#include “mp/model-mgr-with-pb.h
file nl-header-c.h
#include <>

Typedefs

typedef struct NLProblemInfo_C NLProblemInfo_C

Information about an optimization problem.

Full documentation on the NL format: technical report “Writing .nl Files” (https://ampl.github.io/nlwrite.pdf.)

typedef enum NLArithKind NLArithKind

Floating-point arithmetic kind.

typedef int NLFormat

Input/output format.

typedef struct NLInfo_C NLInfo_C

NL technical info.

typedef struct NLHeader_C NLHeader_C

An NL header which contains information about problem dimensions, such as the number of variables and constraints, and the input format.

Enums

enum [anonymous]

Values:

enumerator MAX_AMPL_OPTIONS

Maximum number of options reserved for AMPL use in NL and SOL formats.

enum [anonymous]

Values:

enumerator VBTOL_OPTION_INDEX
enumerator USE_VBTOL_FLAG
enum NLArithKind

Floating-point arithmetic kind.

Values:

enumerator NL_ARITH_UNKNOWN

Unknown floating-point arithmetic.

enumerator NL_ARITH_IEEE_LITTLE_ENDIAN

Standard IEEE-754 floating point - little endian.

enumerator NL_ARITH_IEEE_BIG_ENDIAN

Standard IEEE-754 floating point - big endian.

enumerator NL_ARITH_IBM

IBM floating point.

enumerator NL_ARITH_VAX

VAX floating point (legacy).

enumerator NL_ARITH_CRAY

Cray floating point.

enumerator NL_ARITH_LAST

Last floating point.

enumerator NL_ARITH_UNKNOWN

Unknown floating-point arithmetic.

enumerator NL_ARITH_IEEE_LITTLE_ENDIAN

Standard IEEE-754 floating point - little endian.

enumerator NL_ARITH_IEEE_BIG_ENDIAN

Standard IEEE-754 floating point - big endian.

enumerator NL_ARITH_IBM

IBM floating point.

enumerator NL_ARITH_VAX

VAX floating point (legacy).

enumerator NL_ARITH_CRAY

Cray floating point.

enumerator NL_ARITH_LAST

Last floating point.

enum [anonymous]

Values:

enumerator NL_FORMAT_TEXT

Text format.

The text format is fully portable meaning that an .nl file can be written on a machine of one architecture and then read on a machine of a different architecture.

enumerator NL_FORMAT_BINARY

Binary format.

The binary format is not generally portable and should normally be used on a single machine.

enum [anonymous]

NL Flags.

Values:

enumerator WANT_OUTPUT_SUFFIXES

Flag that specifies whether to write output suffixes to a .sol file.

Functions

NLHeader_C MakeNLHeader_C_Default(void)

Default NLHeader_C.

file nl-header-c.h
#include <>

Typedefs

typedef struct NLProblemInfo_C NLProblemInfo_C

Information about an optimization problem.

Full documentation on the NL format: technical report “Writing .nl Files” (https://ampl.github.io/nlwrite.pdf.)

typedef enum NLArithKind NLArithKind

Floating-point arithmetic kind.

typedef int NLFormat

Input/output format.

typedef struct NLInfo_C NLInfo_C

NL technical info.

typedef struct NLHeader_C NLHeader_C

An NL header which contains information about problem dimensions, such as the number of variables and constraints, and the input format.

Enums

enum [anonymous]

Values:

enumerator MAX_AMPL_OPTIONS

Maximum number of options reserved for AMPL use in NL and SOL formats.

enum [anonymous]

Values:

enumerator VBTOL_OPTION_INDEX
enumerator USE_VBTOL_FLAG
enum NLArithKind

Floating-point arithmetic kind.

Values:

enumerator NL_ARITH_UNKNOWN

Unknown floating-point arithmetic.

enumerator NL_ARITH_IEEE_LITTLE_ENDIAN

Standard IEEE-754 floating point - little endian.

enumerator NL_ARITH_IEEE_BIG_ENDIAN

Standard IEEE-754 floating point - big endian.

enumerator NL_ARITH_IBM

IBM floating point.

enumerator NL_ARITH_VAX

VAX floating point (legacy).

enumerator NL_ARITH_CRAY

Cray floating point.

enumerator NL_ARITH_LAST

Last floating point.

enumerator NL_ARITH_UNKNOWN

Unknown floating-point arithmetic.

enumerator NL_ARITH_IEEE_LITTLE_ENDIAN

Standard IEEE-754 floating point - little endian.

enumerator NL_ARITH_IEEE_BIG_ENDIAN

Standard IEEE-754 floating point - big endian.

enumerator NL_ARITH_IBM

IBM floating point.

enumerator NL_ARITH_VAX

VAX floating point (legacy).

enumerator NL_ARITH_CRAY

Cray floating point.

enumerator NL_ARITH_LAST

Last floating point.

enum [anonymous]

Values:

enumerator NL_FORMAT_TEXT

Text format.

The text format is fully portable meaning that an .nl file can be written on a machine of one architecture and then read on a machine of a different architecture.

enumerator NL_FORMAT_BINARY

Binary format.

The binary format is not generally portable and should normally be used on a single machine.

enum [anonymous]

NL Flags.

Values:

enumerator WANT_OUTPUT_SUFFIXES

Flag that specifies whether to write output suffixes to a .sol file.

Functions

NLHeader_C MakeNLHeader_C_Default(void)

Default NLHeader_C.

file nl-header.h
#include <>
#include <>
#include <>
#include <>
#include <>
#include “”
file nl-header.h
#include <>
#include <>
#include <>
#include <>
#include <>
#include “”
file nl-reader.h
#include “mp/common.h
#include “mp/error.h
#include “mp/nl.h
#include “mp/os.h
#include <>
#include <>
#include <>
#include <>
#include <>
file nl.h
#include “mp/error.h
#include “mp/format.h
#include <>
#include <>
file option.h
#include <>
#include “mp/error.h
file os.h
#include “mp/error.h
#include “mp/posix.h
file posix.h
#include <>
#include <>
#include <>
#include <>
#include <>
#include <>
#include “format.h

Defines

FMT_POSIX(call)
FMT_SYSTEM(call)
FMT_POSIX_CALL(call)
FMT_UNUSED
FMT_USE_STATIC_ASSERT
FMT_CONCAT_(a, b)
FMT_STATIC_ASSERT(cond, message)
FMT_RETRY_VAL(result, expression, error_result)
FMT_RETRY(result, expression)
_O_BINARY

Possible values for the oflag argument to the constructor.

O_BINARY
file problem-builder.h
#include <>
#include <>
#include <>
#include <>
#include <>
#include “mp/common.h
#include “mp/error.h
#include “mp/nl-reader.h
#include “mp/problem.h
file problem.h
#include <>
#include <>
#include <>
#include <>
#include “mp/expr.h
#include “mp/suffix.h

Defines

MP_MAX_PROBLEM_ITEMS

Maximum index of a variable, objective or constraint.

file rstparser.h
#include <>
#include <>
#include <>
file safeint.h
#include <>
#include <>
#include “mp/format.h
file sol.h
#include <>
#include <>
#include <>
#include “mp/common.h
#include “mp/posix.h
file solver-app-base.h
#include <>
#include <>
#include “mp/option.h
#include “mp/solver-base.h
file solver-app.h
#include “mp/solver-app-base.h
#include “mp/solver-io.h
#include “mp/utils-clock.h
#include “mp/ampls-ccallbacks.h
file solver-base.h
#include <>
#include <>
#include “solver-opt.h
#include “common.h
#include “mp/utils-clock.h
file solver-io.h
#include <>
#include “mp/arrayref.h
#include “mp/solver-base.h
#include “mp/nl-reader.h
#include “mp/sol.h
file solver-opt.h
#include <>
#include <>
#include <>
#include <>
#include “mp/error.h
#include “mp/format.h
file solver.h
#include <>
#include <>
#include <>
#include “mp/problem-builder.h
#include “mp/solver-base.h
#include “mp/solver-io.h
#include “mp/solver-app.h
#include “mp/suffix.h
file suffix.h
#include <>
#include <>
#include <>
#include <>
#include <>
#include <>
#include “mp/common.h
#include “mp/error.h
#include “mp/format.h
#include “mp/arrayref.h
file util-json-write.h
#include <>
#include <>
#include <>
#include <>
file util-json-write.hpp
#include <>
#include “mp/format.h
#include “mp/util-json-write.h
file utils-clock.h
#include <>
#include <>
file utils-file.h
#include <>
#include <>
#include “mp/utils-string.h
file utils-hash-stream.h
#include “mp/utils-hash.h
file utils-hash.h
#include <>
file utils-math.h
#include <>
file utils-string.h
#include <>
#include <>
file utils-vec.h
file valcvt-base.h
#include <>
#include <>
#include <>
#include <>
#include “mp/arrayref.h
#include “mp/env.h

Defines

LIST_PRESOLVE_METHODS

Macro for a list of pre- / postsolve method definitions in a ValuePresolver or a link.

Requires PRESOLVE_KIND defined to declare / define corr. pre- and postsolve methods. Generic(Dbl/Int): maximizes suffix value among non-0. Example 1 (presolve): expression exp(y) is used in various places and marked with different values of .funcpieces. The largest is chosen. Example 2 (postsolve): IIS membership value for a converted high-level constraint can be reported as the maximum of those for its low-level representation.

PRESOLVE_KIND(name, ValType)

Pre- / postsolve method declarations.

file valcvt-link.h
#include <>
#include <>
#include <>
#include <>
#include <mp/arrayref.h>
#include “mp/common.h
#include “valcvt-node.h

Defines

PRESOLVE_KIND(name, ValType)

The below pre- / postsolve methods work on a range of link entries.

Pre- / postsolve loops over link entries and calls the derived class’ method for each.

All pre- / postsolves just take max from non-0.

Copy everything, MaxAmongNon0 should not apply.

Postsolves should usually loop the range backwards

PRESOLVE_KIND(name, ValType)

The below pre- / postsolve methods work on a range of link entries.

Pre- / postsolve loops over link entries and calls the derived class’ method for each.

All pre- / postsolves just take max from non-0.

Copy everything, MaxAmongNon0 should not apply.

Postsolves should usually loop the range backwards

PRESOLVE_KIND(name, ValType)

The below pre- / postsolve methods work on a range of link entries.

Pre- / postsolve loops over link entries and calls the derived class’ method for each.

All pre- / postsolves just take max from non-0.

Copy everything, MaxAmongNon0 should not apply.

Postsolves should usually loop the range backwards

PRESOLVE_KIND(name, ValType)

The below pre- / postsolve methods work on a range of link entries.

Pre- / postsolve loops over link entries and calls the derived class’ method for each.

All pre- / postsolves just take max from non-0.

Copy everything, MaxAmongNon0 should not apply.

Postsolves should usually loop the range backwards

file valcvt-node.h
#include <>
#include “valcvt-base.h
file valcvt.h
#include <>
#include <>
#include <>
#include “mp/utils-string.h
#include “mp/util-json-write.hpp
#include “valcvt-node.h
#include “valcvt-link.h

Defines

PRESOLVE_KIND(name, ValType)

Pre- / postsolve loops over link entries and calls the link’s method for each.

file nlsol_ex_easy_api_c.c
#include <>
#include <>
#include <>
#include <>
#include “api/c/nl-solver-c.h

Typedefs

typedef struct NLW2_SolCheckData_C NLW2_SolCheckData_C

C “easy API” example using NLW2_NLModel_C to write NL file, execute solver, and read SOL file for a MILP model.

For full API, see documentation of NLW2 and related tests/examples. Solution checking data

Functions

NLW2_NLModel_C BuildModel(NLW2_SolCheckData_C *p_solchkdata)

Build model.

static int ApproxEqual(double n, double m)

Approx equal?

int NLW2_CheckSolution_C(NLW2_NLSolution_C *p_sol, NLW2_SolCheckData_C *p_sol_ref)

Check solution.

int SolveAndCheck(const char *solver, const char *sopts, int binary, const char *stub)

Solver with given parameters.

int main(int argc, const char *const *argv)

main()

file nlsol_ex_c.c
#include <>
#include <>
#include <>
#include “nlsol_ex_c_model.h
#include “nlsol_ex_c_nl.h
#include “nlsol_ex_c_sol.h
#include “nlsol_ex_c_nlutils.h
#include “api/c/nl-solver-c.h

Functions

int main(int argc, const char *const *argv)

C API example using NLWriter2 and SOLReader2 to write NL file, execute solver, and read SOL file.

main()

file nlsol_ex_c_model.c
#include <>
#include <>
#include <>
#include <>
#include “nlsol_ex_c_model.h

Functions

CAPIExample MakeCAPIExample_Linear_01(void)

Create linear example data.

void DestroyCAPIExample_Linear_01(CAPIExample *pEx)

Destroy linear example data.

void PrintSolution_C(CAPIExample *pex, const char *stub)

Print solution.

file nlsol_ex_c_model.h

Typedefs

typedef struct SparseEntry SparseEntry

Typedef SparseEntry.

typedef struct Suffix Suffix

Suffix.

typedef struct CAPIExample CAPIExample

C API example data.

Functions

CAPIExample MakeCAPIExample_Linear_01(void)

Create linear example data.

void DestroyCAPIExample_Linear_01(CAPIExample*)

Destroy linear example data.

void PrintSolution_C(CAPIExample *pex, const char *stub)

Print solution.

file nlsol_ex_c_nl.c
#include <>
#include <>
#include “nlsol_ex_c_nl.h

Functions

NLHeader_C CAPI_ex_Header(void *pex_void)

Declare, implementation in nlsol_ex_c_nl.c.

const char *ObjDescription(void *p_user_data, int i)
int ObjType(void *p_user_data, int i)
int ObjGradientNNZ(void *p_user_data, int i)
void FeedObjGradient(void *p_user_data, int i, void *p_api_data)
void FeedVarBounds(void *p_user_data, void *p_api_data)
void FeedConBounds(void *p_user_data, void *p_api_data)
const char *ConDescription(void *p_user_data, int i)
int LinearConExprNNZ(void *p_user_data, int i)
void FeedLinearConExpr(void *p_user_data, int i, void *p_api_data)
void FeedColumnSizes(void *p_user_data, void *p_api_data)

The below feature is for AMPL’s internal linearization of piecewise-linear functions.

For user-definable SOS constraints, use suffixes .sosno/.ref.

The below is a feeder interface for .sos/.sosref suffixes. The feeder can provide 3 sparse vectors:

  • .sos for variables: Each nonzero value defines SOS group number. Negative means SOS Type 2, positive - SOS Type 1.

  • .sos for constraints: Each nonzero value denotes a constraint used in a linearization of an SOS. The constraint can be deleted by the solver driver if using solver’s SOS.

  • .sosref for variables: SOS weights. Variables participating in an SOS having zero weights are involved in linearization and can be deleted if the solver accepts SOS natively.

Implementation: auto sosv = plsos.StartSOSVars(nvsos); for (int i=0; i<nvsos; ++i) sosv.Write(i, vsos[i]); if (ncsos) { auto sosc = plsos.StartSOSCons(ncsos); for …. } auto sosrefv = plsos.StartSOSREFVars(ac->nsosref); …. Function definition. Provide definition of function i, i=0..num_funcs-1.

  1. RANDOM VARIABLES ///////////////////// Random variables. Undocumented feature. SNL2006. Example: var z >= 0; let z.stage := 1; var x{0..1, 0..1} random := Uniform(0,2); for {i in 0..1, j in 0..1} {let x[i,j].stage := 1;}; display z.stage, x.stage; c: z * sum{i in 0..1, j in 0..1} x[i,j] <= 3 + Sample(Uniform(0,2));

Feed random variables. Indexes: num_vars+num_common_exprs .. num_vars+num_common_exprs+num_rand_vars-1.

Implementation skeleton: for(j = num_vars+num_common_exprs; j < num_vars+num_common_exprs+num_rand_vars; j++) { auto ew = rvw.StartRandVar(j, rand_var_comment(j)); ew.EPut(rand_var_root_expr(j)); }

int CountNNZ(const double *parray, int len)
void WriteDenseAsSparse(const double *parray, int len, void *p_api_data)
int InitialGuessesNNZ(void *p_user_data)

Implementation: for (size_t i=0; i<n_ini_guess; ++i) NLW2_WriteSparseDblEntry(p_api_data, i, ini_guess[i]);.

void FeedInitialGuesses(void *p_user_data, void *p_api_data)
int InitialDualGuessesNNZ(void *p_user_data)

Initial dual guesses.

void FeedInitialDualGuesses(void *p_user_data, void *p_api_data)
void FeedSuffixes(void *p_user_data, void *p_api_data)

Feed suffixes.

For constraints, assume ordering: first algebraic, then logical.

Implementation: while (….) { void* p_api_2 = NLW2_StartIntSuffix( // or …DblSuffix p_api_data, suf_name, kind, n_nonzeros); for (int i=0; i<n_nonzeros; ++i) NLW2_WriteSparseIntEntry(p_api_2, // <- new API pointer index[i], value[i]); // or …DblEntry }

void FeedRowAndObjNames(void *p_user_data, void *p_api_data)
void FeedColNames(void *p_user_data, void *p_api_data)

Provide deleted row names.

Provide variable names.

NLW2_NLFeeder_C MakeNLFeeder_C(CAPIExample *pex, int binary)

Provide unused variable names.

Custom NLFeeder_C for the C API example.

Provide {fixed variable, extra info} pairs. This includes defined eliminated variables.

Implementation: if ((output_desired) && wrt) for (….) wrt << typename Writer::StrStrValue { name[i].c_str(), comment[i].c_str() }; Provide {obj name, constant term} pairs.

Implementation: if (wrt) for (….) wrt << typename Writer::StrDblValue { name[i].c_str(), (double)obj_offset[i] };

void DestroyNLFeeder_C(NLW2_NLFeeder_C *pf)

Destroy custom NLFeeder_C.

file nlsol_ex_c_nl.h
#include “api/c/nl-feeder-c.h
#include “nlsol_ex_c_model.h

Functions

NLW2_NLFeeder_C MakeNLFeeder_C(CAPIExample*, int binary)

Custom NLFeeder_C for the C API example.

Fill an NLFeeder_C for the C API example

Custom NLFeeder_C for the C API example.

Provide {fixed variable, extra info} pairs. This includes defined eliminated variables.

Implementation: if ((output_desired) && wrt) for (….) wrt << typename Writer::StrStrValue { name[i].c_str(), comment[i].c_str() }; Provide {obj name, constant term} pairs.

Implementation: if (wrt) for (….) wrt << typename Writer::StrDblValue { name[i].c_str(), (double)obj_offset[i] };

void DestroyNLFeeder_C(NLW2_NLFeeder_C*)

Destroy custom NLFeeder_C.

file nlsol_ex_c_nlutils.c
#include “nlsol_ex_c_nlutils.h

Functions

NLW2_NLUtils_C MakeNLUtils_C(void)

Custom NLUtils_C for the C API example.

Fill NLUtils_C for the C API example

void DestroyNLUtils_C(NLW2_NLUtils_C *p)

Destroy custom NLUtils_C.

file nlsol_ex_c_nlutils.h

Functions

NLW2_NLUtils_C MakeNLUtils_C(void)

Custom NLUtils_C for the C API example.

Fill NLUtils_C for the C API example

void DestroyNLUtils_C(NLW2_NLUtils_C*)

Destroy custom NLUtils_C.

file nlsol_ex_c_sol.c
#include <>
#include <>
#include <>
#include “nlsol_ex_c_sol.h

Functions

NLHeader_C CAPI_ex_Header(void *pex_void)

Declare, implementation in nlsol_ex_c_nl.c.

void OnDualSolution(void *p_user_data, int nvals, void *p_api_data)
void OnPrimalSolution(void *p_user_data, int nvals, void *p_api_data)
void OnObjno(void *p_user_data, int on)
void OnSolveCode(void *p_user_data, int sc)
void OnIntSuffix(void *p_user_data, NLW2_SuffixInfo_C si, void *p_api_data)
void OnDblSuffix(void *p_user_data, NLW2_SuffixInfo_C si, void *p_api_data)
NLW2_SOLHandler_C MakeSOLHandler_C(CAPIExample *pex)

Custom SOLHandler_C for the C API example.

Fill a SOLHandler_C for the C API example

void DestroySOLHandler_C(NLW2_SOLHandler_C *p)

Destroy custom SOLHandler_C.

file nlsol_ex_c_sol.h
#include “api/c/sol-handler-c.h
#include “nlsol_ex_c_model.h

Functions

NLW2_SOLHandler_C MakeSOLHandler_C(CAPIExample*)

Custom SOLHandler_C for the C API example.

Fill a SOLHandler_C for the C API example

void DestroySOLHandler_C(NLW2_SOLHandler_C*)

Destroy custom SOLHandler_C.

file nlsol_ex_easy_api.cc
#include <>
#include <>
#include <>
#include “mp/nl-solver.h

Functions

bool SolveAndCheck(std::string solver, std::string sopts, bool binary, std::string stub)

Solve with given parameters.

int main(int argc, const char *const *argv)

Invoke: (this_exe) ipopt [“outlev=1 timelim=500” [text [filestub]]].

file nlsol_ex.cc
#include <>
#include <>
#include “nlsol_ex_mdl.h
#include “nlsol_ex_nl.h
#include “nlsol_ex_sol.h
#include “mp/nl-solver.hpp

Functions

int main(int argc, const char *const *argv)

Invoke: (this_exe) ipopt [“outlev=1 timelim=500” [text [filestub]]].

file nlsol_ex_mdl.h
#include <>
#include <>
#include <>
#include <>
#include <>
#include “”
#include “mp/nl-opcodes.h
file nlsol_ex_nl.h
#include “mp/nl-feeder.h
#include “nlsol_ex_mdl.h
file nlsol_ex_sol.h
#include <>
#include <>
#include “mp/sol-handler.h
#include “nlsol_ex_mdl.h
file nl-feeder-c-impl.h
#include <>
#include “api/c/nl-feeder-c.h
#include “mp/nl-feeder.h
file nl-feeder-c.h
#include “”

Typedefs

typedef struct NLW2_AlgConRange_C NLW2_AlgConRange_C

  • Algebraic constraint bounds (for a single constraint):

  • either range (lb, ub),

  • or complementarity info (k, cvar), when k>0.

  • For a complementarity constraint to hold, if cvar is at

  • its lower bound, then body >= 0; if cvar is at its upper

  • bound, then body <= 0;

  • and if cvar is strictly between its bounds, then body = 0.

  • The integer k in a complementarity constraint line indicates

  • which bounds on cvar are finite: 1 and 3 imply a finite

  • lower bound; 2 and 3 imply a finite upper bound; 0 (which

  • should not occur) would imply no finite bounds, i.e.,

  • body = 0 must always hold.

  • Example:

  • 
    
  • ampl: var x; var y; var z;

  • ampl: s.t. Compl1: x+y >= 3 complements x-z <= 15;

  • ampl: s.t. Compl2: -2 <= 2*y+3*z <= 13 complements 6*z-2*x;

  • ampl: expand;

  • subject to Compl1:

  • 3 <= x + y

  • complements

  • x - z <= 15;

  • subject to Compl2:

  • -2 <= 2*y + 3*z <= 13

  • complements

  • -2*x + 6*z;

  • ampl: solexpand;

  • Nonsquare complementarity system:

  • 4 complementarities including 2 equations

  • 5 variables

  • subject to Compl1.L:

  • x + y + Compl1$cvar = 0;

  • subject to Compl1.R:

  • -15 + x - z <= 0

  • complements

  • Compl1$cvar <= -3;

  • subject to Compl2.L:

  • 2*y + 3*z - Compl2$cvar = 0;

  • subject to Compl2.R:

  • -2*x + 6*z

  • complements

  • -2 <= Compl2$cvar <= 13;

typedef struct NLW2_NLFeeder_C NLW2_NLFeeder_C

Wrap mp::NLFeeder for C API.

NLW2_NLFeeder_C: writes model details on request via provided callback objects. See the examples folder.

To fill some default values and methods, e.g., options and some methods like name feeders, call NLW2_MakeNLFeeder_C_Default() / NLW2_Destroy…().

2023-11: CURRENT IMPLEMENTATION SUPPORTS LINEAR MODELS.

For the NL format, variables and constraints must have certain order.

Variable ordering:** first continuous, then integer. Some solvers might require more elaborate ordering, see NLHeader_C.

Constraint ordering:** first algebraic (including complementarity), then logical. Some solvers might require nonlinear constraints first.

Functions

void NLW2_WriteSparseIntEntry(void *p_api_data_, int index, int value)

Declare callbacks.

Write sparse vector(int) entry

Declare callbacks.

void NLW2_WriteSparseDblEntry(void *p_api_data_, int index, double value)

Write sparse vector(double) entry.

void NLW2_WriteVarLbUb(void *p_api_data, double lb, double ub)

Write next variable’s Lb, Ub.

Write next variable’s Lb, Ub.

void NLW2_WriteColSize(void *p_api_data, int sz)

Write next Jacobian column size.

void NLW2_WriteAlgConRange(void*, NLW2_AlgConRange_C*)

Callback: write next constraint’s range.

Callback: write next constraint’s range.

void *NLW2_StartIntSuffix(void *p_api_1, const char *suf_name, int kind, int nnz)

Callback: start int suffix.

void *NLW2_StartDblSuffix(void *p_api_1, const char *suf_name, int kind, int nnz)

Callback: start dbl suffix.

void NLW2_WriteName(void *p_api_data, const char *name)

Callback: write model item name.

void NLW2_WriteNameAndComment(void *p_api_data, const char *name, const char *comment)

Callback: write fixed var name and comment.

void NLW2_WriteNameAndNumber(void *p_api_data, const char *name, double val)

Callback: write obj name and offset.

NLW2_NLFeeder_C NLW2_MakeNLFeeder_C_Default(void)

Return NLW2_NLFeeder_C with default options / methods.

Return NLW2_NLFeeder_C with default options / methods.

Name information is optional.

Implementation: if ((output_desired) && wrt) for (i: ….) wrt << name[i].c_str(); Provide deleted row names. Provide variable names. Provide unused variable names. Provide {fixed variable, extra info} pairs. This includes defined eliminated variables.

Implementation: if ((output_desired) && wrt) for (….) wrt << typename Writer::StrStrValue { name[i].c_str(), comment[i].c_str() }; Provide {obj name, constant term} pairs.

Implementation: if (wrt) for (….) wrt << typename Writer::StrDblValue { name[i].c_str(), (double)obj_offset[i] };

void NLW2_DestroyNLFeeder_C_Default(NLW2_NLFeeder_C*)

Destroy NLW2_NLFeeder_C created by NLW2_MakeNLFeeder_C_default()

file nl-model-c.h
#include “mp/nl-solver-basics-c.h

Typedefs

typedef struct NLW2_NLModel_C NLW2_NLModel_C

extern “C” wrapper of mp::NLModel.

Intermediate representation for special model types: (MI)LP, (MI)QP. For full modeling capabilities use NLW2_NLFeeder_C, NLW2_SOLHandler_C.

See also

C API tests/examples.

Note

All model data pointers should stay valid until loading the model into NLW2_NLSolver_C.

typedef struct NLW2_NLSuffix_C NLW2_NLSuffix_C

NL suffix type.

typedef struct NLW2_NLSolution_C NLW2_NLSolution_C

NL solution.

Functions

NLW2_NLModel_C NLW2_MakeNLModel_C(const char *probname)

Construct NLW2_NLModel_C.

Note

All model data pointers should stay valid until loading the model into NLW2_NLSolver_C.

Parameters
  • probname – can be NULL.

  • probname – can be NULL.

void NLW2_DestroyNLModel_C(NLW2_NLModel_C*)

Destroy NLW2_NLModel_C.

void NLW2_SetCols_C(NLW2_NLModel_C*, int num_col, const double *lower, const double *upper, const int *type)

Add variables (all at once.)

Note

All model data pointers should stay valid until loading the model into NLW2_NLSolver_C.

void NLW2_SetColNames_C(NLW2_NLModel_C*, const char *const *nm)

Add variable names.

Note

All model data pointers should stay valid until loading the model into NLW2_NLSolver_C.

void NLW2_SetRows_C(NLW2_NLModel_C*, int nr, const double *rlb, const double *rub, NLW2_MatrixFormat format_, size_t num_nz_, const size_t *start_, const int *index_, const double *value_)

Add linear constraints (all at once).

Only rowwise matrix supported.

Only rowwise matrix supported.

Note

All model data pointers should stay valid until loading the model into NLW2_NLSolver_C.

void NLW2_SetRowNames_C(NLW2_NLModel_C*, const char *const *nm)

Add constraint names.

Note

All model data pointers should stay valid until loading the model into NLW2_NLSolver_C.

void NLW2_SetLinearObjective_C(NLW2_NLModel_C*, NLW2_ObjSense sense, double c0, const double *c)

Add linear objective (only single objective supported.) Coefficients: dense vector.

Add linear objective (only single objective supported.) Coefficients: dense vector.

Coefficients: dense vector.

Note

All model data pointers should stay valid until loading the model into NLW2_NLSolver_C.

void NLW2_SetHessian_C(NLW2_NLModel_C*, NLW2_HessianFormat format, int dim, size_t num_nz_, const size_t *start_, const int *index_, const double *value_)

Add Q for the objective quadratic part 0.5 @ x.T @ Q @ x.

Format: NLW2_HessianFormat…

Note

All model data pointers should stay valid until loading the model into NLW2_NLSolver_C.

void NLW2_SetObjName_C(NLW2_NLModel_C*, const char *nm)

Set obj name.

Note

All model data pointers should stay valid until loading the model into NLW2_NLSolver_C.

void NLW2_SetWarmstart_C(NLW2_NLModel_C*, NLW2_SparseVector_C ini_x)

Set initial solution.

Note

All pointers should stay valid until loading the model into NLW2_NLSolver_C.

void NLW2_SetDualWarmstart_C(NLW2_NLModel_C*, NLW2_SparseVector_C ini_y)

Set dual initial solution.

Note

All pointers should stay valid until loading the model into NLW2_NLSolver_C.

int NLW2_AddSuffix_C(NLW2_NLModel_C*, NLW2_NLSuffix_C suf_c)

Add suffix, e.g., basis statuses.

Note

SOS constraints can be modeled as suffixes for some AMPL solvers.

Returns

true iff new suffix added (vs replaced.)

double NLW2_ComputeObjValue_C(NLW2_NLModel_C*, const double *x)

Compute objective value.

const char *NLW2_ProbName_C(NLW2_NLModel_C*)

Get problem name.

NLW2_ColData_C NLW2_Columns_C(NLW2_NLModel_C*)

Get variables.

const char *const *NLW2_ColNames_C(NLW2_NLModel_C*)

Get var names.

const char *NLW2_ColName_C(NLW2_NLModel_C*, int i)

Get var name [i].

NLW2_SparseMatrix_C NLW2_GetA_C(NLW2_NLModel_C*)

Lin con matrix.

int NLW2_NumCols_C(NLW2_NLModel_C*)

N cols.

int NLW2_NumRows_C(NLW2_NLModel_C*)

N rows.

const double *NLW2_RowLowerBounds_C(NLW2_NLModel_C*)

Row lb.

const double *NLW2_RowUpperBounds_C(NLW2_NLModel_C*)

Row ub.

const char *const *NLW2_RowNames_C(NLW2_NLModel_C*)

Row names.

const char *NLW2_RowName_C(NLW2_NLModel_C*, int i)

Row name [i].

int NLW2_ObjSense_C(NLW2_NLModel_C*)

Obj sense.

double NLW2_ObjOffset_C(NLW2_NLModel_C*)

Obj offset.

const double *NLW2_ObjCoefficients_C(NLW2_NLModel_C*)

Obj coefs.

int NLW2_HessianFormat_C(NLW2_NLModel_C*)

Hessian format NLW2_HessianFormat…

NLW2_SparseMatrix_C NLW2_Hessian_C(NLW2_NLModel_C*)

Hessian matrix.

const char *NLW2_ObjName_C(NLW2_NLModel_C*)

Obj name.

file nl-solver-c.h
#include “api/c/nl-model-c.h
#include “api/c/nl-feeder-c.h
#include “api/c/sol-handler-c.h

Typedefs

typedef struct NLW2_NLSolver_C NLW2_NLSolver_C

Manager for solving optimization models via NL files.

It performs zero-overhead model/solution transmission. In particular, it does not store any intermediate model/solution representation.

This wrapper offers both full NL functionality, as well as “easy” but limited interface via NLW2_NLModel_C.

See also

C API tests/examples.

Note

To manipulate, use NLW2_MakeNLSolver_C() / NLW2_DestroyNLSolver_C(), NLW2_LoadNLModel_C(), etc, see the below API.

Functions

NLW2_NLSolver_C NLW2_MakeNLSolver_C(NLW2_NLUtils_C *p_utils)

Construct.

Parameters

p_utils – utils object, can be NULL.

void NLW2_DestroyNLSolver_C(NLW2_NLSolver_C *p_nlsol)

Destroy NLSolver_C.

void NLW2_SetFileStub_C(NLW2_NLSolver_C*, const char *stub)

Set file stub [OPTIONAL].

Used for filename base of .nl, .col, row, etc. input files, as well as .sol output files.

Note

If not provided, a temporary filename is used; then, .nl is deleted upon object desruction.

const char *NLW2_GetFileStub_C(NLW2_NLSolver_C*)

Retrieve file stub.

void NLW2_SetNLOptions_C(NLW2_NLSolver_C*, NLW2_NLOptionsBasic_C)

Set NL options for loading NLW2_NLModel_C [OPTIONAL].

If not provided, default is used.

Note

Not used for loading with NLW2_NLFeeder_C.

NLW2_NLOptionsBasic_C NLW2_GetNLOptions_C(NLW2_NLSolver_C*)

Get NLOptions used for loading NLModel.

const char *NLW2_GetErrorMessage_C(NLW2_NLSolver_C*)

Get error message.

Nonempty iff error occurred.

NLW2_NLSolution_C NLW2_SolveNLModel_C(NLW2_NLSolver_C*, NLW2_NLModel_C*, const char *solver, const char *solver_opts)

Load and solve NLW2_NLModel_C and return result.

Returns

NLW2_Solution_C object with computed obj_value_. Valid as long as the NLW2_NLSolver_C object lives, and until the next Solve() or ReadSolution().

int NLW2_SolveFeederHandler_C(NLW2_NLSolver_C*, NLW2_NLFeeder_C*, NLW2_SOLHandler_C*, const char *solver, const char *solver_opts)

Load NLW2_NLFeeder_C, solve, and read into SOLHandler_C.

See also

NLW2_LoadNLFeed2_C(), NLW2_RunSolver_C(), NLW2_Read2SOLHanlder2_C() for details.

Returns

Non-zero iff all ok.

int NLW2_LoadNLModel_C(NLW2_NLSolver_C*, NLW2_NLModel_C*)

Load NLW2_NLModel_C.

NL file name base and some options can be provided, if non-defaults desired, via SetFileStub() and SetNLOptions().

Returns

true if all ok, otherwise see GetErrorMessage().

int NLW2_LoadNLFeed2_C(NLW2_NLSolver_C*, NLW2_NLFeeder_C *nlf_c)

Write NL and any accompanying files.

Parameters

nlf_c – NL feeder.

Returns

true if all ok, otherwise see GetErrorMessage().

Returns

Non-0 if all ok.

int NLW2_RunSolver_C(NLW2_NLSolver_C*, const char *solver, const char *solver_opts)

Run a solver after loading model.

Parameters
  • solver – solver executable, such as “gurobi”.

  • solver_opts – string of solver options, such as “outlev=1 writeprob=model.lp”.

Returns

Non-0 if all ok.

NLW2_NLSolution_C NLW2_ReadSolution_C(NLW2_NLSolver_C*)

Read solution after solving a model loaded with NLW2_LoadNLModel_C().

Note

To compute objective value, execute NLW2_ComputeObjValue_C() if x_ available.

Returns

NLW2_Solution_C object. Valid as long as the NLW2_NLSolver_C object lives, and until the next Solve() or ReadSolution().

int NLW2_Read2SOLHandler_C(NLW2_NLSolver_C*, NLW2_SOLHandler_C *solh_c)

Read solution to SOLHandler.

Parameters

solh_c – solution handler.

Returns

Non-0 if all ok.

file nl-writer2-misc-c-impl.h
#include “mp/nl-writer2-misc.h
file nl-writer2-misc-c.h

Typedefs

typedef struct NLW2_NLUtils_C NLW2_NLUtils_C

Wrap mp::NLUtils for C API.

NL writer and SOL reader utilities. It provides facilities for logging and error handling.

To fill default methods, call NLW2_MakeNLUtils_C_Default() / NLW2_Destroy…().

The default error handler exit()s.

Functions

NLW2_NLUtils_C NLW2_MakeNLUtils_C_Default(void)

Create a default NLW2_NLUtils_C wrapper object.

User application might change some methods and use the p_user_data_ pointer.

void NLW2_DestroyNLUtils_C_Default(NLW2_NLUtils_C*)

Destroy the NLW2_NLUtils_C object created by the API.

file sol-handler-c-impl.h
#include “api/c/sol-handler-c.h
#include “mp/sol-handler.h
file sol-handler-c.h
#include “”

Typedefs

typedef struct NLW2_SuffixInfo_C NLW2_SuffixInfo_C

Suffix information.

typedef struct AMPLOptions_C AMPLOptions_C

AMPL internal options.

typedef struct NLW2_SOLHandler_C NLW2_SOLHandler_C

Wrap mp::SOLHandler for C API.

NLW2_SOLHandler_C: reads solution details on request via provided callback objects. See the examples folder.

To fill some default methods, call NLW2_MakeSOLHandler_C_Default() / NLW2_Destroy…().

Functions

double NLW2_ReadSolVal(void *p_api_data)

Callback: read next dual/variable value.

Callback: read next dual/variable value.

int NLW2_IntSuffixNNZ(void *p_api_data)

Number of suffix non-zero elements.

int NLW2_DblSuffixNNZ(void *p_api_data)

Number of suffix non-zero elements.

void NLW2_ReadIntSuffixEntry(void *p_api_data, int*, int*)

Read suffix entry.

void NLW2_ReadDblSuffixEntry(void *p_api_data, int*, double*)

Read suffix entry.

void NLW2_ReportDblSuffixError(void *p_api_data, const char *msg)

Report suffix error.

This causes NLW2_DblSuffixNNZ() to return 0.

void NLW2_ReportIntSuffixError(void *p_api_data, const char *msg)

Report suffix error.

This causes NLW2_IntSuffixNNZ() to return 0.

int NLW2_IntSuffixReadOK(void *p_api_data)

Check suffix read result.

int NLW2_DblSuffixReadOK(void *p_api_data)

Check suffix read result.

NLW2_SOLHandler_C NLW2_MakeSOLHandler_C_Default(void)

Create an NLW2_SOLHandler_C with default methods.

void NLW2_DestroySOLHandler_C_Default(NLW2_SOLHandler_C*)

Destroy an NLW2_SOLHandler_C created with NLW2_Make…Default()

file nl-feeder.h
#include <>
#include <>
#include “”
file nl-model.h
#include <>
#include <>
#include <>
#include <>
#include <>
#include “mp/nl-solver-basics-c.h
file nl-opcodes.h
file nl-solver-basics-c.h
#include <>

Typedefs

typedef enum NLW2_ObjSense NLW2_ObjSense

Enum NLW2_ObjSense.

typedef enum NLW2_VarType NLW2_VarType

Enum NLW2_VarType.

typedef enum NLW2_MatrixFormat NLW2_MatrixFormat

Enum NLW2_MatrixFormat.

typedef enum NLW2_HessianFormat NLW2_HessianFormat

Enum NLW2_HessianFormat.

typedef struct NLW2_ColData_C NLW2_ColData_C

Variables’ data by pointers.

typedef struct NLW2_SparseMatrix_C NLW2_SparseMatrix_C

Sparse matrix.

typedef struct NLW2_SparseVector_C NLW2_SparseVector_C

Sparse vector.

typedef struct NLW2_NLOptionsBasic_C NLW2_NLOptionsBasic_C

Basic NL options for NLModel.

Prefer to create by NLW2_MakeNLOptionsBasic_Default().

Enums

enum NLW2_ObjSense

Enum NLW2_ObjSense.

Values:

enumerator NLW2_ObjSenseMinimize
enumerator NLW2_ObjSenseMaximize
enum NLW2_VarType

Enum NLW2_VarType.

Values:

enumerator NLW2_VarTypeContinuous
enumerator NLW2_VarTypeInteger
enum NLW2_MatrixFormat

Enum NLW2_MatrixFormat.

Values:

enumerator NLW2_MatrixFormatIrrelevant
enumerator NLW2_MatrixFormatUnset
enumerator NLW2_MatrixFormatRowwise
enum NLW2_HessianFormat

Enum NLW2_HessianFormat.

Values:

enumerator NLW2_HessianFormatTriangular
enumerator NLW2_HessianFormatSquare
enum NLW2_WriteNLResultCode

NLW2_WriteNLResultCode enum.

Values:

enumerator NLW2_WriteNL_Unset
enumerator NLW2_WriteNL_OK
enumerator NLW2_WriteNL_CantOpen
enumerator NLW2_WriteNL_Failed
enum NLW2_SOLReadResultCode

SOL read result code.

Values:

enumerator NLW2_SOLRead_Result_Not_Set
enumerator NLW2_SOLRead_OK
enumerator NLW2_SOLRead_Fail_Open
enumerator NLW2_SOLRead_Early_EOF
enumerator NLW2_SOLRead_Bad_Format
enumerator NLW2_SOLRead_Bad_Line
enumerator NLW2_SOLRead_Bad_Options
enumerator NLW2_SOLRead_Vector_Not_Finished
enumerator NLW2_SOLRead_Bad_Suffix

Functions

NLW2_NLOptionsBasic_C NLW2_MakeNLOptionsBasic_C_Default()

Use this to create default NL options for NLModel.

file nl-solver.h
#include <>
#include <>
#include <>
#include <>
#include “mp/nl-solver-basics-c.h
#include “mp/nl-model.h
#include “mp/nl-utils.h
file nl-solver.hpp
#include “mp/nl-solver.h
#include “mp/nl-writer2.hpp
#include “mp/sol-reader2.hpp
file nl-utils.h
#include <>
#include <>
#include <>
#include <>
file nl-writer2-misc.h
#include <>
#include <>
#include <>
#include <>
#include <>
#include “”
#include “mp/nl-utils.h
file nl-writer2.h
#include <>
#include <>
#include <>
#include <>
#include <>
#include <>
#include “mp/nl-solver-basics-c.h
#include “mp/nl-writer2-misc.h
#include “mp/nl-feeder.h
file nl-writer2.hpp
#include <>
#include <>
#include “mp/nl-writer2.h

Defines

EOL
file sol-handler.h
#include <>
#include <>
#include “”
file sol-reader2.h
#include <>
#include <>
#include <>
#include <>
#include “mp/nl-solver-basics-c.h
#include “mp/sol-handler.h
#include “mp/nl-utils.h
file sol-reader2.hpp
#include <>
#include “mp/sol-reader2.h
file __init__.py
file __init__.py
file conf.py
file README.md
file README.md
file nlw_bindings.cc
#include <>
#include <>
#include <>
#include “mp/nl-solver.h

Defines

STRINGIFY(x)

NL Writer Python bindings.

Copyright (C) 2024 AMPL Optimization Inc.

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.

The author and AMPL Optimization Inc disclaim all warranties with regard to this software, including all implied warranties of merchantability and fitness. In no event shall the author 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.

Author: Gleb Belov

MACRO_STRINGIFY(x)

Functions

mp::NLSolution NLW2_Solve(mp::NLSolver &nls, const NLWPY_NLModel &mdl, const std::string &solver, const std::string &solver_opts)
PYBIND11_MODULE(_nlwpy, m)
file __main__.py
file test_solve.py
file setup.py
file dtoa.cc
#include “”
#include “”
#include “”
#include “”
#include “”

Defines

Long
assert(x)
Debug(x)
MALLOC
REALLOC
FREE
PRIVATE_MEM
PRIVATE_mem
NO_STRTOD_BIGCOMP
Set_errno(x)
IEEE_8087
IEEE_Arith
Llong
ULLong
USE_BF96
word0(x)
word1(x)
dval(x)
LLval(x)
STRTOD_DIGLIM
strtod_diglim
Storeinc(a, b, c)
Exp_shift
Exp_shift1
Exp_msk1
Exp_msk11
Exp_mask
P
Nbits
Bias
Emax
Emin
Exp_1
Exp_11
Ebits
Frac_mask
Frac_mask1
Ten_pmax
Bletch
Bndry_mask
Bndry_mask1
LSB
Sign_bit
Log2P
Tiny0
Tiny1
Quick_max
Int_max
Avoid_Underflow
Flt_Rounds
Rounding
rounded_product(a, b)
rounded_quotient(a, b)
Big0
Big1
Pack_32
FFFFFFFF
MTa
MTb
MTd
Kmax
freelist
p5s
Bcopy(x, y)
d0
d1
d0
d1
Scale_Bit
n_bigtens
Need_Hexdig
ULbits
kshift
kmask

Typedefs

unsigned Long ULong
typedef struct BF96 BF96
typedef struct BCinfo BCinfo
typedef struct Bigint Bigint
typedef struct ThInfo ThInfo

Enums

enum [anonymous]

Values:

enumerator Round_zero
enumerator Round_near
enumerator Round_up
enumerator Round_down

Functions

double strtod(const char *s00, char **se)
char *dtoa_nlw2(double d, int mode, int ndigits, int *decpt, int *sign, char **rve)
static Bigint * Balloc (int k MTd)
static void Bfree (Bigint *v MTd)
static Bigint * multadd (Bigint *b, int m, int a MTd)
static Bigint * s2b (const char *s, int nd0, int nd, ULong y9, int dplen MTd)
static int hi0bits(ULong x)
static int lo0bits(ULong *y)
static Bigint * i2b (int i MTd)
static Bigint * mult (Bigint *a, Bigint *b MTd)
static Bigint * pow5mult (Bigint *b, int k MTd)
static Bigint * lshift (Bigint *b, int k MTd)
static int cmp(Bigint *a, Bigint *b)
static Bigint * diff (Bigint *a, Bigint *b MTd)
static double ulp(U *x)
static double b2d(Bigint *a, int *e)
static Bigint * d2b (U *d, int *e, int *bits MTd)
static double ratio(Bigint *a, Bigint *b)
static Bigint * increment (Bigint *b MTd)
static void rshift(Bigint *b, int k)
static ULong any_on(Bigint *b, int k)
static void gethex (const char **sp, U *rvp, int rounding, int sign MTd)
static int dshift(Bigint *b, int p2)

NO_HEX_FP}

static int quorem(Bigint *b, Bigint *S)
static double sulp(U *x, BCinfo *bc)
static char * rv_alloc (int i MTd)
static char * nrv_alloc (const char *s, char *s0, size_t s0len, char **rve, int n MTd)
static void freedtoa(char *s)
char *dtoa_r_dmgay(double dd, int mode, int ndigits, int *decpt, int *sign, char **rve, char *buf, size_t blen)

Variables

static double private_mem[PRIVATE_mem]
static double *pmem_next = private_mem
static int dtoa_divmax = 2
static BF96 pten[667]
static short int Lhint[2098]
static ULLong pfive[27] = {5ll, 25ll, 125ll, 625ll, 3125ll, 15625ll, 78125ll, 390625ll, 1953125ll, 9765625ll, 48828125ll, 244140625ll, 1220703125ll, 6103515625ll, 30517578125ll, 152587890625ll, 762939453125ll, 3814697265625ll, 19073486328125ll, 95367431640625ll, 476837158203125ll, 2384185791015625ll, 11920928955078125ll, 59604644775390625ll, 298023223876953125ll, 1490116119384765625ll, 7450580596923828125ll}
static int pfivebits[25] = {3, 5, 7, 10, 12, 14, 17, 19, 21, 24, 26, 28, 31, 33, 35, 38, 40, 42, 45, 47, 49, 52, 54, 56, 59}
static ThInfo TI0
static const double tens[] = {1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22}
static const double bigtens[] = {1e16, 1e32, 1e64, 1e128, 1e256}
static const double tinytens[] = {1e-16, 1e-32, 1e-64, 1e-128, 9007199254740992. * 9007199254740992.e-256}
static unsigned char hexdig[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
static char *dtoa_result
file nl-model-c.cc
#include “api/c/nl-model-c.h
#include “mp/nl-model.h

Functions

NLW2_NLModel_C NLW2_MakeNLModel_C(const char *probname)

Construct NLW2_NLModel_C.

Parameters

probname – can be NULL.

void NLW2_DestroyNLModel_C(NLW2_NLModel_C *nlme)

Destroy NLW2_NLModel_C.

void NLW2_SetCols_C(NLW2_NLModel_C *nlme, int num_col, const double *lower, const double *upper, const int *type)

Add variables (all at once.)

Note

All model data pointers should stay valid until loading the model into NLW2_NLSolver_C.

void NLW2_SetColNames_C(NLW2_NLModel_C *nlme, const char *const *nm)

Add variable names.

Note

All model data pointers should stay valid until loading the model into NLW2_NLSolver_C.

void NLW2_SetRows_C(NLW2_NLModel_C *nlme, int nr, const double *rlb, const double *rub, NLW2_MatrixFormat format, size_t num_nz, const size_t *start, const int *index, const double *value)

Add linear constraints (all at once).

Only rowwise matrix supported.

void NLW2_SetRowNames_C(NLW2_NLModel_C *nlme, const char *const *nm)

Add constraint names.

Note

All model data pointers should stay valid until loading the model into NLW2_NLSolver_C.

void NLW2_SetLinearObjective_C(NLW2_NLModel_C *nlme, NLW2_ObjSense sense, double c0, const double *c)

Add linear objective (only single objective supported.) Sense: NLW2_ObjSenseM….

Add linear objective (only single objective supported.) Coefficients: dense vector.

Coefficients: dense vector.

void NLW2_SetHessian_C(NLW2_NLModel_C *nlme, NLW2_HessianFormat format, int dim, size_t num_nz_, const size_t *start_, const int *index_, const double *value_)

Add Q for the objective quadratic part 0.5 @ x.T @ Q @ x.

Format: NLW2_HessianFormat…

void NLW2_SetObjName_C(NLW2_NLModel_C *nlme, const char *nm)

Set obj name.

Note

All model data pointers should stay valid until loading the model into NLW2_NLSolver_C.

void NLW2_SetWarmstart_C(NLW2_NLModel_C *nlme, NLW2_SparseVector_C ini_x)

Set initial solution.

Note

All pointers should stay valid until loading the model into NLW2_NLSolver_C.

void NLW2_SetDualWarmstart_C(NLW2_NLModel_C *nlme, NLW2_SparseVector_C ini_y)

Set dual initial solution.

Note

All pointers should stay valid until loading the model into NLW2_NLSolver_C.

int NLW2_AddSuffix_C(NLW2_NLModel_C *nlme, NLW2_NLSuffix_C suf_c)

Add suffix, e.g., basis statuses.

Note

SOS constraints can be modeled as suffixes for some AMPL solvers.

Returns

true iff new suffix added (vs replaced.)

double NLW2_ComputeObjValue_C(NLW2_NLModel_C *nlme, const double *x)

Compute objective value.

const char *NLW2_ProbName_C(NLW2_NLModel_C *nlme)

Get problem name.

NLW2_ColData_C NLW2_Columns_C(NLW2_NLModel_C *nlme)

Get variables.

const char *const *NLW2_ColNames_C(NLW2_NLModel_C *nlme)

Get var names.

const char *NLW2_ColName_C(NLW2_NLModel_C *nlme, int i)

Get var name [i].

NLW2_SparseMatrix_C NLW2_GetA_C(NLW2_NLModel_C *nlme)

Lin con matrix.

int NLW2_NumCols_C(NLW2_NLModel_C *nlme)

N cols.

int NLW2_NumRows_C(NLW2_NLModel_C *nlme)

N rows.

const double *NLW2_RowLowerBounds_C(NLW2_NLModel_C *nlme)

Row lb.

const double *NLW2_RowUpperBounds_C(NLW2_NLModel_C *nlme)

Row ub.

const char *const *NLW2_RowNames_C(NLW2_NLModel_C *nlme)

Row names.

const char *NLW2_RowName_C(NLW2_NLModel_C *nlme, int i)

Row name [i].

int NLW2_ObjSense_C(NLW2_NLModel_C *nlme)

Obj sense.

double NLW2_ObjOffset_C(NLW2_NLModel_C *nlme)

Obj offset.

const double *NLW2_ObjCoefficients_C(NLW2_NLModel_C *nlme)

Obj coefs.

int NLW2_HessianFormat_C(NLW2_NLModel_C *nlme)

Hessian format NLW2_HessianFormat…

NLW2_SparseMatrix_C NLW2_Hessian_C(NLW2_NLModel_C *nlme)

Hessian matrix.

const char *NLW2_ObjName_C(NLW2_NLModel_C *nlme)

Obj name.

file nl-solver-c.cc
#include <>
#include <>
#include <>
#include “api/c/nl-feeder-c.h
#include “api/c/sol-handler-c.h
#include “api/c/nl-feeder-c-impl.h
#include “api/c/nl-solver-c.h
#include “mp/nl-solver.hpp

Typedefs

typedef struct NLW2_SuffixWriter_C NLW2_SuffixWriter_C

Functions

void NLW2_WriteSparseIntEntry(void *svw, int index, int value)

Sparse vector writers.

Declare callbacks.

void NLW2_WriteSparseDblEntry(void *svw, int index, double value)

Write sparse vector(double) entry.

void NLW2_WriteVarLbUb(void *vbw, double lb, double ub)

Var bound writer.

Write next variable’s Lb, Ub.

void NLW2_WriteAlgConRange(void *crw, NLW2_AlgConRange_C *pbnd)

Algebraic constraint writer.

Callback: write next constraint’s range.

void NLW2_WriteColSize(void *csw, int sz)

Write next Jacobian column size.

void *NLW2_StartIntSuffix(void *swf, const char *suf_name, int kind, int nnz)

Callback: start int suffix.

void *NLW2_StartDblSuffix(void *swf, const char *suf_name, int kind, int nnz)

Callback: start dbl suffix.

void NLW2_WriteName(void *p_api_data, const char *name)

Callback: write model item name.

void NLW2_WriteNameAndComment(void *p_api_data, const char *name, const char *comment)

Callback: write fixed var name and comment.

void NLW2_WriteNameAndNumber(void *p_api_data, const char *name, double val)

Callback: write obj name and offset.

static const char *NLW2_ObjDescription_C_Default(void*, int)

Default implementations.

static int NLW2_ObjType_C_Default(void*, int)
static int NLW2_ObjGradientNNZ_C_Default(void*, int)
static void NLW2_FeedObjGradient_C_Default(void*, int, void*)
static void NLW2_FeedVarBounds_C_Default(void*, void*)
static void NLW2_FeedConBounds_C_Default(void*, void*)
static const char *NLW2_ConDescription_C_Default(void*, int)
static int NLW2_LinearConExprNNZ_C_Default(void*, int)
static void NLW2_FeedLinearConExpr_C_Default(void*, int, void*)
static void NLW2_FeedColumnSizes_C_Default(void*, void*)

Feed native expression.

This method is recursively called from NLWriter, when Feeder uses ExprWriter::EPut(). Feeder should not call this method itself.

Details of ExprWriter: see NLWriter2. The below feature is for AMPL’s internal linearization of piecewise-linear functions. For user-definable SOS constraints, use suffixes .sosno/.ref.

The below is a feeder interface for .sos/.sosref suffixes. The feeder can provide 3 sparse vectors:

  • .sos for variables: Each nonzero value defines SOS group number. Negative means SOS Type 2, positive - SOS Type 1.

  • .sos for constraints: Each nonzero value denotes a constraint used in a linearization of an SOS. The constraint can be deleted by the solver driver if using solver’s SOS.

  • .sosref for variables: SOS weights. Variables participating in an SOS having zero weights are involved in linearization and can be deleted if the solver accepts SOS natively.

Implementation: auto sosv = plsos.StartSOSVars(nvsos); for (int i=0; i<nvsos; ++i) sosv.Write(i, vsos[i]); if (ncsos) { auto sosc = plsos.StartSOSCons(ncsos); for …. } auto sosrefv = plsos.StartSOSREFVars(ac->nsosref); …. Function definition. Provide definition of function i, i=0..num_funcs-1.

  1. RANDOM VARIABLES ///////////////////// Random variables. Undocumented feature. SNL2006. Example: var z >= 0; let z.stage := 1; var x{0..1, 0..1} random := Uniform(0,2); for {i in 0..1, j in 0..1} {let x[i,j].stage := 1;}; display z.stage, x.stage; c: z * sum{i in 0..1, j in 0..1} x[i,j] <= 3 + Sample(Uniform(0,2));

Feed random variables. Indexes: num_vars+num_common_exprs .. num_vars+num_common_exprs+num_rand_vars-1.

Implementation skeleton: for(j = num_vars+num_common_exprs; j < num_vars+num_common_exprs+num_rand_vars; j++) { auto ew = rvw.StartRandVar(j, rand_var_comment(j)); ew.EPut(rand_var_root_expr(j)); } Jacobian column sizes. Should feed LP column sizes for all but the last variable.

Implementation skeleton: if (WantColumnSizes()) for (int i=0; i < num_vars+num_rand_vars-1; ++i) csw.Write(col_size[i]);

static int NLW2_InitialGuessesNNZ_C_Default(void*)

Initial primal guesses.

Implementation: if (ini_guess.size()) { auto ig = igw.MakeVectorWriter(ini_guess.size()); for (size_t i=0; i<ini_guess.size(); ++i) ig.Write(i, ini_guess[i]); }

static void NLW2_FeedInitialGuesses_C_Default(void*, void*)
static void NLW2_FeedInitialDualGuesses_C_Default(void*, void*)

Initial dual guesses.

static void NLW2_FeedSuffixes_C_Default(void*, void*)

Feed suffixes.

For constraints, assume ordering: first algebraic, then logical.

Implementation: while (….) { auto sw = swf.StartIntSuffix( // or …DblSuffix suf_name, kind, n_nonzeros); for (int i=0; i<n_nonzeros; ++i) sw.Write(index[i], value[i]); }

static void NLW2_FeedNames_C_Default(void*, void*)
NLW2_NLFeeder_C NLW2_MakeNLFeeder_C_Default(void)

FeedRowAndObjNames: Provide constraint, then objective names.

Return NLW2_NLFeeder_C with default options / methods.

Name information is optional.

Implementation: if ((output_desired) && wrt) for (i: ….) wrt << name[i].c_str(); Provide deleted row names. Provide variable names. Provide unused variable names. Provide {fixed variable, extra info} pairs. This includes defined eliminated variables.

Implementation: if ((output_desired) && wrt) for (….) wrt << typename Writer::StrStrValue { name[i].c_str(), comment[i].c_str() }; Provide {obj name, constant term} pairs.

Implementation: if (wrt) for (….) wrt << typename Writer::StrDblValue { name[i].c_str(), (double)obj_offset[i] };

void NLW2_DestroyNLFeeder_C_Default(NLW2_NLFeeder_C*)

Destroy NLW2_NLFeeder_C created by NLW2_MakeNLFeeder_C_default()

static void NLW2_log_message_C_Default(void *p_api_data, const char *format, ...)

log message

static void NLW2_log_warning_C_Default(void *p_api_data, const char *format, ...)

log warning

static void NLW2_myexit_C_Default(void *p_api_data, const char *msg)

Override this to your error handler.

Not using exceptions by default. Only called with wrong output format string (internal error.)

NLW2_NLUtils_C NLW2_MakeNLUtils_C_Default(void)

Create a default NLW2_NLUtils_C wrapper object.

User application might change some methods and use the p_user_data_ pointer.

void NLW2_DestroyNLUtils_C_Default(NLW2_NLUtils_C*)

Destroy the NLW2_NLUtils_C object created by the API.

double NLW2_ReadSolVal(void *p_api_data)

Callbacks.

Callback: read next dual/variable value.

int NLW2_IntSuffixNNZ(void *p_api_data)

Number of suffix non-zero elements.

int NLW2_DblSuffixNNZ(void *p_api_data)

Number of suffix non-zero elements.

void NLW2_ReadIntSuffixEntry(void *p_api_data, int *pi, int *pv)

Read suffix entry.

void NLW2_ReadDblSuffixEntry(void *p_api_data, int *pi, double *pv)

Read suffix entry.

void NLW2_ReportDblSuffixError(void *p_api_data, const char *msg)

Report suffix error.

This causes NLW2_DblSuffixNNZ() to return 0.

void NLW2_ReportIntSuffixError(void *p_api_data, const char *msg)

Report suffix error.

This causes NLW2_IntSuffixNNZ() to return 0.

int NLW2_IntSuffixReadOK(void *p_api_data)

Check suffix read result.

int NLW2_DblSuffixReadOK(void *p_api_data)

Check suffix read result.

static void NLW2_OnSolveMessage_C_Default(void *p_user_data, const char *s, int nbs)

Default methods.

static int NLW2_OnAMPLOptions_C_Default(void *p_user_data, AMPLOptions_C)
static void NLW2_OnDualSolution_C_Default(void *p_user_data, int nvals, void *p_api_data)
static void NLW2_OnPrimalSolution_C_Default(void *p_user_data, int nvals, void *p_api_data)
static void NLW2_OnObjno_C_Default(void *p_user_data, int)
static void NLW2_OnSolveCode_C_Default(void *p_user_data, int)
static void NLW2_OnIntSuffix_C_Default(void *p_user_data, NLW2_SuffixInfo_C si, void *p_api_data)
static void NLW2_OnDblSuffix_C_Default(void *p_user_data, NLW2_SuffixInfo_C si, void *p_api_data)
NLW2_SOLHandler_C NLW2_MakeSOLHandler_C_Default(void)

Create an NLW2_SOLHandler_C with default methods.

void NLW2_DestroySOLHandler_C_Default(NLW2_SOLHandler_C*)

Destroy an NLW2_SOLHandler_C created with NLW2_Make…Default()

NLW2_NLSolver_C NLW2_MakeNLSolver_C(NLW2_NLUtils_C *putl)

Construct.

Parameters

p_utils – utils object, can be NULL.

void NLW2_DestroyNLSolver_C(NLW2_NLSolver_C *pnls)

Destroy NLSolver_C.

void NLW2_SetFileStub_C(NLW2_NLSolver_C *pnls, const char *stub)

Set file stub [OPTIONAL].

Used for filename base of .nl, .col, row, etc. input files, as well as .sol output files.

Note

If not provided, a temporary filename is used; then, .nl is deleted upon object desruction.

const char *NLW2_GetFileStub_C(NLW2_NLSolver_C *pnls)

Retrieve file stub.

void NLW2_SetNLOptions_C(NLW2_NLSolver_C *nlse, NLW2_NLOptionsBasic_C nlo)

Set NL options for loading NLW2_NLModel_C [OPTIONAL].

If not provided, default is used.

Note

Not used for loading with NLW2_NLFeeder_C.

NLW2_NLOptionsBasic_C NLW2_GetNLOptions_C(NLW2_NLSolver_C *nlse)

Get NLOptions used for loading NLModel.

const char *NLW2_GetErrorMessage_C(NLW2_NLSolver_C *pnls)

Get error message.

Nonempty iff error occurred.

static NLW2_NLSolution_C NLW2_WrapNLSOL_Solution_C(NLW2_NLSolver_C *nlse, mp::NLSolution sol)

Add solution data to NLW2_NLSolver_C and return its C wrapper, NLW2_Solution_C.

NLW2_NLSolution_C NLW2_SolveNLModel_C(NLW2_NLSolver_C *nlse, NLW2_NLModel_C *nlme, const char *solver, const char *solver_opts)

Load and solve NLW2_NLModel_C and return result.

Returns

NLW2_Solution_C object with computed obj_value_. Valid as long as the NLW2_NLSolver_C object lives, and until the next Solve() or ReadSolution().

int NLW2_SolveFeederHandler_C(NLW2_NLSolver_C *pnls, NLW2_NLFeeder_C *nlf_c, NLW2_SOLHandler_C *solh_c, const char *solver, const char *solver_opts)

Load NLW2_NLFeeder_C, solve, and read into SOLHandler_C.

See also

NLW2_LoadNLFeed2_C(), NLW2_RunSolver_C(), NLW2_Read2SOLHanlder2_C() for details.

Returns

Non-zero iff all ok.

int NLW2_LoadNLModel_C(NLW2_NLSolver_C *nlse, NLW2_NLModel_C *nlme)

Load NLW2_NLModel_C.

NL file name base and some options can be provided, if non-defaults desired, via SetFileStub() and SetNLOptions().

Returns

true if all ok, otherwise see GetErrorMessage().

int NLW2_LoadNLFeed2_C(NLW2_NLSolver_C *pnls, NLW2_NLFeeder_C *nlf_c)

Write NL and any accompanying files.

Parameters

nlf_c – NL feeder.

Returns

true if all ok, otherwise see GetErrorMessage().

Returns

Non-0 if all ok.

int NLW2_RunSolver_C(NLW2_NLSolver_C *pnls, const char *solver, const char *solver_opts)

Run a solver after loading model.

Parameters
  • solver – solver executable, such as “gurobi”.

  • solver_opts – string of solver options, such as “outlev=1 writeprob=model.lp”.

Returns

Non-0 if all ok.

NLW2_NLSolution_C NLW2_ReadSolution_C(NLW2_NLSolver_C *nlse)

Read solution after solving a model loaded with NLW2_LoadNLModel_C().

Note

To compute objective value, execute NLW2_ComputeObjValue_C() if x_ available.

Returns

NLW2_Solution_C object. Valid as long as the NLW2_NLSolver_C object lives, and until the next Solve() or ReadSolution().

int NLW2_Read2SOLHandler_C(NLW2_NLSolver_C *pnls, NLW2_SOLHandler_C *solh_c)

Read solution to SOLHandler.

Parameters

solh_c – solution handler.

Returns

Non-0 if all ok.

file nl-solver.cc
#include <>
#include <>
#include <>
#include <>
#include <>
#include <>
#include <>
#include <>
#include “mp/nl-solver.hpp
#include “mp/nl-opcodes.h

Functions

NLW2_NLOptionsBasic_C NLW2_MakeNLOptionsBasic_C_Default()

Use this to create default NL options for NLModel.

file nl-utils.cc
#include “mp/nl-utils.h
file nl-writer2.cc
#include <>
#include <>
#include <>
#include <>
#include “mp/nl-writer2.h
#include “mp/nl-writer2.hpp

Defines

ssize_t
DMG

Functions

static void test_nlfeeder_with_nlwriter2()

Check that the stub NLFeeder compiles with NLWriter2.

char *dtoa_r_dmgay(double dd, int mode, int ndigits, int *decpt, int *sign, char **rve, char *buf, size_t blen)
page md__home_docs_checkouts_readthedocs_org_user_builds_amplmp_checkouts_latest_nl_writer2_nlwpy_README

An example project built with pybind11. This requires Python 3.7+; for older versions of Python, check the commit history.

Installation

  • clone this repository

  • pip install ./nlwpy [--prefix=.]

CI Examples

There are examples for CI in .github/workflows. A simple way to produces binary “wheels” for all platforms is illustrated in the “wheels.yml” file, using . You can also see a basic recipe for building and testing in pip.yml, and conda.yml has an example of a conda recipe build.

Building the documentation

Documentation for the example project is generated using Sphinx. Sphinx has the ability to automatically inspect the signatures and documentation strings in the extension module to generate beautiful documentation in a variety formats. The following command generates HTML-based reference documentation; for other formats please refer to the Sphinx manual:

  • cd python_example/docs

  • make html

License

pybind11 is provided under a BSD-style license that can be found in the LICENSE file. By using, distributing, or contributing to this project, you agree to the terms and conditions of this license.

Test call

Inline:

import nlwpy as m
m.add(1, 2)

Use tests:

[PYTHONPATH=./<installation path++>] python test.py

page md__home_docs_checkouts_readthedocs_org_user_builds_amplmp_checkouts_latest_nl_writer2_README

A lightweight AMPL NL file writer and SOL file reader.

See mp.ampl.com.

page todo

Member mp::ConGroupName  (int cg)

Keep consistent with the ConstraintGroups enum.

Member mp::ConstraintGroup

Keep consistent with congroup_names

Class NLWPY_NLModel

check array lengths etc.

Member NLWPY_NLModel::SetCols  (std::vector< double > lb, std::vector< double > ub, std::vector< int > ty)

ty can be None.

dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/nl-writer2/include/api
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/nl-writer2/examples/c
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/nl-writer2/include/api/c
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/include/mp/flat/redef/conic
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/include/mp/flat/redef/MIP/core
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/nl-writer2/examples/cpp
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/nl-writer2/nlwpy/docs
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/nl-writer2/examples/c/easyAPI_1_MILP
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/nl-writer2/examples/cpp/easyAPI_1_MIQP
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/nl-writer2/examples
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/include/mp/flat/expr
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/include/mp/flat
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/nl-writer2/examples/cpp/fullAPI_1
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/nl-writer2/examples/c/fullAPI_1
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/nl-writer2/include
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/include
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/include/mp/flat/redef/MIP
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/include/mp
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/nl-writer2/include/mp
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/nl-writer2
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/nl-writer2/nlwpy
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/include/mp/flat/redef
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/nl-writer2/nlwpy/src
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/nl-writer2/src
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/include/mp/flat/redef/std
dir /home/docs/checkouts/readthedocs.org/user_builds/amplmp/checkouts/latest/nl-writer2/nlwpy/test