List of all members | Classes | Public Types | Public Member Functions | Protected Member Functions | Static Protected Member Functions | Protected Attributes | Friends
casadi::DaeBuilderInternal Class Reference

#include <dae_builder_internal.hpp>

Detailed Description

Internal class for DaeBuilder, see comments on the public class.

Definition at line 218 of file dae_builder_internal.hpp.

Inheritance diagram for casadi::DaeBuilderInternal:
Inheritance graph
[legend]
Collaboration diagram for casadi::DaeBuilderInternal:
Collaboration graph
[legend]

Classes

struct  CallIO
 Helper class, represents inputs and outputs for a function call node. More...
 

Public Types

using weak_ref_type = WeakRefInternal
 

Public Member Functions

 DaeBuilderInternal (const std::string &name, const std::string &path, const Dict &opts)
 Constructor. More...
 
 ~DaeBuilderInternal () override
 Destructor. More...
 
std::string class_name () const override
 Readable name of the internal class. More...
 
void sanity_check () const
 Check if dimensions match. More...
 
std::vector< MXinputs (Category ind) const
 
std::vector< MXoutputs (Category ind) const
 
std::vector< MXinputs (const std::vector< Category > &ind) const
 
std::vector< MXoutputs (const std::vector< Category > &ind) const
 
void add_lc (const std::string &name, const std::vector< std::string > &f_out)
 Add a named linear combination of output expressions. More...
 
Function create (const std::string &fname, const std::vector< std::string > &name_in, const std::vector< std::string > &name_out, const Dict &opts, bool sx, bool lifted_calls) const
 Construct a function object. More...
 
Function fmu_fun (const std::string &fname, const std::vector< std::string > &name_in, const std::vector< std::string > &name_out, const Dict &opts) const
 Construct function from an FMU DLL. More...
 
Function dependent_fun (const std::string &fname, const std::vector< std::string > &s_in, const std::vector< std::string > &s_out) const
 Construct a function for evaluating dependent parameters. More...
 
Function transition (const std::string &fname, casadi_int index, bool dummy_index_input=false) const
 Construct a function describing transition at a specific event. More...
 
Function transition (const std::string &fname) const
 Construct a function describing transition at all events. More...
 
Function gather_eq () const
 Function corresponding to all equations. More...
 
const MXvar (const std::string &name) const
 Get variable expression by name. More...
 
MX get_der (size_t ind) const
 Get a derivative expression by variable index (const, never create) More...
 
MX get_der (size_t ind, bool may_allocate=true)
 Get a derivative expression by variable index (non-const, may create) More...
 
MX der (const MX &var) const
 Get a derivative expression by non-differentiated expression (const, never create) More...
 
MX der (const MX &var, bool may_allocate=true)
 Get a derivative expression by non-differentiated expression (non-const, may create) More...
 
std::string unique_name (const std::string &prefix, bool allow_no_prefix=false) const
 Find a unique name, with a specific prefix. More...
 
std::string type_name () const
 Readable name of the class. More...
 
void disp (std::ostream &stream, bool more) const override
 Print description. More...
 
std::string get_str (bool more=false) const
 Get string representation. More...
 
Variablenew_variable (const std::string &name, const std::vector< casadi_int > &dimension={1}, const MX &expr=MX())
 Create a new variable. More...
 
bool has (const std::string &name) const
 Check if a particular variable exists. More...
 
std::vector< std::string > all () const
 Get a list of all variables. More...
 
std::vector< std::string > all (Category cat) const
 Get a list of all variables of a particular category. More...
 
size_t n_variables () const
 Length of variables array. More...
 
size_t n_mem () const
 Length of memory for all variables. More...
 
std::vector< double > start_all () const
 Start values for all variables. More...
 
const MXvar (size_t ind) const
 Get variable expression by index. More...
 
const MXvar (Category cat, size_t ind) const
 Get variable expression by category and index. More...
 
std::vector< MXvar (const std::vector< size_t > &ind) const
 Get variable expressions by index. More...
 
std::vector< MXvar (Category cat) const
 Get variable expressions by category. More...
 
size_t find (const std::string &name) const
 Get index of variable, given name. More...
 
size_t find (const MX &v) const
 Get index of variable, given expression. More...
 
std::vector< size_t > find (const std::vector< std::string > &name) const
 Get indices of variable, given multiple names. More...
 
std::vector< size_t > find (const std::vector< MX > &v) const
 Get indices of variable, given multiple expressions. More...
 
const std::string & name (size_t ind) const
 Get variable name by index. More...
 
std::vector< std::string > name (const std::vector< size_t > &ind) const
 Get variable names by indices. More...
 
const Functionoracle (bool sx=false, bool elim_w=false, bool lifted_calls=false) const
 Get the (cached) oracle, SX or MX. More...
 
Sparsity jac_sparsity (const std::vector< size_t > &oind, const std::vector< size_t > &iind) const
 Get Jacobian sparsity. More...
 
Sparsity hess_sparsity (const std::vector< size_t > &oind, const std::vector< size_t > &iind) const
 Get what is known of the Hessian sparsity. More...
 
casadi_int getCount () const
 Get the reference count. More...
 
std::string debug_repr (const SharedObjectInternal *) const
 
GenericWeakRef< SharedObject, SharedObjectInternal > * weak ()
 Get a weak reference to the object. More...
 
Manipulation

Reformulate the dynamic optimization problem.

void eliminate (Category cat)
 Eliminate all variables of a category. More...
 
void sort (Category cat)
 Sort all variables of a category. More...
 
void lift (bool lift_shared, bool lift_calls)
 Lift problem formulation by extracting shared subexpressions. More...
 
void sort_z (const std::vector< std::string > &z_order)
 Sort algebraic variables. More...
 
std::vector< size_t > & indices (Category cat)
 Classified variable indices (mutable) More...
 
const std::vector< size_t > & indices (Category cat) const
 Classified variable indices (immutable) More...
 
size_t size (Category cat) const
 Number of indices with a particular category. More...
 
void reorder (Category cat, const std::vector< size_t > &v)
 Reorder variables in a category. More...
 
void reorder (const std::string &n, std::vector< size_t > &ind, const std::vector< size_t > &v) const
 Reorder any index vector. More...
 
void prune (bool prune_p, bool prune_u)
 Prune unused controls. More...
 
void tearing_variables (std::vector< std::string > *res, std::vector< std::string > *iv, std::vector< std::string > *iv_on_hold) const
 Identify free variables and residual equations. More...
 
void tear ()
 Identify free variables and residual equations. More...
 
Variablevariable (size_t ind)
 
const Variablevariable (size_t ind) const
 
Variablevariable (Category cat, size_t ind)
 
const Variablevariable (Category cat, size_t ind) const
 
Variablevariable (const std::string &name)
 
const Variablevariable (const std::string &name) const
 
Variablevariable (const MX &v)
 
const Variablevariable (const MX &v) const
 

Protected Member Functions

casadi_int convert_index (casadi_int index) const
 
bool has_t () const
 Is there a time variable? More...
 
const MXtime () const
 
std::vector< MXcdef () const
 Definitions of dependent constants. More...
 
std::vector< MXinit_lhs () const
 Initial conditions, left-hand-side. More...
 
std::vector< MXinit_rhs () const
 Initial conditions, right-hand-side. More...
 
Variableadd (const std::string &name, Causality causality, Variability variability, const Dict &opts)
 Add a new variable. More...
 
Variableadd (const std::string &name, Causality causality, Variability variability, const MX &expr, const Dict &opts)
 Add a new variable, expression provided. More...
 
Variableadd (const std::string &name, Causality causality, const Dict &opts)
 Add a new variable, default variability. More...
 
Variableadd (const std::string &name, const Dict &opts)
 Add a new variable, default variability and causality. More...
 
void categorize (size_t ind, Category cat)
 Set or change the category for a variable. More...
 
void insert (std::vector< size_t > &v, size_t ind) const
 Insert into list of variables, keeping it ordered. More...
 
void remove (std::vector< size_t > &v, size_t ind) const
 Remove from list of variables. More...
 
Causality causality (size_t ind) const
 Get causality. More...
 
void set_causality (size_t ind, Causality causality)
 Set causality. More...
 
Variability variability (size_t ind) const
 Get variability. More...
 
void set_variability (size_t ind, Variability variability)
 Set variability. More...
 
Category category (size_t ind) const
 Get category. More...
 
void set_category (size_t ind, Category cat)
 Set category. More...
 
void eq (const MX &lhs, const MX &rhs, const Dict &opts)
 Add a simple equation. More...
 
void when (const MX &cond, const std::vector< std::string > &eqs, const Dict &opts)
 Add when equations. More...
 
Variableassign (const std::string &name, const MX &val)
 Assignment inside when-equations or if-else equations. More...
 
Variablereinit (const std::string &name, const MX &val)
 Reinitialize a state inside when-equations. More...
 
void set_init (const std::string &name, const MX &init_rhs)
 Set a initial equation. More...
 
MX read_expr (const XmlNode &node)
 Read an equation. More...
 
MX read_identifier (const XmlNode &node)
 Read an identifier expression. More...
 
Variableread_variable (const XmlNode &node, Attribute *att=nullptr)
 Read a variable. More...
 
void import_default_experiment (const XmlNode &n)
 
std::vector< casadi_int > read_dependencies (const XmlNode &n)
 
std::vector< DependenciesKindread_dependencies_kind (const XmlNode &n, size_t ndep)
 
void import_model_exchange (const XmlNode &n)
 
void import_model_variables (const XmlNode &modvars)
 Read ModelVariables. More...
 
void import_model_structure (const XmlNode &n)
 
XmlNode import_ls_dae (const std::string &lsdae)
 
void import_binding_equations (const XmlNode &eqs)
 
void import_dynamic_equations (const XmlNode &eqs)
 
void import_initial_equations (const XmlNode &eqs)
 
void clear_cache () const
 Problem structure has changed: Clear cache. More...
 
Function add_fun (const std::string &name, const std::vector< std::string > &arg, const std::vector< std::string > &res, const Dict &opts=Dict())
 Add a function from loaded expressions. More...
 
Function add_fun (const Function &f)
 Add an already existing function. More...
 
bool has_fun (const std::string &name) const
 Does a particular function already exist? More...
 
Function fun (const std::string &name) const
 Get function by name. More...
 
void reset ()
 
casadi_int size (Attribute a, const std::vector< std::string > &name) const
 Total number of elements for a particular attribute. More...
 
MX jac_vdef_v_from_calls (std::map< MXNode *, CallIO > &call_nodes, const std::vector< casadi_int > &h_offsets) const
 Calculate contribution to jac_vdef_v from lifted calls. More...
 
MX hess_v_v_from_calls (std::map< MXNode *, CallIO > &call_nodes, const std::vector< casadi_int > &h_offsets) const
 Calculate contribution to hess_?_v_v from lifted calls. More...
 
void initSingleton ()
 
void destroySingleton ()
 
shared_from_this ()
 Get a shared object from the current internal object. More...
 
const B shared_from_this () const
 Get a shared object from the current internal object. More...
 
double attribute (Attribute a, const std::string &name) const
 
std::vector< double > attribute (Attribute a, const std::vector< std::string > &name) const
 
void set_attribute (Attribute a, const std::string &name, double val)
 
void set_attribute (Attribute a, const std::vector< std::string > &name, const std::vector< double > &val)
 
std::string string_attribute (Attribute a, const std::string &name) const
 
std::vector< std::string > string_attribute (Attribute a, const std::vector< std::string > &name) const
 
void set_string_attribute (Attribute a, const std::string &name, const std::string &val)
 
void set_string_attribute (Attribute a, const std::vector< std::string > &name, const std::vector< std::string > &val)
 

Static Protected Member Functions

static std::string qualified_name (const XmlNode &nn, Attribute *att=nullptr)
 Get the qualified name. More...
 
static Variability default_variability (Causality causality, Type type)
 Default variability attribute, per the FMI specification. More...
 
static Initial default_initial (Causality causality, Variability variability)
 
static void sort_dependent (std::vector< MX > &v, std::vector< MX > &vdef)
 

Protected Attributes

bool debug_
 
double fmutol_
 
bool ignore_time_
 
bool enable_ls_dae_
 
bool enable_ls_serialization_
 
std::string fmi_version_
 
std::string model_name_
 
std::string instantiation_token_
 
std::string description_
 
std::string author_
 
std::string copyright_
 
std::string license_
 
std::string generation_tool_
 
std::string generation_date_and_time_
 
std::string variable_naming_convention_
 
casadi_int nzero_
 
double start_time_
 
double stop_time_
 
double tolerance_
 
double step_size_
 
std::string model_identifier_
 
bool provides_directional_derivatives_
 
bool provides_adjoint_derivatives_
 
bool can_be_instantiated_only_once_per_process_
 
std::vector< std::string > source_files_
 
std::string name_
 Name of instance. More...
 
Resource resource_
 
bool symbolic_
 
casadi_int orig_time_index_
 
bool detect_quad_
 
casadi_int fmi_major_
 
std::vector< Variable * > variables_
 All variables. More...
 
std::vector< size_t > der_
 
std::vector< size_t > initial_unknowns_
 
std::unordered_map< std::string, size_t > varind_
 Find of variable by name. More...
 
std::unordered_map< unsigned int, size_t > vrmap_
 Find of variable by value reference. More...
 
std::vector< std::vector< size_t > > indices_
 Ordered variables. More...
 
std::vector< size_t > init_
 
std::vector< std::pair< size_t, std::vector< size_t > > > when_
 
Function::AuxOut lc_
 Linear combinations of output expressions. More...
 
std::vector< Functionfun_
 Functions. More...
 
Function oracle_ [2][2][2]
 Function oracles (cached) More...
 
bool clear_cache_
 Should the cache be cleared? More...
 

Friends

class DaeBuilder
 
class FmuInternal
 
class FmuFunction
 
class Variable
 

Import and export

void load_fmi_description (const std::string &filename)
 
Dict export_fmu (const Dict &opts) const
 Export instance into an FMU (experimental) More...
 
Dict compile_fmu (const Dict &files, const Dict &opts) const
 Compile the sources produced by export_fmu, returning the augmented file map. More...
 
std::string pack_fmu (const Dict &files, const Dict &opts) const
 Pack files (from export_fmu / compile_fmu) into a single .fmu archive (experimental) More...
 
std::string generate_wrapper (const std::string &guid, const CodeGenerator &gen) const
 Generate FMU wrapper file (fmi3Functions.c) More...
 
std::string generate_build_description (const std::vector< std::string > &cfiles) const
 Generate buildDescription.xml. More...
 
std::string generate_model_description (const std::string &guid) const
 Generate modelDescription.xml. More...
 
XmlNode generate_model_variables () const
 Generate FMU ModelVariables. More...
 
XmlNode generate_model_structure (bool dae=false) const
 Generate FMU ModelStructure. More...
 
void update_dependencies () const
 Update model variable dependencies. More...
 
static std::string iso_8601_time ()
 Get current date and time in the ISO 8601 format. More...
 
static std::string generate_guid ()
 
static std::string generate (const std::vector< size_t > &v)
 
static std::string generate (const std::vector< double > &v)
 

Member Typedef Documentation

◆ weak_ref_type

Definition at line 152 of file shared_object.hpp.

Constructor & Destructor Documentation

◆ DaeBuilderInternal()

casadi::DaeBuilderInternal::DaeBuilderInternal ( const std::string &  name,
const std::string &  path,
const Dict opts 
)
explicit

Definition at line 660 of file dae_builder_internal.cpp.

662  clear_cache_ = false;
663  nzero_ = 0;
667  symbolic_ = true;
668  detect_quad_ = false;
669  start_time_ = nan;
670  stop_time_ = nan;
671  tolerance_ = nan;
672  step_size_ = nan;
673  // Default options
674  debug_ = false;
675  fmutol_ = 0;
676  ignore_time_ = false;
677  enable_ls_dae_ = true;
679  // Read options
680  for (auto&& op : opts) {
681  if (op.first=="debug") {
682  debug_ = op.second;
683  } else if (op.first=="fmutol") {
684  fmutol_ = op.second;
685  } else if (op.first=="ignore_time") {
686  ignore_time_ = op.second;
687  } else if (op.first=="detect_quad") {
688  detect_quad_ = op.second;
689  } else if (op.first=="resource_serialize_mode") {
690  resource_.change_option("serialize_mode", op.second);
691  } else if (op.first=="enable_ls_dae") {
692  enable_ls_dae_ = op.second;
693  } else if (op.first=="enable_ls_serialization") {
694  enable_ls_serialization_ = op.second;
695  } else {
696  casadi_error("No such option: " + op.first);
697  }
698  }
700 }
bool clear_cache_
Should the cache be cleared?
std::vector< std::vector< size_t > > indices_
Ordered variables.
const std::string & name(size_t ind) const
Get variable name by index.
std::string name_
Name of instance.
void change_option(const std::string &option_name, const GenericType &option_value)
Change option after object creation for debugging.
Definition: resource.cpp:74
static Resource open_resource(const std::string &path)
const double nan
Not a number.
Definition: calculus.hpp:53
std::vector< casadi_int > path(const std::vector< casadi_int > &map, casadi_int i_start)
static const size_t n_enum
Definition: casadi_enum.hpp:42

References can_be_instantiated_only_once_per_process_, casadi::Resource::change_option(), clear_cache_, debug_, detect_quad_, enable_ls_dae_, enable_ls_serialization_, fmutol_, ignore_time_, indices_, casadi::nan, nzero_, provides_adjoint_derivatives_, provides_directional_derivatives_, resource_, start_time_, step_size_, stop_time_, symbolic_, and tolerance_.

◆ ~DaeBuilderInternal()

casadi::DaeBuilderInternal::~DaeBuilderInternal ( )
override

Definition at line 635 of file dae_builder_internal.cpp.

635  {
636  for (Variable* v : variables_) {
637  if (v) delete v;
638  }
639 }
std::vector< Variable * > variables_
All variables.

References variables_.

Member Function Documentation

◆ add() [1/4]

Variable & casadi::DaeBuilderInternal::add ( const std::string &  name,
Causality  causality,
const Dict opts 
)
protected

Definition at line 3375 of file dae_builder_internal.cpp.

3375  {
3376  // Get type
3377  Type type = Type::FLOAT64;
3378  if (opts.find("type") != opts.end()) {
3379  type = to_enum<Type>(opts.at("type").to_string());
3380  }
3381 
3382  // Default variability per FMI 3.0.2, section 2.4.7.4
3383  return add(name, causality, default_variability(causality, type), opts);
3384 }
Causality causality(size_t ind) const
Get causality.
static Variability default_variability(Causality causality, Type type)
Default variability attribute, per the FMI specification.
Variable & add(const std::string &name, Causality causality, Variability variability, const Dict &opts)
Add a new variable.
Type
Variable type (FMI 3)

References add(), causality(), default_variability(), casadi::FLOAT64, and name().

◆ add() [2/4]

Variable & casadi::DaeBuilderInternal::add ( const std::string &  name,
Causality  causality,
Variability  variability,
const Dict opts 
)
protected

Definition at line 3199 of file dae_builder_internal.cpp.

3200  {
3201  // No expression provided
3202  return add(name, causality, variability, MX(), opts);
3203 }
Variability variability(size_t ind) const
Get variability.

References causality(), name(), and variability().

Referenced by add(), assign(), eq(), import_model_variables(), reinit(), and when().

◆ add() [3/4]

Variable & casadi::DaeBuilderInternal::add ( const std::string &  name,
Causality  causality,
Variability  variability,
const MX expr,
const Dict opts 
)
protected

Definition at line 3205 of file dae_builder_internal.cpp.

3206  {
3207  // We will require that an independent variable is always added first in the list of variables
3208  if (causality != Causality::INDEPENDENT && n_variables() == 0) {
3209  // Add a default time variable before adding other variables
3211  // Do not categorize in T by default
3212  categorize(t.index, Category::NUMEL);
3213  // Max value if automatically added
3214  t.value_reference = static_cast<unsigned int>(-1);
3215  // Set index to -1 to indicate that it has not (yet) been encountered
3216  orig_time_index_ = -1;
3217  }
3218 
3219  // Default options
3220  std::string description, type, initial, unit, display_unit;
3221  std::vector<casadi_int> dimension = {1};
3222  double min = -casadi::inf, max = casadi::inf, nominal = 1;
3223  std::vector<double> start;
3224  // Read options
3225  for (auto&& op : opts) {
3226  if (op.first=="dimension") {
3227  dimension = op.second.to_int_vector();
3228  } else if (op.first=="description") {
3229  description = op.second.to_string();
3230  } else if (op.first=="unit") {
3231  unit = op.second.to_string();
3232  } else if (op.first=="display_unit") {
3233  display_unit = op.second.to_string();
3234  } else if (op.first=="min") {
3235  min = op.second.to_double();
3236  } else if (op.first=="max") {
3237  max = op.second.to_double();
3238  } else if (op.first=="nominal") {
3239  nominal = op.second.to_double();
3240  } else if (op.first=="start") {
3241  if (op.second.can_cast_to(OT_DOUBLE)) {
3242  start.resize(1, op.second.to_double());
3243  } else {
3244  start = op.second.to_double_vector();
3245  }
3246  } else if (op.first=="type") {
3247  type = op.second.to_string();
3248  } else if (op.first=="initial") {
3249  initial = op.second.to_string();
3250  } else {
3251  casadi_error("No such option: " + op.first);
3252  }
3253  }
3254 
3255  // Independent variable is handled separately, to ensure it's always the first variable
3256  Variable* t_var = nullptr;
3258  if (n_variables() == 0) {
3259  // Independent variable declared as first model variable
3260  orig_time_index_ = 0;
3261  } else {
3262  // Independent variable already declared automatically
3263  casadi_assert(orig_time_index_ == -1, "Only one independent variable is permitted");
3264  orig_time_index_ = n_variables() - 1;
3265  // Pointer to existing time variable
3266  t_var = &variable(0);
3267  // Revert default value reference
3268  t_var->value_reference = 0;
3269  // Update its name, if needed
3270  if (t_var->name != name) {
3271  // Remove old name from varind_
3272  varind_.erase(t_var->name);
3273  // Update Variable instance
3274  t_var->name = name;
3275  t_var->v = casadi::MX::sym(name, t_var->v.sparsity());
3276  // Add new name to varind_
3277  varind_[t_var->name] = t_var->index;
3278  }
3279  }
3280  }
3281 
3282  // Create a new variable or use existing time variable
3283  Variable& v = t_var ? *t_var : new_variable(name, dimension, expr);
3284  v.description = description;
3285  if (!type.empty()) v.type = to_enum<Type>(type);
3286  v.causality = causality;
3287  v.variability = variability;
3288  if (!start.empty()) v.value = v.start = start;
3289  if (!initial.empty()) {
3290  v.initial = to_enum<Initial>(initial);
3291  } else {
3292  v.initial = default_initial(causality, variability);
3293  }
3294  if (!unit.empty()) v.unit = unit;
3295  if (!display_unit.empty()) v.display_unit = display_unit;
3296  if (min != -casadi::inf) v.min = min;
3297  if (max != casadi::inf) v.max = max;
3298  v.nominal = nominal;
3299  // Handle different categories
3300  switch (causality) {
3301  case Causality::PARAMETER:
3302  // Parameter
3304  categorize(v.index, Category::P);
3305  } else if (variability == Variability::FIXED) {
3306  categorize(v.index, Category::C);
3307  } else {
3308  casadi_error("'parameter' causality requires 'fixed' or 'tunable' variability");
3309  }
3310  break;
3313  "'calculatedParameter' causality requires 'fixed' or 'tunable' variability");
3314  categorize(v.index, Category::D);
3315  break;
3316  case Causality::INPUT:
3317  // Control
3318  casadi_assert(variability == Variability::CONTINUOUS
3320  "'input' causality requires 'continuous' or 'discrete' variability");
3321  categorize(v.index, Category::U);
3322  break;
3323  case Causality::OUTPUT:
3324  // Type determined by providing equation, unless discrete variability
3326  // Constant output
3327  categorize(v.index, Category::C);
3328  } else if (variability == Variability::DISCRETE) {
3329  // Discrete variables are considered states with zero derivatives
3331  } else if (variability == Variability::CONTINUOUS) {
3332  // Continuous variables are considered algebraic variables until given a defining equation
3333  categorize(v.index, Category::Z);
3334  } else {
3335  casadi_error("'output' causality requires 'constant', 'continuous' or "
3336  "'discrete' variability");
3337  }
3338  break;
3339  case Causality::LOCAL:
3340  // Type determined by providing equation, unless discrete variability
3342  // Constant local
3343  categorize(v.index, Category::C);
3344  } else if (variability == Variability::DISCRETE) {
3345  // Discrete variables are considered states with zero derivatives
3347  } else if (variability == Variability::CONTINUOUS) {
3348  // Continuous variables are considered algebraic variables until given a defining equation
3349  categorize(v.index, Category::Z);
3351  // Fixed or tunable local
3352  categorize(v.index, Category::D);
3353  } else {
3354  casadi_error("'output' causality requires 'constant', 'fixed', 'tunable', 'discrete' or "
3355  "'continuous' variability");
3356  }
3357  break;
3359  // Independent variable
3360  casadi_assert(variability == Variability::CONTINUOUS,
3361  "Independent variable must be continuous");
3362  categorize(v.index, Category::T);
3363  // Initialize value to start time
3364  v.set_attribute(Attribute::VALUE, start_time_);
3365  break;
3366  default:
3367  casadi_error("Unknown causality: " + to_string(causality));
3368  }
3369  // If an output, add to list of outputs
3370  if (causality == Causality::OUTPUT) indices(Category::Y).push_back(v.index);
3371  // Return variable reference
3372  return v;
3373 }
size_t n_variables() const
Length of variables array.
std::vector< size_t > & indices(Category cat)
Classified variable indices (mutable)
std::unordered_map< std::string, size_t > varind_
Find of variable by name.
Variable & variable(size_t ind)
static Initial default_initial(Causality causality, Variability variability)
Variable & new_variable(const std::string &name, const std::vector< casadi_int > &dimension={1}, const MX &expr=MX())
Create a new variable.
void categorize(size_t ind, Category cat)
Set or change the category for a variable.
static MX sym(const std::string &name, casadi_int nrow=1, casadi_int ncol=1)
Create an nrow-by-ncol symbolic primitive.
std::string description(Category v)
GenericType::Dict Dict
C++ equivalent of Python's dict or MATLAB's struct.
const double inf
infinity
Definition: calculus.hpp:50
std::string to_string(TypeFmi2 v)

References add(), casadi::C, casadi::CALCULATED_PARAMETER, categorize(), casadi::Variable::causality, causality(), casadi::CONSTANT, casadi::CONTINUOUS, casadi::D, default_initial(), casadi::description(), casadi::Variable::description, detect_quad_, casadi::DISCRETE, casadi::Variable::display_unit, casadi::FIXED, casadi::INDEPENDENT, casadi::Variable::index, indices(), casadi::inf, casadi::Variable::initial, casadi::INPUT, casadi::LOCAL, casadi::Variable::max, casadi::Variable::min, n_variables(), casadi::Variable::name, name(), new_variable(), casadi::Variable::nominal, casadi::NUMEL, orig_time_index_, casadi::OT_DOUBLE, casadi::OUTPUT, casadi::P, casadi::PARAMETER, casadi::Q, casadi::Variable::set_attribute(), casadi::MX::sparsity(), casadi::Variable::start, start_time_, casadi::GenericMatrix< MX >::sym(), casadi::T, casadi::to_string(), casadi::TUNABLE, casadi::Variable::type, casadi::U, casadi::Variable::unit, casadi::Variable::v, casadi::VALUE, casadi::Variable::value, casadi::Variable::value_reference, casadi::Variable::variability, variability(), variable(), varind_, casadi::X, casadi::Y, and casadi::Z.

◆ add() [4/4]

Variable& casadi::DaeBuilderInternal::add ( const std::string &  name,
const Dict opts 
)
inlineprotected

Definition at line 612 of file dae_builder_internal.hpp.

612  {
613  // Per FMI 3.0.2 specification, section 2.4.7.4: Default causality is LOCAL
614  return add(name, Causality::LOCAL, opts);
615  }

References casadi::LOCAL.

◆ add_fun() [1/2]

Function casadi::DaeBuilderInternal::add_fun ( const Function f)
protected

Definition at line 4585 of file dae_builder_internal.cpp.

4585  {
4586  casadi_assert(!has_fun(f.name()), "Function '" + f.name() + "' already exists");
4587  fun_.push_back(f);
4588  return f;
4589 }
bool has_fun(const std::string &name) const
Does a particular function already exist?
std::vector< Function > fun_
Functions.

References fun_, has_fun(), and casadi::Function::name().

◆ add_fun() [2/2]

Function casadi::DaeBuilderInternal::add_fun ( const std::string &  name,
const std::vector< std::string > &  arg,
const std::vector< std::string > &  res,
const Dict opts = Dict() 
)
protected

Definition at line 4591 of file dae_builder_internal.cpp.

4593  {
4594  casadi_assert(!has_fun(name), "Function '" + name + "' already exists");
4595 
4596  // Dependent variable definitions
4597  std::vector<MX> wdef = outputs(Category::WDEF);
4598  // Get inputs
4599  std::vector<MX> arg_ex, res_ex;
4600  for (auto&& s : arg) arg_ex.push_back(var(s));
4601  for (auto&& s : res) {
4602  // Find the binding expression FIXME(@jaeandersson)
4603  casadi_int v_ind;
4604  for (v_ind = 0; v_ind < size(Category::W); ++v_ind) {
4605  if (s == variable(indices(Category::W).at(v_ind)).name) {
4606  res_ex.push_back(wdef.at(v_ind));
4607  break;
4608  }
4609  }
4610  casadi_assert(v_ind < size(Category::W), "Cannot find dependent '" + s + "'");
4611  }
4612  Function ret(name, arg_ex, res_ex, arg, res, opts);
4613  return add_fun(ret);
4614 }
Function add_fun(const std::string &name, const std::vector< std::string > &arg, const std::vector< std::string > &res, const Dict &opts=Dict())
Add a function from loaded expressions.
size_t size(Category cat) const
Number of indices with a particular category.
const MX & var(const std::string &name) const
Get variable expression by name.
std::vector< MX > outputs(Category ind) const
std::string name
Name of the variable.

References has_fun(), indices(), casadi::Variable::name, name(), outputs(), size(), var(), variable(), casadi::W, and casadi::WDEF.

◆ add_lc()

void casadi::DaeBuilderInternal::add_lc ( const std::string &  name,
const std::vector< std::string > &  f_out 
)

Definition at line 2304 of file dae_builder_internal.cpp.

2304  {
2305  // Make sure object valid
2306  sanity_check();
2307 
2308  // Make sure name is valid
2309  casadi_assert(!name.empty(), "DaeBuilderInternal::add_lc: \"name\" is empty");
2310  for (std::string::const_iterator i=name.begin(); i!=name.end(); ++i) {
2311  casadi_assert(isalnum(*i),
2312  "DaeBuilderInternal::add_lc: \"name\" must be alphanumeric");
2313  }
2314 
2315  // Consistency checks
2316  casadi_assert(!f_out.empty(), "DaeBuilderInternal::add_lc: Linear combination is empty");
2317  std::vector<bool> in_use(enum_traits<Category>::n_enum, false);
2318  for (casadi_int i=0; i < f_out.size(); ++i) {
2319  auto oind = static_cast<size_t>(to_enum<Category>(f_out[i]));
2320  casadi_assert(!in_use[oind], "DaeBuilderInternal::add_lc: Duplicate expression " + f_out[i]);
2321  in_use[oind] = true;
2322  }
2323 
2324  std::vector<std::string>& ret1 = lc_[name];
2325  if (!ret1.empty()) casadi_warning("DaeBuilderInternal::add_lc: Overwriting " << name);
2326  ret1 = f_out;
2327 }
void sanity_check() const
Check if dimensions match.
Function::AuxOut lc_
Linear combinations of output expressions.

References lc_, name(), and sanity_check().

◆ all() [1/2]

std::vector< std::string > casadi::DaeBuilderInternal::all ( ) const

Definition at line 2026 of file dae_builder_internal.cpp.

2026  {
2027  std::vector<std::string> r;
2028  r.reserve(n_variables());
2029  for (const Variable* v : variables_) r.push_back(v->name);
2030  return r;
2031 }

References n_variables(), and variables_.

◆ all() [2/2]

std::vector< std::string > casadi::DaeBuilderInternal::all ( Category  cat) const

Definition at line 2033 of file dae_builder_internal.cpp.

2033  {
2034  return name(indices(cat));
2035 }

References indices(), and name().

◆ assign()

Variable & casadi::DaeBuilderInternal::assign ( const std::string &  name,
const MX val 
)
protected

Definition at line 3762 of file dae_builder_internal.cpp.

3762  {
3763  // Create a unique name for the reinit variable
3764  std::string assign_name = unique_name("__assign__" + name + "__", true);
3765  // Add a new dependent variable defined by val
3767  val, Dict());
3768  // Classify as assign variable
3769  categorize(v.index, Category::CALCULATED);
3770  v.parent = variable(name).index;
3771  // Return the variable name
3772  return v;
3773 }
std::string unique_name(const std::string &prefix, bool allow_no_prefix=false) const
Find a unique name, with a specific prefix.
casadi_int index
Location in variable vector.

References add(), casadi::CALCULATED, categorize(), casadi::CONTINUOUS, casadi::Variable::index, casadi::LOCAL, name(), casadi::Variable::parent, unique_name(), and variable().

Referenced by import_binding_equations(), import_dynamic_equations(), lift(), load_fmi_description(), and read_expr().

◆ attribute() [1/2]

double casadi::DaeBuilderInternal::attribute ( Attribute  a,
const std::string &  name 
) const
protected

Get by attribute name

Definition at line 4638 of file dae_builder_internal.cpp.

4638  {
4639  double ret;
4640  variable(name).get_attribute(a, &ret);
4641  return ret;
4642 }
void get_attribute(Attribute a, double *val) const

References casadi::Variable::get_attribute(), name(), and variable().

◆ attribute() [2/2]

std::vector< double > casadi::DaeBuilderInternal::attribute ( Attribute  a,
const std::vector< std::string > &  name 
) const
protected

Get by attribute name

Definition at line 4644 of file dae_builder_internal.cpp.

4645  {
4646  // Allocate return
4647  std::vector<double> r;
4648  r.reserve(size(a, name));
4649  // Get contribution from each variable
4650  std::vector<double> r1;
4651  for (const auto& n : name) {
4652  variable(n).get_attribute(a, &r1);
4653  r.insert(r.end(), r1.begin(), r1.end());
4654  }
4655  return r;
4656 }

References casadi::Variable::get_attribute(), name(), size(), and variable().

◆ categorize()

void casadi::DaeBuilderInternal::categorize ( size_t  ind,
Category  cat 
)
protected

Definition at line 3386 of file dae_builder_internal.cpp.

3386  {
3387  // Get variable reference
3388  Variable& v = variable(ind);
3389  // If same category, quick return
3390  if (v.category == cat) return;
3391  // Remove from current category, if any
3392  if (v.category != Category::NUMEL) {
3393  remove(indices(v.category), ind);
3394  v.category = Category::NUMEL;
3395  }
3396  // Add to new category, if any
3397  if (cat != Category::NUMEL) {
3398  std::vector<size_t>& indices = this->indices(cat);
3399  if (is_acyclic(cat)) {
3400  indices.push_back(ind);
3401  } else {
3402  insert(indices, ind);
3403  }
3404  v.category = cat;
3405  }
3406 }
void insert(std::vector< size_t > &v, size_t ind) const
Insert into list of variables, keeping it ordered.
void remove(std::vector< size_t > &v, size_t ind) const
Remove from list of variables.
bool is_acyclic(Category cat)

References casadi::Variable::category, indices(), insert(), casadi::is_acyclic(), casadi::NUMEL, remove(), and variable().

Referenced by add(), assign(), eliminate(), import_dynamic_equations(), import_ls_dae(), import_model_structure(), import_model_variables(), load_fmi_description(), reinit(), set_category(), set_variability(), and when().

◆ category()

Category casadi::DaeBuilderInternal::category ( size_t  ind) const
protected

Definition at line 3523 of file dae_builder_internal.cpp.

3523  {
3524  return variable(ind).category;
3525 }
Category category
CasADi's classification of the variable.

References casadi::Variable::category, and variable().

◆ causality()

Causality casadi::DaeBuilderInternal::causality ( size_t  ind) const
protected

Definition at line 3430 of file dae_builder_internal.cpp.

3430  {
3431  return variable(ind).causality;
3432 }

References casadi::Variable::causality, and variable().

Referenced by add(), default_initial(), default_variability(), import_model_variables(), and set_causality().

◆ cdef()

std::vector< MX > casadi::DaeBuilderInternal::cdef ( ) const
protected

Extra doc: https://github.com/casadi/casadi/wiki/L_2c7

Definition at line 3131 of file dae_builder_internal.cpp.

3131  {
3132  std::vector<MX> ret;
3133  ret.reserve(size(Category::C));
3134  for (size_t c : indices(Category::C)) ret.push_back(variable(variable(c).bind).v);
3135  return ret;
3136 }

References casadi::C, indices(), size(), and variable().

Referenced by oracle().

◆ class_name()

std::string casadi::DaeBuilderInternal::class_name ( ) const
inlineoverridevirtual

Implements casadi::SharedObjectInternal.

Definition at line 233 of file dae_builder_internal.hpp.

233 {return "DaeBuilderInternal";}

◆ clear_cache()

void casadi::DaeBuilderInternal::clear_cache ( ) const
protected

Definition at line 2639 of file dae_builder_internal.cpp.

2639  {
2640  for (bool sx : {false, true}) {
2641  for (bool elim_w : {false, true}) {
2642  for (bool lifted_calls : {false, true}) {
2643  Function& fref = oracle_[sx][elim_w][lifted_calls];
2644  if (!fref.is_null()) fref = Function();
2645  }
2646  }
2647  }
2648  clear_cache_ = false;
2649 }
Function oracle_[2][2][2]
Function oracles (cached)

References clear_cache_, casadi::GenericShared< Shared, Internal >::is_null(), and oracle_.

Referenced by oracle().

◆ compile_fmu()

Dict casadi::DaeBuilderInternal::compile_fmu ( const Dict files,
const Dict opts 
) const

Definition at line 1343 of file dae_builder_internal.cpp.

1343  {
1344  return FmuInternal::compile_fmu(name_, files, opts);
1345 }
static Dict compile_fmu(const std::string &name, const Dict &files, const Dict &opts)
Definition: fmu.cpp:736

References casadi::FmuInternal::compile_fmu(), and name_.

◆ convert_index()

casadi_int casadi::DaeBuilderInternal::convert_index ( casadi_int  index) const
protected

Definition at line 3104 of file dae_builder_internal.cpp.

3104  {
3105  // XML index is 1-based
3106  index--;
3107  // Handle added time variables and time variables in non-first position
3108  if (orig_time_index_ < 0) {
3109  // Adjust for added time variable
3110  index++;
3111  } else if (index == orig_time_index_) {
3112  // Time variable position
3113  index = 0;
3114  } else if (orig_time_index_ > 0) {
3115  // Adjust for time variable not in first position
3116  // Example, orig_time_index_ is 2: [x0:1, x1:2, t:0, x2:3] in XML [t, x0, x1, x2] in variables_
3117  if (index == orig_time_index_) {
3118  index = 0;
3119  } else if (index < orig_time_index_) {
3120  index++;
3121  }
3122  }
3123  // Return index in variables_
3124  return index;
3125 }

References orig_time_index_.

Referenced by import_model_structure(), import_model_variables(), and read_dependencies().

◆ create()

Function casadi::DaeBuilderInternal::create ( const std::string &  fname,
const std::vector< std::string > &  name_in,
const std::vector< std::string > &  name_out,
const Dict opts,
bool  sx,
bool  lifted_calls 
) const

Definition at line 2329 of file dae_builder_internal.cpp.

2331  {
2332  // Are there any '_' in the names?
2333  bool with_underscore = false;
2334  for (const auto *s_io : {&s_in, &s_out}) {
2335  for (const std::string& s : *s_io) {
2336  with_underscore = with_underscore || std::count(s.begin(), s.end(), '_');
2337  }
2338  }
2339  // Model equations in DLL
2340  if (!symbolic_) {
2341  // Cannot lift calls in an FMU
2342  casadi_assert(!lifted_calls, "Lifting requires a symbolic representation");
2343  // Cannot convert to SX
2344  casadi_assert(!sx, "SX expansion requires a symbolic representation");
2345  // Redirect to FmuFunction creation
2346  return fmu_fun(fname, s_in, s_out, opts);
2347  }
2348  // Replace '_' with ':', if needed
2349  if (with_underscore) {
2350  std::vector<std::string> s_in_mod(s_in), s_out_mod(s_out);
2351  for (auto *s_io : {&s_in_mod, &s_out_mod}) {
2352  for (std::string& s : *s_io) std::replace(s.begin(), s.end(), '_', ':');
2353  }
2354  // Recursive call
2355  return create(fname, s_in_mod, s_out_mod, opts, sx, lifted_calls);
2356  }
2357  // Check if dependent variables are given and needed
2358  bool elim_w = false;
2359  if (size(Category::W) > 0) {
2360  // Dependent variables exists, eliminate unless v is given
2361  elim_w = true;
2362  for (const std::string& s : s_in) {
2363  if (s == "w") {
2364  // Dependent variables are given
2365  elim_w = false;
2366  break;
2367  }
2368  }
2369  }
2370  // Are lifted calls really needed?
2371  if (lifted_calls) {
2372  // Consistency check
2373  casadi_assert(!elim_w, "Lifted calls cannot be used if dependent variables are eliminated");
2374  // Only lift calls if really needed
2375  lifted_calls = false;
2376  for (const MX& vdef_comp : outputs(Category::WDEF)) {
2377  if (vdef_comp.is_output()) {
2378  // There are indeed function calls present
2379  lifted_calls = true;
2380  break;
2381  }
2382  }
2383  }
2384  // Call factory without lifted calls
2385  std::string fname_nocalls = lifted_calls ? fname + "_nocalls" : fname;
2386  Function ret = oracle(sx, elim_w, lifted_calls).factory(fname_nocalls, s_in, s_out, lc_);
2387  // If no lifted calls, done
2388  if (!lifted_calls) return ret;
2389  // MX expressions for ret without lifted calls
2390  std::vector<MX> ret_in = ret.mx_in();
2391  std::vector<MX> ret_out = ret(ret_in);
2392  // Offsets in v
2393  std::vector<casadi_int> h_offsets = offset(var(indices(Category::W)));
2394  // Split "w", "lam_wdef" into components
2395  std::vector<MX> v_in, lam_vdef_in;
2396  for (size_t i = 0; i < s_in.size(); ++i) {
2397  if (ret.name_in(i) == "w") {
2398  v_in = vertsplit(ret_in[i], h_offsets);
2399  } else if (ret.name_in(i) == "lam_wdef") {
2400  lam_vdef_in = vertsplit(ret_in[i], h_offsets);
2401  }
2402  }
2403  // Map dependent variables into index in vector
2404  std::map<MXNode*, size_t> v_map;
2405  for (size_t i = 0; i < size(Category::W); ++i) {
2406  v_map[var(Category::W, i).get()] = i;
2407  }
2408  // Definitions of w
2409  std::vector<MX> wdef = outputs(Category::WDEF);
2410  // Collect all the call nodes
2411  std::map<MXNode*, CallIO> call_nodes;
2412  for (size_t vdefind = 0; vdefind < wdef.size(); ++vdefind) {
2413  // Current element handled
2414  const MX& vdefref = wdef.at(vdefind);
2415  // Handle function call nodes
2416  if (vdefref.is_output()) {
2417  // Get function call node
2418  MX c = vdefref.dep(0);
2419  // Find the corresponding call node in the map
2420  auto call_it = call_nodes.find(c.get());
2421  // If first time this call node is encountered
2422  if (call_it == call_nodes.end()) {
2423  // Create new CallIO struct
2424  CallIO cio;
2425  // Save function instance
2426  cio.f = c.which_function();
2427  // Expressions for function call inputs
2428  cio.v.resize(c.n_dep(), -1);
2429  cio.arg.resize(cio.v.size());
2430  for (casadi_int i = 0; i < cio.v.size(); ++i) {
2431  if (c.dep(i).is_constant()) {
2432  cio.arg.at(i) = c.dep(i);
2433  } else {
2434  size_t v_ind = v_map.at(c.dep(i).get());
2435  cio.v.at(i) = v_ind;
2436  cio.arg.at(i) = v_in.at(v_ind);
2437  }
2438  }
2439  // Allocate memory for function call outputs
2440  cio.vdef.resize(c.n_out(), -1);
2441  cio.res.resize(cio.vdef.size());
2442  // Allocate memory for adjoint seeds, if any
2443  if (!lam_vdef_in.empty()) cio.adj1_arg.resize(c.n_out());
2444  // Save to map and update iterator
2445  call_it = call_nodes.insert(std::make_pair(c.get(), cio)).first;
2446  }
2447  // Which output of the function are we calculating?
2448  casadi_int oind = vdefref.which_output();
2449  // Save output expression to structure
2450  call_it->second.vdef.at(oind) = vdefind;
2451  call_it->second.res.at(oind) = v_in.at(vdefind);
2452  // Save adjoint seed to structure, if any
2453  if (!lam_vdef_in.empty()) call_it->second.adj1_arg.at(oind) = lam_vdef_in.at(vdefind);
2454  }
2455  }
2456  // Additional term in jac_vdef_v
2457  for (size_t i = 0; i < ret_out.size(); ++i) {
2458  if (ret.name_out(i) == "jac_wdef_w") {
2459  ret_out.at(i) += jac_vdef_v_from_calls(call_nodes, h_offsets);
2460  }
2461  }
2462  // Additional term in hess_?_v_v where ? is any linear combination containing vdef
2463  MX extra_hess_v_v; // same for all linear combinations, if multiple
2464  for (auto&& e : lc_) {
2465  // Find out of vdef is part of the linear combination
2466  bool has_vdef = false;
2467  for (const std::string& r : e.second) {
2468  if (r == "wdef") {
2469  has_vdef = true;
2470  break;
2471  }
2472  }
2473  // Skip if linear combination does not depend on vdef
2474  if (!has_vdef) continue;
2475  // Search for matching function outputs
2476  for (size_t i = 0; i < ret_out.size(); ++i) {
2477  if (ret.name_out(i) == "hess_" + e.first + "_w_w") {
2478  // Calculate contribution to hess_?_v_v
2479  if (extra_hess_v_v.is_empty())
2480  extra_hess_v_v = hess_v_v_from_calls(call_nodes, h_offsets);
2481  // Add contribution to output
2482  ret_out.at(i) += extra_hess_v_v;
2483  }
2484  }
2485  }
2486  // Assemble modified return function and return
2487  ret = Function(fname, ret_in, ret_out, ret.name_in(), ret.name_out());
2488  return ret;
2489 }
Function create(const std::string &fname, const std::vector< std::string > &name_in, const std::vector< std::string > &name_out, const Dict &opts, bool sx, bool lifted_calls) const
Construct a function object.
const Function & oracle(bool sx=false, bool elim_w=false, bool lifted_calls=false) const
Get the (cached) oracle, SX or MX.
MX hess_v_v_from_calls(std::map< MXNode *, CallIO > &call_nodes, const std::vector< casadi_int > &h_offsets) const
Calculate contribution to hess_?_v_v from lifted calls.
Function fmu_fun(const std::string &fname, const std::vector< std::string > &name_in, const std::vector< std::string > &name_out, const Dict &opts) const
Construct function from an FMU DLL.
MX jac_vdef_v_from_calls(std::map< MXNode *, CallIO > &call_nodes, const std::vector< casadi_int > &h_offsets) const
Calculate contribution to jac_vdef_v from lifted calls.
const MX mx_in(casadi_int ind) const
Get symbolic primitives equivalent to the input expressions.
Definition: function.cpp:1781
Function factory(const std::string &name, const std::vector< std::string > &s_in, const std::vector< std::string > &s_out, const AuxOut &aux=AuxOut(), const Dict &opts=Dict()) const
Definition: function.cpp:2009
MXNode * get() const
Get a const pointer to the node.
Definition: mx.cpp:564

References casadi::DaeBuilderInternal::CallIO::adj1_arg, casadi::DaeBuilderInternal::CallIO::arg, casadi::MX::dep(), casadi::DaeBuilderInternal::CallIO::f, casadi::Function::factory(), casadi::MX::find(), fmu_fun(), casadi::MX::get(), hess_v_v_from_calls(), indices(), casadi::MX::is_constant(), casadi::GenericMatrix< MatType >::is_empty(), casadi::MX::is_output(), jac_vdef_v_from_calls(), lc_, casadi::Function::mx_in(), casadi::MX::n_dep(), casadi::MX::n_out(), casadi::Function::name_in(), casadi::Function::name_out(), oracle(), outputs(), casadi::DaeBuilderInternal::CallIO::res, size(), symbolic_, casadi::DaeBuilderInternal::CallIO::v, var(), casadi::DaeBuilderInternal::CallIO::vdef, casadi::W, casadi::WDEF, casadi::MX::which_function(), and casadi::MX::which_output().

◆ debug_repr()

std::string casadi::GenericSharedInternal< SharedObject , SharedObjectInternal >::debug_repr ( const Internal *  i) const
inherited

Definition at line 62 of file generic_shared_internal.hpp.

175  {
176  // Note: i != this because of something something multiple inheritance
177  return str( (casadi_int)(i)) + "/" + static_cast<const Internal*>(this)->class_name();
178  }
std::string str(const T &v)
String representation, any type.

◆ default_initial()

Initial casadi::DaeBuilderInternal::default_initial ( Causality  causality,
Variability  variability 
)
staticprotected

Definition at line 3172 of file dae_builder_internal.cpp.

3172  {
3173  // According to table in FMI 2.0.2 specification, section 2.2.7
3174  switch (variability) {
3175  case Variability::CONSTANT:
3177  return Initial::EXACT;
3178  break;
3179  case Variability::FIXED:
3180  // Fall-through
3181  case Variability::TUNABLE:
3183  return Initial::EXACT;
3185  return Initial::CALCULATED;
3186  break;
3187  case Variability::DISCRETE:
3188  // Fall-through
3191  return Initial::CALCULATED;
3192  break;
3193  default: break;
3194  }
3195  // Initial value not available
3196  return Initial::NA;
3197 }

References casadi::CALCULATED, casadi::CALCULATED_PARAMETER, causality(), casadi::CONSTANT, casadi::CONTINUOUS, casadi::DISCRETE, casadi::EXACT, casadi::FIXED, casadi::LOCAL, casadi::NA, casadi::OUTPUT, casadi::PARAMETER, casadi::TUNABLE, and variability().

Referenced by add(), and import_model_variables().

◆ default_variability()

Variability casadi::DaeBuilderInternal::default_variability ( Causality  causality,
Type  type 
)
staticprotected

Definition at line 3156 of file dae_builder_internal.cpp.

3156  {
3157  // Default variability per FMI 3.0.2, section 2.4.7.4
3158  // "The default for variables of causality parameter, structural parameter or
3159  // calculated parameter is fixed."
3161  return Variability::FIXED;
3162  }
3163  // "The default for variables of type Float32 and Float64 and causality other
3164  // than parameter, structuralParameter or calculatedParameter is continuous"
3165  if (type == Type::FLOAT32 || type == Type::FLOAT64) {
3166  return Variability::CONTINUOUS;
3167  } else {
3168  return Variability::DISCRETE;
3169  }
3170 }

References casadi::CALCULATED_PARAMETER, causality(), casadi::CONTINUOUS, casadi::DISCRETE, casadi::FIXED, casadi::FLOAT32, casadi::FLOAT64, and casadi::PARAMETER.

Referenced by add(), and import_model_variables().

◆ dependent_fun()

Function casadi::DaeBuilderInternal::dependent_fun ( const std::string &  fname,
const std::vector< std::string > &  s_in,
const std::vector< std::string > &  s_out 
) const

Definition at line 2867 of file dae_builder_internal.cpp.

2869  {
2870  // Are we calculating d and/or w
2871  bool calc_d = false, calc_w = false;
2872  // Convert outputs to enums
2873  std::vector<Category> v_out;
2874  v_out.reserve(v_out.size());
2875  for (const std::string& s : s_out) {
2876  Category e = to_enum<Category>(s);
2877  if (e == Category::D) {
2878  calc_d = true;
2879  } else if (e == Category::W) {
2880  calc_w = true;
2881  } else {
2882  casadi_error("Can only calculate d and/or w");
2883  }
2884  v_out.push_back(e);
2885  }
2886  // Consistency check
2887  casadi_assert(calc_d || calc_w, "Nothing to calculate");
2888  // Convert inputs to enums
2889  std::vector<Category> v_in;
2890  v_in.reserve(v_in.size());
2891  for (const std::string& s : s_in) {
2892  Category e = to_enum<Category>(s);
2893  if (calc_d && e == Category::D) casadi_error("'d' cannot be both input and output");
2894  if (calc_w && e == Category::W) casadi_error("'w' cannot be both input and output");
2895  v_in.push_back(e);
2896  }
2897  // Collect input expressions
2898  std::vector<MX> f_in;
2899  f_in.reserve(s_in.size());
2900  for (Category v : v_in) f_in.push_back(vertcat(inputs(v)));
2901  // Collect output expressions
2902  std::vector<MX> f_out;
2903  f_out.reserve(s_out.size());
2904  for (Category v : v_out) f_out.push_back(vertcat(inputs(v)));
2905  // Variables to be substituted
2906  std::vector<MX> dw, dwdef;
2907  if (calc_d) {
2908  std::vector<MX> d = var(indices(Category::D));
2909  dw.insert(dw.end(), d.begin(), d.end());
2910  std::vector<MX> ddef = outputs(Category::DDEF);
2911  dwdef.insert(dwdef.end(), ddef.begin(), ddef.end());
2912  }
2913  if (calc_w) {
2914  std::vector<MX> w = var(indices(Category::W));
2915  dw.insert(dw.end(), w.begin(), w.end());
2916  std::vector<MX> wdef = outputs(Category::WDEF);
2917  dwdef.insert(dwdef.end(), wdef.begin(), wdef.end());
2918  }
2919  // Perform elimination
2920  substitute_inplace(dw, dwdef, f_out);
2921  // Assemble return function
2922  return Function(fname, f_in, f_out, s_in, s_out);
2923 }
std::vector< MX > inputs(Category ind) const

References casadi::D, casadi::DDEF, indices(), inputs(), outputs(), var(), casadi::W, and casadi::WDEF.

◆ der() [1/2]

MX casadi::DaeBuilderInternal::der ( const MX var) const

Definition at line 2115 of file dae_builder_internal.cpp.

2115  {
2116  return const_cast<DaeBuilderInternal*>(this)->der(var, false);
2117 }
MX der(const MX &var) const
Get a derivative expression by non-differentiated expression (const, never create)
DaeBuilderInternal(const std::string &name, const std::string &path, const Dict &opts)
Constructor.

References var().

Referenced by der(), disp(), generate_model_structure(), generate_wrapper(), import_dynamic_equations(), lift(), and update_dependencies().

◆ der() [2/2]

MX casadi::DaeBuilderInternal::der ( const MX var,
bool  may_allocate = true 
)

Definition at line 2119 of file dae_builder_internal.cpp.

2119  {
2120  // Must be a vector
2121  casadi_assert(var.is_column(), "Input expression must be a vector");
2122  // Quick return if symbolic variable
2123  if (var.is_symbolic()) return get_der(find(var), may_allocate);
2124  // If a vertical concatenation
2125  if (var.is_valid_input()) {
2126  // Differentiate each primitive
2127  auto var_split = var.primitives();
2128  for (MX& s : var_split) s = der(s, may_allocate);
2129  // Return the concatenation
2130  return var.join_primitives(var_split);
2131  }
2132  // Handle general case: Get dependent symbolic primitives
2133  std::vector<MX> dep = symvar(var);
2134  // Get derivatives of dependent symbolic primitives
2135  std::vector<MX> dep_der;
2136  for (size_t ind : find(dep)) dep_der.push_back(get_der(ind, may_allocate));
2137  // Forward directional derivative to get time derivative:
2138  // dot(var) = d_var/d_dep * dot(dep)
2139  std::vector<std::vector<MX>> r = {dep_der};
2140  r = forward(std::vector<MX>{var}, dep, r);
2141  casadi_assert_dev(r.size() == 1);
2142  return vertcat(r.at(0));
2143 }
MX get_der(size_t ind) const
Get a derivative expression by variable index (const, never create)
size_t find(const std::string &name) const
Get index of variable, given name.
bool is_column() const
Check if the matrix is a column vector (i.e. size2()==1)
bool is_valid_input() const
Check if matrix can be used to define function inputs.
Definition: mx.cpp:954
std::vector< MX > primitives() const
Get primitives.
Definition: mx.cpp:962
MX join_primitives(const std::vector< MX > &v) const
Join an expression along symbolic primitives.
Definition: mx.cpp:994
bool is_symbolic() const
Check if symbolic.
Definition: mx.cpp:795

References der(), find(), get_der(), casadi::GenericMatrix< MatType >::is_column(), casadi::MX::is_symbolic(), casadi::MX::is_valid_input(), casadi::MX::join_primitives(), casadi::MX::primitives(), and var().

◆ destroySingleton()

void casadi::GenericSharedInternal< SharedObject , SharedObjectInternal >::destroySingleton ( )
inlineprotectedinherited

Called in the destructor of singletons

Definition at line 77 of file generic_shared_internal.hpp.

77  {
78  static_cast<Internal*>(this)->count--;
79  }

◆ disp()

void casadi::DaeBuilderInternal::disp ( std::ostream &  stream,
bool  more 
) const
overridevirtual

Implements casadi::SharedObjectInternal.

Definition at line 1659 of file dae_builder_internal.cpp.

1659  {
1660  // Assert correctness
1661  if (more) sanity_check();
1662 
1663  // Print dimensions
1664  stream << "nt = " << size(Category::T) << ", "
1665  << "nx = " << size(Category::X) << ", "
1666  << "nz = " << size(Category::Z) << ", "
1667  << "nq = " << size(Category::Q) << ", "
1668  << "ny = " << size(Category::Y) << ", "
1669  << "np = " << size(Category::P) << ", "
1670  << "nc = " << size(Category::C) << ", "
1671  << "nd = " << size(Category::D) << ", "
1672  << "nw = " << size(Category::W) << ", "
1673  << "nu = " << size(Category::U);
1674 
1675  // Quick return?
1676  if (!more) return;
1677  stream << std::endl;
1678 
1679  // Print the functions
1680  if (!fun_.empty()) {
1681  stream << "Functions:" << std::endl;
1682  for (const Function& f : fun_) {
1683  stream << " " << f << std::endl;
1684  }
1685  }
1686 
1687  // Print the variables, including outputs
1688  stream << "Model variables:" << std::endl;
1691  if (size(cat) > 0) {
1692  stream << " " << to_string(cat) << " = " << var(indices(cat)) << std::endl;
1693  }
1694  }
1695 
1696  // All variables that can have dependent variables
1697  for (Category cat : {Category::C, Category::D, Category::W}) {
1698  if (size(cat) > 0) {
1699  stream << "List of " << description(cat) << "s (" << to_string(cat) << "):" << std::endl;
1700  for (size_t c : indices(cat)) {
1701  const Variable& v = variable(c);
1702  stream << " " << v.name;
1703  if (v.bind >= 0) stream << " := " << variable(v.bind).v;
1704  stream << std::endl;
1705  }
1706  }
1707  }
1708 
1709  // Print derivatives
1710  for (Category cat : {Category::T, Category::X, Category::Q}) {
1711  if (size(cat) > 0) {
1712  if (cat == Category::T && indices(cat).front() == 0) continue; // skip if trivial
1713  stream << "Time derivatives of " << description(cat) << "s (" << to_string(cat) << "):"
1714  << std::endl;
1715  for (size_t k : indices(cat)) {
1716  const Variable& v = variable(k);
1717  stream << " " << v.name << ": " << der(v.v) << std::endl;
1718  }
1719  }
1720  }
1721 
1722  // Outputs
1723  if (size(Category::Y) > 0) {
1724  stream << "Outputs (y):" << std::endl;
1725  for (size_t k : indices(Category::Y)) {
1726  const Variable& v = variable(k);
1727  stream << " " << v.name << ": " << v.v << std::endl;
1728  }
1729  }
1730 
1731  if (size(Category::ALG) > 0) {
1732  stream << "Algebraic equations:" << std::endl;
1733  for (size_t k : indices(Category::ALG)) {
1734  stream << " 0 == " << variable(k).v << std::endl;
1735  }
1736  }
1737 
1738  if (!init_.empty()) {
1739  stream << "Initial equations:" << std::endl;
1740  for (size_t k : init_) {
1741  const Variable& v = variable(k);
1742  stream << " " << v.name;
1743  if (!v.ieq.is_empty()) stream << " := " << v.ieq;
1744  stream << std::endl;
1745  }
1746  }
1747 
1748  if (!when_.empty()) {
1749  stream << "When equations:" << std::endl;
1750  for (auto weq : when_) {
1751  stream << " when " << variable(weq.first).v << " < 0 : " << std::endl;
1752  for (size_t eq : weq.second) {
1753  auto v = variable(eq).parent;
1754  stream << " " << variable(v).name << " := " << variable(eq).v << std::endl;
1755  }
1756  }
1757  }
1758 }
std::vector< std::pair< size_t, std::vector< size_t > > > when_
void eq(const MX &lhs, const MX &rhs, const Dict &opts)
Add a simple equation.
MX v
Variable expression (always a vector)

References casadi::ALG, casadi::Variable::bind, casadi::C, casadi::D, der(), casadi::description(), eq(), fun_, casadi::Variable::ieq, indices(), init_, casadi::GenericMatrix< MatType >::is_empty(), casadi::Variable::name, casadi::P, casadi::Variable::parent, casadi::Q, sanity_check(), size(), casadi::T, casadi::to_string(), casadi::U, casadi::Variable::v, var(), variable(), casadi::W, when_, casadi::X, casadi::Y, and casadi::Z.

Referenced by import_binding_equations(), import_dynamic_equations(), and import_initial_equations().

◆ eliminate()

void casadi::DaeBuilderInternal::eliminate ( Category  cat)

