comando.utility module
Utility functions used in various parts of COMANDO.
- class comando.utility.DefaultStringMap[source]
Bases:
defaultdict
A default dict implementation whose factory is called with the key.
- class comando.utility.StrParser(sym_map, str_map=None, override_default_str_map=True, add_callback=None, mul_callback=None, pow_callback=None)[source]
Bases:
object
A class for creating interface-specific string representations.
Callbacks must have a signature consisting of three arguments: The parser the expression to be parsed and an optional index Arguments: =========
sym_map str_map add_callback mul_callback pow_callback
- comando.utility.as_numer_denom(expr)[source]
Normalize as_numer_denom for sympy and symengine.
Also see: https://github.com/symengine/symengine/issues/681#issuecomment-724039779
- comando.utility.bEq(x, y)[source]
Return the truth value of x == y, if it can be determined, else None.
- comando.utility.bGe(x, y)[source]
Return the truth value of x >= y, if it can be determined, else None.
- comando.utility.bLe(x, y)[source]
Return the truth value of x <= y, if it can be determined, else None.
- comando.utility.bounds_cost_turton(x, c1, c2, c3)[source]
Compute bounds for the the Guthrie cost function.
cost_turton(x, c1, c2, c3) = pow(10, c1 + c2 * log10(x) + c3 * log10(x) ** 2)
- comando.utility.canonical_file_name(base_name, suffix, file_name=None) -> (<class 'str'>, <class 'str'>)[source]
Get a canonical file name and the corresponding base name.
- Parameters:
base_name (str) – the fallback if filename is None
suffix (str) – desired suffix
file_name (str or None) – a desired name with or without the desired suffix or None
- Returns:
base_name (str) – the canonical base_name
file_name (str) – the canonical file_name
- comando.utility.check_reuse_or_overwrite(file_name, reuse) None [source]
Check whether a file exists for reuse or overwriting.
- Parameters:
file_name (str) – the name of the file to reuse or overwrite
reuse (bool or None) – whether to reuse the given file. There are three cases:
reuse is False -> do nothing
reuse is True -> check if file_name is a valid file
reuse is None -> if file_name is a file, ask before overwriting
- comando.utility.cleanup()[source]
Take a snapshot of all files on current path and remove new ones.
- comando.utility.cont_univ_bounds(expr, var)[source]
Compute tight bounds for bounded continuous univariate expressions.
A bounded continuous expression of a single variable can be bounded exactly by looking at its function values at ‘critical points’, i.e., the union of its bounds and the points at which its derivative is zero that are in the interval implied by the bounds.
- comando.utility.define_function(name, implementation)[source]
Define a new symbolic function with a name and an implementation.
The given implementation will be used when the function is called with nonsymbolic arguments only.
- Parameters:
name (str) – the function’s name
implementation (callable) – a callable that serves as the numerical implementation and is used when no symbols are within the arguments. Must have a fixed number of positional arguments.
- Returns:
new_function – the newly defined function
- Return type:
sympy.FunctionClass
- comando.utility.evaluate(expr, idx=None)[source]
Evaluate the given expression at the symbols’ current values.
Note
To allow for indexed espressions to be evaluated, evaluate uses numpy and thus double arithmetic instead of the arbitrary precision arithmetic usually used by sympy or symengine backends. This can result in different results in comparison to those obtained by other tools such as solvers or AMLs interfaced to COMANDO.
- Parameters:
expr (comando.Expr) – The expression to be evaluated
idx (double, str, list, tuple) – The index at which to evaluate
returns
result (float or pandas.Series) – The numerical result of the evaluation
- comando.utility.get_index(expr)[source]
Get the index of the current expression or None if it is not indexed.
- comando.utility.get_latest(path_glob)[source]
Get the path to the latest file matching the path_glob.
- comando.utility.handle_state_equations(P, callback=None)[source]
Generate and add discretized state equations from the problem P.
- Parameters:
P (Problem) – The problem to generate the state equations for.
callback (function, optional) – A function that is called for each generated constraint. The first argument is the name of the constraint and the second argument is the constraint expression. If no callback is given, the constraints are added to the problem P.
- comando.utility.is_negated(expr)[source]
Check if expr is a negated expression or a negative number.
- comando.utility.lambdify(expr, vars=None, eval_params=True, **kwargs)[source]
Create a function for evaluation of expr with numpy.
A variant of sympy’s lambdify which creates a function for fast numerical evaluation of an expression.
- Parameters:
expr (Expression) – the expression to be turned into a function
eval_params (bool) – Whether to replace parameters by their values (if expr contains indexed parameters, evaluating the function will thus return a Series) default: True
- Returns:
f – a function returning the value of the expression for given variable values
- Return type:
callable
- comando.utility.lmtd_bounds(dT1, dT2)[source]
Calculate the logarithmic mean temperature difference.
lmtd(dT1, dT2) = (dT1 - dT2) / log(dT1 / dT2)
- comando.utility.make_function(expr)[source]
Create a callable function from the given expression.
The user can either specify values for all Variables in the order specified by the returned function’s ‘__doc__’ (in alphabetical order), or pass keyword arguments in the form of identifier-value pairs. The values are taken as alternatives for the default values used in the evaluation for the Variables or Parameters with matching identifiers.
- comando.utility.make_mayer_objective(system)[source]
Create a Mayer term objective.
An option for dynamic optimization phi(t_f) is minimized and phi_dot = f(operation)
- comando.utility.make_str_func(name)[source]
Create a default string representation of functions.
- Parameters:
name (str) – name of the function to be represented
- Returns:
func – function that returns a string representation for the function with given string arguments
- Return type:
callable
- comando.utility.make_tac_objective(system, ic_labels=None, fc_labels=None, vc_labels=None, n=10, i=0.08)[source]
Create the objective components corresponding to total annualized cost.
- Parameters:
ic_labels (iterable of str) – labels for the investment cost expressions
fc_labels (iterable of str) – labels for the fixed cost expressions
vc_labels (iterable of str) – labels for the variable cost expressions
n (int) – number of repetitions of the time-period specified by timesteps.
i (float) – interest_rate
- Returns:
Expressions for design_objective and operational_objective forming part
of the total annualized costs.
- comando.utility.parse(expr, sym_map=None, op_map=None, idx=None, const_fun=<class 'float'>)[source]
Parse the sympy expression expr, replacing symbols and operators.
The sym_map provides the possibility to replace symbols (Parameters and Variables) with new objects, if the symbol map is empty or there is no mapping for a given symbol, it is replaced with its value attrubute; if value is None, the symbol is not replaced. The op_map provides the possibility to replace sympy’s operator objects with other operators. If no op map is provided, the default python operators are used.
- comando.utility.pow_bounds(a, b)[source]
Return the result of a ** b if a[0] == a[1] or b[0] == b[1].
The power function is monotonous on any domain that excludes zero! We therefore only need to consider special cases explicitly and can return the sorted tuple of powers of the base boundaries otherwise.
- comando.utility.precedence(expr)[source]
Get the operator precedence of the expression.
If the argument of an expression has a higher precedence than the expression itself, precedence needs to be represented explicitly in string representations. An example is (a + b) * c, where dropping the parentheses changes the result. We define precedences as:
±x, f(x): 0 x ** y: 1 x * y, x/y: 2 x ± y: 3
- comando.utility.rlmtd_bounds(dT1, dT2)[source]
Calculate bounds for the inverse of the LMTD.
rlmtd(dT1, dT2) = log(dT1 / dT2) / (dT1 - dT2)
- comando.utility.split(iterable, condition, c_type=None)[source]
Sort iterable’s elements into two containers based on condition.
- Parameters:
iterable (iterable) – iterable to be sorted
condition (callable) – function used for sorting, return value must convert to bool
c_type (type) – type of the resulting containers; if unset will attempt to use type(iterable) to create the containers or default to list if that fails. If after this both isinstance and c_type() are mappings, the new containers will be submappings of iterable and condition is only applied to the values of iterable.
- Returns:
cond_true, cond_false – tuple containing: - the container of elements that do not satisfy condition - the container of elements that do satisfy condition
- Return type:
- comando.utility.str_parse(expr, sym_map=None, str_map=None, idx=None)[source]
Parse the sympy expression expr, replacing symbols and operators.
The sym_map provides the possibility to replace symbols (Parameters and Variables) with their string representations, if the symbol map is empty or there is no mapping for a given symbol, it is replaced with its value attribute. The str_map provides the possibility to replace sympy’s operator objects with string representations.
- comando.utility.syscall(executable, *args, log_name='/dev/null', silent=False)[source]
Issue a system call.
- Parameters:
executable (str) – the name of the executable to be called. Needs to be an executable in one of the directories listed in the PATH environment variable.
args (list of str) – the arguments passed to the executable
log_name (str) – the location of a file to which the output of the system call is mirrored in parralel to execution (default: os.devnull)
silent (bool) – whether the output should be hidden from stdout (default: False)
- Returns:
ret – the return code of the system call
- Return type: