utils

This module consists of helpful utility functions

eeco.utils.check_cvx_type(input_var)[source]

Checks if input is a CVXPY variable, expression, or parameter.

Parameters:

input_var (object) – Input parameter to check

Return type:

bool

eeco.utils.check_indexed_np_array(input_var)[source]

Checks if input is an array-like type (e.g., np.ndarray).

Parameters:

input_var (object) – Input parameter to check

Return type:

bool

eeco.utils.check_indexed_pyomo_type(input_var)[source]

Checks if input is an indexed Pyomo variable, expression, or parameter. Returns False if a non-indexed variable, parameter, or expression (or non-Pyomo type).

Parameters:

input_var (object) – Input parameter to check

Return type:

boolean

eeco.utils.check_nonindexed_pyomo_type(input_var)[source]

Checks if input is a non-indexed Pyomo variable, expression, or parameter. Returns False if an indexed variable, parameter, or expression (or non-Pyomo type).

Parameters:

input_var (object) – Input parameter to check

Return type:

bool

eeco.utils.check_nonindexed_python_type(input_var)[source]

Checks if input is a general int/float variable, expression, or parameter (e.g., np.int32 or np.float64)

Parameters:

input_var (object) – Input parameter to check

Return type:

bool

eeco.utils.check_pandas_type(input_var)[source]

Checks if input is a pandas Series or DataFrame.

Parameters:

input_var (object) – Input parameter to check

Return type:

bool

eeco.utils.check_simultaneous_import_export(positive, negative, tol=1e-06, varstr=None, raise_error=False)[source]

Warn (or raise) if any timestep has both import and export above tol.

Call after solving to verify that a decomposition_type=”linear” split is exact. Simultaneous import and export means the charges allowed arbitrage (e.g., export charge > energy charge). Can also validate user-provided numeric imports and exports before solving with raise_error=True.

Parameters:
  • positive ([numpy.Array, cvxpy.Expression, pyomo.environ.Var]) – Solved import component. CVXPY objects are read via .value and indexed Pyomo objects via pyomo.environ.value.

  • negative ([numpy.Array, cvxpy.Expression, pyomo.environ.Var]) – Solved export component (stored as positive magnitudes)

  • tol (float, optional) – Components at or below this value are treated as zero. Default 1e-6.

  • varstr (str, optional) – Name used to identify the utility in the warning or error message.

  • raise_error (bool, optional) – If True, raise a ValueError instead of warning. Default False.

Returns:

Indices of timesteps where both components exceed tol (empty if none)

Return type:

numpy.ndarray

Raises:

ValueError – If raise_error is True and any timestep has both components above tol

eeco.utils.convert_utc_to_timezone(utc_hour, timezone_str)[source]

Convert UTC hour (0-23) to the corresponding hour in a specified timezone.

Parameters:
  • utc_hour (int) – Hour in UTC (0-23).

  • timezone_str (str) – Timezone string, e.g., ‘America/New_York’.

  • Returns

  • int (Corresponding hour in the specified timezone.)

eeco.utils.create_pyomo_model_index_ref(model, var, overwrite=False, warns=True)[source]

Attach time index to the model for Pyomo variables and expressions.

Builds a mapping between the entries in var’s index set and their positional order, and stores both on the model as private attributes. This makes it easy to translate between a Pyomo indexed variable’s index values and plain integer positions (e.g. when aligning with a NumPy array or another positional data structure).

Parameters:
  • model (pyomo.environ.Model) – The Pyomo model (or Block) to attach the index bookkeeping to.

  • var (pyomo.environ.Param or pyomo.environ.Var) – A Pyomo indexed component (e.g. an indexed Var) whose index_set() will be enumerated.

  • overwrite (bool) – Ignored if index does not exist yet. If index exists, must be set to True for updates to take effect. If False, no changes are made to the index.

  • warns (bool) – If True, warn when the index exists and overwrite is False.

Warns:

UserWarning – When the index already exists, overwrite is False, and warns is True, suggesting overwrite=True to enforce index updates.

Returns:

Sets the following attributes on model: - _var_index_ref (dict): maps each index value in

var.index_set() to its integer position.

  • _var_index (list): the index values of var.index_set()

    in enumeration order.

Return type:

None

eeco.utils.decompose_consumption(expression, model=None, varstr=None, decomposition_type='absolute_value', big_m=1000000.0)[source]

Decomposes consumption data into positive and negative components.

Adds constraint such that total consumption equals positive values minus negative values (where negative values are stored as positive magnitudes).

Parameters:
  • expression ([) – numpy.Array, cvxpy.Expression, pyomo.core.expr.numeric_expr.NumericExpression, pyomo.core.expr.numeric_expr.NumericNDArray, pyomo.environ.Param, pyomo.environ.Var

  • ] – Expression representing consumption data

  • model (pyomo.environ.Model) – The model object associated with the problem. Only used in the case of Pyomo, so None by default.

  • varstr (str) – Name prefix for the variables to be created if using a Pyomo model

  • decomposition_type ({“absolute_value”, “binary_big_M”, “linear”}) – Type of decomposition to use. - “absolute_value”: Uses max(x, 0) constraints. Creates nonlinear problem

    for Pyomo due to abs() constraint. Not supported for CVXPY.

    • “binary_big_M”: Uses binary indicator with Big-M constraints. Creates a MILP (mixed-integer linear program). Supported for both Pyomo and CVXPY (requires MIP solver).

    • “linear”: Plain LP split with non-negative import/export variables and no magnitude constraint. Supported for both Pyomo and CVXPY and needs no MIP/NLP solver. Exact only when export charge <= energy charge and demand charges are non-negative; otherwise the solver may import and export simultaneously. See check_simultaneous_import_export.

    Note: For numpy.ndarray inputs, decomposition_type is ignored

  • big_m (float, optional) – Big-M value for binary decomposition. Should be larger than maximum possible consumption magnitude. Default is 1e6. Only used when decomposition_type=”binary_big_M”.

Raises:
  • NotImplementedError – When decomposition_type is anything other than “absolute_value”, “binary_big_M” or “linear” for Pyomo, or anything other than “binary_big_M” or “linear” for CVXPY. Never raised for numpy.Array.

  • TypeError – When expression is not of type numpy.Array, cvxpy.Expression, pyomo.core.expr.numeric_expr.NumericExpression, pyomo.core.expr.numeric_expr.NumericNDArray, pyomo.environ.Param, or pyomo.environ.Var

Returns:

(positive, negative, model_objects), where model_objects matches the second return value of calculate_cost:

  • numpy: (positive_values, negative_values, model) - model is untouched

  • Pyomo: (positive_var, negative_var, model) - constraints added to model

  • CVXPY: (positive_var, negative_var, constraints) - list of constraints

Return type:

tuple

eeco.utils.get_decomposed_var_names(utility)[source]

Get consistent variable names for decomposed consumption variables.

eeco.utils.get_freq_binsize_minutes(freq)[source]

Gets size of a given time frequency expressed in units of minutes

Parameters:

freq (str) – a string of the form [type][freq_binsize], where type corresponds to a numpy.timedelta64 encoding and freq binsize is an integer giving the number of increments of type of one binned increment of our time variable (for example ‘6h’ means the data are grouped into increments of 6 hours)

Raises:

ValueError – when resolution is not minute, hourly, or daily

Returns:

integer giving the number of minutes in the given time frequency unit

Return type:

int

eeco.utils.idxparam_value(idx_param)[source]

Returns the parameter value at the given index.

Parameters:

idx_param (pyomo.environ.Param or pyomo.environ.Var) – The Pyomo parameter or variable to be converted

Returns:

Indexed variable or parameter as a numpy array

Return type:

numpy.ndarray

eeco.utils.max(expression, model=None, varstr=None, index_set=None)[source]

Elementwise maximum of an expression or array

Parameters:
  • expression ([) – numpy.Array, cvxpy.Expression, pyomo.core.expr.numeric_expr.NumericExpression, pyomo.core.expr.numeric_expr.NumericNDArray, pyomo.environ.Param, pyomo.environ.Var

  • ] – The expression to find the maximum of

  • model (pyomo.environ.Model) – The model object associated with the problem. Only used in the case of Pyomo, so None by default.

  • varstr (str) – Name of the variable to be created if using a Pyomo model

  • index_set ([pyomo.environ.Set, list]) – Index values to constrain the maximum over when using a Pyomo model. Default is None, meaning the model-wide _var_index. Pass a subset to skip timesteps that cannot affect the maximum.

Raises:

TypeError – When expression is not of type numpy.Array, cvxpy.Expression, pyomo.core.expr.numeric_expr.NumericExpression, pyomo.core.expr.numeric_expr.NumericNDArray, pyomo.environ.Param, or pyomo.environ.Var

Returns:

Expression representing max of expression

Return type:

([numpy.Array, cvxpy.Expression, pyomo.environ.Var], pyomo.environ.Model)

eeco.utils.max_pos(expression, model=None, varstr=None)[source]

Returns the element-wise maximum positive value of an expression. Returns scalar for scalar input, indexed for indexed input.

Parameters:
  • expression ([) – numpy.Array, cvxpy.Expression, pyomo.core.expr.numeric_expr.NumericExpression, pyomo.core.expr.numeric_expr.NumericNDArray, pyomo.environ.Param, pyomo.environ.Var

  • ] – Expression representing a matrix, vector, or scalar

  • model (pyomo.environ.Model) – The model object associated with the problem. Only used in the case of Pyomo, so None by default.

  • varstr (str) – Name of the variable to be created if using a Pyomo model

Raises:

TypeError – When expression is not of type numpy.Array, cvxpy.Expression, pyomo.core.expr.numeric_expr.NumericNDArray, pyomo.core.expr.numeric_expr.NumericExpression, pyomo.environ.Param, or pyomo.environ.Var

Returns:

  • ( – [numpy.float, numpy.int, numpy.Array, cvxpy.Expression, or pyomo.environ.Var], pyomo.environ.Model

  • ) – Expression representing element-wise maximum positive value of expression. Scalar input returns scalar output, indexed input returns indexed output.

eeco.utils.multiply(expression1, expression2, model=None, varstr=None)[source]

Implements elementwise multiplication operation on two optimization expressions

Parameters:
  • expression1 ([) – numpy.Array, cvxpy.Expression, pyomo.core.expr.numeric_expr.NumericExpression, pyomo.core.expr.numeric_expr.NumericNDArray, pyomo.environ.Param, pyomo.environ.Var

  • ] – LHS of multiply operation

  • expression2 ([) – numpy.Array, cvxpy.Expression, pyomo.core.expr.numeric_expr.NumericExpression, pyomo.core.expr.numeric_expr.NumericNDArray, pyomo.environ.Param, pyomo.environ.Var

  • ] – RHS of multiply operation

  • model (pyomo.environ.Model) – The model object associated with the problem. Only used in the case of Pyomo, so None by default.

  • varstr (str) – Name of the variable to be created if using a Pyomo model

Raises:

TypeError – When expression is not of type numpy.Array, cvxpy.Expression, pyomo.core.expr.numeric_expr.NumericNDArray, pyomo.core.expr.numeric_expr.NumericExpression, pyomo.environ.Param, or pyomo.environ.Var

Returns:

  • [ – numpy.Array, cvxpy.Expression, pyomo.core.expr.numeric_expr.NumericNDArray, pyomo.environ.Expression

  • ] – result from elementwise multiplication of expression1 and expression2

eeco.utils.parse_freq(freq)[source]

Parses a time frequency code string, returning its type and its freq_binsize

Parameters:

freq (str) – a string of the form [type][freq_binsize], where type corresponds to a numpy.timedelta64 encoding and freq binsize is an integer giving the number of increments of type of one binned increment of our time variable (for example ‘6h’ means the data are grouped into increments of 6 hours)

Returns:

tuple of the form (int,`str`) giving the binsize and units (freq_type)

Return type:

tuple

eeco.utils.sanitize_varstr(varstr)[source]

Sanitizes a variable string by removing non-alphanumeric characters and replacing spaces with underscores.

Parameters:

varstr (str) – The variable string to sanitize.

Returns:

The sanitized variable string.

Return type:

str

eeco.utils.sum(expression, axis=0, model=None, varstr=None)[source]

Elementwise sum of values in an expression or array

Parameters:
  • expression ([) – numpy.Array, cvxpy.Expression, pyomo.core.expr.numeric_expr.NumericExpression, pyomo.core.expr.numeric_expr.NumericNDArray, pyomo.environ.Param, pyomo.environ.Var

  • ] – Expression representing a matrix to sum

  • axis (int) – Optional axis along which to compute sum. Default is 0

  • model (pyomo.environ.Model) – The model object associated with the problem. Only used in the case of Pyomo, so None by default.

  • varstr (str) – Name of the variable to be created if using a Pyomo model

Raises:

TypeError – When expression is not of type numpy.Array, cvxpy.Expression, pyomo.core.expr.numeric_expr.NumericExpression, pyomo.core.expr.numeric_expr.NumericNDArray pyomo.environ.Param, or pyomo.environ.Var

Returns:

Expression representing sum of expression along axis

Return type:

[numpy.Array, cvxpy.Expression, pyomo.environ.Expression]