Definition at line 2156 of file dae_builder_internal.cpp.

2156  {
2157  // Eliminate quadratures
2158  if (cat == Category::Q) {
2159  for (size_t q : indices(cat)) set_category(q, Category::X);
2160  return;
2161  }
2162 
2163  // Assume dependent variable (c, d, w)
2164  casadi_assert(is_acyclic(cat), "Elimination not supported for category " + to_string(cat));
2165 
2166  // Quick return if no dependent variables
2167  if (size(cat) == 0) return;
2168  // Clear cache after this
2169  clear_cache_ = true;
2170  // Ensure variables are sorted
2171  sort(cat);
2172  // Expressions where the variables are also being used
2173  std::vector<MX> ex;
2174  for (const Variable* v : variables_) {
2175  if (!v->v.is_constant()) ex.push_back(v->v);
2176  }
2177  // Perform elimination
2178  std::vector<size_t> ind = indices(cat);
2179  std::vector<MX> v = var(ind);
2180  std::vector<MX> vdef = outputs(dependent_definition(cat));
2181  substitute_inplace(v, vdef, ex);
2182  // Replace binding equations
2183  auto it = ex.begin();
2184  for (Variable* v : variables_) {
2185  if (!v->v.is_constant()) v->v = *it++;
2186  }
2187  // Consistency check
2188  casadi_assert_dev(it == ex.end());
2189  // Reclassify as calculated variables
2190  for (size_t k : ind) {
2192  }
2193 }
void sort(Category cat)
Sort all variables of a category.
void set_category(size_t ind, Category cat)
Set category.
Category dependent_definition(Category cat)

References casadi::CALCULATED, categorize(), clear_cache_, casadi::dependent_definition(), indices(), casadi::is_acyclic(), outputs(), casadi::Q, set_category(), size(), sort(), casadi::to_string(), var(), variable(), variables_, and casadi::X.

◆ eq()

void casadi::DaeBuilderInternal::eq ( const MX lhs,
const MX rhs,
const Dict opts 
)
protected

Definition at line 3597 of file dae_builder_internal.cpp.

3597  {
3598  // Read options
3599  for (auto&& op : opts) {
3600  casadi_error("No such option: " + op.first);
3601  }
3602  // Make sure vectors
3603  casadi_assert(lhs.is_column(), "Left-hand-side must be a column vector");
3604  casadi_assert(rhs.is_column(), "Right-hand-side must be a column vector");
3605  // Make sure dense
3606  if (!lhs.is_dense()) {
3607  eq(densify(lhs), rhs, opts);
3608  return;
3609  }
3610  if (!rhs.is_dense()) {
3611  eq(lhs, densify(rhs), opts);
3612  return;
3613  }
3614  // Make sure dimensions agree
3615  if (lhs.size1() != rhs.size1()) {
3616  // Handle mismatching dimnensions by recursion
3617  if (lhs.size1() == 1 && rhs.size1() > 1) {
3618  eq(repmat(lhs, rhs.size1()), rhs, opts);
3619  return;
3620  } else if (lhs.size1() > 1 && rhs.size1() == 1) {
3621  eq(lhs, repmat(rhs, lhs.size1()), opts);
3622  return;
3623  } else {
3624  casadi_error("Mismatched dimensions: " + str(lhs.size1()) + " vs " + str(rhs.size1()));
3625  }
3626  }
3627  // Make sure right-hand-side only depends on known model variables
3628  std::vector<size_t> rhs_vars = find(symvar(rhs));
3629  // If right-hand-side contains a time derivative that hasn't been defined yet,
3630  // add a new algebraic variable der_x and the ODE "der(x) = der_x"
3631  // This ensures that the DAE stays in semi-explicit form
3632  for (size_t rhs : rhs_vars) {
3633  Variable& v = variable(rhs);
3634  if (v.category == Category::Z && v.parent >= 0) {
3635  // Find the corresponding state variable
3636  Variable& x = variable(v.parent);
3637  // The "parent" attribute is used in some other cases, like assignments
3638  casadi_assert(x.der == v.index, "Cannot handle right-hand-side variable: " + v.name);
3639  // Create a new algebraic variable der_{name}, to distinguish from der({name})
3640  Variable& der_x = add(unique_name("der_" + x.name, true),
3642  {{"dimension", {x.dimension}}});
3643  // Add the trivial ODE
3644  eq(x.get_der(*this), der_x.v, Dict());
3645  }
3646  }
3647  // Try to honor a == b as an explicit equation
3648  if (lhs.is_valid_input()) {
3649  // Explicit equation
3650  if (lhs.is_symbolic()) {
3651  // Regular symbolic: Find the variable
3652  Variable& v = variable(lhs);
3653  // Set the binding equation
3654  if (v.has_beq()) {
3655  // Treat as implicit equation via recursion
3656  eq(MX::zeros(lhs.sparsity()), lhs - rhs, opts);
3657  return;
3658  } else {
3659  // Set the binding equation
3660  Variable& beq = assign(v.name, rhs);
3661  v.bind = beq.index;
3662  }
3663  // (Re)classify variables
3664  if (v.parent >= 0) {
3665  // Derivative variable is being set - find the corresponding state variable
3666  Variable& x = variable(v.parent);
3667  // The "parent" attribute is used in some other cases, like assignments
3668  casadi_assert(x.der == v.index, "Cannot handle left-hand-side: " + str(lhs));
3669  // Reclassify as a differential state and derivative as a dependent variable
3670  if (x.category == Category::Z) {
3671  // Not previously used: Reclassify as differential state
3672  categorize(x.index, detect_quad_ && !x.in_rhs ? Category::Q : Category::X);
3673  categorize(v.index, Category::W);
3674  } else if (x.category == Category::W) {
3675  // Already given a defining equation: Create a new dependent variable and use this
3676  // for the previous definition
3677  Variable& def_x = add(unique_name("def_" + x.name, true),
3679  {{"dimension", {x.dimension}}});
3680  categorize(def_x.index, Category::W);
3681  def_x.bind = x.bind;
3682  // We can now reclassify x as a differential state
3683  x.bind = -1;
3684  categorize(x.index, Category::X);
3685  categorize(v.index, Category::W);
3686  // Add a new implicit equation: 0 == x - def_x
3688  x.v - def_x.v, {{"dimension", x.dimension}});
3689  categorize(alg.index, Category::CALCULATED);
3690  indices(Category::ALG).push_back(alg.index);
3691  } else {
3692  casadi_error("Unexpected category for " + x.name + ": " + to_string(x.category));
3693  }
3694  } else if (v.category == Category::Z) {
3695  // Reclassify as dependent variable
3696  categorize(v.index, Category::W);
3697  } else {
3698  casadi_error("Cannot handle left-hand-side: " + str(lhs) + " of category '"
3699  + to_string(v.category) + "'");
3700  }
3701  } else {
3702  // Concatenation: Split into primitives
3703  auto lhs_split = lhs.primitives();
3704  std::vector<MX> rhs_split = lhs.split_primitives(rhs);
3705  // Call recursively
3706  for (size_t k = 0; k < lhs_split.size(); ++k) {
3707  eq(lhs_split.at(k), rhs_split.at(k), opts);
3708  }
3709  return;
3710  }
3711  } else {
3712  // Implicit equation: Create residual variable
3714  lhs - rhs, {{"dimension", std::vector<casadi_int>{lhs.size1()}}});
3715  categorize(alg.index, Category::CALCULATED);
3716  indices(Category::ALG).push_back(alg.index);
3717  }
3718  // Do not allow any quadrature states in the right-hand-sides
3719  for (size_t rhs : rhs_vars) {
3720  Variable& v = variable(rhs);
3721  if (!v.in_rhs) {
3722  v.in_rhs = true;
3723  if (v.category == Category::Q) categorize(v.index, Category::X);
3724  }
3725  }
3726 }
Variable & assign(const std::string &name, const MX &val)
Assignment inside when-equations or if-else equations.
static MX zeros(casadi_int nrow=1, casadi_int ncol=1)
Create a dense matrix or a matrix with specified sparsity with all entries zero.

References add(), casadi::Variable::category, casadi::CONTINUOUS, casadi::Variable::der, find(), casadi::Variable::index, casadi::GenericMatrix< MatType >::is_column(), casadi::GenericMatrix< MatType >::is_dense(), casadi::LOCAL, casadi::Variable::name, casadi::Variable::parent, casadi::GenericMatrix< MatType >::size1(), casadi::str(), unique_name(), variable(), and casadi::Z.

Referenced by disp(), import_binding_equations(), import_dynamic_equations(), import_initial_equations(), load_fmi_description(), transition(), and when().

◆ export_fmu()

Dict casadi::DaeBuilderInternal::export_fmu ( const Dict opts) const

Definition at line 1234 of file dae_builder_internal.cpp.

1234  {
1235  // Default options
1236  bool no_warning = false;
1237  bool with_serialization = true;
1238  for (auto&& op : opts) {
1239  if (op.first == "no_warning") {
1240  no_warning = op.second;
1241  } else if (op.first == "with_serialization") {
1242  with_serialization = op.second;
1243  } else {
1244  casadi_error("No such option: " + op.first);
1245  }
1246  }
1247  // Feature incomplete
1248  if (!no_warning) casadi_warning("FMU generation is experimental and incomplete")
1249  // GUID
1250  std::string guid = generate_guid();
1251  // Generate model function
1252  std::string dae_filename = name_;
1253  casadi_assert(size(Category::Q) == 0, "Not implemented");
1254  Function dae = shared_from_this<DaeBuilder>().create(dae_filename,
1255  {"t", "x", "z", "p", "u"}, {"ode", "alg", "y", "zero"});
1256  // Event transition function, if needed
1257  Function tfun;
1258  if (size(Category::ZERO) > 0) tfun = transition("transition_" + name_);
1259  // Generate C code for model equations
1260  Dict codegen_opts;
1261  codegen_opts["with_header"] = true;
1262  CodeGenerator gen(dae_filename, codegen_opts);
1263  gen.add(dae);
1264  gen.add(dae.forward(1));
1265  gen.add(dae.reverse(1));
1266  if (!tfun.is_null()) gen.add(tfun);
1267  // Source files
1268  std::vector<std::string> sources;
1269  sources.push_back(gen.generate());
1270  sources.push_back(dae_filename + ".h");
1271  // Make sure dependencies are up-to-date
1273  // Generate FMU wrapper file
1274  sources.push_back(generate_wrapper(guid, gen));
1275  // Generate build description
1276  sources.push_back(generate_build_description(sources));
1277  // Return object
1278  Dict ret;
1279  for (const std::string& s : sources) ret[s] = "sources/" + s;
1280  // Generate modelDescription file
1281  ret[generate_model_description(guid)] = "./modelDescription.xml";
1282 
1283  // Serialize expressions
1284  if (with_serialization) {
1285  // Layered standard for serialized CasADi
1286  std::string serialization_ls = "org.casadi.fmi-ls-serialization";
1287  // Serialized oracle
1288  std::string oracle_filename = "oracle.casadi";
1289  shared_from_this<DaeBuilder>().oracle().save(oracle_filename);
1290  ret[oracle_filename] = "extra/" + serialization_ls + "/" + oracle_filename;
1291  // Manifest file for serialized expressions
1292  XmlNode r;
1293  r.name = "fmiLayeredStandardManifest";
1294  r.set_attribute("fmi-ls:fmi-ls-name", serialization_ls);
1295  r.set_attribute("fmi-ls:fmi-ls-version", "1.0.0");
1296  r.set_attribute("fmi-ls:fmi-ls-description",
1297  "Layered standard for serialized CasADi expressions in FMU");
1298  XmlNode manifest;
1299  manifest.children.push_back(r);
1300  // Export and add to return
1301  XmlFile xml_file("tinyxml");
1302  std::string manifest_filename = serialization_ls + ".fmi-ls-manifest.xml";
1303  xml_file.dump(manifest_filename, manifest);
1304  ret[manifest_filename] = "extra/" + serialization_ls + "/fmi-ls-manifest.xml";
1305  }
1306  // LS-DAE
1307  if (size(Category::Z) > 0) {
1308  // Layered standard for DAE
1309  std::string dae_ls = "org.fmi-standard.fmi-ls-dae";
1310  // Manifest file for serialized expressions
1311  XmlNode r;
1312  r.name = "fmiLayeredStandardManifest";
1313  r.set_attribute("fmi-ls:fmi-ls-name", dae_ls);
1314  r.set_attribute("fmi-ls:fmi-ls-version", "");
1315  r.set_attribute("fmi-ls:fmi-ls-description",
1316  "Layered standard for DAE support in FMU");
1317  // Algebraic variables
1318  XmlNode a;
1319  a.name = "AlgebraicVariables";
1320  for (size_t i : indices(Category::Z)) {
1321  XmlNode v;
1322  v.name = "AlgebraicVariable";
1323  v.set_attribute("valueReference",
1324  static_cast<casadi_int>(variable(i).value_reference));
1325  a.children.push_back(v);
1326  }
1327  r.children.push_back(a);
1328  // Modified model structure
1329  r.children.push_back(generate_model_structure(true));
1330  // Finish manifest file
1331  XmlNode manifest;
1332  manifest.children.push_back(r);
1333  // Export and add to return
1334  XmlFile xml_file("tinyxml");
1335  std::string manifest_filename = dae_ls + ".fmi-ls-manifest.xml";
1336  xml_file.dump(manifest_filename, manifest);
1337  ret[manifest_filename] = "extra/" + dae_ls + "/fmi-ls-manifest.xml";
1338  }
1339  // Return list of files
1340  return ret;
1341 }
Function transition(const std::string &fname, casadi_int index, bool dummy_index_input=false) const
Construct a function describing transition at a specific event.
void update_dependencies() const
Update model variable dependencies.
std::string generate_wrapper(const std::string &guid, const CodeGenerator &gen) const
Generate FMU wrapper file (fmi3Functions.c)
XmlNode generate_model_structure(bool dae=false) const
Generate FMU ModelStructure.
std::string generate_build_description(const std::vector< std::string > &cfiles) const
Generate buildDescription.xml.
std::string generate_model_description(const std::string &guid) const
Generate modelDescription.xml.
B shared_from_this()
Get a shared object from the current internal object.
Definition: sx_elem.cpp:508

References casadi::CodeGenerator::add(), casadi::XmlNode::children, casadi::Function::create(), casadi::XmlFile::dump(), casadi::Function::forward(), casadi::CodeGenerator::generate(), generate_build_description(), generate_guid(), generate_model_description(), generate_model_structure(), generate_wrapper(), indices(), casadi::GenericShared< Shared, Internal >::is_null(), casadi::XmlNode::name, name_, casadi::Q, casadi::Function::reverse(), casadi::XmlNode::set_attribute(), size(), transition(), update_dependencies(), variable(), casadi::Z, and casadi::ZERO.

◆ find() [1/4]

size_t casadi::DaeBuilderInternal::find ( const MX v) const

Definition at line 4551 of file dae_builder_internal.cpp.

4551  {
4552  // Make sure it is a valid input
4553  casadi_assert(v.is_symbolic(), "Variable must be symbolic");
4554  // Find the prospective variable
4555  size_t ind = find(v.name());
4556  // Make sure that the expression (not just the name) is correct
4557  casadi_assert(is_equal(v, variables_.at(ind)->v),
4558  "Variable \"" + v.name() + "\" has mismatching symbolic expression");
4559  // Return index
4560  return ind;
4561 }
bool is_equal(double x, double y, casadi_int depth=0)
Definition: calculus.hpp:287

References find(), casadi::is_equal(), casadi::MX::is_symbolic(), casadi::MX::name(), and variables_.

◆ find() [2/4]

size_t casadi::DaeBuilderInternal::find ( const std::string &  name) const

Definition at line 4545 of file dae_builder_internal.cpp.

4545  {
4546  auto it = varind_.find(name);
4547  casadi_assert(it != varind_.end(), "No such variable: \"" + name + "\".");
4548  return it->second;
4549 }

References name(), and varind_.

Referenced by der(), eq(), find(), fmu_fun(), load_fmi_description(), sort(), sort_z(), and tear().

◆ find() [3/4]

std::vector< size_t > casadi::DaeBuilderInternal::find ( const std::vector< MX > &  v) const

Definition at line 4569 of file dae_builder_internal.cpp.

4569  {
4570  std::vector<size_t> r(v.size());
4571  for (size_t i = 0; i < r.size(); ++i) r[i] = find(v[i]);
4572  return r;
4573 }

References find().

◆ find() [4/4]

std::vector< size_t > casadi::DaeBuilderInternal::find ( const std::vector< std::string > &  name) const

Definition at line 4563 of file dae_builder_internal.cpp.

4563  {
4564  std::vector<size_t> r(name.size());
4565  for (size_t i = 0; i < r.size(); ++i) r[i] = find(name[i]);
4566  return r;
4567 }

References find(), and name().

◆ fmu_fun()

Function casadi::DaeBuilderInternal::fmu_fun ( const std::string &  fname,
const std::vector< std::string > &  name_in,
const std::vector< std::string > &  name_out,
const Dict opts 
) const

Definition at line 2996 of file dae_builder_internal.cpp.

2999  {
3000  // Iterator for options lookup
3001  Dict::const_iterator it;
3002  // Scheme inputs
3003  std::vector<std::string> scheme_in;
3004  bool has_in = false;
3005  it = opts.find("scheme_in");
3006  if (it != opts.end()) {
3007  try {
3008  scheme_in = it->second;
3009  } catch (std::exception& e) {
3010  casadi_error(std::string("Cannot read 'scheme_in': ") + e.what());
3011  }
3012  has_in = true;
3013  }
3014 
3015  // Scheme outputs
3016  std::vector<std::string> scheme_out;
3017  bool has_out = false;
3018  it = opts.find("scheme_out");
3019  if (it != opts.end()) {
3020  try {
3021  scheme_out = it->second;
3022  has_out = true;
3023  } catch (std::exception& e) {
3024  casadi_error(std::string("Cannot read 'scheme_out': ") + e.what());
3025  }
3026  }
3027  // If scheme_in and/or scheme_out not provided, identify from name_in, name_out
3028  if (!has_in || !has_out) {
3029  FmuFunction::identify_io(has_in ? nullptr : &scheme_in,
3030  has_out ? nullptr : &scheme_out, name_in, name_out);
3031  }
3032  // IO scheme
3033  std::map<std::string, std::vector<size_t>> scheme;
3034  it = opts.find("scheme");
3035  if (it != opts.end()) {
3036  try {
3037  // Argument is a Dict
3038  Dict scheme_dict = it->second;
3039  // Convert indices
3040  for (auto&& e : scheme_dict) {
3041  std::vector<std::string> v = e.second;
3042  scheme[e.first] = find(v);
3043  }
3044  } catch (std::exception& e) {
3045  casadi_error(std::string("Cannot read 'scheme': ") + e.what());
3046  }
3047  } else {
3048  // Initialize all scheme entries
3049  for (auto&& s : dyn_in()) scheme[s] = std::vector<size_t>();
3050  for (auto&& s : dyn_out()) scheme[s] = std::vector<size_t>();
3051  // Default IO scheme
3052  scheme["t"] = indices(Category::T);
3053  scheme["x"] = indices(Category::X);
3054  scheme["u"] = indices(Category::U);
3055  scheme["z"] = indices(Category::Z);
3056  scheme["p"] = indices(Category::P);
3057  scheme["ode"] = indices(Category::X);
3058  for (size_t& i : scheme["ode"]) i = variable(i).der;
3059  scheme["quad"] = indices(Category::Q);
3060  for (size_t& i : scheme["quad"]) i = variable(i).der;
3061  scheme["alg"] = indices(Category::ALG);
3062  scheme["y"] = indices(Category::Y);
3063  }
3064  // Auxilliary variables, if any
3065  std::vector<std::string> aux;
3066  it = opts.find("aux");
3067  if (it != opts.end()) {
3068  try {
3069  aux = it->second;
3070  } catch (std::exception& e) {
3071  casadi_error(std::string("Cannot read 'aux': ") + e.what());
3072  }
3073  }
3074  // New FMU instance (to be shared between derivative functions)
3075  Fmu fmu(name, fmi_major_ >= 3 ? FmuApi::FMI3 : FmuApi::FMI2, this,
3076  scheme_in, scheme_out, scheme, aux);
3077 
3078  // Crete new function
3079  return Function::create(new FmuFunction(name, fmu, name_in, name_out), opts);
3080 }
static void identify_io(std::vector< std::string > *scheme_in, std::vector< std::string > *scheme_out, const std::vector< std::string > &name_in, const std::vector< std::string > &name_out)
static Function create(FunctionInternal *node)
Create from node.
Definition: function.cpp:488
std::vector< std::string > dyn_out()
Get output scheme of a DAE function.
Definition: integrator.cpp:236
std::vector< std::string > dyn_in()
Get input scheme of a DAE function.
Definition: integrator.cpp:232

References casadi::ALG, casadi::Function::create(), casadi::Variable::der, casadi::dyn_in(), casadi::dyn_out(), find(), casadi::FMI2, casadi::FMI3, fmi_major_, FmuFunction, casadi::FmuFunction::identify_io(), indices(), name(), casadi::P, casadi::Q, casadi::T, casadi::U, variable(), casadi::X, casadi::Y, and casadi::Z.

Referenced by create().

◆ fun()

Function casadi::DaeBuilderInternal::fun ( const std::string &  name) const
protected

Definition at line 4623 of file dae_builder_internal.cpp.

4623  {
4624  casadi_assert(has_fun(name), "No such function: '" + name + "'");
4625  for (const Function& f : fun_) {
4626  if (f.name()==name) return f;
4627  }
4628  return Function();
4629 }

References fun_, has_fun(), and name().

◆ gather_eq()

Function casadi::DaeBuilderInternal::gather_eq ( ) const

Definition at line 3082 of file dae_builder_internal.cpp.

3082  {
3083  // Output expressions
3084  std::vector<MX> f_out;
3085  // Names of outputs
3086  std::vector<std::string> f_out_name;
3087  // Get all expressions
3088  for (Category cat : output_categories()) {
3089  std::vector<MX> v = outputs(cat);
3090  if (!v.empty()) {
3091  f_out.push_back(vertcat(v));
3092  f_out_name.push_back(to_string(cat));
3093  }
3094  }
3095  // Construct function
3096  return Function("all_eq", {}, f_out, {}, f_out_name, {{"allow_free", true}});
3097 }
std::vector< Category > output_categories()

References casadi::output_categories(), outputs(), and casadi::to_string().

◆ generate() [1/2]

std::string casadi::DaeBuilderInternal::generate ( const std::vector< double > &  v)
static

Import existing problem from FMI/XML

Definition at line 1374 of file dae_builder_internal.cpp.

1374  {
1375  std::stringstream ss;
1376  ss << "{";
1377  bool first = true;
1378  for (double e : v) {
1379  // Separator
1380  if (!first) ss << ", ";
1381  first = false;
1382  // Print element
1383  ss << std::scientific << std::setprecision(std::numeric_limits<double>::digits10 + 1) << e;
1384  }
1385  ss << "}";
1386  return ss.str();
1387 }

◆ generate() [2/2]

std::string casadi::DaeBuilderInternal::generate ( const std::vector< size_t > &  v)
static

Helper function: generate constants

Definition at line 1359 of file dae_builder_internal.cpp.

1359  {
1360  std::stringstream ss;
1361  ss << "{";
1362  bool first = true;
1363  for (double e : v) {
1364  // Separator
1365  if (!first) ss << ", ";
1366  first = false;
1367  // Print element
1368  ss << e;
1369  }
1370  ss << "}";
1371  return ss.str();
1372 }

Referenced by generate_wrapper().

◆ generate_build_description()

std::string casadi::DaeBuilderInternal::generate_build_description ( const std::vector< std::string > &  cfiles) const

Definition at line 1004 of file dae_builder_internal.cpp.

1005  {
1006  // Default arguments
1007  int fmi_major = 3;
1008  int fmi_minor = 0;
1009  std::string model_name = name_;
1010  // Construct XML file
1011  XmlNode r;
1012  // Preamble
1013  r.name = "fmiBuildDescription";
1014  r.set_attribute("fmiVersion", std::to_string(fmi_major) + "." + std::to_string(fmi_minor));
1015  // Set of source files
1016  XmlNode source_file_set;
1017  source_file_set.name = "SourceFileSet";
1018  for (auto&& f : cfiles) {
1019  XmlNode source_file;
1020  source_file.name = "SourceFile";
1021  source_file.set_attribute("name", f);
1022  source_file_set.children.push_back(source_file);
1023  }
1024  // Build configurations
1025  XmlNode bc;
1026  bc.name = "BuildConfiguration";
1027  bc.set_attribute("modelIdentifier", model_name);
1028  bc.children.push_back(source_file_set);
1029  r.children.push_back(bc);
1030  // XML file name
1031  std::string xml_filename = "buildDescription.xml";
1032  // Construct ModelDescription
1033  XmlNode build_description;
1034  build_description.children.push_back(r);
1035  // Export to file
1036  XmlFile xml_file("tinyxml");
1037  xml_file.dump(xml_filename, build_description);
1038  return xml_filename;
1039 }

References casadi::XmlNode::children, casadi::XmlFile::dump(), casadi::XmlNode::name, name_, and casadi::XmlNode::set_attribute().

Referenced by export_fmu().

◆ generate_guid()

std::string casadi::DaeBuilderInternal::generate_guid ( )
static

Import existing problem from FMI/XML

Definition at line 4805 of file dae_builder_internal.cpp.

4805  {
4806  // Initialize random seed
4807  static bool initialized = false;
4808  if (!initialized) {
4809  srand(::time(nullptr)); // NOLINT(runtime/threadsafe_fn)
4810  initialized = true;
4811  }
4812  // Possible characters
4813  const char h[] = "0123456789abcdef";
4814  // Length of GUID
4815  const size_t len = 32;
4816  // Generate random hex string
4817  std::vector<char> buf(len);
4818  for (size_t i = 0; i < len; ++i)
4819  buf[i] = h[rand() % 16]; // NOLINT(runtime/threadsafe_fn)
4820  return std::string(&buf.front(), len);
4821 }

References time().

Referenced by export_fmu().

◆ generate_model_description()

std::string casadi::DaeBuilderInternal::generate_model_description ( const std::string &  guid) const

Definition at line 1041 of file dae_builder_internal.cpp.

1041  {
1042  // Default arguments
1043  int fmi_major = 3;
1044  int fmi_minor = 0;
1045  std::string model_name = name_;
1046  std::string description; // none
1047  std::string author; // none
1048  std::string version; // none
1049  std::string copyright; // none
1050  std::string license; // none
1051  // Construct XML file
1052  XmlNode r;
1053  // Preamble
1054  r.name = "fmiModelDescription";
1055  r.set_attribute("fmiVersion", std::to_string(fmi_major) + "." + std::to_string(fmi_minor));
1056  r.set_attribute("modelName", model_name);
1057  r.set_attribute(fmi_major >= 3 ? "instantiationToken" : "guid", guid);
1058  if (!description.empty()) r.set_attribute("description", description);
1059  if (!author.empty()) r.set_attribute("author", author);
1060  if (!version.empty()) r.set_attribute("version", version);
1061  if (!copyright.empty()) r.set_attribute("copyright", copyright);
1062  if (!license.empty()) r.set_attribute("license", license);
1063  r.set_attribute("generationTool", "CasADi");
1064  r.set_attribute("generationDateAndTime", iso_8601_time());
1065  r.set_attribute("variableNamingConvention", "structured"); // flat better?
1066  if (fmi_major < 3) r.set_attribute("numberOfEventIndicators", "0");
1067 
1068  // Model exchange marker
1069  XmlNode me;
1070  me.name = "ModelExchange";
1071  me.set_attribute("modelIdentifier", model_name); // sanitize name?
1072  me.set_attribute("providesDirectionalDerivatives", "true");
1073  me.set_attribute("providesAdjointDerivatives", "true");
1074  r.children.push_back(me);
1075 
1076  // Default experiment
1077  XmlNode def_exp;
1078  def_exp.name = "DefaultExperiment";
1079  if (!std::isnan(start_time_)) def_exp.set_attribute("startTime", start_time_);
1080  if (!std::isnan(stop_time_)) def_exp.set_attribute("stopTime", stop_time_);
1081  if (!std::isnan(tolerance_)) def_exp.set_attribute("tolerance", tolerance_);
1082  if (!std::isnan(step_size_)) def_exp.set_attribute("stepSize", step_size_);
1083  if (!def_exp.attributes.empty()) r.children.push_back(def_exp);
1084 
1085  // Model variables
1086  r.children.push_back(generate_model_variables());
1087  // Model structure
1088  r.children.push_back(generate_model_structure());
1089  // XML file name
1090  std::string xml_filename = "modelDescription.xml";
1091  // Construct ModelDescription
1092  XmlNode model_description;
1093  model_description.children.push_back(r);
1094  // Export to file
1095  XmlFile xml_file("tinyxml");
1096  xml_file.dump(xml_filename, model_description);
1097  return xml_filename;
1098 }
XmlNode generate_model_variables() const
Generate FMU ModelVariables.
static std::string iso_8601_time()
Get current date and time in the ISO 8601 format.

References casadi::XmlNode::attributes, casadi::XmlNode::children, casadi::description(), casadi::XmlFile::dump(), generate_model_structure(), generate_model_variables(), iso_8601_time(), casadi::XmlNode::name, name_, casadi::XmlNode::set_attribute(), start_time_, step_size_, stop_time_, and tolerance_.

Referenced by export_fmu().

◆ generate_model_structure()

XmlNode casadi::DaeBuilderInternal::generate_model_structure ( bool  dae = false) const

Definition at line 1110 of file dae_builder_internal.cpp.

1110  {
1111  XmlNode r;
1112  r.name = "ModelStructure";
1113  // Add outputs
1114  for (size_t i : indices(Category::Y)) {
1115  const Variable& y = variable(i);
1116  XmlNode c;
1117  c.name = "Output";
1118  c.set_attribute("valueReference", static_cast<casadi_int>(y.value_reference));
1119  c.set_attribute("dependencies", y.dependencies);
1120  r.children.push_back(c);
1121  }
1122  // Add state derivatives
1123  for (size_t i : indices(Category::X)) {
1124  const Variable& xdot = variable(variable(i).der);
1125  XmlNode c;
1126  c.name = "ContinuousStateDerivative";
1127  c.set_attribute("valueReference", static_cast<casadi_int>(xdot.value_reference));
1128  c.set_attribute("dependencies", xdot.dependencies);
1129  r.children.push_back(c);
1130  }
1131  if (dae) {
1132  for (size_t i : indices(Category::ALG)) {
1133  XmlNode f;
1134  f.name = "Formulation";
1135  f.set_attribute("index", "1");
1136  f.set_attribute("valueReference", static_cast<casadi_int>(variable(i).value_reference));
1137  f.set_attribute("dependencies", variable(i).dependencies);
1138  XmlNode c;
1139  c.name = "Residual";
1140  c.children.push_back(f);
1141  r.children.push_back(c);
1142  }
1143  } else {
1144  // Add initial unknowns: Outputs
1145  for (size_t i : indices(Category::Y)) {
1146  const Variable& y = variable(i);
1147  XmlNode c;
1148  c.name = "InitialUnknown";
1149  c.set_attribute("valueReference", static_cast<casadi_int>(y.value_reference));
1150  c.set_attribute("dependencies", y.dependencies);
1151  r.children.push_back(c);
1152  }
1153  // Add initial unknowns: State derivative
1154  for (size_t i : indices(Category::X)) {
1155  const Variable& xdot = variable(variable(i).der);
1156  XmlNode c;
1157  c.name = "InitialUnknown";
1158  c.set_attribute("valueReference", static_cast<casadi_int>(xdot.value_reference));
1159  c.set_attribute("dependencies", xdot.dependencies);
1160  r.children.push_back(c);
1161  }
1162  // Add event indicators
1163  for (size_t i : indices(Category::ZERO)) {
1164  const Variable& zero = variable(i);
1165  XmlNode c;
1166  c.name = "EventIndicator";
1167  c.set_attribute("valueReference", static_cast<casadi_int>(zero.value_reference));
1168  c.set_attribute("dependencies", zero.dependencies);
1169  r.children.push_back(c);
1170  }
1171  }
1172  return r;
1173 }

References casadi::ALG, casadi::XmlNode::children, casadi::Variable::dependencies, der(), indices(), casadi::XmlNode::name, casadi::XmlNode::set_attribute(), casadi::Variable::value_reference, variable(), casadi::X, casadi::Y, and casadi::ZERO.

Referenced by export_fmu(), and generate_model_description().

◆ generate_model_variables()

XmlNode casadi::DaeBuilderInternal::generate_model_variables ( ) const

Definition at line 1101 of file dae_builder_internal.cpp.

1101  {
1102  XmlNode r;
1103  r.name = "ModelVariables";
1104  for (auto&& v : variables_) {
1105  r.children.push_back(v->export_xml(*this));
1106  }
1107  return r;
1108 }

References casadi::XmlNode::children, casadi::XmlNode::name, and variables_.

Referenced by generate_model_description().

◆ generate_wrapper()

std::string casadi::DaeBuilderInternal::generate_wrapper ( const std::string &  guid,
const CodeGenerator gen 
) const

Definition at line 1397 of file dae_builder_internal.cpp.

1398  {
1399  // Create file
1400  std::string wrapper_filename = name_ + "_wrap.c";
1401 
1402  auto f_ptr = Filesystem::ofstream_ptr(wrapper_filename);
1403  std::ostream& f = *f_ptr;
1404  CodeGenerator::stream_open(f, false);
1405 
1406  // Add includes
1407  f << "#include <fmi3Functions.h>\n"
1408  << "#include \"" << name_ << ".h\"\n"
1409  << "\n";
1410 
1411  // Total number of variables
1412  f << "#define N_VAR " << n_variables() << "\n";
1413 
1414  // Memory size
1415  f << "#define SZ_MEM " << n_mem() << "\n";
1416 
1417  // Work vectors sizes
1418  size_t sz_arg, sz_res, sz_iw, sz_w;
1419  gen.sz_work(sz_arg, sz_res, sz_iw, sz_w);
1420  f << "#define SZ_ARG " << sz_arg << "\n"
1421  << "#define SZ_RES " << sz_res << "\n"
1422  << "#define SZ_IW " << sz_iw << "\n"
1423  << "#define SZ_W " << sz_w << "\n";
1424 
1425  // Memory offsets
1426  f << "const size_t var_offset[N_VAR + 1] = {0";
1427  size_t mem_ind = 0;
1428  for (const Variable* v : variables_) {
1429  mem_ind += v->numel;
1430  f << ", " << mem_ind;
1431  }
1432  f << "};\n\n";
1433 
1434  // Start attributes
1435  f << "casadi_real start[SZ_MEM] = " << generate(start_all()) << ";\n\n";
1436 
1437  // Differential states
1438  f << "#define N_X " << size(Category::X) << "\n"
1439  << "fmi3ValueReference x_vr[N_X] = " << generate(indices(Category::X)) << ";\n"
1440  << "\n";
1441 
1442  // Algebraic variables
1443  f << "#define N_Z " << size(Category::Z) << "\n"
1444  << "fmi3ValueReference z_vr[N_Z] = " << generate(indices(Category::Z)) << ";\n"
1445  << "\n";
1446 
1447  // Controls
1448  f << "#define N_U " << size(Category::U) << "\n"
1449  << "fmi3ValueReference u_vr[N_U] = " << generate(indices(Category::U)) << ";\n"
1450  << "\n";
1451 
1452  // Parameters
1453  f << "#define N_P " << size(Category::P) << "\n"
1454  << "fmi3ValueReference p_vr[N_P] = " << generate(indices(Category::P)) << ";\n"
1455  << "\n";
1456 
1457  // State derivatives
1458  std::vector<size_t> xdot;
1459  for (size_t v : indices(Category::X)) xdot.push_back(variable(v).der);
1460  f << "fmi3ValueReference xdot_vr[N_X] = " << generate(xdot) << ";\n"
1461  << "\n";
1462 
1463  // Outputs
1464  f << "fmi3ValueReference alg_vr[N_Z] = " << generate(indices(Category::ALG)) << ";\n"
1465  << "\n";
1466 
1467  // Outputs
1468  f << "#define N_Y " << size(Category::Y) << "\n"
1469  << "fmi3ValueReference y_vr[N_Y] = " << generate(indices(Category::Y)) << ";\n"
1470  << "\n";
1471 
1472  // Event indicators
1473  f << "#define N_ZERO " << size(Category::ZERO) << "\n"
1474  << "fmi3ValueReference zero_vr[N_ZERO] = " << generate(indices(Category::ZERO)) << ";\n"
1475  << "\n";
1476 
1477  // Memory structure
1479 
1480  // Finalize file
1481  CodeGenerator::stream_close(f, false);
1482  return wrapper_filename;
1483 }
static std::string fmu_helpers(const std::string &modelname)
FMU helper functions.
static void stream_open(std::ostream &f, bool cpp)
Print file header.
static void stream_close(std::ostream &f, bool cpp)
Print file header.
size_t n_mem() const
Length of memory for all variables.
static std::string generate(const std::vector< size_t > &v)
std::vector< double > start_all() const
Start values for all variables.
static std::unique_ptr< std::ostream > ofstream_ptr(const std::string &path, std::ios_base::openmode mode=std::ios_base::out)
Definition: filesystem.cpp:115

References casadi::ALG, der(), casadi::CodeGenerator::fmu_helpers(), generate(), indices(), n_mem(), n_variables(), name_, casadi::Filesystem::ofstream_ptr(), casadi::P, size(), start_all(), casadi::CodeGenerator::stream_close(), casadi::CodeGenerator::stream_open(), casadi::CodeGenerator::sz_work(), casadi::U, variable(), variables_, casadi::X, casadi::Y, casadi::Z, and casadi::ZERO.

Referenced by export_fmu().

◆ get_der() [1/2]

MX casadi::DaeBuilderInternal::get_der ( size_t  ind) const
inline

Definition at line 373 of file dae_builder_internal.hpp.

373 {return variable(ind).get_der(*this);}
MX get_der(DaeBuilderInternal &self, bool may_allocate=true)

Referenced by der().

◆ get_der() [2/2]

MX casadi::DaeBuilderInternal::get_der ( size_t  ind,
bool  may_allocate = true 
)
inline

Definition at line 376 of file dae_builder_internal.hpp.

376  {
377  return variable(ind).get_der(*this, may_allocate);
378  }

◆ get_str()

std::string casadi::DaeBuilderInternal::get_str ( bool  more = false) const
inline

Definition at line 396 of file dae_builder_internal.hpp.

396  {
397  std::stringstream ss;
398  disp(ss, more);
399  return ss.str();
400  }
void disp(std::ostream &stream, bool more) const override
Print description.

◆ getCount()

Definition at line 60 of file generic_shared_internal.hpp.

205  {
206  return static_cast<const Internal*>(this)->count;
207  }

◆ has()

bool casadi::DaeBuilderInternal::has ( const std::string &  name) const

Definition at line 2022 of file dae_builder_internal.cpp.

2022  {
2023  return varind_.find(name) != varind_.end();
2024 }

References name(), and varind_.

Referenced by new_variable(), tearing_variables(), and unique_name().

◆ has_fun()

bool casadi::DaeBuilderInternal::has_fun ( const std::string &  name) const
protected

Definition at line 4616 of file dae_builder_internal.cpp.

4616  {
4617  for (const Function& f : fun_) {
4618  if (f.name()==name) return true;
4619  }
4620  return false;
4621 }

References fun_, and name().

Referenced by add_fun(), and fun().

◆ has_t()

bool casadi::DaeBuilderInternal::has_t ( ) const
protected

Extra doc: https://github.com/casadi/casadi/wiki/L_2bx

Definition at line 3127 of file dae_builder_internal.cpp.

3127  {
3128  return size(Category::T) > 0;
3129 }

References size(), and casadi::T.

Referenced by set_category(), and time().

◆ hess_sparsity()

Sparsity casadi::DaeBuilderInternal::hess_sparsity ( const std::vector< size_t > &  oind,
const std::vector< size_t > &  iind 
) const

Definition at line 4743 of file dae_builder_internal.cpp.

4744  {
4745  // Mark inputs
4746  std::vector<casadi_int> lookup(n_variables(), -1);
4747  for (size_t i = 0; i < iind.size(); ++i) lookup.at(iind[i]) = i;
4748  // Which variables enter as a nonlinear dependency in any variable in oind
4749  std::vector<bool> nonlin(iind.size(), false);
4750  // List of nonlinearly entering variables for the specific output
4751  std::vector<casadi_int> nonlin_list;
4752  // Rows and columns of the Hessian
4753  std::vector<casadi_int> row, col;
4754  // Loop over output variables
4755  for (casadi_int j = 0; j < oind.size(); ++j) {
4756  const Variable& v = variable(oind[j]);
4757  // Loop over dependencies
4758  for (size_t k = 0; k < v.dependencies.size(); ++k) {
4759  if (v.dependenciesKind.empty() || v.dependenciesKind.at(k) == DependenciesKind::DEPENDENT) {
4760  casadi_int i = lookup.at(v.dependencies[k]);
4761  if (i >= 0 && !nonlin.at(i)) {
4762  // Add to list
4763  nonlin_list.push_back(i);
4764  nonlin.at(i) = true;
4765  }
4766  }
4767  }
4768  // Add all combinations to sparsity pattern
4769  for (casadi_int k1 : nonlin_list) {
4770  for (casadi_int k2 : nonlin_list) {
4771  row.push_back(k1);
4772  col.push_back(k2);
4773  }
4774  }
4775  // If row/col vectors grow too large, remove duplicates
4776  if (col.size() > 2 * iind.size() * iind.size()) {
4777  Sparsity r = Sparsity::triplet(iind.size(), iind.size(), row, col);
4778  row = r.get_row();
4779  col = r.get_col();
4780  }
4781  // Reset nonlin, nonlin_list for next iteration
4782  for (casadi_int k : nonlin_list) nonlin[k] = false;
4783  nonlin_list.clear();
4784  }
4785  // Create sparsity pattern
4786  return Sparsity::triplet(iind.size(), iind.size(), row, col);
4787 }
static Sparsity triplet(casadi_int nrow, casadi_int ncol, const std::vector< casadi_int > &row, const std::vector< casadi_int > &col, std::vector< casadi_int > &mapping, bool invert_mapping)
Create a sparsity pattern given the nonzeros in sparse triplet form *.
Definition: sparsity.cpp:1143

References casadi::Variable::dependencies, casadi::Variable::dependenciesKind, casadi::DEPENDENT, casadi::Sparsity::get_col(), casadi::Sparsity::get_row(), n_variables(), casadi::Sparsity::triplet(), and variable().

Referenced by casadi::FmuInternal::init().

◆ hess_v_v_from_calls()

MX casadi::DaeBuilderInternal::hess_v_v_from_calls ( std::map< MXNode *, CallIO > &  call_nodes,
const std::vector< casadi_int > &  h_offsets 
) const
protected

Definition at line 2562 of file dae_builder_internal.cpp.

2563  {
2564  // Calculate all Hessian expressions
2565  for (auto&& call_ref : call_nodes) call_ref.second.calc_hess();
2566  // Row offsets in hess_v_v
2567  casadi_int voffset_begin = 0, voffset_end = 0, voffset_last = 0;
2568  // Vertical and horizontal slices of hess_v_v
2569  std::vector<MX> vblocks, hblocks;
2570  // All blocks for a block row
2571  std::map<size_t, MX> hess_brow;
2572  // Loop over block rows
2573  for (size_t vind1 = 0; vind1 < size(Category::W); ++vind1) {
2574  // Current element handled
2575  const MX& vref = var(Category::W, vind1);
2576  // Update vertical offset
2577  voffset_begin = voffset_end;
2578  voffset_end += vref.numel();
2579  // Collect all blocks for this block row
2580  hess_brow.clear();
2581  for (auto&& call_ref : call_nodes) {
2582  // Locate the specific index
2583  for (size_t iind1 = 0; iind1 < call_ref.second.v.size(); ++iind1) {
2584  if (call_ref.second.v.at(iind1) == vind1) {
2585  // Add contribution to block row
2586  for (size_t iind2 = 0; iind2 < call_ref.second.v.size(); ++iind2) {
2587  // Corresponding index in v
2588  size_t vind2 = call_ref.second.v[iind2];
2589  if (vind2 == size_t(-1)) continue;
2590  // Hessian contribution
2591  MX H_contr = call_ref.second.hess(iind1, iind2);
2592  // Insert new block or add to existing one
2593  auto it = hess_brow.find(vind2);
2594  if (it != hess_brow.end()) {
2595  it->second += H_contr;
2596  } else {
2597  hess_brow[vind2] = H_contr;
2598  }
2599  }
2600  // An index can only appear once
2601  break;
2602  }
2603  }
2604  }
2605  // If no blocks, skip row
2606  if (hess_brow.empty()) continue;
2607  // Add empty rows to vblocks, if any
2608  if (voffset_last != voffset_begin) {
2609  vblocks.push_back(MX(voffset_begin - voffset_last, h_offsets.back()));
2610  }
2611  // Collect horizontal blocks
2612  hblocks.clear();
2613  casadi_int hoffset = 0;
2614  for (auto e : hess_brow) {
2615  // Add empty block before Jacobian block, if needed
2616  if (hoffset < h_offsets.at(e.first))
2617  hblocks.push_back(MX(vref.numel(), h_offsets.at(e.first) - hoffset));
2618  // Add Jacobian block
2619  hblocks.push_back(e.second);
2620  // Update offsets
2621  hoffset = h_offsets.at(e.first + 1);
2622  }
2623  // Add trailing empty block, if needed
2624  if (hoffset < h_offsets.back())
2625  hblocks.push_back(MX(vref.numel(), h_offsets.back() - hoffset));
2626  // Add new block row to vblocks
2627  vblocks.push_back(horzcat(hblocks));
2628  // Keep track of the offset handled in jac_brow
2629  voffset_last = voffset_end;
2630  }
2631  // Add empty trailing row to vblocks, if any
2632  if (voffset_last != voffset_end) {
2633  vblocks.push_back(MX(voffset_end - voffset_last, h_offsets.back()));
2634  }
2635  // Return additional term in jac_vdef_v
2636  return vertcat(vblocks);
2637 }

References casadi::MX::find(), casadi::GenericMatrix< MatType >::numel(), size(), var(), and casadi::W.

Referenced by create().

◆ import_binding_equations()

void casadi::DaeBuilderInternal::import_binding_equations ( const XmlNode eqs)
protected

Definition at line 4342 of file dae_builder_internal.cpp.

4342  {
4343  if (debug_) {
4344  uout() << "== Structure before importing binding equations ==" << std::endl;
4345  disp(uout(), true);
4346  }
4347 
4348  // Loop over binding equations
4349  for (casadi_int i = 0; i < eqs.size(); ++i) {
4350  const XmlNode& eq = eqs[i];
4351  std::string eq_name = "beq_" + str(i);
4352  // Try to read the node
4353  try {
4354  // Get the variable and binding expression
4355  Variable& var = read_variable(eq[0]);
4356  if (eq[1].size() == 1) {
4357  // Set the binding equation
4358  var.bind = assign(var.name, read_expr(eq[1][0])).index;
4359  } else {
4360  // OpenModelica 1.17 occationally generates integer values without type specifier (bug?)
4361  casadi_assert(eq[1].size() == 0, "Not implemented");
4362  casadi_int val;
4363  eq[1].get(&val);
4364  casadi_warning(var.name + " has binding equation without type specifier: " + str(val));
4365  // Set the binding equation
4366  var.bind = assign(var.name, val).index;
4367  }
4368  // Add to list of dependent parameters
4369  indices(Category::D).push_back(var.index);
4370  } catch (std::exception& e) {
4371  casadi_error("Failed to read " + eq_name + ":" + str(e.what()));
4372  }
4373  }
4374 }
Variable & read_variable(const XmlNode &node, Attribute *att=nullptr)
Read a variable.
MX read_expr(const XmlNode &node)
Read an equation.
std::string name() const
Get the name.
Definition: mx.cpp:791
std::ostream & uout()

References assign(), casadi::D, debug_, disp(), eq(), casadi::Variable::index, indices(), casadi::MX::name(), read_expr(), read_variable(), casadi::XmlNode::size(), size(), casadi::str(), casadi::uout(), and var().

Referenced by load_fmi_description().

◆ import_default_experiment()

void casadi::DaeBuilderInternal::import_default_experiment ( const XmlNode n)
protected

Definition at line 3823 of file dae_builder_internal.cpp.

3823  {
3824  start_time_ = n.attribute<double>("startTime", nan);
3825  stop_time_ = n.attribute<double>("stopTime", nan);
3826  tolerance_ = n.attribute<double>("tolerance", nan);
3827  step_size_ = n.attribute<double>("stepSize", nan);
3828 }

References casadi::XmlNode::attribute(), casadi::nan, start_time_, step_size_, stop_time_, and tolerance_.

Referenced by load_fmi_description().

◆ import_dynamic_equations()

void casadi::DaeBuilderInternal::import_dynamic_equations ( const XmlNode eqs)
protected

Definition at line 4376 of file dae_builder_internal.cpp.

4376  {
4377  if (debug_) {
4378  uout() << "== Structure before importing dynamic equations ==" << std::endl;
4379  disp(uout(), true);
4380  }
4381  // Add discrete states to x_
4382  // Note: Make generic, should also apply to regular FMUs
4383  for (Variable* v : variables_) {
4384  if (v->variability == Variability::DISCRETE) {
4385  categorize(v->index, Category::X);
4386  }
4387  }
4388  // Add equations
4389  for (casadi_int i = 0; i < eqs.size(); ++i) {
4390  const XmlNode& eq = eqs[i];
4391  std::string eq_name = "dyneq_" + str(i);
4392  // Try to read the node
4393  try {
4394  if (eq.name == "equ:When") { // When equation
4395  // Nodes for condition, equations
4396  const XmlNode& n_cond = eq["equ:Condition"];
4397  const XmlNode& n_equ = eq["equ:Equation"];
4398  // Consistency checks - only working for very simple expressions
4399  casadi_assert(n_cond.size() == 1, "Only one condition in when equation supported");
4400  casadi_assert(n_equ.size() == 1, "Only one equation in when equation supported");
4401  // Get expression for condition
4402  std::string cond_name = n_cond[0][0].attribute<std::string>("name");
4403  std::string when_prefix = "$whenCondition";
4404  cond_name = cond_name.substr(when_prefix.size());
4405  casadi_int ind = std::stoi(cond_name) - 1;
4406  // Left-hand-side and right-hand-side
4407  MX lhs, rhs;
4408  // Handle different types of equations
4409  if (n_equ[0].name == "exp:Sub") {
4410  // Assume equation is an assignment
4411  lhs = read_identifier(n_equ[0][0]);
4412  rhs = read_expr(n_equ[0][1]);
4413  when_.at(ind).second.push_back(assign(lhs.name(), rhs).index);
4414  } else if (n_equ[0].name == "exp:Reinit") {
4415  // Reinitialization
4416  lhs = read_identifier(n_equ[0][0]);
4417  rhs = read_expr(n_equ[0][1]);
4418  when_.at(ind).second.push_back(reinit(lhs.name(), rhs).index);
4419  } else {
4420  // Not implemented
4421  casadi_error(n_equ[0].name + " in when equation not supported");
4422  }
4423  } else if (eq.name == "equ:Equation") { // Residual equation
4424  // Consistency checks
4425  casadi_assert_dev(eq.size() == 1 && eq[0].name == "exp:Sub");
4426  // Skip if empty
4427  if (eq[0].size() == 0) {
4428  casadi_warning(eq_name + " is empty, ignored.");
4429  continue;
4430  }
4431  // Get the left-hand-sides and right-hand-sides
4432  const XmlNode& lhs = eq[0][0];
4433  const XmlNode& rhs = eq[0][1];
4434  // Right-hand-side is the binding equation
4435  MX beq = read_expr(rhs);
4436  // Left-hand-side is a variable or derivative
4437  std::string when_prefix = "$whenCondition";
4438  if (lhs.name == "exp:Der") {
4439  // Differential equation
4440  Variable& v = read_variable(lhs[0]);
4441  this->eq(der(v.v), beq, Dict());
4442  } else if (lhs.size() > 0
4443  && lhs[0].attribute<std::string>("name").rfind(when_prefix, 0) == 0) {
4444  // Get the index
4445  std::string cond_name = lhs[0].attribute<std::string>("name");
4446  if (debug_) {
4447  uout() << "Reading event indicator: " << cond_name << " := " << beq << std::endl;
4448  }
4449  cond_name = cond_name.substr(when_prefix.size());
4450  casadi_int ind = std::stoi(cond_name) - 1;
4451  // Ensure consequitive for now
4452  casadi_assert(ind == when_.size(), "Non-consequitive when conditions");
4453  // Create a when equation with no equations
4454  when(beq, {}, Dict());
4455  } else {
4456  // Regular equation
4457  Variable& v = read_variable(lhs);
4458  if (debug_) uout() << "Reading equation: " << v.name << " == " << beq << std::endl;
4459  this->eq(v.v, beq, Dict());
4460  }
4461  } else {
4462  casadi_error("Unknown dynamic equation type, got:" + eq.name);
4463  }
4464  } catch (std::exception& e) {
4465  casadi_error("Failed to read " + eq_name + ":" + str(e.what()));
4466  }
4467  }
4468 }
void when(const MX &cond, const std::vector< std::string > &eqs, const Dict &opts)
Add when equations.
MX read_identifier(const XmlNode &node)
Read an identifier expression.
Variable & reinit(const std::string &name, const MX &val)
Reinitialize a state inside when-equations.

References assign(), casadi::XmlNode::attribute(), categorize(), debug_, der(), casadi::DISCRETE, disp(), eq(), casadi::Variable::index, casadi::Variable::name, casadi::MX::name(), name(), casadi::XmlNode::name, read_expr(), read_identifier(), read_variable(), reinit(), casadi::XmlNode::size(), size(), casadi::str(), casadi::uout(), casadi::Variable::v, variables_, when(), when_, and casadi::X.

Referenced by load_fmi_description().

◆ import_initial_equations()

void casadi::DaeBuilderInternal::import_initial_equations ( const XmlNode eqs)
protected

Definition at line 4470 of file dae_builder_internal.cpp.

4470  {
4471  if (debug_) {
4472  uout() << "== Structure before importing initial equations ==" << std::endl;
4473  disp(uout(), true);
4474  }
4475 
4476  // Hack: OpenModelica XML may contain duplicate expressions, ignore these
4477  std::set<std::string> already_added;
4478  // Add equations
4479  for (casadi_int i = 0; i < eqs.size(); ++i) {
4480  const XmlNode& eq = eqs[i];
4481  // Try to read the node
4482  std::string eq_name = "initeq_" + str(i);
4483  try {
4484  if (eq.name == "equ:Equation") { // Residual equation
4485  // Consistency checks
4486  casadi_assert_dev(eq.size() == 1 && eq[0].name == "exp:Sub");
4487  // Ensure not empty
4488  if (eq[0].size() == 0) {
4489  casadi_warning(eq_name + " is empty, ignored.");
4490  continue;
4491  }
4492  // Get the left-hand-sides and right-hand-sides
4493  const XmlNode& lhs = eq[0][0];
4494  const XmlNode& rhs = eq[0][1];
4495 
4496  // Ignore initalizations of when equation indicators
4497  if (lhs.size() > 0
4498  && lhs[0].attribute<std::string>("name").rfind("$whenCondition", 0) == 0) {
4499  continue;
4500  }
4501 
4502  // Hack: Ignore expressions that just set a $PRE variable
4503  if (lhs.size() > 0 && lhs[0].attribute<std::string>("name") == "$PRE") {
4504  casadi_warning(eq_name + " defines a pre-variable, ignored");
4505  continue;
4506  }
4507  // Right-hand-side is the binding equation
4508  MX beq = read_expr(rhs);
4509  // Left-hand-side is a variable
4510  Variable& v = read_variable(lhs);
4511  // Hack: ignore initial equations for tunable parameters
4512  if (v.variability == Variability::TUNABLE) {
4513  casadi_warning(eq_name + " defines a tunable parameter, ignored")
4514  continue;
4515  }
4516  // Hack: avoid duplicate equations
4517  std::string eq_str = str(v.v) + " == " + str(beq);
4518  auto it = already_added.insert(eq_str);
4519  if (!it.second) {
4520  casadi_warning(eq_name + " duplicate of previous equation " + eq_str + ", ignored")
4521  continue;
4522  }
4523  // Set initial condition
4524  set_init(v.name, beq);
4525  } else {
4526  casadi_error("Unknown initial equation type, got:" + eq.name);
4527  }
4528  } catch (std::exception& e) {
4529  casadi_error("Failed to read " + eq_name + ":" + str(e.what()));
4530  }
4531  }
4532 }
void set_init(const std::string &name, const MX &init_rhs)
Set a initial equation.

References casadi::XmlNode::attribute(), debug_, disp(), eq(), casadi::Variable::name, read_expr(), read_variable(), set_init(), casadi::XmlNode::size(), size(), casadi::str(), casadi::TUNABLE, casadi::uout(), casadi::Variable::v, and casadi::Variable::variability.

Referenced by load_fmi_description().

◆ import_ls_dae()

XmlNode casadi::DaeBuilderInternal::import_ls_dae ( const std::string &  lsdae)
protected

Definition at line 4320 of file dae_builder_internal.cpp.

4320  {
4321  // Load function oracle from file
4322  XmlFile xml_file("tinyxml");
4323  XmlNode ls_manifest = xml_file.parse(lsdae)[0]; // One child; fmiLayeredStandardManifest
4324 
4325  // Read attributes
4326  auto ls_version = ls_manifest.attribute<std::string>("fmi-ls:fmi-ls-version", "");
4327  casadi_assert(ls_version.empty() || ls_version == "1.0",
4328  "Unsupported LS-DAE version: " + ls_version);
4329 
4330  // Process algebraic variables
4331  casadi_assert(ls_manifest.has_child("AlgebraicVariables"), "Missing 'AlgebraicVariables'");
4332  for (const XmlNode& e : ls_manifest["AlgebraicVariables"].children) {
4333  auto vr = static_cast<unsigned int>(e.attribute<casadi_int>("valueReference"));
4334  categorize(vrmap_.at(vr), Category::Z);
4335  }
4336 
4337  // Return replacement
4338  casadi_assert(ls_manifest.has_child("ModelStructure"), "Missing 'ModelStructure'");
4339  return ls_manifest["ModelStructure"];
4340 }
std::unordered_map< unsigned int, size_t > vrmap_
Find of variable by value reference.

References casadi::XmlNode::attribute(), categorize(), casadi::XmlNode::has_child(), casadi::XmlFile::parse(), vrmap_, and casadi::Z.

Referenced by import_model_structure().

◆ import_model_exchange()

void casadi::DaeBuilderInternal::import_model_exchange ( const XmlNode n)
protected

Definition at line 3830 of file dae_builder_internal.cpp.

3830  {
3831  // Read attributes
3832  provides_directional_derivatives_ = n.attribute<bool>(
3833  fmi_major_ >= 3 ? "providesDirectionalDerivatives" : "providesDirectionalDerivative", false);
3835  = n.attribute<bool>("providesAdjointDerivatives", false);
3836  model_identifier_ = n.attribute<std::string>("modelIdentifier");
3838  n.attribute<bool>("canBeInstantiatedOnlyOncePerProcess", false);
3839  // Get list of source files
3840  if (n.has_child("SourceFiles")) {
3841  for (const XmlNode& sf : n["SourceFiles"].children) {
3842  source_files_.push_back(sf.attribute<std::string>("name"));
3843  }
3844  }
3845 }
std::vector< std::string > source_files_

References casadi::XmlNode::attribute(), can_be_instantiated_only_once_per_process_, fmi_major_, casadi::XmlNode::has_child(), model_identifier_, provides_adjoint_derivatives_, provides_directional_derivatives_, and source_files_.

Referenced by load_fmi_description().

◆ import_model_structure()

void casadi::DaeBuilderInternal::import_model_structure ( const XmlNode n)
protected

Definition at line 4070 of file dae_builder_internal.cpp.

4070  {
4071  // Do not use the automatic selection of outputs based on output causality
4072  indices(Category::Y).clear();
4073 
4074  // Algebraic variables are handled internally in the FMU by default
4075  for (size_t i = 0; i < n_variables(); ++i) {
4076  Variable& v = variable(i);
4077  if (v.category == Category::Z) {
4078  // Mark as dependent variable, no need for an algebraic equation anymore
4079  categorize(v.index, Category::W);
4080  }
4081  }
4082 
4083  // Read structure
4084  if (fmi_major_ >= 3) {
4085  // LS-DAE
4086  bool has_lsdae = false; // use ModelStructure from LS-DAE manifest
4087  std::string lsdae = resource_.path() + "/extra/org.fmi-standard.fmi-ls-dae/fmi-ls-manifest.xml";
4088  XmlNode lsdae_ms;
4089  if (enable_ls_dae_ && Filesystem::exists(lsdae)) {
4090  try {
4091  // Import replacement ModelStructure
4092  lsdae_ms = import_ls_dae(lsdae);
4093  // Append unchanged elements
4094  for (casadi_int i = 0; i < n.size(); ++i) {
4095  const XmlNode& e = n[i];
4096  if (e.name != "ContinuousStateDerivative" && e.name != "Output") {
4097  lsdae_ms.children.push_back(e);
4098  }
4099  }
4100  // Use instead of original ModelStructure
4101  has_lsdae = true;
4102  } catch (const std::exception& e) {
4103  casadi_warning("Failed to load LS-DAE manifest: " + std::string(e.what()));
4104  }
4105  }
4106 
4107  // Loop over ModelStructure elements
4108  const XmlNode& ms = has_lsdae ? lsdae_ms : n;
4109  for (casadi_int i = 0; i < ms.size(); ++i) {
4110  const XmlNode& e = ms[i];
4111  try {
4112  // Get a reference to the variable
4113  if (e.name == "Output") {
4114  // Get index
4115  indices(Category::Y).push_back(vrmap_.at(e.attribute<size_t>("valueReference")));
4116  // Corresponding variable
4117  Variable& v = variable(indices(Category::Y).back());
4118  // Get dependencies
4119  v.dependencies = read_dependencies(e);
4120  v.dependenciesKind = read_dependencies_kind(e, v.dependencies.size());
4121  // Mark interdependencies
4122  for (casadi_int d : v.dependencies) variable(d).dependency = true;
4123  for (casadi_int d : v.dependencies) variable(d).in_rhs = true;
4124  } else if (e.name == "ContinuousStateDerivative") {
4125  // Get index
4126  der_.push_back(vrmap_.at(e.attribute<size_t>("valueReference")));
4127  // Corresponding variable
4128  Variable& v = variable(der_.back());
4129  // Add to list of states and derivative to list of dependent variables
4130  casadi_assert(v.parent >= 0, "Error processing derivative info for " + v.name);
4131  categorize(v.index, Category::W);
4132  categorize(v.parent, Category::X);
4133  // Map der field to derivative variable
4134  variable(v.parent).der = der_.back();
4135  // Get dependencies
4136  v.dependencies = read_dependencies(e);
4137  v.dependenciesKind = read_dependencies_kind(e, v.dependencies.size());
4138  // Mark interdependencies
4139  for (casadi_int d : v.dependencies) variable(d).dependency = true;
4140  for (casadi_int d : v.dependencies) variable(d).in_rhs = true;
4141  } else if (e.name == "ClockedState") {
4142  // Clocked state
4143  casadi_message("ClockedState not implemented, ignoring");
4144  } else if (e.name == "InitialUnknown") {
4145  // Get index
4146  initial_unknowns_.push_back(vrmap_.at(e.attribute<size_t>("valueReference")));
4147  // Get dependencies
4148  for (casadi_int d : read_dependencies(e)) variable(d).dependency = true;
4149  } else if (e.name == "EventIndicator") {
4150  // Event indicator
4151  indices(Category::ZERO).push_back(vrmap_.at(e.attribute<size_t>("valueReference")));
4152  nzero_++;
4153  } else if (e.name == "Residual") {
4154  // Loop over formulations
4155  bool found = false;
4156  for (casadi_int form = 0; form < e.size(); ++form) {
4157  const XmlNode& f = e[form];
4158  auto form_index = f.attribute<size_t>("index");
4159  if (form_index == 1) {
4160  // Index-1 formulation
4161  casadi_assert(!found, "Duplicate index-1 formulations");
4162  found = true;
4163  // Get index
4164  indices(Category::ALG).push_back(vrmap_.at(
4165  f.attribute<size_t>("valueReference")));
4166  // Corresponding variable
4167  Variable& v = variable(indices(Category::ALG).back());
4168  // Get dependencies
4169  v.dependencies = read_dependencies(f);
4170  v.dependenciesKind = read_dependencies_kind(f, v.dependencies.size());
4171  }
4172  }
4173  casadi_assert(found, "Missing index-1 formulation");
4174  } else {
4175  // Unknown
4176  casadi_error("Unknown ModelStructure element: " + e.name);
4177  }
4178  } catch (const std::exception& ex) {
4179  casadi_error("Error processing ModelStructure element: " + e.name + ": " + ex.what());
4180  }
4181  }
4182  } else {
4183  // Derivatives
4184  if (n.has_child("Derivatives")) {
4185  for (const auto& e : n["Derivatives"].children) {
4186  // Get index
4187  der_.push_back(convert_index(e.attribute<casadi_int>("index", 0)));
4188  // Corresponding variable
4189  Variable& v = variable(der_.back());
4190  // Add to list of states and derivative to list of dependent variables
4191  casadi_assert(v.parent >= 0, "Error processing derivative info for " + v.name);
4192  categorize(v.index, Category::W);
4193  categorize(v.parent, Category::X);
4194  // Map der field to derivative variable
4195  variable(v.parent).der = der_.back();
4196  }
4197  }
4198 
4199  // What if dependencies attributed is missing from Outputs,Derivatives?
4200  // Depends on x_ having been populated
4201  std::vector<casadi_int> default_dependencies;
4202  default_dependencies.insert(default_dependencies.begin(),
4203  indices(Category::T).begin(), indices(Category::T).end());
4204  default_dependencies.insert(default_dependencies.begin(),
4205  indices(Category::X).begin(), indices(Category::X).end());
4206  default_dependencies.insert(default_dependencies.begin(),
4207  indices(Category::U).begin(), indices(Category::U).end());
4208  std::sort(default_dependencies.begin(), default_dependencies.end());
4209 
4210  // FMI2 standard does not allow parameters to be included in dependencies attribute
4211  // (Table in section 2.2.8)
4212  // FMI3 standard does (Table in section 2.4.8)
4213  //
4214  // A uniform treatment is unconditionally add dense dependencies to all parameters
4215  // when loading FMI2
4216 
4217  std::vector<casadi_int> additional_dependencies;
4218  additional_dependencies.insert(additional_dependencies.begin(),
4219  indices(Category::P).begin(), indices(Category::P).end());
4220  std::vector<DependenciesKind> additional_dependencies_kind(size(Category::P),
4222 
4223  // Derivatives
4224  if (n.has_child("Derivatives")) {
4225  // Separate pass for dependencies
4226  for (const auto& e : n["Derivatives"].children) {
4227  casadi_int index = convert_index(e.attribute<casadi_int>("index", 0));
4228 
4229  // Corresponding variable
4230  Variable& v = variable(index);
4231 
4232  // Get dependencies
4233  if (e.has_attribute("dependencies")) {
4234  v.dependencies = read_dependencies(e);
4235  } else {
4236  v.dependencies = default_dependencies;
4237  }
4238  v.dependenciesKind = read_dependencies_kind(e, v.dependencies.size());
4239 
4240  v.dependencies.insert(v.dependencies.end(),
4241  additional_dependencies.begin(), additional_dependencies.end());
4242  v.dependenciesKind.insert(v.dependenciesKind.end(),
4243  additional_dependencies_kind.begin(), additional_dependencies_kind.end());
4244 
4245  // Mark interdependencies
4246  for (casadi_int d : v.dependencies) variable(d).dependency = true;
4247  for (casadi_int d : v.dependencies) variable(d).in_rhs = true;
4248  }
4249  }
4250  // Outputs
4251  if (n.has_child("Outputs")) {
4252  for (const auto& e : n["Outputs"].children) {
4253  // Get index
4254  indices(Category::Y).push_back(convert_index(e.attribute<casadi_int>("index", 0)));
4255  // Corresponding variable
4256  Variable& v = variable(indices(Category::Y).back());
4257 
4258  // Get dependencies
4259  if (e.has_attribute("dependencies")) {
4260  v.dependencies = read_dependencies(e);
4261  } else {
4262  v.dependencies = default_dependencies;
4263  }
4264  v.dependenciesKind = read_dependencies_kind(e, v.dependencies.size());
4265 
4266  v.dependencies.insert(v.dependencies.end(),
4267  additional_dependencies.begin(), additional_dependencies.end());
4268  v.dependenciesKind.insert(v.dependenciesKind.end(),
4269  additional_dependencies_kind.begin(), additional_dependencies_kind.end());
4270 
4271  // Mark interdependencies
4272  for (casadi_int d : v.dependencies) variable(d).dependency = true;
4273  for (casadi_int d : v.dependencies) variable(d).in_rhs = true;
4274  }
4275  }
4276  // What if dependencies is missing from InitialUnknowns?
4277  // Depends on x_ having been populated
4278  default_dependencies.clear();
4279  default_dependencies.insert(default_dependencies.begin(),
4280  indices(Category::T).begin(), indices(Category::T).end());
4281  for (const Variable* v : variables_) {
4282  if (v->initial == Initial::EXACT) default_dependencies.push_back(v->index);
4283  }
4284  default_dependencies.insert(default_dependencies.begin(),
4285  indices(Category::U).begin(), indices(Category::U).end());
4286  std::sort(default_dependencies.begin(), default_dependencies.end());
4287 
4288  // Initial unknowns
4289  if (n.has_child("InitialUnknowns")) {
4290  for (const auto& e : n["InitialUnknowns"].children) {
4291  // Get index
4292  initial_unknowns_.push_back(convert_index(e.attribute<casadi_int>("index", 0)));
4293 
4294  std::vector<casadi_int> dependencies;
4295  // Get dependencies
4296  if (e.has_attribute("dependencies")) {
4297  dependencies = read_dependencies(e);
4298  } else {
4299  dependencies = default_dependencies;
4300  }
4301 
4302  dependencies.insert(dependencies.end(),
4303  additional_dependencies.begin(), additional_dependencies.end());
4304 
4305  // Get dependencies
4306  for (casadi_int d : dependencies) variable(d).dependency = true;
4307  }
4308  }
4309  }
4310 
4311  // Reclassify some states as quadratures
4312  if (detect_quad_ && fmi_major_ >= 2) {
4313  for (size_t i : der_) {
4314  size_t x = variable(i).parent;
4315  if (!variable(x).in_rhs) categorize(x, Category::Q);
4316  }
4317  }
4318 }
std::vector< size_t > initial_unknowns_
std::vector< DependenciesKind > read_dependencies_kind(const XmlNode &n, size_t ndep)
casadi_int convert_index(casadi_int index) const
std::vector< casadi_int > read_dependencies(const XmlNode &n)
XmlNode import_ls_dae(const std::string &lsdae)
static bool exists(const std::string &path)
Definition: filesystem.cpp:150
const std::string & path() const
Get path for a consumer.
Definition: resource.cpp:70
bool dependency
Do other expressions depend on this variable.

References casadi::ALG, casadi::XmlNode::attribute(), categorize(), casadi::Variable::category, casadi::XmlNode::children, convert_index(), casadi::Variable::dependencies, casadi::Variable::dependenciesKind, casadi::Variable::dependency, casadi::DEPENDENT, casadi::Variable::der, der_, detect_quad_, enable_ls_dae_, casadi::EXACT, casadi::Filesystem::exists(), fmi_major_, casadi::XmlNode::has_child(), import_ls_dae(), casadi::Variable::in_rhs, casadi::Variable::index, indices(), initial_unknowns_, n_variables(), casadi::Variable::name, casadi::XmlNode::name, nzero_, casadi::P, casadi::Variable::parent, casadi::Resource::path(), casadi::Q, read_dependencies(), read_dependencies_kind(), resource_, casadi::XmlNode::size(), size(), casadi::T, casadi::U, variable(), variables_, vrmap_, casadi::W, casadi::X, casadi::Y, casadi::Z, and casadi::ZERO.

Referenced by load_fmi_description().

◆ import_model_variables()

void casadi::DaeBuilderInternal::import_model_variables ( const XmlNode modvars)
protected

Extra doc: https://github.com/casadi/casadi/wiki/L_2ft

Definition at line 3847 of file dae_builder_internal.cpp.

3847  {
3848  // Mapping from derivative variables to corresponding state variables, FMUX only
3849  std::vector<std::pair<std::string, std::string>> fmi1_der;
3850 
3851  // Add variables
3852  for (casadi_int i = 0; i < modvars.size(); ++i) {
3853  // Get a reference to the variable
3854  const XmlNode& vnode = modvars[i];
3855 
3856  // Name of variable
3857  std::string name = vnode.attribute<std::string>("name");
3858 
3859  // Handle variable categories (FMUX)
3860  if (fmi_major_ == 1 && vnode.has_child("VariableCategory")) {
3861  std::string variable_category = vnode["VariableCategory"].text;
3862  if (variable_category == "derivative") {
3863  // Create a new derivative variable
3864  std::string x_name = vnode["QualifiedName"][0].attribute<std::string>("name");
3865  fmi1_der.push_back(std::make_pair(x_name, name));
3866  }
3867  }
3868 
3869  // When conditions are reformulated into continuous zero-crossing functions
3870  if (fmi_major_ == 1 && name.rfind("$whenCondition", 0) == 0) continue;
3871 
3872  // Ignore duplicate variables
3873  if (varind_.find(name) != varind_.end()) {
3874  casadi_warning("Duplicate variable '" + name + "' ignored");
3875  continue;
3876  }
3877 
3878  // Type specific properties
3879  Dict opts;
3880  Type type = Type::NUMEL;
3881  casadi_int derivative = -1;
3882  if (fmi_major_ >= 3) {
3883  // FMI 3.0: Type information in the same node
3884  type = to_enum<Type>(vnode.name);
3885  switch (type) {
3886  case Type::FLOAT32: // fall-through
3887  case Type::FLOAT64:
3888  // Floating point valued variables
3889  opts["unit"] = vnode.attribute<std::string>("unit", "");
3890  opts["display_unit"] = vnode.attribute<std::string>("displayUnit", "");
3891  opts["min"] = vnode.attribute<double>("min", -inf);
3892  opts["max"] = vnode.attribute<double>("max", inf);
3893  opts["nominal"] = vnode.attribute<double>("nominal", 1.);
3894  opts["start"] = vnode.attribute<double>("start", 0.);
3895  derivative = vnode.attribute<casadi_int>("derivative", -1);
3896  break;
3897  case Type::INT8: // fall-through
3898  case Type::UINT8: // fall-through
3899  case Type::INT16: // fall-through
3900  case Type::UINT16: // fall-through
3901  case Type::INT32: // fall-through
3902  case Type::UINT32: // fall-through
3903  case Type::INT64: // fall-through
3904  case Type::UINT64: // fall-through
3905  // Integer valued variables
3906  opts["min"] = vnode.attribute<double>("min", -inf);
3907  opts["max"] = vnode.attribute<double>("max", inf);
3908  break;
3909  default:
3910  break;
3911  }
3912  } else {
3913  // FMI 1.0 / 2.0: Type information in a separate node
3914  if (vnode.has_child("Real")) {
3915  type = Type::FLOAT64;
3916  const XmlNode& props = vnode["Real"];
3917  opts["unit"] = props.attribute<std::string>("unit", "");
3918  opts["display_unit"] = props.attribute<std::string>("displayUnit", "");
3919  opts["min"] = props.attribute<double>("min", -inf);
3920  opts["max"] = props.attribute<double>("max", inf);
3921  opts["nominal"] = props.attribute<double>("nominal", 1.);
3922  opts["start"] = props.attribute<double>("start", 0.);
3923  derivative = props.attribute<casadi_int>("derivative", -1);
3924  } else if (vnode.has_child("Integer")) {
3925  type = Type::INT32;
3926  const XmlNode& props = vnode["Integer"];
3927  opts["min"] = props.attribute<double>("min", -inf);
3928  opts["max"] = props.attribute<double>("max", inf);
3929  } else if (vnode.has_child("Boolean")) {
3930  type = Type::BOOLEAN;
3931  } else if (vnode.has_child("String")) {
3932  type = Type::STRING;
3933  } else if (vnode.has_child("Enumeration")) {
3934  type = Type::ENUMERATION;
3935  } else {
3936  casadi_warning("Unknown type for " + name);
3937  }
3938  }
3939 
3940  // Description
3941  std::string description = vnode.attribute<std::string>("description", "");
3942 
3943  // Causality (FMI 1.0 -> FMI 2.0+)
3944  std::string causality_str = vnode.attribute<std::string>("causality", "local");
3945  if (fmi_major_ == 1 && causality_str == "internal") causality_str = "local";
3946  Causality causality = to_enum<Causality>(causality_str);
3947 
3948  // Variability (FMI 1.0 -> FMI 2.0+)
3949  std::string variability_str = vnode.attribute<std::string>("variability",
3951  if (fmi_major_ == 1 && variability_str == "parameter") variability_str = "fixed";
3952  Variability variability = to_enum<Variability>(variability_str);
3953 
3954  // Initial property
3956  std::string initial_str = vnode.attribute<std::string>("initial", "");
3957  if (!initial_str.empty()) {
3958  // Consistency check
3960  "The combination causality = '" + to_string(causality) + "', "
3961  "initial = '" + initial_str + "' is not allowed per the FMI specification.");
3962  initial = to_enum<Initial>(initial_str);
3963  }
3964 
3965  // If an input has a description that starts with "PARAMETER:",
3966  // treat it as a tunable parameter
3967  if (causality == Causality::INPUT && description.rfind("PARAMETER:", 0) == 0) {
3968  // Make tunable parameter
3971  }
3972 
3973  // Create the new variable
3974  opts["type"] = to_string(type);
3975  opts["initial"] = to_string(initial);
3976  opts["description"] = description;
3977  Variable& var = add(name, causality, variability, opts);
3978  if (debug_) uout() << "Added variable: " << var.name << std::endl;
3979 
3980  // Ignore time variable?
3982  categorize(var.index, Category::NUMEL);
3983  }
3984 
3985  // Do not permit discrete variables in x, for now
3987  categorize(var.index, Category::NUMEL);
3988  }
3989 
3990  // Derivative attribute
3991  var.der_of = derivative;
3992 
3993  // Unless detect_quad has been set, assume all variables in the right-hand-sides
3994  // Prevents changing X to Q
3995  var.in_rhs = !detect_quad_ && fmi_major_ >= 2;
3996  var.value_reference = static_cast<unsigned int>(vnode.attribute<casadi_int>("valueReference"));
3997 
3998  // Add to variable reference map
3999  vrmap_[var.value_reference] = var.index;
4000  }
4001 
4002  // Set "parent" property using "derivative" attribute
4003  for (size_t i = 0; i < n_variables(); ++i) {
4004  Variable& v = variable(i);
4005  if (v.der_of >= 0) {
4006  if (fmi_major_ >= 3) {
4007  // Value reference is given: Find corresponding variable
4008  v.parent = vrmap_.at(static_cast<unsigned int>(v.der_of));
4009  } else if (fmi_major_ > 1) {
4010  // Variable given with index-1, make index 0
4011  v.parent = convert_index(v.der_of);
4012  }
4013  // TODO(@jaeandersson): Remove this redefinition of der_of
4014  v.der_of = v.parent;
4015  }
4016  }
4017 
4018  // Map derivative variables to corresponding state variables, FMUX only
4019  for (auto& p : fmi1_der) {
4020  // Add to list of derivatives
4021  Variable& v = variable(p.first);
4022  Variable& der_v = variable(p.second);
4023  categorize(der_v.index, Category::Z);
4024  der_v.der_of = der_v.parent = v.index;
4025  v.der = der_v.index;
4026  der_.push_back(der_v.index);
4027  }
4028 }
Variability
Variability: FMI 2.0 specification, section 2.2.7 or FMI 3.0 specification, section 2....
Initial
Initial: FMI 2.0 specification, section 2.2.7 or FMI 3.0 specification, section 2....
Causality
Causality: FMI 2.0 specification, section 2.2.7 or FMI 3.0 specification, section 2....

References add(), casadi::XmlNode::attribute(), casadi::BOOLEAN, categorize(), causality(), convert_index(), debug_, default_initial(), default_variability(), casadi::Variable::der, der_, casadi::Variable::der_of, casadi::description(), detect_quad_, casadi::DISCRETE, casadi::ENUMERATION, casadi::FLOAT32, casadi::FLOAT64, fmi_major_, casadi::XmlNode::has_child(), ignore_time_, casadi::INDEPENDENT, casadi::Variable::index, casadi::inf, casadi::INPUT, casadi::INT16, casadi::INT32, casadi::INT64, casadi::INT8, n_variables(), casadi::MX::name(), name(), casadi::XmlNode::name, casadi::NUMEL, casadi::PARAMETER, casadi::Variable::parent, casadi::XmlNode::size(), casadi::STRING, casadi::XmlNode::text, casadi::to_string(), casadi::TUNABLE, casadi::UINT16, casadi::UINT32, casadi::UINT64, casadi::UINT8, casadi::uout(), var(), variability(), variable(), varind_, vrmap_, and casadi::Z.

Referenced by load_fmi_description().

◆ indices() [1/2]

std::vector< size_t > & casadi::DaeBuilderInternal::indices ( Category  cat)

◆ indices() [2/2]

const std::vector< size_t > & casadi::DaeBuilderInternal::indices ( Category  cat) const

Definition at line 1793 of file dae_builder_internal.cpp.

1793  {
1794  return const_cast<DaeBuilderInternal*>(this)->indices(cat);
1795 }

References indices().

◆ init_lhs()

std::vector< MX > casadi::DaeBuilderInternal::init_lhs ( ) const
protected

Extra doc: https://github.com/casadi/casadi/wiki/L_2a7

Definition at line 3138 of file dae_builder_internal.cpp.

3138  {
3139  std::vector<MX> ret;
3140  ret.reserve(init_.size());
3141  for (size_t ind : init_) {
3142  ret.push_back(variable(ind).v);
3143  }
3144  return ret;
3145 }

References init_, and variable().

◆ init_rhs()

std::vector< MX > casadi::DaeBuilderInternal::init_rhs ( ) const
protected

Extra doc: https://github.com/casadi/casadi/wiki/L_2a8

Definition at line 3147 of file dae_builder_internal.cpp.

3147  {
3148  std::vector<MX> ret;
3149  ret.reserve(init_.size());
3150  for (size_t ind : init_) {
3151  ret.push_back(variable(ind).ieq);
3152  }
3153  return ret;
3154 }

References init_, and variable().

Referenced by set_init().

◆ initSingleton()

void casadi::GenericSharedInternal< SharedObject , SharedObjectInternal >::initSingleton ( )
inlineprotectedinherited

Called in the constructor of singletons to avoid that the counter reaches zero

Definition at line 71 of file generic_shared_internal.hpp.

71  {
72  casadi_assert_dev(static_cast<Internal*>(this)->count==0);
73  static_cast<Internal*>(this)->count++;
74  }

◆ inputs() [1/2]

std::vector< MX > casadi::DaeBuilderInternal::inputs ( Category  ind) const

Definition at line 2236 of file dae_builder_internal.cpp.

2236  {
2237  // Operation only permitted for input categories
2238  casadi_assert(is_input_category(ind),
2239  to_string(ind) + " is not an input category");
2240  // Get the expressions
2241  return var(indices(ind));
2242 }
bool is_input_category(Category cat)

References indices(), casadi::is_input_category(), casadi::to_string(), and var().

Referenced by dependent_fun(), inputs(), oracle(), and prune().

◆ inputs() [2/2]

std::vector< MX > casadi::DaeBuilderInternal::inputs ( const std::vector< Category > &  ind) const

Definition at line 2244 of file dae_builder_internal.cpp.

2244  {
2245  std::vector<MX> ret(ind.size());
2246  for (casadi_int i=0; i<ind.size(); ++i) {
2247  ret[i] = vertcat(inputs(ind[i]));
2248  }
2249  return ret;
2250 }

References inputs().

◆ insert()

void casadi::DaeBuilderInternal::insert ( std::vector< size_t > &  v,
size_t  ind 
) const
protected

Definition at line 3408 of file dae_builder_internal.cpp.

3408  {
3409  // Keep list ordered: Insert at location corresponding to model variable index
3410  size_t loc = v.size();
3411  for (size_t i = 0; i < v.size(); ++i) {
3412  if (variable(v[i]).index >= ind) {
3413  loc = i;
3414  break;
3415  }
3416  }
3417  v.insert(v.begin() + loc, ind);
3418 }

References variable().

Referenced by categorize(), and set_causality().

◆ iso_8601_time()

std::string casadi::DaeBuilderInternal::iso_8601_time ( )
static

Definition at line 4789 of file dae_builder_internal.cpp.

4789  {
4790  // Get current time
4791  auto now = std::chrono::system_clock::now();
4792  std::time_t tt = std::chrono::system_clock::to_time_t(now);
4793  auto local_tm = *std::localtime(&tt); // NOLINT(runtime/threadsafe_fn)
4794  // Convert to ISO 8601 (YYYY-MM-DDThh:mm:ssZ) format and return
4795  std::stringstream ss;
4796  ss << local_tm.tm_year + 1900 << '-'; // YYYY-
4797  ss << std::setfill('0') << std::setw(2) << local_tm.tm_mon + 1 << '-'; // MM-
4798  ss << std::setfill('0') << std::setw(2) << local_tm.tm_mday << 'T'; // DDT
4799  ss << std::setfill('0') << std::setw(2) << local_tm.tm_hour << ':'; // hh:
4800  ss << std::setfill('0') << std::setw(2) << local_tm.tm_min << ':'; // mm:
4801  ss << std::setfill('0') << std::setw(2) << local_tm.tm_sec << 'Z'; // ssZ
4802  return ss.str();
4803 }

Referenced by generate_model_description().

◆ jac_sparsity()

Sparsity casadi::DaeBuilderInternal::jac_sparsity ( const std::vector< size_t > &  oind,
const std::vector< size_t > &  iind 
) const

Definition at line 4721 of file dae_builder_internal.cpp.

4722  {
4723  // Mark inputs
4724  std::vector<casadi_int> lookup(n_variables(), -1);
4725  for (size_t i = 0; i < iind.size(); ++i)
4726  lookup.at(iind[i]) = i;
4727  // Sparsity pattern for the Jacobian block
4728  std::vector<casadi_int> row, col;
4729  // Loop over output nonzeros
4730  for (casadi_int j = 0; j < oind.size(); ++j) {
4731  for (casadi_int d : variable(oind[j]).dependencies) {
4732  casadi_int i = lookup.at(d);
4733  if (i >= 0) {
4734  row.push_back(j); // Note: May not be sorted in ascending order
4735  col.push_back(i);
4736  }
4737  }
4738  }
4739  // Assemble sparsity in triplet format
4740  return Sparsity::triplet(oind.size(), iind.size(), row, col);
4741 }

References n_variables(), casadi::Sparsity::triplet(), and variable().

Referenced by casadi::FmuInternal::init().

◆ jac_vdef_v_from_calls()

MX casadi::DaeBuilderInternal::jac_vdef_v_from_calls ( std::map< MXNode *, CallIO > &  call_nodes,
const std::vector< casadi_int > &  h_offsets 
) const
protected

Definition at line 2491 of file dae_builder_internal.cpp.

2492  {
2493  // Calculate all Jacobian expressions
2494  for (auto call_it = call_nodes.begin(); call_it != call_nodes.end(); ++call_it) {
2495  call_it->second.calc_jac();
2496  }
2497  // Row offsets in jac_vdef_v
2498  casadi_int voffset_begin = 0, voffset_end = 0, voffset_last = 0;
2499  // Vertical and horizontal slices of jac_vdef_v
2500  std::vector<MX> vblocks, hblocks;
2501  // All blocks for this block row
2502  std::map<size_t, MX> jac_brow;
2503  // Definitions of w
2504  std::vector<MX> wdef = outputs(Category::WDEF);
2505  // Collect all Jacobian blocks
2506  for (size_t vdefind = 0; vdefind < wdef.size(); ++vdefind) {
2507  // Current element handled
2508  const MX& vdefref = wdef.at(vdefind);
2509  // Update vertical offset
2510  voffset_begin = voffset_end;
2511  voffset_end += vdefref.numel();
2512  // Handle function call nodes
2513  if (vdefref.is_output()) {
2514  // Which output of the function are we calculating?
2515  casadi_int oind = vdefref.which_output();
2516  // Get function call node
2517  MX c = vdefref.dep(0);
2518  // Find data about inputs and outputs
2519  auto call_it = call_nodes.find(c.get());
2520  casadi_assert_dev(call_it != call_nodes.end());
2521  // Collect all blocks for this block row
2522  jac_brow.clear();
2523  for (casadi_int iind = 0; iind < call_it->second.arg.size(); ++iind) {
2524  size_t vind = call_it->second.v.at(iind);
2525  if (vind != size_t(-1)) {
2526  jac_brow[vind] = call_it->second.jac(oind, iind);
2527  }
2528  }
2529  // Add empty rows to vblocks, if any
2530  if (voffset_last != voffset_begin) {
2531  vblocks.push_back(MX(voffset_begin - voffset_last, h_offsets.back()));
2532  }
2533  // Collect horizontal blocks
2534  hblocks.clear();
2535  casadi_int hoffset = 0;
2536  for (auto e : jac_brow) {
2537  // Add empty block before Jacobian block, if needed
2538  if (hoffset < h_offsets.at(e.first))
2539  hblocks.push_back(MX(vdefref.numel(), h_offsets.at(e.first) - hoffset));
2540  // Add Jacobian block
2541  hblocks.push_back(e.second);
2542  // Update offsets
2543  hoffset = h_offsets.at(e.first + 1);
2544  }
2545  // Add trailing empty block, if needed
2546  if (hoffset < h_offsets.back())
2547  hblocks.push_back(MX(vdefref.numel(), h_offsets.back() - hoffset));
2548  // Add new block row to vblocks
2549  vblocks.push_back(horzcat(hblocks));
2550  // Keep track of the offset handled in jac_brow
2551  voffset_last = voffset_end;
2552  }
2553  }
2554  // Add empty trailing row to vblocks, if any
2555  if (voffset_last != voffset_end) {
2556  vblocks.push_back(MX(voffset_end - voffset_last, h_offsets.back()));
2557  }
2558  // Return additional term in jac_vdef_v
2559  return vertcat(vblocks);
2560 }

References casadi::MX::dep(), casadi::MX::find(), casadi::MX::get(), casadi::MX::is_output(), casadi::GenericMatrix< MatType >::numel(), outputs(), casadi::WDEF, and casadi::MX::which_output().

Referenced by create().

◆ lift()

void casadi::DaeBuilderInternal::lift ( bool  lift_shared,
bool  lift_calls 
)

Definition at line 2195 of file dae_builder_internal.cpp.

2195  {
2196  // Not tested if w is non-empty before
2197  if (size(Category::W) > 0) casadi_warning("'w' already has entries");
2198  // Expressions where the variables are also being used
2199  std::vector<MX> ex;
2200  for (size_t v : indices(Category::X)) ex.push_back(variable(variable(variable(v).der).bind).v);
2201  for (size_t v : indices(Category::Q)) ex.push_back(variable(variable(variable(v).der).bind).v);
2202  for (size_t v : indices(Category::ALG)) ex.push_back(variable(v).v);
2203  // Lift expressions
2204  std::vector<MX> new_w, new_wdef;
2205  Dict opts{{"lift_shared", lift_shared}, {"lift_calls", lift_calls},
2206  {"prefix", "w_"}, {"suffix", ""}, {"offset", static_cast<casadi_int>(size(Category::W))}};
2207  extract(ex, new_w, new_wdef, opts);
2208  // Register as dependent variables
2209  for (size_t i = 0; i < new_w.size(); ++i) {
2210  Variable& v = new_variable(new_w.at(i).name());
2211  v.v = new_w.at(i);
2212  Variable& v_beq = assign(v.name, new_wdef.at(i));
2213  v.bind = v_beq.index;
2214  indices(Category::W).push_back(v.index);
2215  }
2216  // Get expressions
2217  auto it = ex.begin();
2218  for (size_t v : indices(Category::X)) variable(variable(variable(v).der).bind).v = *it++;
2219  for (size_t v : indices(Category::Q)) variable(variable(variable(v).der).bind).v = *it++;
2220  for (size_t v : indices(Category::ALG)) variable(v).v = *it++;
2221  // Consistency check
2222  casadi_assert_dev(it == ex.end());
2223 }

References casadi::ALG, assign(), casadi::Variable::bind, der(), casadi::Variable::index, indices(), casadi::Variable::name, new_variable(), casadi::Q, size(), casadi::Variable::v, variable(), casadi::W, and casadi::X.

◆ load_fmi_description()

void casadi::DaeBuilderInternal::load_fmi_description ( const std::string &  filename)

Import existing problem from FMI/XML

Definition at line 702 of file dae_builder_internal.cpp.

702  {
703  // Check if file exists
705  if (Filesystem::is_enabled()) {
706  casadi_error("Could not open file '" + filename + "'.");
707  } else {
708  casadi_error("Could not open file '" + filename + "'. "
709  "Note that, since CasADi was compiled without WITH_GHC_FILESYSTEM=ON, "
710  "passing fmu files to DaeBuilder is unsupported. "
711  "You could manually unzip the FMU file and "
712  "pass the path to the unzipped directory instead.");
713  }
714  }
715 
716  // Ensure no variables already
717  casadi_assert(n_variables() == 0, "Instance already has variables");
718 
719  // Parse XML file
720  XmlFile xml_file("tinyxml");
721  XmlNode fmi_desc = xml_file.parse(filename)[0]; // One child; fmiModelDescription
722 
723  // Read FMU version
724  fmi_version_ = fmi_desc.attribute<std::string>("fmiVersion", "");
725  if (fmi_version_.rfind("1.", 0) == 0) {
726  // FMI 1.0: Only for symbolic FMUs
727  fmi_major_ = 1;
728  } else if (fmi_version_.rfind("2.", 0) == 0) {
729  // FMI 2.0
730  fmi_major_ = 2;
731  } else if (fmi_version_.rfind("3.", 0) == 0) {
732  // FMI 3
733  fmi_major_ = 3;
734  } else {
735  casadi_error("Unknown FMI version: " + fmi_version_);
736  }
737 
738  // Read attributes
739  model_name_ = fmi_desc.attribute<std::string>("modelName", "");
740  instantiation_token_ = fmi_desc.attribute<std::string>(
741  fmi_major_ >= 3 ? "instantiationToken" : "guid");
742  description_ = fmi_desc.attribute<std::string>("description", "");
743  author_ = fmi_desc.attribute<std::string>("author", "");
744  copyright_ = fmi_desc.attribute<std::string>("copyright", "");
745  license_ = fmi_desc.attribute<std::string>("license", "");
746  generation_tool_ = fmi_desc.attribute<std::string>("generationTool", "");
747  generation_date_and_time_ = fmi_desc.attribute<std::string>("generationDateAndTime", "");
748  variable_naming_convention_ = fmi_desc.attribute<std::string>("variableNamingConvention", "");
749  if (fmi_major_ >= 3) {
750  nzero_ = 0; // In FMI 3: Obtain from binary
751  } else {
752  nzero_ = fmi_desc.attribute<casadi_int>("numberOfEventIndicators", 0);
753  }
754 
755  // Process DefaultExperiment
756  if (fmi_desc.has_child("DefaultExperiment")) {
757  import_default_experiment(fmi_desc["DefaultExperiment"]);
758  }
759 
760  // Process ModelExchange
761  bool has_model_exchange = false;
762  if (fmi_desc.has_child("ModelExchange")) {
763  has_model_exchange = true;
764  import_model_exchange(fmi_desc["ModelExchange"]);
765  }
766 
767  // Process ModelVariables
768  casadi_assert(fmi_desc.has_child("ModelVariables"), "Missing 'ModelVariables'");
769  import_model_variables(fmi_desc["ModelVariables"]);
770 
771  // Process model structure
772  if (fmi_desc.has_child("ModelStructure")) {
773  import_model_structure(fmi_desc["ModelStructure"]);
774  }
775 
776  // Is a symbolic representation available?
777  symbolic_ = false; // use DLL by default
778 
779  // Look for serialized CasADi expressions
781  try {
782  // Load function oracle from file
783  Function oracle = Function::load(resource_.path()
784  + "/extra/org.casadi.fmi-ls-serialization/oracle.casadi");
785  // Get expressions
786  auto oracle_in = oracle.mx_in();
787  auto oracle_out = oracle(oracle_in);
788  // Get all substitutions
789  std::vector<MX> v, vdef;
790  for (auto& arg : oracle_in) {
791  // Loop over symbolic primitives
792  for (auto& vp : arg.primitives()) {
793  // Find the variable
794  size_t ind = find(vp.name());
795  // Add to list of replacements
796  v.push_back(vp);
797  vdef.push_back(var(ind));
798  }
799  }
800  // Substitute expressions in oracle_in, oracle_out
801  oracle_in = substitute(oracle_in, v, vdef);
802  oracle_out = substitute(oracle_out, v, vdef);
803  // Process dependent variables
804  MX w_all = oracle_in.at(oracle.index_in("w"));
805  std::vector<MX> w = w_all.primitives();
806  std::vector<MX> wdef = w_all.split_primitives(oracle_out.at(oracle.index_out("wdef")));
807  // Loop over w
808  for (size_t i = 0; i < w.size(); ++i) {
809  // Find variable, corresponding assignment variable
810  Variable& w_i = variable(w[i].name());
811  Variable& assign_w_i = variable("__assign__" + w[i].name() + "__");
812  // Reclassify assign_w_i as dependent variable and update expression
813  categorize(assign_w_i.index, Category::CALCULATED);
814  assign_w_i.parent = w_i.index;
815  assign_w_i.v = wdef[i];
816  // Map binding equation
817  w_i.bind = assign_w_i.index;
818  }
819 
820  // Substitute expressions for algebraic variables, if any
821  if (size(Category::ALG) > 0) {
822  std::vector<MX> alg;
823  // Collect expressions to be replaced
824  for (size_t i : indices(Category::ALG)) {
825  alg.push_back(variable(i).v);
826  }
827  // Substitute expressions
828  MX alg_all = vertcat(alg);
829  alg = alg_all.split_primitives(oracle_out.at(oracle.index_out("alg")));
830  auto alg_it = alg.begin();
831  // Update expressions
832  for (size_t i : indices(Category::ALG)) {
833  // Substitute expression
834  Variable& v = variable(i);
836  v.v = *alg_it++;
837  }
838  }
839 
840  symbolic_ = true;
841  } catch (std::exception& e) {
842  // May want to output this information
843  (void)e; // unused
844  }
845  }
846 
847 
848  std::string onnx_filename = resource_.path()
849  + "/extra/org.lacemodelica.ls-onnx-serialization/model.onnx";
850  if (Filesystem::exists(onnx_filename)) {
851  // Load and symbolically import the ONNX model
852  GraphBuilder b(onnx_filename);
853  Function oracle = b.create("oracle", {{"symbolic", true}});
854 
855  // Get expressions
856  auto oracle_in = oracle.mx_in();
857  auto oracle_out = oracle(oracle_in);
858 
859  // Build mapping from input index to variable name
860  std::vector<std::string> input_var_names;
861  for (casadi_int i = 0; i < oracle.n_in(); ++i) {
862  input_var_names.push_back(oracle.name_in(i));
863  }
864 
865  // Get all substitutions: map oracle variables to DaeBuilder variables
866  std::vector<MX> v, vdef;
867  for (auto& arg : oracle_in) {
868  // Loop over symbolic primitives
869  for (auto& vp : arg.primitives()) {
870  // Find the variable by name
871  size_t ind = find(vp.name());
872  // Add to list of replacements
873  v.push_back(vp);
874  vdef.push_back(var(ind));
875  }
876  }
877 
878  // Substitute expressions in oracle outputs
879  oracle_out = substitute(oracle_out, v, vdef);
880 
881  // Process each output based on its category
882  // Output naming convention from Lace Modelica:
883  // eq[N] - equation residual (lhs - rhs = 0)
884  // init_eq[N] - initial equation residual
885  // start[N] - start value for variable at input index N
886  // min[N] - minimum bound for variable at input index N
887  // max[N] - maximum bound for variable at input index N
888  for (size_t i = 0; i < oracle_out.size(); ++i) {
889  std::string out_name = oracle.name_out(i);
890  MX expr = oracle_out[i];
891 
892  // Parse the output name to determine category
893  bool is_init_eq = out_name.substr(0, 8) == "init_eq[";
894  bool is_dyn_eq = out_name.substr(0, 3) == "eq[" && !is_init_eq;
895 
896  if (is_dyn_eq || is_init_eq) {
897  // Equation residual: (lhs - rhs) = 0, so lhs = rhs
898  // Check if it's a subtraction with 2 dependencies
899  if (expr.n_dep() == 2) {
900  MX lhs = expr.dep(0); // The left-hand side
901  MX rhs = expr.dep(1); // The right-hand side
902 
903  if (is_init_eq) {
904  // Initial equation: set initial value for the variable
905  if (lhs.is_symbolic()) {
906  std::string var_name = lhs.name();
907  set_init(var_name, rhs);
908  }
909  } else {
910  // Dynamic equation
911  if (lhs.is_symbolic()) {
912  // Simple variable on LHS: var = rhs (binding equation)
913  std::string var_name = lhs.name();
914  size_t var_ind = find(var_name);
915  Variable& var_ref = variable(var_ind);
916  var_ref.bind = assign(var_name, rhs).index;
917  } else {
918  // Complex expression on LHS (e.g., m*c_p*der(T))
919  // Use implicit residual form: 0 = lhs - rhs
920  eq(MX(0), lhs - rhs, Dict());
921  }
922  }
923  }
924  } else if (out_name.substr(0, 6) == "start[") {
925  // Start value: start[N] where N is the input index
926  size_t bracket_pos = out_name.find('[');
927  size_t close_pos = out_name.find(']');
928  if (bracket_pos != std::string::npos && close_pos != std::string::npos) {
929  casadi_int idx = std::stoi(out_name.substr(bracket_pos + 1, close_pos - bracket_pos - 1));
930  if (idx >= 0 && idx < static_cast<casadi_int>(input_var_names.size())) {
931  std::string var_name = input_var_names[idx];
932  Variable& var_ref = variable(var_name);
933  // If it's a constant, we can evaluate it
934  if (expr.is_constant()) {
935  DM dm_val = static_cast<DM>(expr);
936  var_ref.start = std::vector<double>(dm_val->begin(), dm_val->end());
937  }
938  // TODO(jgillis): Handle symbolic start expressions
939  }
940  }
941  } else if (out_name.substr(0, 4) == "min[") {
942  // Minimum bound: min[N] where N is the input index
943  size_t bracket_pos = out_name.find('[');
944  size_t close_pos = out_name.find(']');
945  if (bracket_pos != std::string::npos && close_pos != std::string::npos) {
946  casadi_int idx = std::stoi(out_name.substr(bracket_pos + 1, close_pos - bracket_pos - 1));
947  if (idx >= 0 && idx < static_cast<casadi_int>(input_var_names.size())) {
948  std::string var_name = input_var_names[idx];
949  Variable& var_ref = variable(var_name);
950  // If it's a constant, we can evaluate it
951  if (expr.is_constant()) {
952  DM dm_val = static_cast<DM>(expr);
953  var_ref.min = static_cast<double>(dm_val);
954  }
955  // TODO(jgillis): Handle symbolic min expressions
956  }
957  }
958  } else if (out_name.substr(0, 4) == "max[") {
959  // Maximum bound: max[N] where N is the input index
960  size_t bracket_pos = out_name.find('[');
961  size_t close_pos = out_name.find(']');
962  if (bracket_pos != std::string::npos && close_pos != std::string::npos) {
963  casadi_int idx = std::stoi(out_name.substr(bracket_pos + 1, close_pos - bracket_pos - 1));
964  if (idx >= 0 && idx < static_cast<casadi_int>(input_var_names.size())) {
965  std::string var_name = input_var_names[idx];
966  Variable& var_ref = variable(var_name);
967  // If it's a constant, we can evaluate it
968  if (expr.is_constant()) {
969  DM dm_val = static_cast<DM>(expr);
970  var_ref.max = static_cast<double>(dm_val);
971  }
972  // TODO(jgillis): Handle symbolic max expressions
973  }
974  }
975  }
976  }
977 
978  symbolic_ = true;
979  }
980 
981  // Add symbolic binding equations
982  if (fmi_desc.has_child("equ:BindingEquations")) {
983  symbolic_ = true;
984  import_binding_equations(fmi_desc["equ:BindingEquations"]);
985  }
986 
987  // Add symbolic initial equations
988  if (fmi_desc.has_child("equ:InitialEquations")) {
989  symbolic_ = true;
990  import_initial_equations(fmi_desc["equ:InitialEquations"]);
991  }
992 
993  // Add symbolic dynamic equations
994  if (fmi_desc.has_child("equ:DynamicEquations")) {
995  symbolic_ = true;
996  import_dynamic_equations(fmi_desc["equ:DynamicEquations"]);
997  }
998 
999  // Ensure model equations are available, binary or symbolic
1000  casadi_assert(symbolic_ || has_model_exchange,
1001  "FMU must be of ModelExchange type or be symbolic (FMUX)");
1002 }
void import_model_structure(const XmlNode &n)
void import_dynamic_equations(const XmlNode &eqs)
void import_model_variables(const XmlNode &modvars)
Read ModelVariables.
void import_model_exchange(const XmlNode &n)
void import_initial_equations(const XmlNode &eqs)
void import_default_experiment(const XmlNode &n)
void import_binding_equations(const XmlNode &eqs)
static bool is_enabled()
Definition: filesystem.cpp:83
const std::vector< std::string > & name_in() const
Get input scheme.
Definition: function.cpp:1113
casadi_int index_in(const std::string &name) const
Find the index for a string describing a particular entry of an input scheme.
Definition: function.cpp:1121
casadi_int n_in() const
Get the number of function inputs.
Definition: function.cpp:971
static Function load(const std::string &filename)
Build function from serialization.
Definition: function.cpp:1546
casadi_int index_out(const std::string &name) const
Find the index for a string describing a particular entry of an output scheme.
Definition: function.cpp:1129
const std::vector< std::string > & name_out() const
Get output scheme.
Definition: function.cpp:1117
Matrix< double > DM
Definition: dm_fwd.hpp:33
std::string filename(const std::string &path)
Definition: ghc.cpp:55

References casadi::ALG, assign(), casadi::XmlNode::attribute(), author_, casadi::Variable::bind, casadi::CALCULATED, categorize(), copyright_, casadi::GraphBuilder::create(), casadi::MX::dep(), description_, enable_ls_serialization_, eq(), casadi::Filesystem::exists(), casadi::filename(), find(), fmi_major_, fmi_version_, generation_date_and_time_, generation_tool_, casadi::XmlNode::has_child(), import_binding_equations(), import_default_experiment(), import_dynamic_equations(), import_initial_equations(), import_model_exchange(), import_model_structure(), import_model_variables(), casadi::Variable::index, casadi::Function::index_in(), casadi::Function::index_out(), indices(), instantiation_token_, casadi::MX::is_constant(), casadi::Filesystem::is_enabled(), casadi::MX::is_symbolic(), license_, casadi::Function::load(), casadi::Variable::max, casadi::Variable::min, model_name_, casadi::Function::mx_in(), casadi::MX::n_dep(), casadi::Function::n_in(), n_variables(), casadi::MX::name(), name(), casadi::Function::name_in(), casadi::Function::name_out(), nzero_, oracle(), casadi::Variable::parent, casadi::XmlFile::parse(), casadi::Resource::path(), casadi::MX::primitives(), resource_, set_init(), size(), casadi::MX::split_primitives(), casadi::Variable::start, symbolic_, casadi::Variable::v, var(), variable(), and variable_naming_convention_.

◆ n_mem()

size_t casadi::DaeBuilderInternal::n_mem ( ) const

Definition at line 2037 of file dae_builder_internal.cpp.

2037  {
2038  size_t n = 0;
2039  for (const Variable* v : variables_) n += v->numel;
2040  return n;
2041 }

References variables_.

Referenced by generate_wrapper().

◆ n_variables()

size_t casadi::DaeBuilderInternal::n_variables ( ) const
inline

◆ name() [1/2]

std::vector< std::string > casadi::DaeBuilderInternal::name ( const std::vector< size_t > &  ind) const

Extra doc: https://github.com/casadi/casadi/wiki/L_2bw

Definition at line 4579 of file dae_builder_internal.cpp.

4579  {
4580  std::vector<std::string> r(ind.size());
4581  for (size_t i = 0; i < r.size(); ++i) r[i] = name(ind[i]);
4582  return r;
4583 }

References name().

◆ name() [2/2]

const std::string & casadi::DaeBuilderInternal::name ( size_t  ind) const

◆ new_variable()

Variable & casadi::DaeBuilderInternal::new_variable ( const std::string &  name,
const std::vector< casadi_int > &  dimension = {1},
const MX expr = MX() 
)

Definition at line 2043 of file dae_builder_internal.cpp.

2044  {
2045  // Name check
2046  casadi_assert(!name.empty(), "Name is empty string");
2047  // Try to find the component
2048  casadi_assert(!has(name), "Variable \"" + name + "\" already exists.");
2049  // Index of the variable
2050  size_t ind = n_variables();
2051  // Add to the map of all variables
2052  varind_[name] = ind;
2053  variables_.push_back(new Variable(ind, name, dimension, expr));
2054  // Clear cache
2055  clear_cache_ = true;
2056  // Return reference to new variable
2057  return *variables_.back();
2058 }
bool has(const std::string &name) const
Check if a particular variable exists.

References clear_cache_, has(), n_variables(), name(), Variable, variables_, and varind_.

Referenced by add(), lift(), and read_expr().

◆ oracle()

const Function & casadi::DaeBuilderInternal::oracle ( bool  sx = false,
bool  elim_w = false,
bool  lifted_calls = false 
) const

Definition at line 2651 of file dae_builder_internal.cpp.

2651  {
2652  casadi_assert(symbolic_, "DaeBuilder oracle only available if symbolic representation");
2653 
2654  // Clear cache now, if necessary
2655  if (clear_cache_) clear_cache();
2656  // Create an MX oracle, if needed
2657  if (oracle_[false][elim_w][lifted_calls].is_null()) {
2658  // Oracle function inputs and outputs
2659  std::vector<MX> f_in, f_out, v;
2660  std::vector<std::string> f_in_name, f_out_name;
2661  // Index for wdef
2662  casadi_int wdef_ind = -1;
2663  // Options consistency check
2664  casadi_assert(!(elim_w && lifted_calls), "Incompatible options");
2665  // Do we need to substitute out v
2666  bool subst_v = false;
2667  // Do we need to substitute out c
2668  bool subst_c = false;
2669  // Collect all DAE input variables
2670  for (Category cat : input_categories()) {
2671  v = inputs(cat);
2672  if (elim_w && cat == Category::W) {
2673  if (!v.empty()) subst_v = true;
2674  } else if (cat == Category::C) {
2675  if (!v.empty()) subst_c = true;
2676  } else {
2677  if (v.empty()) {
2678  f_in.push_back(MX(0, 1));
2679  } else {
2680  f_in.push_back(vertcat(v));
2681  }
2682  f_in_name.push_back(to_string(cat));
2683  }
2684  }
2685 
2686  // Collect all DAE output variables
2687  for (Category cat : output_categories()) {
2688  f_out_name.push_back(to_string(cat));
2689  v = outputs(cat);
2690  if (v.empty()) {
2691  f_out.push_back(MX(0, 1));
2692  } else {
2693  if (cat == Category::WDEF) wdef_ind = f_out.size();
2694  f_out.push_back(vertcat(v));
2695  }
2696  }
2697  // Eliminate v from inputs
2698  if (subst_v) {
2699  // Dependent variable definitions
2700  std::vector<MX> wdef = outputs(Category::WDEF);
2701  // Perform in-place substitution
2702  substitute_inplace(var(Category::W), wdef, f_out, false);
2703  } else if (lifted_calls && wdef_ind >= 0) {
2704  // Dependent variable definitions
2705  std::vector<MX> wdef = outputs(Category::WDEF);
2706  // Remove references to call nodes
2707  for (MX& wdefref : wdef) {
2708  if (wdefref.is_output()) wdefref = MX::zeros(wdefref.sparsity());
2709  }
2710  // Save to oracle outputs
2711  f_out.at(wdef_ind) = vertcat(wdef);
2712  }
2713  // Substitute out c from output expressions
2714  if (subst_c) {
2715  // Expression for c and corresponding definition
2716  auto c = var(Category::C);
2717  std::vector<casadi::MX> cdef;
2718  for (size_t i = 0; i < c.size(); ++i) {
2719  cdef.push_back(variable(Category::C, i).value);
2720  }
2721  // Substitute out
2722  f_out = substitute(f_out, c, cdef);
2723  }
2724 
2725  // Create oracle
2726  oracle_[false][elim_w][lifted_calls]
2727  = Function("mx_oracle", f_in, f_out, f_in_name, f_out_name);
2728  }
2729  // Return MX oracle, if requested
2730  if (!sx) return oracle_[false][elim_w][lifted_calls];
2731  // Create SX oracle, if needed
2732  Function& sx_oracle = oracle_[true][elim_w][lifted_calls];
2733  if (sx_oracle.is_null()) sx_oracle = oracle_[false][elim_w][lifted_calls].expand("sx_oracle");
2734  // Return SX oracle reference
2735  return sx_oracle;
2736 }
std::vector< MX > cdef() const
Definitions of dependent constants.
void clear_cache() const
Problem structure has changed: Clear cache.
Function expand() const
Expand a function to SX.
Definition: function.cpp:312
std::vector< Category > input_categories()

References casadi::C, cdef(), clear_cache(), clear_cache_, casadi::Function::expand(), casadi::input_categories(), inputs(), casadi::GenericShared< Shared, Internal >::is_null(), oracle_, casadi::output_categories(), outputs(), symbolic_, casadi::to_string(), var(), variable(), casadi::W, casadi::WDEF, and casadi::GenericMatrix< MX >::zeros().

Referenced by create(), load_fmi_description(), transition(), and update_dependencies().

◆ outputs() [1/2]

std::vector< MX > casadi::DaeBuilderInternal::outputs ( Category  ind) const

Definition at line 2252 of file dae_builder_internal.cpp.

2252  {
2253  // If defined by index set
2254  switch (ind) {
2255  case Category::Y: // fall-through
2256  case Category::ZERO: // fall-through
2257  case Category::ALG:
2258  return var(indices(ind));
2259  default: break;
2260  }
2261  // Otherwise: Defined by corresponding input category
2262  Category cat = input_category(ind);
2263 
2264  // Return object
2265  std::vector<MX> ret;
2266  ret.reserve(size(cat));
2267  // Handle different categories
2268  switch (ind) {
2269  case Category::ODE: // fall-through
2270  case Category::QUAD:
2271  // Differential state
2272  for (size_t v : indices(cat)) {
2273  const Variable& x = variable(v);
2274  if (x.der >= 0) {
2275  // Derivative variable
2276  ret.push_back(variable(variable(x.der).bind).v);
2277  } else if (x.variability == Variability::DISCRETE) {
2278  // Discrete variable - derivative is zero
2279  ret.push_back(MX::zeros(x.v.sparsity()));
2280  } else {
2281  // Missing ODE?
2282  casadi_error("Missing derivative for " + str(x.name));
2283  }
2284  }
2285  break;
2286  case Category::DDEF: // fall-through
2287  case Category::WDEF:
2288  // Defined by binding expression
2289  for (size_t d : indices(cat)) ret.push_back(variable(variable(d).bind).v);
2290  break;
2291  default: break;
2292  }
2293  return ret;
2294 }
Category input_category(Category cat)

References casadi::ALG, casadi::Variable::bind, casadi::DDEF, casadi::Variable::der, casadi::DISCRETE, indices(), casadi::input_category(), casadi::Variable::name, casadi::ODE, casadi::QUAD, size(), casadi::MX::sparsity(), casadi::str(), casadi::Variable::v, var(), casadi::Variable::variability, variable(), casadi::WDEF, casadi::Y, casadi::ZERO, and casadi::GenericMatrix< MX >::zeros().

Referenced by add_fun(), create(), dependent_fun(), eliminate(), gather_eq(), jac_vdef_v_from_calls(), oracle(), outputs(), prune(), sort(), and transition().

◆ outputs() [2/2]

std::vector< MX > casadi::DaeBuilderInternal::outputs ( const std::vector< Category > &  ind) const

Definition at line 2296 of file dae_builder_internal.cpp.

2296  {
2297  std::vector<MX> ret(ind.size());
2298  for (casadi_int i=0; i<ind.size(); ++i) {
2299  ret[i] = vertcat(outputs(ind[i]));
2300  }
2301  return ret;
2302 }

References outputs().

◆ pack_fmu()

std::string casadi::DaeBuilderInternal::pack_fmu ( const Dict files,
const Dict opts 
) const

Definition at line 1347 of file dae_builder_internal.cpp.

1347  {
1348  std::string path = name_ + ".fmu";
1349  for (auto&& op : opts) {
1350  if (op.first == "path") {
1351  path = op.second.to_string();
1352  } else {
1353  casadi_error("No such option: " + op.first);
1354  }
1355  }
1356  return FmuInternal::pack_fmu(files, path);
1357 }
static std::string pack_fmu(const Dict &files, const std::string &path)
Definition: fmu.cpp:785

References name_, casadi::FmuInternal::pack_fmu(), and casadi::path().

◆ prune()

void casadi::DaeBuilderInternal::prune ( bool  prune_p,
bool  prune_u 
)

Definition at line 1816 of file dae_builder_internal.cpp.

1816  {
1817  // Function inputs and outputs
1818  std::vector<MX> f_in, f_out, v;
1819  std::vector<std::string> f_in_name, f_out_name;
1820  // Collect all DAE input variables with at least one entry, skip u
1821  for (Category cat : input_categories()) {
1822  if (prune_p && cat == Category::P) continue;
1823  if (prune_u && cat == Category::U) continue;
1824  v = inputs(cat);
1825  if (!v.empty()) {
1826  f_in.push_back(vertcat(v));
1827  f_in_name.push_back(to_string(cat));
1828  }
1829  }
1830  // Collect all DAE output variables with at least one entry
1831  for (Category cat : output_categories()) {
1832  v = outputs(cat);
1833  if (!v.empty()) {
1834  f_out.push_back(vertcat(v));
1835  f_out_name.push_back(to_string(cat));
1836  }
1837  }
1838  // Create a function
1839  Function f("prune_fcn", f_in, f_out, f_in_name, f_out_name);
1840  // Mark which variables are free
1841  std::vector<bool> free_variables(n_variables(), false);
1842  for (const std::string& s : f.get_free()) {
1843  auto it = varind_.find(s);
1844  casadi_assert(it != varind_.end(), "No such variable: \"" + s + "\".");
1845  free_variables.at(it->second) = true;
1846  }
1847  // Prune p
1848  if (prune_p) {
1849  size_t np = 0;
1850  for (size_t i = 0; i < size(Category::P); ++i) {
1851  if (!free_variables.at(indices(Category::P).at(i))) {
1852  indices(Category::P).at(np++) = indices(Category::P).at(i);
1853  }
1854  }
1855  indices(Category::P).resize(np);
1856  }
1857  // Prune u
1858  if (prune_u) {
1859  size_t nu = 0;
1860  std::vector<size_t>& u = indices(Category::U);
1861  for (size_t i = 0; i < u.size(); ++i) {
1862  if (!free_variables.at(u.at(i))) u.at(nu++) = u.at(i);
1863  }
1864  u.resize(nu);
1865  }
1866 }

References casadi::Function::get_free(), indices(), casadi::input_categories(), inputs(), n_variables(), casadi::output_categories(), outputs(), casadi::P, size(), casadi::to_string(), casadi::U, and varind_.

◆ qualified_name()

std::string casadi::DaeBuilderInternal::qualified_name ( const XmlNode nn,
Attribute att = nullptr 
)
staticprotected

Definition at line 2068 of file dae_builder_internal.cpp.

2068  {
2069  // std::stringstream to assemble name
2070  std::stringstream qn;
2071  bool first_part = true;
2072  if (att) *att = Attribute::VALUE; // value attribute by default
2073 
2074  // Loop over name parts
2075  for (casadi_int i=0; i<nn.size(); ++i) {
2076  // Get the name part
2077  std::string np = nn[i].attribute<std::string>("name");
2078 
2079  // Check if an attribute
2080  if (np == "$START") {
2081  if (att) {
2082  *att = Attribute::START;
2083  } else {
2084  casadi_error("Ignoring attribute " + np);
2085  }
2086  continue;
2087  } else if (np == "$PRE") {
2088  casadi_warning("$PRE attribute has not been implemented, ignoring");
2089  continue;
2090  }
2091 
2092  // Add the name part to the variable name
2093  if (!first_part) qn << ".";
2094  qn << np;
2095 
2096  // Get the index, if any
2097  if (nn[i].size()>0) {
2098  casadi_int ind;
2099  nn[i]["exp:ArraySubscripts"]["exp:IndexExpression"]["exp:IntegerLiteral"].get(&ind);
2100  qn << "[" << ind << "]";
2101  }
2102 
2103  // Dot prefix if a additional parts
2104  first_part = false;
2105  }
2106 
2107  // Return the name
2108  return qn.str();
2109 }

References casadi::XmlNode::attribute(), casadi::XmlNode::get(), casadi::XmlNode::size(), size(), casadi::START, and casadi::VALUE.

Referenced by read_expr(), and read_variable().

◆ read_dependencies()

std::vector< casadi_int > casadi::DaeBuilderInternal::read_dependencies ( const XmlNode n)
protected

Definition at line 4030 of file dae_builder_internal.cpp.

4030  {
4031  // Default behaviour should be no known structure
4032  casadi_assert(n.has_attribute("dependencies"),
4033  "Default 'dependencies' not implemented");
4034  // Read list of dependencies
4035  std::vector<casadi_int> r = n.attribute<std::vector<casadi_int>>("dependencies", {});
4036  // Get corresponding variable index
4037  for (casadi_int& e : r) {
4038  if (fmi_major_ >= 3) {
4039  // Value reference is given
4040  e = vrmap_.at(static_cast<unsigned int>(e));
4041  } else {
4042  // Convert XML index to variable index
4043  e = convert_index(e);
4044  }
4045  }
4046  // Return list of dependencies
4047  return r;
4048 }

References casadi::XmlNode::attribute(), convert_index(), fmi_major_, casadi::XmlNode::has_attribute(), and vrmap_.

Referenced by import_model_structure().

◆ read_dependencies_kind()

std::vector< DependenciesKind > casadi::DaeBuilderInternal::read_dependencies_kind ( const XmlNode n,
size_t  ndep 
)
protected

Definition at line 4050 of file dae_builder_internal.cpp.

4051  {
4052  // Quick return if node not provided
4053  if (!n.has_attribute("dependenciesKind")) {
4054  // No structure known, assume general dependency
4055  return std::vector<DependenciesKind>(ndep, DependenciesKind::DEPENDENT);
4056  } else {
4057  // Read list of strings
4058  auto dk_str = n.attribute<std::vector<std::string>>("dependenciesKind");
4059  // Make sure expected length
4060  casadi_assert(dk_str.size() == ndep, "Mismatching 'dependenciesKind'");
4061  // Convert to enums
4062  std::vector<DependenciesKind> r(ndep);
4063  for (size_t i = 0; i < ndep; ++i) {
4064  r[i] = to_enum<DependenciesKind>(dk_str[i]);
4065  }
4066  return r;
4067  }
4068 }

References casadi::XmlNode::attribute(), casadi::DEPENDENT, and casadi::XmlNode::has_attribute().

Referenced by import_model_structure().

◆ read_expr()

MX casadi::DaeBuilderInternal::read_expr ( const XmlNode node)
protected

Definition at line 1510 of file dae_builder_internal.cpp.

