core package

Submodules

core.agent module

class core.agent.AbstractAgent(name='', objectives=None, inequations=None, equations=None, functions=None, params=None, dim_dict=None)[source]

Bases: AgentValidator

Core methods for Agent models.

Methods:

Constructors:

  1. __init__: Init Agent from its parts: see method args.

  2. read_from_tex: Parse Agent model from .tex file written in YAML (json-like) format. See examples at /models/inputs/.

Private:

  1. __generate_duals: Generate dual variables and functions due to Lagrange principum.

Public:

Additional:

  1. Support system

Methods that helps system to understand which variables are phase, which are controls etc.

  1. time : extract time variable in agent model

  2. time_horizon : extract time horizon boundaries from integral part of objective functions

  3. transitions : extract first-order differential equations from all boundaries

  4. phases : extract phase variables from all functions

  5. external : extract exogenous constants from all functions

  6. controls : extract control variables from all functions

  7. variables : extract all model variable (not-functions)

  8. expr : extract all expressions (with objectives)

  9. boundaries : all equations and inequations (no differential equations)

  10. constant_ineqs : inequations with no terminal values

  11. diff_degree : Divide all expressions over differential equation degrees

  12. validate : provide Agent model validation from subclass

  1. Misc

Basic class methods to provide comfort.

  1. args : Args to re-init

  2. kwargs : Kwargs to re-init

  3. process : Pre-process model to be used in core methods

  4. compress : Evaluate all Pontragin Principle conditions

  5. dump : Process model to PDF file with optimal conditions (Pontryagin Principle) [compress + dump]

  1. Core

Methods that conduct Maximum Principle Conditions due to Lagrange principum.

  1. Lagrangian : integral part of L

  2. lagrangian : termination part of L

  3. euler_equations : Euler-Lagrange equations

  4. transversality_conditions : Transversality conditions

  5. control_optimality : Control optimality conditions

  6. KKT: Dual-feasibility and Complementary Slackness conditions

property Hamiltonian_Gamkrelidze

not tested yet

KKT()[source]

Dual feasibility and Complementary slackness conditions :return: List[Expr]

property Lagrangian

Intergal part of L :return: Expr

property args

Args, to re-init :return:

property boundaries

Expressions with these types:

  1. Differential degree == 0

  2. Constant inequalities

Returns

List[Expr]

compress(to_tex=False, headers=True)[source]
Parameters
  • to_tex – bool. If True – .tex file will be generated

  • headers – If True – .tex file will contain headers

Returns

Union[None, RenderedJinjaTemplate]

property constant_ineqs

Constant inequalities: those which contains only functions in terminant (constant) values. :return:

control_boundaries()[source]
control_optimality()[source]

Control optimality conditions, using smoothness of L function wrt control variables :return: List[Eq]

property controls

Extract all controls: controls = functions - external - phases :return: List[Symbol]

diff_degree(deg=None)[source]

Returns all expr with Derivative degree == deg. :param deg: int. Derivative degree of returning equations :return: Dict[Expr->deg] if None else Dict[Expr->`deg`]

dump(destination=None, is_absolute=False)[source]

Create .tex and PDF files with Agent optimal conditions. :param destination: filepath or fd. :return: PDF, .tex files saved in destination

emitent = False
euler_equations()[source]

Euler Equations: d/dt L_{x’} = L_{x} :return: List[Eq]

property expr

All expressions in model :return: List[Expr]

property external

Extract exogenous functions, they must be substricted :return: List[Symbol]

property kwargs

Kwargs, to re-init :return:

property lagrangian

Terminant part of L :return: Expr

phase_boundaries()[source]
property phases

Extract phase variables from model: functions which appears as arguments in Differential operators in transitions :return: Union[List[Symbol], AnyPropertyNotFound]

process(skip_validation=False)[source]

Process model to be used in core methods. :param skip_validation: bool – If True validation process will be skipped :return: Union[None, AnyError]

classmethod read_from_tex(f)[source]

Contructor from .tex files. See Knowledge base to get guidelines. :param f: filename or fd :return: Agent

regularity_conditions()[source]
property time
Extract time variable from:
  1. Integral in objectives

  2. Differential variable in boundaries

Returns

Union[Symbol, TimeVariableNotFound]

property time_horizon

If time is extracted from objective integrals then collect integral boundaries. :return: Union[Tuple, AnyPropertyNotFound]

property transitions

Extract linear differential equations from model. :return: List[Eq]

transversality_conditions()[source]

Transversality conditions: L_{x’}(t_i) = (-1)^i l_{x(t_i)} :return: List[Eq]

property variables

All symbols in model :return: List[Symbol]

class core.agent.AgentValidator[source]

Bases: object

Validation class for Agent class. Provides Agent validation and correction to be processed by ECOMOD Core.

Methods:

Private:

  1. __dimension_check

    Uses KV-storage gained from input Agent model with variables -> dimensions to proceed Dimension check in Agent equations and inequations (expressions).

  2. __variable_completeness

    Checks if there are no extra initialized Agent variables in model, which are unused in model Expressions and if there are uninitialized variables in model.

Open:

  1. validate

    Provides full blackbox checks + emitent check

Class variables:

emitent = None: bool Shows that this Validation process is for Simple Agents – with objective functional.

emitent = None
validate(objectives, inequations, equations, functions, params, dim_dict)[source]

See __variable_completeness and __dimension_check docstrings. :param objectives: Agent objectives functions :param inequations: Agent inequation boundaries :param equations: Agent equation boundaries :param functions: Agent phase variables, controls and exogenous constants (but those are functions of time) :param params: Agent not-functional variables :param dim_dict: Union[List, Dict] – KV-storage: variable -> dimension :return: Union[AnyError, NonSympyfiableError, ExtraVariableError, DimensionCheckingFailed]

class core.agent.LinkedAgent(*args)[source]

Bases: AbstractAgent

Methods:
Constructors:
  1. __init__

    Basic contructor

  2. from_abstract

    Init LinkedAgent from Agent instance

Private:
  1. __merge_prepare

    Use Agent model output to gain tagged Agent model output.

Public:
  1. add_flow

  2. delete_flow

  3. print_flows

add_flow(flow: Flow)[source]
delete_flow(flow: Flow)[source]
emitent = False
static from_abstract(a: AbstractAgent)[source]
print_flows()[source]
core.agent.create_empty_agents(names, cls=<class 'core.agent.AbstractAgent'>)[source]

Additional function to provide test cases in scenarios/debug_scenarios.py :param names: Agent tags separated by space ‘ ‘. :param cls: Default=AbstractAgent. Class for returned agents. :return: List[Union[AbstractAgent, LinkedAgent]]

core.datamodel module

class core.datamodel.Boundary[source]

Bases: object

class core.datamodel.Parameter(name, **kwargs)[source]

Bases: Symbol

Superclass for ECOMOD parameters. 1-1 with sympy.Symbol

default_assumptions = {}
name: str
class core.datamodel.Phase(*args)[source]

Bases: Function

Superclass for ECOMOD parameters. 1-1 with sympy.Function

default_assumptions = {}

core.deserialiser module

core.deserialiser.main()[source]
core.deserialiser.parse_yaml(stream: str)[source]

Simple YAML decoder, to distinguish errors. :param stream: string value after reducing tex-header :return: dict: decoded yaml

core.deserialiser.read_model_from_tex(f)[source]

Full blackbox model parsing from .tex file. Used as subfunction in Agent.read_from_tex :param f: filename or fd :return: .tex header and KV-storage (json-like) with raw model

core.deserialiser.read_tex(f)[source]

Read tex file and split to yamlable and header :param f: filename or fd :return: yaml parsable object + header

core.ecomod_utils module

core.ecomod_utils.KKT_mask(dual: dict)[source]

Returns Dual Feasibility and Complementary Slackness for dual dict :param dual: Dict[Union[datamodel.Parameter, datamodel.Phase] –> Expr] :return: List[Expr] = [K*V]

core.ecomod_utils.add_subscript(symb, tag)[source]

Add subscript tag to symbol :param symb: Union[datamodel.Parameter, datamodel.Phase] - untagged :param tag: str :return: Union[datamodel.Parameter, datamodel.Phase] – tagged

core.ecomod_utils.deriv_degree(bc)[source]

Returns maximum degree of differential operator inside bc expression. :param bc: Expr :return: int

core.ecomod_utils.eq2func(eq)[source]

Return Expr:= lhs - rhs from Eq :param eq: Eq to be transformed :return: Expr

core.ecomod_utils.euler_mask(L, x, t)[source]

Provide Euler-Lagrange equations for passed Lagrangian and variables [phase, time] :param L: Expr – Lagrangian :param x: datamodel.Phase – Phase variables :param t: datamodel.Parameter – Time variable :return: List[Expr]

core.ecomod_utils.generate_symbols(tag, count, cls)[source]

Generate symbols function. Used for dual variables and parameters generation in Agent.process :param tag: str – Alias for generated symbols :param count: int – count of symbols :param cls: Class[Union[datamodel.Parameter, datamodel.Phase]] :return: Iter[Symbol]

core.ecomod_utils.gradient(expr, varss)[source]
core.ecomod_utils.is_spec_function(func)[source]

Bool version of spec_funcs. Return true if func is listed in spec_funcs, otherwise else. :param func: function to be checked :return: bool

core.ecomod_utils.is_substricted(symb, tag=None)[source]

Check if symbol is substricted with tag. :param symb: Union[datamodel.Parameter, datamodel.Phase] :param tag: Union[string, None] :return: bool

core.ecomod_utils.latexify(exprs: list, to_str=False)[source]

Provide latex codesnippets to expressions. Can be returned as joined string or as List[str] :param exprs: List[Expr] :param to_str: bool :return: Union[List[Expr], str]

core.ecomod_utils.pi_theorem(vars, eq)[source]

Deprecated method for dimension checking in equations. :param vars: :param eq: :return:

core.ecomod_utils.remove_subscript(symb)[source]

Firstly check if symbol is substricted, then if true remove !ANY! substricted. :param symb: Union[datamodel.Parameter, datamodel.Phase] :return: Union[datamodel.Parameter, datamodel.Phase] – unsubscripted.

core.ecomod_utils.span(coefs, variables)[source]

Return linear span of KV-storage. ret = sum_0^N[L_1[i] * L_2[i]] :param coefs: List[Expr] :param variables: List[Expr] :return: Expr

core.ecomod_utils.span_dict(d: dict)[source]

Return linear span of KV-storage. ret = sum_0^N[K[i] * V[i]] :param d: Dict[Expr -> Expr] :return: Expr

core.ecomod_utils.spec_funcs()[source]

Set of special analytical functions in sympy. Used to dimension check of its args. :return: set

core.ecomod_utils.transversality_mask(L, x, t, l, t0, t1)[source]

Transveraslity condition for agent optimal control problem :param L: Expr – Lagrangian :param x: datamodel.Phase – phase variable :param t: datamodel.Parameter – time variable :param l: Expr – termination lagrangian :param t0: datamodel.Parameter – time horizon[0] :param t1: datamodel.Parameter – time horizon[1] :return: List[Eq]

core.logger module

core.logger.log(comment=None)[source]

Basic logger: logger as decorator. If any function needs to be decorated use @log() decorator :param comment: LOG message before func exec :return: wrapped func

core.market module

class core.market.Balances(agent_names, eqs)[source]

Bases: object

atoms(name=None, detag=True)[source]
compress()[source]
process()[source]
classmethod read_from_tex(f)[source]
validate()[source]
class core.market.Flow(producer, receiver, value, dim)[source]

Bases: object

Here we will contain parsing results from flows file?

invert(new=False)[source]
class core.market.Market(eq, dim, lagents)[source]

Bases: object

class core.market.MarketValidator[source]

Bases: object

validate_market(markets)[source]

core.model module

class core.model.AgentMerger[source]

Bases: object

merge(lagents: List[AbstractAgent])[source]
class core.model.Model(name, balances=None, lagents: Optional[List[LinkedAgent]] = None)[source]

Bases: ModelValidator

Merged model with several agents and markets or agents and balances or agents and flows

add_agent(lagent: LinkedAgent)[source]
dump(destination=None)[source]
process()[source]
visualize(f)[source]
class core.model.ModelValidator[source]

Bases: MarketValidator, AgentValidator, AgentMerger

validate(markets, lagents)[source]

See __variable_completeness and __dimension_check docstrings. :param objectives: Agent objectives functions :param inequations: Agent inequation boundaries :param equations: Agent equation boundaries :param functions: Agent phase variables, controls and exogenous constants (but those are functions of time) :param params: Agent not-functional variables :param dim_dict: Union[List, Dict] – KV-storage: variable -> dimension :return: Union[AnyError, NonSympyfiableError, ExtraVariableError, DimensionCheckingFailed]

core.pprint module

core.sympyfier module

core.sympyfier.ecomodify(raw_model, xreplace=True)[source]

DEPRECATED Transfer raw model from .tex file to input of AbstractAgent. :param raw_model :param xreplace: bool, always True. False will convert model to Sympy Expr representations. For dev purposes only.

Returns

List[AbstractAgent.args]

core.sympyfier.ecomodify_(raw_model)[source]
core.sympyfier.sympify(raw_obj)[source]

Transfer data to internal representation. see datamodel module. :param raw_obj: str – string representation of Value expression in YAML :return:

core.utils module

core.utils.dict_substract(a, b)[source]
core.utils.embrace(s: str, brackets='()')[source]
core.utils.extract_dim_desc(raw_desc)[source]
core.utils.find_objective_markers(s: str)[source]
core.utils.get_root_dir() str[source]
core.utils.global_path(f)[source]

f: abspath linux-type

core.utils.iterable_substract(a, b)[source]
Parameters
  • a

  • b

Returns

a - b

core.utils.set_equality(set1, set2)[source]
core.utils.timeit(func)[source]
core.utils.trim(s: str, i=1, j=-1)[source]
Parameters
  • s – input string

  • i – start

  • j – end

Returns

substring s[i:j]. by default trimming from start and end 1 symbol

core.utils.unpack(yaml_dict)[source]

Module contents