1510  {
1511  try {
1512  const std::string& fullname = node.name;
1513 
1514  if (fullname == "fun:If") {
1515  // Expression for condition, if and else
1516  const XmlNode& cond = node["fun:Condition"];
1517  const XmlNode& then_stmt = node["fun:Statements"];
1518  const XmlNode& else_stmt = node["fun:Else"];
1519  // Only scalar expression implemented
1520  casadi_assert(cond.size() == 1, "Only one condition in if expression supported");
1521  casadi_assert(then_stmt.size() == 1, "Only one then statement in if expression supported");
1522  casadi_assert(else_stmt.size() == 1, "Only one else statement in if expression supported");
1523  return if_else(read_expr(cond[0]), read_expr(then_stmt[0]), read_expr(else_stmt[0]));
1524  }
1525 
1526  if (fullname.find("exp:")== std::string::npos) {
1527  casadi_error("DaeBuilderInternal::read_expr: unknown - expression is supposed to "
1528  "start with 'exp:' , got " + fullname);
1529  }
1530 
1531  // Chop the 'exp:'
1532  std::string name = fullname.substr(4);
1533 
1534  // The switch below is alphabetical, and can be thus made more efficient,
1535  // for example by using a switch statement of the first three letters,
1536  // if it would ever become a bottleneck
1537  if (name=="Add") {
1538  return read_expr(node[0]) + read_expr(node[1]);
1539  } else if (name=="Acos") {
1540  return acos(read_expr(node[0]));
1541  } else if (name=="Asin") {
1542  return asin(read_expr(node[0]));
1543  } else if (name=="Atan") {
1544  return atan(read_expr(node[0]));
1545  } else if (name=="Cos") {
1546  return cos(read_expr(node[0]));
1547  } else if (name=="Der") {
1548  return variable(read_variable(node[0]).der_of).v;
1549  } else if (name=="Div") {
1550  return read_expr(node[0]) / read_expr(node[1]);
1551  } else if (name=="Exp") {
1552  return exp(read_expr(node[0]));
1553  } else if (name=="Identifier") {
1554  return read_identifier(node);
1555  } else if (name=="IntegerLiteral" || name=="BooleanLiteral") {
1556  casadi_int val;
1557  node.get(&val);
1558  return val;
1559  } else if (name=="Instant") {
1560  double val;
1561  node.get(&val);
1562  return val;
1563  } else if (name=="Log") {
1564  return log(read_expr(node[0]));
1565  } else if (name=="Not") { // Logical not
1566  return !read_expr(node[0]);
1567  } else if (name=="LogLeq") { // Logical less than equal
1568  return read_expr(node[0]) <= read_expr(node[1]);
1569  } else if (name=="LogGeq") { // Logical greater than equal
1570  return read_expr(node[0]) >= read_expr(node[1]);
1571  } else if (name=="LogLt") { // Logical less than
1572  return read_expr(node[0]) < read_expr(node[1]);
1573  } else if (name=="LogGt") { // Logical greater than
1574  return read_expr(node[0]) > read_expr(node[1]);
1575  } else if (name=="Max") {
1576  return fmax(read_expr(node[0]), read_expr(node[1]));
1577  } else if (name=="Min") {
1578  return fmin(read_expr(node[0]), read_expr(node[1]));
1579  } else if (name=="Mul") { // Multiplication
1580  return read_expr(node[0]) * read_expr(node[1]);
1581  } else if (name=="Neg") {
1582  return -read_expr(node[0]);
1583  } else if (name=="NoEvent") {
1584  // NOTE: This is a workaround, we assume that whenever NoEvent occurs,
1585  // what is meant is a switch
1586  casadi_int n = node.size();
1587 
1588  // Default-expression
1589  MX ex = read_expr(node[n-1]);
1590 
1591  // Evaluate ifs
1592  for (casadi_int i=n-3; i>=0; i -= 2) {
1593  ex = if_else(read_expr(node[i]), read_expr(node[i+1]), ex);
1594  }
1595 
1596  return ex;
1597  } else if (name=="Pow") {
1598  return pow(read_expr(node[0]), read_expr(node[1]));
1599  } else if (name=="Pre") {
1600  casadi_warning("Ignoring pre attribute");
1601  return read_expr(node[0]);
1602  } else if (name=="RealLiteral") {
1603  double val;
1604  node.get(&val);
1605  return val;
1606  } else if (name=="Sin") {
1607  return sin(read_expr(node[0]));
1608  } else if (name=="Sqrt") {
1609  return sqrt(read_expr(node[0]));
1610  } else if (name=="StringLiteral") {
1611  casadi_error(node.text);
1612  } else if (name=="Sub") {
1613  return read_expr(node[0]) - read_expr(node[1]);
1614  } else if (name=="Tan") {
1615  return tan(read_expr(node[0]));
1616  } else if (name=="Time") {
1617  return var(indices(Category::T).at(0));
1618  } else if (name=="TimedVariable") {
1619  return read_variable(node[0]).v;
1620  } else if (name=="FunctionCall") {
1621  // Get the name of the function
1622  std::string fname = qualified_name(node["exp:Name"]);
1623  casadi_warning("Function call to '" + fname + "' incomplete");
1624  // Collect the arguments
1625  const XmlNode& args = node["exp:Arguments"];
1626  std::vector<MX> farg(args.size());
1627  for (casadi_int i = 0; i < args.size(); ++i) {
1628  // Lift input arguments
1629  Variable& v = new_variable("w_" + str(size(Category::W)));
1630  // Add to list of variables
1631  indices(Category::W).push_back(v.index);
1632  // Set binding expression
1633  Variable& v_beq = assign(v.name, read_expr(args[i]));
1634  v.bind = v_beq.index;
1635  // Add to list of function arguments
1636  farg[i] = v.v;
1637  }
1638  // Return argument (scalar for now)
1639  Variable& r = new_variable("w_" + str(size(Category::W)));
1640  // Add to list of variables
1641  indices(Category::W).push_back(r.index);
1642  // Return output variable
1643  return r.v;
1644  } else if (name=="Array") {
1645  // Array of arguments
1646  std::vector<MX> v(node.size());
1647  for (casadi_int i = 0; i < v.size(); ++i) v[i] = read_expr(node[i]);
1648  return vertcat(v);
1649  }
1650 
1651  // throw error if reached this point
1652  casadi_error("Unknown node: " + name);
1653  } catch (std::exception& e) {
1654  THROW_ERROR_NODE("read_expr", node, e.what());
1655  return {};
1656  }
1657 }
static std::string qualified_name(const XmlNode &nn, Attribute *att=nullptr)
Get the qualified name.
double if_else(double x, double y, double z)
Definition: calculus.hpp:296

References assign(), casadi::Variable::bind, casadi::XmlNode::get(), casadi::if_else(), casadi::Variable::index, indices(), casadi::Variable::name, name(), casadi::XmlNode::name, new_variable(), qualified_name(), read_identifier(), read_variable(), casadi::XmlNode::size(), size(), casadi::str(), casadi::T, casadi::XmlNode::text, casadi::Variable::v, var(), variable(), and casadi::W.

Referenced by import_binding_equations(), import_dynamic_equations(), and import_initial_equations().

◆ read_identifier()

MX casadi::DaeBuilderInternal::read_identifier ( const XmlNode node)
protected

Definition at line 1497 of file dae_builder_internal.cpp.

1497  {
1498  Attribute att; // attribute
1499  Variable& v = read_variable(node, &att);
1500  if (att == Attribute::VALUE) {
1501  return v.v;
1502  } else if (att == Attribute::START) {
1503  return v.start;
1504  } else {
1505  casadi_error("Cannot read attribute " + to_string(att));
1506  return MX();
1507  }
1508 }

References read_variable(), casadi::START, casadi::Variable::start, casadi::to_string(), casadi::Variable::v, and casadi::VALUE.

Referenced by import_dynamic_equations(), and read_expr().

◆ read_variable()

Variable & casadi::DaeBuilderInternal::read_variable ( const XmlNode node,
Attribute att = nullptr 
)
protected

Definition at line 1485 of file dae_builder_internal.cpp.

1485  {
1486  try {
1487  // Qualified name
1488  std::string qn = qualified_name(node, att);
1489 
1490  return variable(qn);
1491  } catch (std::exception& e) {
1492  THROW_ERROR_NODE("read_variable", node, e.what());
1493  //return {};
1494  }
1495 }

References qualified_name(), and variable().

Referenced by import_binding_equations(), import_dynamic_equations(), import_initial_equations(), read_expr(), and read_identifier().

◆ reinit()

Variable & casadi::DaeBuilderInternal::reinit ( const std::string &  name,
const MX val 
)
protected

Definition at line 3775 of file dae_builder_internal.cpp.

3775  {
3776  // Create a unique name for the reinit variable
3777  std::string reinit_name = unique_name("__reinit__" + name + "__");
3778  // Add a new dependent variable defined by val
3779  Variable& v = add(reinit_name, Causality::LOCAL, Variability::CONTINUOUS, val, Dict());
3780  // Classify as a defined variable
3781  categorize(v.index, Category::CALCULATED);
3782  v.parent = variable(name).index;
3783  // Return the variable name
3784  return v;
3785 }

References add(), casadi::CALCULATED, categorize(), casadi::CONTINUOUS, casadi::Variable::index, casadi::LOCAL, name(), casadi::Variable::parent, unique_name(), and variable().

Referenced by import_dynamic_equations().

◆ remove()

void casadi::DaeBuilderInternal::remove ( std::vector< size_t > &  v,
size_t  ind 
) const
protected

Definition at line 3420 of file dae_builder_internal.cpp.

3420  {
3421  for (auto it = v.begin(); it != v.end(); ++it) {
3422  if (*it == ind) {
3423  v.erase(it);
3424  return;
3425  }
3426  }
3427  casadi_error("Variable not found");
3428 }

Referenced by categorize(), and set_causality().

◆ reorder() [1/2]

void casadi::DaeBuilderInternal::reorder ( Category  cat,
const std::vector< size_t > &  v 
)

Definition at line 1797 of file dae_builder_internal.cpp.

1797  {
1798  reorder(to_string(cat), indices(cat), v);
1799 }
void reorder(Category cat, const std::vector< size_t > &v)
Reorder variables in a category.

References indices(), and casadi::to_string().

◆ reorder() [2/2]

void casadi::DaeBuilderInternal::reorder ( const std::string &  n,
std::vector< size_t > &  ind,
const std::vector< size_t > &  v 
) const

Definition at line 1801 of file dae_builder_internal.cpp.

1802  {
1803  // Check if the sizes match
1804  casadi_assert(ind.size() == v.size(), "Cannot reorder " + n + ": "
1805  + str(v.size()) + " elements provided for " + str(ind.size()) + " components.");
1806  // Mark elements to be set
1807  std::vector<bool> set(n_variables(), false);
1808  for (size_t i : v) set.at(i) = true;
1809  // Make sure all elements are present
1810  for (size_t i : ind) casadi_assert(set.at(i), "Cannot reorder " + n + ": "
1811  + variable(i).name + " is missing.");
1812  // Set the new order
1813  std::copy(v.begin(), v.end(), ind.begin());
1814 }

References n_variables(), name(), casadi::str(), and variable().

◆ reset()

void casadi::DaeBuilderInternal::reset ( )
protected

Definition at line 4631 of file dae_builder_internal.cpp.

4631  {
4632  for (Variable* v : variables_) {
4633  std::fill(v->value.begin(), v->value.end(), nan);
4634  v->stringvalue = std::string();
4635  }
4636 }

References casadi::nan, and variables_.

◆ sanity_check()

void casadi::DaeBuilderInternal::sanity_check ( ) const

Definition at line 2060 of file dae_builder_internal.cpp.

2060  {
2061  // Time
2062  if (size(Category::T) > 0) {
2063  casadi_assert(size(Category::T) == 1, "At most one time variable allowed");
2064  casadi_assert(variable(Category::T, 0).v.is_scalar(), "Non-scalar time t");
2065  }
2066 }

References size(), casadi::T, and variable().

Referenced by add_lc(), and disp().

◆ set_attribute() [1/2]

void casadi::DaeBuilderInternal::set_attribute ( Attribute  a,
const std::string &  name,
double  val 
)
protected

Set by attribute name

Definition at line 4658 of file dae_builder_internal.cpp.

4658  {
4659  variable(name).set_attribute(a, val);
4660 }
void set_attribute(Attribute a, double val)

References name(), casadi::Variable::set_attribute(), and variable().

◆ set_attribute() [2/2]

void casadi::DaeBuilderInternal::set_attribute ( Attribute  a,
const std::vector< std::string > &  name,
const std::vector< double > &  val 
)
protected

Set by attribute name

Definition at line 4662 of file dae_builder_internal.cpp.

4663  {
4664  if (name.size() == val.size()) {
4665  // One scalar value per variable
4666  for (size_t k = 0; k < name.size(); ++k) variable(name[k]).set_attribute(a, val[k]);
4667  } else if (val.size() == size(a, name)) {
4668  // One vector slice per variable
4669  auto val_it = val.begin();
4670  for (size_t k = 0; k < name.size(); ++k) {
4671  Variable& v = variable(name[k]);
4672  auto val_next = val_it + v.size(a);
4673  v.set_attribute(a, std::vector<double>(val_it, val_next));
4674  val_it = val_next;
4675  }
4676  } else {
4677  casadi_error("Cannot set attribute " + to_string(a) + ": Argument is of length " +
4678  str(val.size()) + ", expected number of elements (" + str(size(a, name))
4679  + ") or number of variables (" + str(name.size()) + ")");
4680  }
4681 }

References name(), casadi::Variable::set_attribute(), casadi::Variable::size(), size(), casadi::str(), casadi::to_string(), and variable().

◆ set_category()

void casadi::DaeBuilderInternal::set_category ( size_t  ind,
Category  cat 
)
protected

Definition at line 3527 of file dae_builder_internal.cpp.

3527  {
3528  // Get variable reference
3529  Variable& v = variable(ind);
3530  // Quick return if same category
3531  if (v.category == cat) return;
3532  // Update category: See comment for public interface
3533  switch (cat) {
3534  case Category::U:
3535  if (v.category == Category::P || v.category == Category::C) {
3537  return;
3538  }
3539  break;
3540  case Category::P:
3541  if (v.category == Category::U || v.category == Category::C) {
3543  return;
3544  }
3545  break;
3546  case Category::C:
3547  if (v.category == Category::U || v.category == Category::P) {
3549  return;
3550  }
3551  break;
3552  case Category::X:
3553  // Can convert from Q, T or unused derivative variable
3554  if (v.category == Category::Q || v.category == Category::T
3555  || (v.category == Category::NUMEL && v.has_der())) {
3556  categorize(v.index, Category::X);
3557  return;
3558  }
3559  break;
3560  case Category::Q:
3561  // Can convert from X or T, but only if not in right-hand-side, or from unused derivative
3562  if ((!v.in_rhs && (v.category == Category::X || v.category == Category::T))
3563  || (v.category == Category::NUMEL && v.has_der())) {
3564  categorize(v.index, Category::Q);
3565  return;
3566  }
3567  break;
3568  case Category::T:
3569  // Can convert from X, Q, or unused derivative, but existing T must be removed first
3570  if (v.category == Category::X || v.category == Category::Q
3571  || (v.category == Category::NUMEL && v.has_der())) {
3572  if (has_t()) {
3573  // Move existing T variable to X or remove
3574  Variable& t_old = variable(indices(Category::T).front());
3575  categorize(t_old.index, t_old.in_rhs ? Category::X : Category::NUMEL);
3576  }
3577  categorize(v.index, Category::T);
3578  return;
3579  }
3580  break;
3581  case Category::NUMEL:
3582  // If not in right-hand-side, can convert from X, Q, or T
3583  if (!v.in_rhs && (v.category == Category::X
3584  || v.category == Category::Q
3585  || v.category == Category::T)) {
3586  categorize(v.index, Category::NUMEL);
3587  return;
3588  }
3589  default:
3590  break;
3591  }
3592  // Failure if reached this point
3593  casadi_error("Cannot change category of " + v.name + " from '"
3594  + to_string(v.category) + "' to '" + to_string(cat) + "'");
3595 }
void set_variability(size_t ind, Variability variability)
Set variability.
bool has_t() const
Is there a time variable?

References casadi::C, categorize(), casadi::Variable::category, casadi::CONTINUOUS, casadi::FIXED, casadi::Variable::has_der(), has_t(), casadi::Variable::in_rhs, casadi::Variable::index, indices(), casadi::Variable::name, casadi::NUMEL, casadi::P, casadi::Q, set_variability(), casadi::T, casadi::to_string(), casadi::TUNABLE, casadi::U, variable(), and casadi::X.

Referenced by eliminate().

◆ set_causality()

void casadi::DaeBuilderInternal::set_causality ( size_t  ind,
Causality  causality 
)
protected

Definition at line 3434 of file dae_builder_internal.cpp.

3434  {
3435  // Get variable reference
3436  Variable& v = variable(ind);
3437  // Quick return if same causality
3438  if (v.causality == causality) return;
3439  // Handle permitted changes
3440  if (v.causality == Causality::LOCAL && causality == Causality::OUTPUT) {
3441  // Add to list of outputs
3442  insert(indices(Category::Y), v.index);
3443  } else if (v.causality == Causality::OUTPUT && causality == Causality::LOCAL) {
3444  // Remove from list of outputs
3445  remove(indices(Category::Y), v.index);
3446  } else {
3447  // Not possible
3448  casadi_error("Cannot change causality of " + v.name + " which is of category '"
3449  + to_string(v.category) + "'");
3450  }
3451  // Success: Update causality
3452  v.causality = causality;
3453  // The oracle would need to be regenerated after changes to the categorization
3454  clear_cache_ = true;
3455 }

References casadi::Variable::category, casadi::Variable::causality, causality(), clear_cache_, casadi::Variable::index, indices(), insert(), casadi::LOCAL, casadi::Variable::name, casadi::OUTPUT, remove(), casadi::to_string(), variable(), and casadi::Y.

◆ set_init()

void casadi::DaeBuilderInternal::set_init ( const std::string &  name,
const MX init_rhs 
)
protected

Definition at line 3787 of file dae_builder_internal.cpp.

3787  {
3788  // Find the algebraic variable
3789  Variable& v = variable(name);
3790  // If variable already has an initial binding equation, remove it
3791  if (!v.ieq.is_empty()) {
3792  // Remove from list of initial equations
3793  auto old_loc = std::find(init_.begin(), init_.end(), v.index);
3794  if (old_loc == init_.end()) casadi_error("Corrupted list of initial equations");
3795  init_.erase(old_loc);
3796  v.ieq = MX();
3797  }
3798  // If right-hand-side is empty, just erase
3799  if (init_rhs.is_empty()) return;
3800 
3801  // Make sure not already in list of initial equations
3802  if (std::find(init_.begin(), init_.end(), v.index) != init_.end()) {
3803  casadi_error("Initial equation for " + name + " has already been set");
3804  }
3805  // Add to list of initial equations
3806  init_.push_back(v.index);
3807  v.ieq = init_rhs;
3808 }
std::vector< MX > init_rhs() const
Initial conditions, right-hand-side.

References casadi::Variable::ieq, casadi::Variable::index, init_, init_rhs(), casadi::GenericMatrix< MatType >::is_empty(), name(), and variable().

Referenced by import_initial_equations(), and load_fmi_description().

◆ set_string_attribute() [1/2]

void casadi::DaeBuilderInternal::set_string_attribute ( Attribute  a,
const std::string &  name,
const std::string &  val 
)
protected

Set by attribute name (string-valued)

Definition at line 4704 of file dae_builder_internal.cpp.

4705  {
4706  variable(name).set_attribute(a, val);
4707 }

References name(), casadi::Variable::set_attribute(), and variable().

◆ set_string_attribute() [2/2]

void casadi::DaeBuilderInternal::set_string_attribute ( Attribute  a,
const std::vector< std::string > &  name,
const std::vector< std::string > &  val 
)
protected

Set by attribute name (string-valued)

Definition at line 4709 of file dae_builder_internal.cpp.

4710  {
4711  casadi_assert(name.size() == val.size(), "Dimension mismatch");
4712  for (size_t k = 0; k < name.size(); ++k) variable(name[k]).set_attribute(a, val[k]);
4713 }

References name(), casadi::Variable::set_attribute(), and variable().

◆ set_variability()

void casadi::DaeBuilderInternal::set_variability ( size_t  ind,
Variability  variability 
)
protected

Definition at line 3461 of file dae_builder_internal.cpp.

3461  {
3462  // Get variable reference
3463  Variable& v = variable(ind);
3464  // Quick return if same variability
3465  if (v.variability == variability) return;
3466  // Update category: See comment for public interface
3467  switch (v.category) {
3468  case Category::U:
3470  // Make fixed parameter
3471  categorize(v.index, Category::C);
3472  v.causality = Causality::PARAMETER;
3473  } else if (variability == Variability::TUNABLE) {
3474  // Make tunable parameter
3475  categorize(v.index, Category::P);
3476  v.causality = Causality::PARAMETER;
3477  } else {
3478  // Not possible
3479  casadi_error("The variability of " + v.name + ", which is of category 'u', can only be "
3480  "changed to 'fixed' (for no category) or 'tunable' (for category 'p')");
3481  }
3482  break;
3483  case Category::P:
3485  // Make input
3486  categorize(v.index, Category::U);
3487  v.causality = Causality::INPUT;
3488  } else if (variability == Variability::FIXED) {
3489  // Make fixed parameter
3490  categorize(v.index, Category::C);
3491  v.causality = Causality::PARAMETER;
3492  } else {
3493  // Not possible
3494  casadi_error("The variability of " + v.name + ", which is of category 'p', can only be "
3495  "changed to 'continuous' (for category 'u') or 'fixed' (for no category)");
3496  }
3497  break;
3498  case Category::C:
3500  // Make input
3501  categorize(v.index, Category::U);
3502  v.causality = Causality::INPUT;
3503  } else if (variability == Variability::TUNABLE) {
3504  // Make tunable parameter
3505  categorize(v.index, Category::P);
3506  v.causality = Causality::PARAMETER;
3507  } else {
3508  // Not possible
3509  casadi_error("The variability of " + v.name + ", which is of type 'c', can only be "
3510  "changed to 'continuous' (for category 'u') or 'tunable' (for category 'p')");
3511  }
3512  break;
3513  default:
3514  casadi_error("Cannot change variability of " + v.name + ", which is of category '"
3515  + to_string(v.category) + "'");
3516  }
3517  // Success: Update variability
3518  v.variability = variability;
3519  // The oracle would need to be regenerated after changes to the categorization
3520  clear_cache_ = true;
3521 }

References casadi::C, categorize(), casadi::Variable::category, casadi::Variable::causality, clear_cache_, casadi::CONTINUOUS, casadi::FIXED, casadi::Variable::index, casadi::INPUT, casadi::Variable::name, casadi::P, casadi::PARAMETER, casadi::to_string(), casadi::TUNABLE, casadi::U, casadi::Variable::variability, variability(), and variable().

Referenced by set_category().

◆ shared_from_this() [1/2]

B casadi::GenericSharedInternal< SharedObject , SharedObjectInternal >::shared_from_this ( )
inlineprotectedinherited

Definition at line 83 of file generic_shared_internal.hpp.

83  {
84  casadi_assert_dev(B::test_cast(static_cast<Internal*>(this)));
85  B ret;
86  ret.own(static_cast<Internal*>(this));
87  return ret;
88  }

◆ shared_from_this() [2/2]

const B casadi::GenericSharedInternal< SharedObject , SharedObjectInternal >::shared_from_this ( ) const
inlineprotectedinherited

Definition at line 92 of file generic_shared_internal.hpp.

92  {
93  casadi_assert_dev(B::test_cast(static_cast<const Internal*>(this)));
94  B ret;
95  ret.own(const_cast<Internal*>(static_cast<const Internal*>(this)));
96  return ret;
97  }

◆ size() [1/2]

casadi_int casadi::DaeBuilderInternal::size ( Attribute  a,
const std::vector< std::string > &  name 
) const
protected

Definition at line 4715 of file dae_builder_internal.cpp.

4715  {
4716  casadi_int r = 0;
4717  for (const auto& n : name) r += variable(n).size(a);
4718  return r;
4719 }
casadi_int size(Attribute a) const
Total number of elements for a particular attribute.

References name(), casadi::Variable::size(), and variable().

◆ size() [2/2]

size_t casadi::DaeBuilderInternal::size ( Category  cat) const
inline

◆ sort()

void casadi::DaeBuilderInternal::sort ( Category  cat)

Definition at line 1760 of file dae_builder_internal.cpp.

1760  {
1761  casadi_assert(is_acyclic(cat), "Sorting not supported for category " + to_string(cat));
1762  // Find new order based on interdependencies
1763  std::vector<MX> v = var(indices(cat)), vdef = outputs(dependent_definition(cat));
1764  sort_dependent(v, vdef);
1765  // New order
1766  std::vector<size_t> new_order;
1767  for (const MX& e : v) new_order.push_back(find(e.name()));
1768  std::copy(new_order.begin(), new_order.end(), indices(cat).begin());
1769 }
static void sort_dependent(std::vector< MX > &v, std::vector< MX > &vdef)

References casadi::dependent_definition(), find(), indices(), casadi::is_acyclic(), outputs(), sort_dependent(), casadi::to_string(), and var().

Referenced by eliminate().

◆ sort_dependent()

void casadi::DaeBuilderInternal::sort_dependent ( std::vector< MX > &  v,
std::vector< MX > &  vdef 
)
staticprotected

Definition at line 2813 of file dae_builder_internal.cpp.

2813  {
2814  // Form function to evaluate dependent variables
2815  Function vfcn("vfcn", {vertcat(v)}, {vertcat(vdef)}, {"v"}, {"vdef"},
2816  Dict{{"allow_free", true}});
2817  // Is any variable vector-valued?
2818  bool any_vector_valued = false;
2819  for (const MX& v_i : v) {
2820  casadi_assert(!v_i.is_empty(), "Cannot have zero-dimension dependent variables");
2821  if (!v_i.is_scalar()) {
2822  any_vector_valued = true;
2823  break;
2824  }
2825  }
2826  // If vector-valued variables exists, collapse them
2827  if (any_vector_valued) {
2828  // New v corresponding to one scalar input per v argument
2829  std::vector<MX> vfcn_in(v), vfcn_arg(v);
2830  for (size_t i = 0; i < v.size(); ++i) {
2831  if (!v.at(i).is_scalar()) {
2832  vfcn_in.at(i) = MX::sym(v.at(i).name());
2833  vfcn_arg.at(i) = repmat(vfcn_in.at(i), v.at(i).size1());
2834  }
2835  }
2836  // Wrap vfcn
2837  std::vector<MX> vfcn_out = vfcn(vertcat(vfcn_arg));
2838  vfcn_out = vertsplit(vfcn_out.at(0), offset(v));
2839  // Collapse vector-valued outputs
2840  for (size_t i = 0; i < v.size(); ++i) {
2841  if (!v.at(i).is_scalar()) {
2842  vfcn_out.at(i) = dot(vfcn_out.at(i), vfcn_out.at(i));
2843  }
2844  }
2845  // Recreate vfcn with smaller dimensions
2846  vfcn = Function(vfcn.name(), {vertcat(vfcn_in)}, {vertcat(vfcn_out)},
2847  vfcn.name_in(), vfcn.name_out(), {{"allow_free", true}});
2848  }
2849  // Calculate sparsity pattern of dvdef/dv
2850  Sparsity Jv = vfcn.jac_sparsity(0, 0);
2851  // Add diagonal (equation is v-vdef = 0)
2852  Jv = Jv + Sparsity::diag(Jv.size1());
2853  // If lower triangular, nothing to do
2854  if (Jv.is_triu()) return;
2855  // Perform a Dulmage-Mendelsohn decomposition
2856  std::vector<casadi_int> rowperm, colperm, rowblock, colblock, coarse_rowblock, coarse_colblock;
2857  (void)Jv.btf(rowperm, colperm, rowblock, colblock, coarse_rowblock, coarse_colblock);
2858  // Reorder the variables
2859  std::vector<MX> tmp(v.size());
2860  for (size_t k = 0; k < v.size(); ++k) tmp[k] = v.at(colperm.at(k));
2861  std::copy(tmp.begin(), tmp.end(), v.begin());
2862  // Reorder the equations
2863  for (size_t k = 0; k < v.size(); ++k) tmp[k] = vdef.at(rowperm.at(k));
2864  std::copy(tmp.begin(), tmp.end(), vdef.begin());
2865 }
static Sparsity diag(casadi_int nrow)
Create diagonal sparsity pattern *.
Definition: sparsity.hpp:190
T dot(const std::vector< T > &a, const std::vector< T > &b)

References casadi::dot(), and casadi::GenericMatrix< MX >::sym().

Referenced by sort().

◆ sort_z()

void casadi::DaeBuilderInternal::sort_z ( const std::vector< std::string > &  z_order)

Definition at line 1771 of file dae_builder_internal.cpp.

1771  {
1772  // Make sure lengths agree
1773  casadi_assert(z_order.size() == size(Category::Z), "Dimension mismatch");
1774  // Mark existing components in z
1775  std::vector<bool> old_z(n_variables(), false);
1776  for (size_t i : indices(Category::Z)) old_z.at(i) = true;
1777  // New vector of z
1778  std::vector<size_t> new_z;
1779  new_z.reserve(z_order.size());
1780  for (const std::string& s : z_order) {
1781  size_t i = find(s);
1782  casadi_assert(old_z.at(i), "Variable \"" + s + "\" is not an algebraic variable.");
1783  new_z.push_back(i);
1784  }
1785  // Success: Update z
1786  std::copy(new_z.begin(), new_z.end(), indices(Category::Z).begin());
1787 }

References find(), indices(), n_variables(), size(), and casadi::Z.

◆ start_all()

std::vector< double > casadi::DaeBuilderInternal::start_all ( ) const

Definition at line 1389 of file dae_builder_internal.cpp.

1389  {
1390  std::vector<double> r;
1391  for (const Variable* v : variables_) {
1392  for (double s : v->start) r.push_back(s);
1393  }
1394  return r;
1395 }

References variables_.

Referenced by generate_wrapper().

◆ string_attribute() [1/2]

std::string casadi::DaeBuilderInternal::string_attribute ( Attribute  a,
const std::string &  name 
) const
protected

Get by attribute name (string-valued)

Definition at line 4683 of file dae_builder_internal.cpp.

4684  {
4685  std::string r;
4686  variable(name).get_attribute(a, &r);
4687  return r;
4688 }

References casadi::Variable::get_attribute(), name(), and variable().

◆ string_attribute() [2/2]

std::vector< std::string > casadi::DaeBuilderInternal::string_attribute ( Attribute  a,
const std::vector< std::string > &  name 
) const
protected

Get by attribute name (string-valued)

Definition at line 4690 of file dae_builder_internal.cpp.

4691  {
4692  // Allocate return
4693  std::vector<std::string> r;
4694  r.reserve(size(a, name));
4695  // Get contribution from each variable
4696  std::string r1;
4697  for (const auto& n : name) {
4698  variable(n).get_attribute(a, &r1);
4699  r.push_back(r1);
4700  }
4701  return r;
4702 }

References casadi::Variable::get_attribute(), name(), size(), and variable().

◆ tear()

void casadi::DaeBuilderInternal::tear ( )

Definition at line 1868 of file dae_builder_internal.cpp.

1868  {
1869  // Get residual variables, iteration variables
1870  std::vector<std::string> res, iv, iv_on_hold;
1871  tearing_variables(&res, &iv, &iv_on_hold);
1872  // All iteration variables
1873  std::set<std::string> iv_set;
1874  for (auto& e : iv) iv_set.insert(e);
1875  for (auto& e : iv_on_hold) iv_set.insert(e);
1876  // Remove any (held or not held) iteration variables, equations from z and alg
1877  size_t sz = 0;
1878  for (size_t k = 0; k < size(Category::Z); ++k) {
1879  if (!iv_set.count(variable(Category::Z, k).name)) {
1880  // Non-iteration variable: Keep
1881  indices(Category::Z).at(k) = indices(Category::Z).at(sz);
1882  sz++;
1883  }
1884  }
1885  indices(Category::Z).resize(sz);
1886  // Remove any (held or not held) iteration variables, equations from u
1887  sz = 0;
1888  for (size_t k = 0; k < size(Category::U); ++k) {
1889  if (!iv_set.count(variable(Category::U, k).name)) {
1890  // Non-iteration variable: Keep
1891  indices(Category::U).at(k) = indices(Category::U).at(sz++);
1892  }
1893  }
1894  indices(Category::U).resize(sz);
1895  // Add algebraic variables
1896  for (auto& e : iv) indices(Category::Z).push_back(find(e));
1897  // Add output variables
1898  for (auto& e : iv_on_hold) indices(Category::U).push_back(find(e));
1899 }
void tearing_variables(std::vector< std::string > *res, std::vector< std::string > *iv, std::vector< std::string > *iv_on_hold) const
Identify free variables and residual equations.

References find(), indices(), name(), size(), tearing_variables(), casadi::U, variable(), and casadi::Z.

◆ tearing_variables()

void casadi::DaeBuilderInternal::tearing_variables ( std::vector< std::string > *  res,
std::vector< std::string > *  iv,
std::vector< std::string > *  iv_on_hold 
) const

Definition at line 1901 of file dae_builder_internal.cpp.

1902  {
1903  // Clear output
1904  if (res) res->clear();
1905  if (iv) iv->clear();
1906  if (iv_on_hold) iv_on_hold->clear();
1907  // Prefix
1908  const std::string res_prefix = "res__";
1909  // Collect hold indices
1910  std::vector<MX> r_hold, iv_hold;
1911  // Any hold variable?
1912  bool any_hold = false;
1913  // Collect residual variables, iteration variables, expression for hold indices, if any
1914  for (const Variable* v : variables_) {
1915  // Residual variables are specified with a "res__" prefix
1916  if (v->name.rfind(res_prefix, 0) == 0) {
1917  // Process iteration variable name, names of hold markers
1918  std::string iv_name, res_hold_name, iv_hold_name;
1919  // Iteration variable, hold markers are contained in the remainder of the name
1920  try {
1921  size_t pos = res_prefix.size();
1922  // Find the next "__", if any
1923  size_t end = v->name.find("__", pos);
1924  if (end == std::string::npos) end = v->name.size();
1925  // Look up iteration variable
1926  iv_name = v->name.substr(pos, end - pos);
1927  // Ensure that the variable exists
1928  casadi_assert(has(iv_name), "No such variable: " + iv_name);
1929  // Get hold indices, if any
1930  if (end != v->name.size()) {
1931  // Find next "__", read hold index for residual variable
1932  pos = end + 2;
1933  end = v->name.find("__", pos);
1934  if (end == std::string::npos) end = v->name.size();
1935  res_hold_name = v->name.substr(pos, end - pos);
1936  // Ensure that the variable exists
1937  casadi_assert(has(res_hold_name), "No such variable: " + res_hold_name);
1938  // The remainder of the name contains iv_hold_name
1939  if (end != v->name.size()) {
1940  iv_hold_name = v->name.substr(end + 2);
1941  casadi_assert(has(iv_hold_name), "No such variable: " + iv_hold_name);
1942  }
1943  }
1944  } catch (std::exception& e) {
1945  // Generate warning
1946  casadi_warning("Cannot process residual variable: " + v->name + ":" +
1947  std::string(e.what()));
1948  continue;
1949  }
1950  // Add residual variable, corresponding hold variable
1951  if (res_hold_name.empty()) {
1952  r_hold.push_back(false);
1953  } else {
1954  any_hold = true;
1955  r_hold.push_back(variable(res_hold_name).v);
1956  casadi_assert(r_hold.back().is_scalar(), "Non-scalar hold variable for " + res_hold_name);
1957  }
1958  if (res) res->push_back(v->name);
1959  // Add iteration variable, corresponding hold variable
1960  if (iv_hold_name.empty()) {
1961  iv_hold.push_back(false);
1962  } else {
1963  any_hold = true;
1964  iv_hold.push_back(variable(iv_hold_name).v);
1965  casadi_assert(iv_hold.back().is_scalar(), "Non-scalar hold variable for " + iv_hold_name);
1966  }
1967  if (iv) iv->push_back(iv_name);
1968  }
1969  }
1970  // Evaluate hold variables, if needed
1971  if (any_hold) {
1972  try {
1973  // Code below needs to be refactored
1974  casadi_error("not implemented");
1975 #if 0
1976  // Get start attributes for p
1977  Function startfun_p = attribute_fun("startfun_p", {}, {"start_p"});
1978  if (startfun_p.has_free()) {
1979  casadi_error("startfun has free variables: " + str(startfun_p.get_free()));
1980  }
1981  DM p0 = startfun_p(std::vector<DM>{}).at(0);
1982  // Create function to evaluate the hold attributes
1983  Function holdfun("holdfun", {vertcat(var(p_))},
1984  {vertcat(r_hold), vertcat(iv_hold)}, {"p"}, {"r_hold", "iv_hold"});
1985  if (holdfun.has_free()) {
1986  casadi_error("holdfun has free variables: " + str(holdfun.get_free()));
1987  }
1988  // Evaluate holdfun to get hold attributes
1989  std::vector<DM> hold0 = holdfun(std::vector<DM>{p0});
1990  std::vector<double> r_hold0 = hold0.at(0).nonzeros();
1991  std::vector<double> iv_hold0 = hold0.at(1).nonzeros();
1992  casadi_assert_dev(r_hold0.size() == res->size());
1993  casadi_assert_dev(iv_hold0.size() == iv->size());
1994  // Remove hold variables from residual variables
1995  size_t sz = 0;
1996  if (res) {
1997  for (size_t k = 0; k < res->size(); ++k) {
1998  if (!static_cast<bool>(r_hold0.at(k))) {
1999  res->at(sz++) = res->at(k);
2000  }
2001  }
2002  res->resize(sz);
2003  }
2004  // Remove hold variables from iteration variables
2005  sz = 0;
2006  for (size_t k = 0; k < iv->size(); ++k) {
2007  if (!static_cast<bool>(iv_hold0.at(k))) {
2008  if (iv) iv->at(sz++) = iv->at(k);
2009  } else {
2010  if (iv_on_hold) iv_on_hold->push_back(iv->at(k));
2011  }
2012  }
2013  if (iv) iv->resize(sz);
2014 #endif
2015  } catch (std::exception& e) {
2016  // Warning instead of error
2017  casadi_warning("Failed to evaluate hold variables: " + std::string(e.what()));
2018  }
2019  }
2020 }

References casadi::Function::get_free(), has(), casadi::Function::has_free(), casadi::str(), var(), variable(), and variables_.

Referenced by tear().

◆ time()

const MX & casadi::DaeBuilderInternal::time ( ) const
protected

Definition at line 3099 of file dae_builder_internal.cpp.

3099  {
3100  casadi_assert(has_t(), "No explicit time variable");
3101  return var(indices(Category::T).at(0));
3102 }

References has_t(), indices(), casadi::T, and var().

Referenced by generate_guid().

◆ transition() [1/2]

Function casadi::DaeBuilderInternal::transition ( const std::string &  fname) const

Definition at line 2974 of file dae_builder_internal.cpp.

2974  {
2975  // If no events, return null
2976  if (when_.empty()) return Function();
2977 
2978  // If just a single event, create an event function with a dummy index input
2979  if (when_.size() == 1) return transition(fname, 0, true);
2980 
2981  // Create separate transition functions for each event
2982  std::vector<Function> f_all;
2983  for (casadi_int i = 0; i < when_.size(); ++i) {
2984  f_all.push_back(transition(fname + "_" + str(i), i));
2985  }
2986 
2987  // Make the last function the default value in the switch
2988  Function f_def = f_all.back();
2989  f_all.pop_back();
2990 
2991  // Create a switch function
2992  return Function::conditional(fname, f_all, f_def);
2993 }
static Function conditional(const std::string &name, const std::vector< Function > &f, const Function &f_def, const Dict &opts=Dict())
Constuct a switch function.
Definition: function.cpp:917

References casadi::Function::conditional(), casadi::str(), transition(), and when_.

◆ transition() [2/2]

Function casadi::DaeBuilderInternal::transition ( const std::string &  fname,
casadi_int  index,
bool  dummy_index_input = false 
) const

Definition at line 2925 of file dae_builder_internal.cpp.

2926  {
2927 
2928  // Make sure that the index is valid
2929  casadi_assert(index >= 0 && index < when_.size(), "Illegal event index");
2930 
2931  // Get input expressions for the oracle
2932  const Function& oracle = this->oracle();
2933  std::vector<MX> oracle_in = oracle.mx_in();
2934 
2935  // Input expressions for the event functions, without the index
2936  std::vector<MX> ret_in(DYN_NUM_IN);
2937  ret_in[DYN_T] = oracle_in.at(oracle.index_in("t"));
2938  ret_in[DYN_X] = oracle_in.at(oracle.index_in("x"));
2939  ret_in[DYN_Z] = oracle_in.at(oracle.index_in("z"));
2940  ret_in[DYN_P] = oracle_in.at(oracle.index_in("p"));
2941  ret_in[DYN_U] = oracle_in.at(oracle.index_in("u"));
2942 
2943  // When equation left-hand sides and right-hand sides
2944  std::vector<MX> when_lhs, when_rhs;
2945  for (size_t eq : when_.at(index).second) {
2946  auto v = variable(eq).parent;
2947  when_lhs.push_back(variable(v).v);
2948  when_rhs.push_back(variable(eq).v);
2949  }
2950 
2951  // Expressions for x and z after event
2952  std::vector<MX> ret_out = {ret_in[DYN_X], ret_in[DYN_Z]};
2953  ret_out = MX::substitute(ret_out, when_lhs, when_rhs);
2954 
2955  // Remove dependent variables, if any
2956  if (size(Category::W) > 0) {
2957  // Dependent variable definitions
2958  std::vector<MX> wdef = outputs(Category::WDEF);
2959  // Perform in-place substitution
2960  substitute_inplace(var(Category::W), wdef, ret_out, false);
2961  }
2962 
2963  // Check if a dummy index input needes to be included
2964  if (dummy_index_input) {
2965  // Create a function with the transition input signature
2966  ret_in.insert(ret_in.begin(), MX());
2967  return Function(fname, ret_in, ret_out, event_in(), event_out());
2968  } else {
2969  // Create a function with the DAE function input signature
2970  return Function(fname, ret_in, ret_out, dyn_in(), event_out());
2971  }
2972 }
static MX substitute(const MX &ex, const MX &v, const MX &vdef)
Definition: mx.cpp:1525
std::vector< std::string > event_in()
Get input scheme of an event transition function.
Definition: integrator.cpp:256
std::vector< std::string > event_out()
Get output scheme of an event transition functions.
Definition: integrator.cpp:260
@ DYN_NUM_IN
Definition: integrator.hpp:196

References casadi::dyn_in(), casadi::DYN_NUM_IN, casadi::DYN_P, casadi::DYN_T, casadi::DYN_U, casadi::DYN_X, casadi::DYN_Z, eq(), casadi::event_in(), casadi::event_out(), casadi::Function::index_in(), casadi::Function::mx_in(), oracle(), outputs(), casadi::Variable::parent, size(), casadi::MX::substitute(), var(), variable(), casadi::W, casadi::WDEF, and when_.

Referenced by export_fmu(), and transition().

◆ type_name()

std::string casadi::DaeBuilderInternal::type_name ( ) const
inline

Definition at line 390 of file dae_builder_internal.hpp.

390 {return "DaeBuilderInternal";}

◆ unique_name()

std::string casadi::DaeBuilderInternal::unique_name ( const std::string &  prefix,
bool  allow_no_prefix = false 
) const

Definition at line 2145 of file dae_builder_internal.cpp.

2146  {
2147  // Check if the variable exists without any prefix
2148  if (allow_no_prefix && !has(prefix)) return prefix;
2149  // Find the first available index
2150  size_t i = 0;
2151  while (has(prefix + str(i))) i++;
2152  // Return the unique name
2153  return prefix + str(i);
2154 }

References has(), and casadi::str().

Referenced by assign(), eq(), reinit(), and when().

◆ update_dependencies()

void casadi::DaeBuilderInternal::update_dependencies ( ) const

Definition at line 1175 of file dae_builder_internal.cpp.

1175  {
1176  // Get oracle function
1177  const Function& oracle = this->oracle(false, true);
1178  // Dependendencies of the ODE right-hand-side
1179  Sparsity dode_dxT = oracle.jac_sparsity(oracle.index_out("ode"), oracle.index_in("x")).T();
1180  Sparsity dode_duT = oracle.jac_sparsity(oracle.index_out("ode"), oracle.index_in("u")).T();
1181  Sparsity dode_dzT = oracle.jac_sparsity(oracle.index_out("ode"), oracle.index_in("z")).T();
1182  for (casadi_int i = 0; i < size(Category::X); ++i) {
1183  // Get output variable
1184  const Variable& xdot = variable(variable(Category::X, i).der);
1185  // Clear dependencies
1186  xdot.dependencies.clear();
1187  // Dependencies on states
1188  for (casadi_int k = dode_dxT.colind(i); k < dode_dxT.colind(i + 1); ++k) {
1189  casadi_int j = dode_dxT.row(k);
1190  xdot.dependencies.push_back(variable(Category::X, j).value_reference);
1191  }
1192  // Dependencies on algebraic variables
1193  for (casadi_int k = dode_dzT.colind(i); k < dode_dzT.colind(i + 1); ++k) {
1194  casadi_int j = dode_dzT.row(k);
1195  xdot.dependencies.push_back(variable(Category::Z, j).value_reference);
1196  }
1197  // Dependencies on controls
1198  for (casadi_int k = dode_duT.colind(i); k < dode_duT.colind(i + 1); ++k) {
1199  casadi_int j = dode_duT.row(k);
1200  xdot.dependencies.push_back(variable(Category::U, j).value_reference);
1201  }
1202  }
1203  // Dependendencies of the outputs and event indicators
1205  auto catname = to_string(cat);
1206  const std::vector<size_t>& oind = indices(cat);
1207  Sparsity dy_dxT = oracle.jac_sparsity(oracle.index_out(catname), oracle.index_in("x")).T();
1208  Sparsity dy_dzT = oracle.jac_sparsity(oracle.index_out(catname), oracle.index_in("z")).T();
1209  Sparsity dy_duT = oracle.jac_sparsity(oracle.index_out(catname), oracle.index_in("u")).T();
1210  for (casadi_int i = 0; i < oind.size(); ++i) {
1211  // Get output variable
1212  const Variable& y = variable(oind.at(i));
1213  // Clear dependencies
1214  y.dependencies.clear();
1215  // Dependencies on states
1216  for (casadi_int k = dy_dxT.colind(i); k < dy_dxT.colind(i + 1); ++k) {
1217  casadi_int j = dy_dxT.row(k);
1218  y.dependencies.push_back(variable(Category::X, j).value_reference);
1219  }
1220  // Dependencies on algebraic variables
1221  for (casadi_int k = dy_dzT.colind(i); k < dy_dzT.colind(i + 1); ++k) {
1222  casadi_int j = dy_dzT.row(k);
1223  y.dependencies.push_back(variable(Category::Z, j).value_reference);
1224  }
1225  // Dependencies on controls
1226  for (casadi_int k = dy_duT.colind(i); k < dy_duT.colind(i + 1); ++k) {
1227  casadi_int j = dy_duT.row(k);
1228  y.dependencies.push_back(variable(Category::U, j).value_reference);
1229  }
1230  }
1231  }
1232 }
const std::vector< Sparsity > & jac_sparsity(bool compact=false) const
Get, if necessary generate, the sparsity of all Jacobian blocks.
Definition: function.cpp:1092

References casadi::ALG, casadi::Sparsity::colind(), casadi::Variable::dependencies, der(), casadi::Function::index_in(), casadi::Function::index_out(), indices(), casadi::Function::jac_sparsity(), oracle(), casadi::Sparsity::row(), size(), casadi::to_string(), casadi::U, variable(), casadi::X, casadi::Y, casadi::Z, and casadi::ZERO.

Referenced by export_fmu().

◆ var() [1/5]

std::vector<MX> casadi::DaeBuilderInternal::var ( Category  cat) const
inline

Definition at line 461 of file dae_builder_internal.hpp.

461 {return var(indices(cat));}

References var().

Referenced by var().

◆ var() [2/5]

const MX& casadi::DaeBuilderInternal::var ( Category  cat,
size_t  ind 
) const
inline

Definition at line 455 of file dae_builder_internal.hpp.

455 {return var(indices(cat).at(ind));}

References var().

Referenced by var().

◆ var() [3/5]

const MX & casadi::DaeBuilderInternal::var ( const std::string &  name) const

◆ var() [4/5]

std::vector< MX > casadi::DaeBuilderInternal::var ( const std::vector< size_t > &  ind) const

Definition at line 4538 of file dae_builder_internal.cpp.

4538  {
4539  std::vector<MX> ret;
4540  ret.reserve(ind.size());
4541  for (size_t i : ind) ret.push_back(var(i));
4542  return ret;
4543 }

References var().

◆ var() [5/5]

const MX & casadi::DaeBuilderInternal::var ( size_t  ind) const

Definition at line 4534 of file dae_builder_internal.cpp.

4534  {
4535  return variable(ind).v;
4536 }

References casadi::Variable::v, and variable().

◆ variability()

Variability casadi::DaeBuilderInternal::variability ( size_t  ind) const
protected

Definition at line 3457 of file dae_builder_internal.cpp.

3457  {
3458  return variable(ind).variability;
3459 }

References casadi::Variable::variability, and variable().

Referenced by add(), default_initial(), import_model_variables(), and set_variability().

◆ variable() [1/8]

Variable& casadi::DaeBuilderInternal::variable ( Category  cat,
size_t  ind 
)
inline

Access a variable by Category and index

Definition at line 433 of file dae_builder_internal.hpp.

433 {return variable(indices(cat).at(ind));}

References variable().

Referenced by variable().

◆ variable() [2/8]

const Variable& casadi::DaeBuilderInternal::variable ( Category  cat,
size_t  ind 
) const
inline

Access a variable by Category and index

Definition at line 434 of file dae_builder_internal.hpp.

434  {
435  return variable(indices(cat).at(ind));
436  }

◆ variable() [3/8]

Variable& casadi::DaeBuilderInternal::variable ( const MX v)
inline

Access a variable by expression

Definition at line 447 of file dae_builder_internal.hpp.

447 {return variable(find(v));}

References casadi::find(), and variable().

Referenced by variable().

◆ variable() [4/8]

const Variable& casadi::DaeBuilderInternal::variable ( const MX v) const
inline

Access a variable by expression

Definition at line 448 of file dae_builder_internal.hpp.

448 {return variable(find(v));}

References casadi::find(), and variable().

Referenced by variable().

◆ variable() [5/8]

Variable& casadi::DaeBuilderInternal::variable ( const std::string &  name)
inline

Access a variable by name

Definition at line 441 of file dae_builder_internal.hpp.

441 {return variable(find(name));}

References casadi::find(), and variable().

Referenced by variable().

◆ variable() [6/8]

const Variable& casadi::DaeBuilderInternal::variable ( const std::string &  name) const
inline

Access a variable by name

Definition at line 442 of file dae_builder_internal.hpp.

442 {return variable(find(name));}

References casadi::find(), and variable().

Referenced by variable().

◆ variable() [7/8]

Variable& casadi::DaeBuilderInternal::variable ( size_t  ind)
inline

◆ variable() [8/8]

const Variable& casadi::DaeBuilderInternal::variable ( size_t  ind) const
inline

Access a variable by index

Definition at line 428 of file dae_builder_internal.hpp.

428 {return *variables_.at(ind);}

◆ weak()

Extra doc: https://github.com/casadi/casadi/wiki/L_1ai

Definition at line 67 of file generic_shared_internal.hpp.

210  {
211 #ifdef CASADI_WITH_THREADSAFE_SYMBOLICS
212  auto* w = weak_ref_.load(std::memory_order_acquire);
213  if (!w) {
214  auto* nw = new GenericWeakRef<Shared, Internal>(static_cast<Internal*>(this));
215  GenericWeakRef<Shared, Internal>* expected = nullptr;
216  if (weak_ref_.compare_exchange_strong(
217  expected, nw, std::memory_order_release, std::memory_order_acquire)) {
218  w = nw;
219  } else {
220  delete nw; // lost the race; another thread published first
221  w = expected;
222  }
223  }
224  return w;
225 #else
226  if (weak_ref_==nullptr) {
227  weak_ref_ = new GenericWeakRef<Shared, Internal>(static_cast<Internal*>(this));
228  }
229  return weak_ref_;
230 #endif // CASADI_WITH_THREADSAFE_SYMBOLICS
231  }

◆ when()

void casadi::DaeBuilderInternal::when ( const MX cond,
const std::vector< std::string > &  eqs,
const Dict opts 
)
protected

Definition at line 3728 of file dae_builder_internal.cpp.

3729  {
3730  // Read options
3731  for (auto&& op : opts) {
3732  casadi_error("No such option: " + op.first);
3733  }
3734  // Convert condition into a smooth zero crossing condition
3735  MX zero;
3736  if (cond.is_op(OP_LT)) {
3737  zero = cond.dep(0) - cond.dep(1); // Reformulate a < b to a - b < 0
3738  } else if (cond.is_op(OP_LE)) {
3739  casadi_error("Only strict inequality in zero-crossing conditions permitted, got: "
3740  + str(cond));
3741  } else {
3742  casadi_error("Cannot parse zero-crossing condition: " + str(cond));
3743  }
3744  // Create a new dependent variable for the event indicator
3746  zero, Dict());
3747  indices(Category::ZERO).push_back(e.index);
3748  categorize(e.index, Category::CALCULATED);
3749  // Convert to legacy format, pending refactoring
3750  std::vector<MX> all_lhs, all_rhs;
3751  std::vector<size_t> all_eqs;
3752  for (auto&& eq : eqs) {
3753  Variable& ee = variable(eq);
3754  casadi_assert_dev(ee.category == Category::CALCULATED);
3755  all_lhs.push_back(var(ee.parent));
3756  all_rhs.push_back(ee.v);
3757  all_eqs.push_back(ee.index);
3758  }
3759  when_.push_back(std::make_pair(e.index, all_eqs));
3760 }
@ OP_LT
Definition: calculus.hpp:70
@ OP_LE
Definition: calculus.hpp:70

References add(), casadi::CALCULATED, categorize(), casadi::Variable::category, casadi::CONTINUOUS, casadi::MX::dep(), eq(), casadi::Variable::index, indices(), casadi::MX::is_op(), casadi::LOCAL, casadi::OP_LE, casadi::OP_LT, casadi::Variable::parent, casadi::str(), unique_name(), casadi::Variable::v, var(), variable(), when_, and casadi::ZERO.

Referenced by import_dynamic_equations().

Friends And Related Function Documentation

◆ DaeBuilder

friend class DaeBuilder
friend

Definition at line 219 of file dae_builder_internal.hpp.

◆ FmuFunction

friend class FmuFunction
friend

Definition at line 221 of file dae_builder_internal.hpp.

Referenced by fmu_fun().

◆ FmuInternal

friend class FmuInternal
friend

Definition at line 220 of file dae_builder_internal.hpp.

◆ Variable

friend class Variable
friend

Definition at line 222 of file dae_builder_internal.hpp.

Referenced by new_variable().

Member Data Documentation

◆ author_

std::string casadi::DaeBuilderInternal::author_
protected

Definition at line 511 of file dae_builder_internal.hpp.

Referenced by load_fmi_description().

◆ can_be_instantiated_only_once_per_process_

bool casadi::DaeBuilderInternal::can_be_instantiated_only_once_per_process_
protected

◆ clear_cache_

bool casadi::DaeBuilderInternal::clear_cache_
mutableprotected

◆ copyright_

std::string casadi::DaeBuilderInternal::copyright_
protected

Definition at line 512 of file dae_builder_internal.hpp.

Referenced by load_fmi_description().

◆ debug_

bool casadi::DaeBuilderInternal::debug_
protected

◆ der_

std::vector<size_t> casadi::DaeBuilderInternal::der_
protected

Definition at line 551 of file dae_builder_internal.hpp.

Referenced by import_model_structure(), and import_model_variables().

◆ description_

std::string casadi::DaeBuilderInternal::description_
protected

Definition at line 510 of file dae_builder_internal.hpp.

Referenced by load_fmi_description().

◆ detect_quad_

bool casadi::DaeBuilderInternal::detect_quad_
protected

◆ enable_ls_dae_

bool casadi::DaeBuilderInternal::enable_ls_dae_
protected

Definition at line 504 of file dae_builder_internal.hpp.

Referenced by DaeBuilderInternal(), and import_model_structure().

◆ enable_ls_serialization_

bool casadi::DaeBuilderInternal::enable_ls_serialization_
protected

Definition at line 504 of file dae_builder_internal.hpp.

Referenced by DaeBuilderInternal(), and load_fmi_description().

◆ fmi_major_

casadi_int casadi::DaeBuilderInternal::fmi_major_
protected

◆ fmi_version_

std::string casadi::DaeBuilderInternal::fmi_version_
protected

Definition at line 507 of file dae_builder_internal.hpp.

Referenced by load_fmi_description().

◆ fmutol_

double casadi::DaeBuilderInternal::fmutol_
protected

Definition at line 502 of file dae_builder_internal.hpp.

Referenced by DaeBuilderInternal(), and casadi::FmuInternal::init().

◆ fun_

std::vector<Function> casadi::DaeBuilderInternal::fun_
protected

Extra doc: https://github.com/casadi/casadi/wiki/L_11

Definition at line 665 of file dae_builder_internal.hpp.

Referenced by add_fun(), disp(), fun(), and has_fun().

◆ generation_date_and_time_

std::string casadi::DaeBuilderInternal::generation_date_and_time_
protected

Definition at line 515 of file dae_builder_internal.hpp.

Referenced by load_fmi_description().

◆ generation_tool_

std::string casadi::DaeBuilderInternal::generation_tool_
protected

Definition at line 514 of file dae_builder_internal.hpp.

Referenced by casadi::FmuInternal::init(), and load_fmi_description().

◆ ignore_time_

bool casadi::DaeBuilderInternal::ignore_time_
protected

Definition at line 503 of file dae_builder_internal.hpp.

Referenced by DaeBuilderInternal(), and import_model_variables().

◆ indices_

std::vector<std::vector<size_t> > casadi::DaeBuilderInternal::indices_
protected

Definition at line 560 of file dae_builder_internal.hpp.

Referenced by DaeBuilderInternal(), and indices().

◆ init_

std::vector<size_t> casadi::DaeBuilderInternal::init_
protected

Definition at line 563 of file dae_builder_internal.hpp.

Referenced by disp(), init_lhs(), init_rhs(), and set_init().

◆ initial_unknowns_

std::vector<size_t> casadi::DaeBuilderInternal::initial_unknowns_
protected

Definition at line 551 of file dae_builder_internal.hpp.

Referenced by import_model_structure().

◆ instantiation_token_

std::string casadi::DaeBuilderInternal::instantiation_token_
protected

Definition at line 509 of file dae_builder_internal.hpp.

Referenced by casadi::FmuInternal::init(), and load_fmi_description().

◆ lc_

Function::AuxOut casadi::DaeBuilderInternal::lc_
protected

Definition at line 660 of file dae_builder_internal.hpp.

Referenced by add_lc(), and create().

◆ license_

std::string casadi::DaeBuilderInternal::license_
protected

Definition at line 513 of file dae_builder_internal.hpp.

Referenced by load_fmi_description().

◆ model_identifier_

std::string casadi::DaeBuilderInternal::model_identifier_
protected

Definition at line 523 of file dae_builder_internal.hpp.

Referenced by import_model_exchange(), and casadi::FmuInternal::init().

◆ model_name_

std::string casadi::DaeBuilderInternal::model_name_
protected

Definition at line 508 of file dae_builder_internal.hpp.

Referenced by load_fmi_description().

◆ name_

std::string casadi::DaeBuilderInternal::name_
protected

◆ nzero_

casadi_int casadi::DaeBuilderInternal::nzero_
protected

◆ oracle_

Function casadi::DaeBuilderInternal::oracle_[2][2][2]
mutableprotected

Extra doc: https://github.com/casadi/casadi/wiki/L_12

Definition at line 670 of file dae_builder_internal.hpp.

Referenced by clear_cache(), and oracle().

◆ orig_time_index_

casadi_int casadi::DaeBuilderInternal::orig_time_index_
protected

Definition at line 539 of file dae_builder_internal.hpp.

Referenced by add(), and convert_index().

◆ provides_adjoint_derivatives_

bool casadi::DaeBuilderInternal::provides_adjoint_derivatives_
protected

◆ provides_directional_derivatives_

bool casadi::DaeBuilderInternal::provides_directional_derivatives_
protected

◆ resource_

Resource casadi::DaeBuilderInternal::resource_
protected

◆ source_files_

std::vector<std::string> casadi::DaeBuilderInternal::source_files_
protected

Definition at line 527 of file dae_builder_internal.hpp.

Referenced by import_model_exchange().

◆ start_time_

double casadi::DaeBuilderInternal::start_time_
protected

◆ step_size_

double casadi::DaeBuilderInternal::step_size_
protected

◆ stop_time_

double casadi::DaeBuilderInternal::stop_time_
protected

◆ symbolic_

bool casadi::DaeBuilderInternal::symbolic_
protected

Definition at line 536 of file dae_builder_internal.hpp.

Referenced by create(), DaeBuilderInternal(), load_fmi_description(), and oracle().

◆ tolerance_

double casadi::DaeBuilderInternal::tolerance_
protected

◆ variable_naming_convention_

std::string casadi::DaeBuilderInternal::variable_naming_convention_
protected

Definition at line 516 of file dae_builder_internal.hpp.

Referenced by load_fmi_description().

◆ variables_

std::vector<Variable*> casadi::DaeBuilderInternal::variables_
protected

◆ varind_

std::unordered_map<std::string, size_t> casadi::DaeBuilderInternal::varind_
protected

Definition at line 554 of file dae_builder_internal.hpp.

Referenced by add(), find(), has(), import_model_variables(), new_variable(), and prune().

◆ vrmap_

std::unordered_map<unsigned int, size_t> casadi::DaeBuilderInternal::vrmap_
protected

◆ when_

std::vector<std::pair<size_t, std::vector<size_t> > > casadi::DaeBuilderInternal::when_
protected

Definition at line 566 of file dae_builder_internal.hpp.

Referenced by disp(), import_dynamic_equations(), transition(), and when().


The documentation for this class was generated from the following files: