eeco package
Submodules
eeco.costs module
Functions to calculate costs from electricity consumption data.
- eeco.costs.add_to_charge_array(charge_dict, key_str, charge_array)[source]
Add to an existing charge array, or an array of all zeros if this charge array does not exist.
This functionality is useful for noncontiguous charges that should be saved under the same key. For example, partial peak hours from 3-5 and 8-10 PM that are billing as a single demand period.
Modifies charge_dict in-place, so nothing is returned.
- Parameters:
charge_dict (dict of numpy.ndarray) – Dictionary of arrays with keys of the form utility`_`charge_type`_`name`_`start_date`_`end_date`_`charge_limit and values being the $ per kW (electric demand), kWh (electric energy/export), cubic meter / hour (gas demand), cubic meter (gas energy), or $ / month (customer)
key_str (str) – The key for the charge array we’d like to modify of the form utility`_`charge_type`_`name`_`start_date`_`end_date`_`charge_limit
charge_array (numpy.ndarray) – Value of the charge to add in $ per kW (electric demand), kWh (electric energy/export), cubic meter / hour (gas demand), cubic meter (gas energy), or $ / month (customer)
- eeco.costs.build_pyomo_costing(charge_dict, consumption_data_dict, model, electric_consumption_units=Unit("kilowatt"), gas_consumption_units=Unit("meter ** 3 / hour"), resolution='15m', prev_demand_dict=None, prev_consumption_dict=None, consumption_estimate=0, desired_utility=None, desired_charge_type=None, demand_scale_factor=1, additional_objective_terms=None, decomposition_type=None, varstr_alias_func=<function default_varstr_alias_func>)[source]
Wrapper for calculate_cost to build the cost components into a Pyomo model. An objective function will be created in model.objective.
- Parameters:
charge_dict (dict) – dictionary of arrays with keys of the form utility`_`charge_type`_`name`_`start_date`_`end_date`_`charge_limit and values being the $ per kW (electric demand), kWh (electric energy/export), cubic meter / hour (gas demand), cubic meter (gas energy), or $ / month (customer)
consumption_data_dict (dict) – Baseline electrical and gas usage data as an optimization variable object with keys “electric” and “gas”. Values of the dictionary must be of type numpy.ndarray, cvxpy.Expression, or pyomo.environ.Var
model (pyomo.Model) – The model object associated with the problem.
electric_consumption_units (pint.Unit) – Units for the electricity consumption data. Default is kW
gas_consumption_units (pint.Unit) – Units for the natural gas consumption data. Default is cubic meters / hour
resolution (str) – String of the form [int][str] giving the temporal resolution on which charges are assessed, the str portion corresponds to numpy.timedelta64 types for example ‘15m’ specifying demand charges that are applied to 15-minute intervals of electricity consumption
prev_demand_dict (dict) – Nested dictionary previous maximmum demand charges with an entry of the form {“cost” : float, “demand” : float} for each charge. Default is None, which results in an a prev_demand and prev_demand_cost of zero for all charges.
prev_consumption_dict (dict) – Dictionary of previous total energy consumption with a key for each charge to be used when starting the cost calculation partway into a billing period (e.g., while using a moving horizon that is shorter than a month). Default is None, resulting in an a prev_consumption of zero for all charges.
consumption_estimate (float) – Estimate of the total monthly demand or energy consumption from baseline data. Only used when consumption_data is cvxpy.Expression or pyomo.environ.Var for convex relaxation of tiered charges, while numpy.ndarray consumption_data will use actual consumption and ignore the estimate.
desired_charge_type (list or str) – Name of desired charge type for itemized costs. Either ‘customer’, ‘energy’, ‘demand’, ‘export’, or a list of charge types. Default is None, meaning that all costs will be summed together.
desired_utility (list or str) – Name of desired utility for itemized costs. Either ‘electric’, ‘gas’, or a list of utilities (e.g., [‘electric’, ‘gas’]). Default is None, meaning that all costs will be summed together.
demand_scale_factor (float) – Optional factor for scaling demand charges relative to energy charges when the optimization/simulation period is not a full billing cycle. Applied to monthly charges where end_date - start_date > 1 day. Default is 1
additional_objective_terms (pyomo.Expression, list) – Additional terms to be added to the objective function. Can be a single pyomo Expression or a list of pyomo Expressions. Only used in the case of Pyomo, so None by default.
decomposition_type ({“absolute_value”, “binary_big_M”, “linear”, None}) – Type of decomposition to use for consumption data. - “absolute_value”: Uses max(x, 0) constraints. Creates nonlinear problem
for Pyomo due to abs() constraint.
“binary_big_M”: Uses binary indicator with Big-M constraints. Creates a MILP (mixed-integer linear program) for Pyomo or CVXPY.
“linear”: Plain LP split into non-negative imports and exports for Pyomo or CVXPY. Exact only when export charge <= energy charge and energy/demand charges are non-negative (warns otherwise).
None (default): No decomposition, treats all consumption as imports
varstr_alias_func (function) – Function to generate variable name for pyomo, should take in a 6 inputs and generate a string output. The function will receive following six inputs:
utility: str
charge_type: str
name: str
start_date: str
end_date: str
charge_limit: str
- Examples of functions:
f_no_dates=lambda utility, charge_type, name, start_date, end_date, charge_limit: f”{utility}_{charge_type}_{name}_{charge_limit}”
- Raises:
ValueError – When invalid utility, charge_type, or assessed is provided in charge_arrays
- Returns:
The model object associated with the problem with costing components added.
- Return type:
pyomo.Model
- Warns:
UserWarning – When decomposition_type=”linear” and an export charge exceeds the energy charge, since the LP split may then import and export simultaneously
- eeco.costs.calculate_cost(charge_dict, consumption_data_dict, electric_consumption_units=Unit("kilowatt"), gas_consumption_units=Unit("meter ** 3 / hour"), resolution='15m', prev_demand_dict=None, prev_consumption_dict=None, consumption_estimate=0, desired_utility=None, desired_charge_type=None, demand_scale_factor=1, fixed_scale_factor=1, model=None, decomposition_type=None, big_m=1000000.0, varstr_alias_func=<function default_varstr_alias_func>)[source]
Calculates the cost of given charges (demand or energy) for the given billing rate structure, utility, and consumption information as a cvxpy expression or numpy array
- Parameters:
charge_dict (dict) – dictionary of arrays with keys of the form utility`_`charge_type`_`name`_`start_date`_`end_date`_`charge_limit and values being the $ per kW (electric demand), kWh (electric energy/export), cubic meter / hour (gas demand), cubic meter (gas energy), or $ / month (customer)
consumption_data_dict (dict) – Baseline electrical and gas usage data as an optimization variable object with keys “electric” and “gas”. Supports two formats:
- Default format:
Values are cumulative consumption data Example: {“electric”: np.array([]), “gas”: np.array([])}
- Extended format for imports/exports:
Values are dictionaries with decomposed “imports” and “exports” keys Example: {“electric”: {“imports”: np.array([]), “exports”: np.array([])}}
Values must be of type numpy.ndarray, cvxpy.Expression, or pyomo.environ.Var.
electric_consumption_units (pint.Unit) – Units for the electricity consumption data. Default is kW
gas_consumption_units (pint.Unit) – Units for the natural gas consumption data. Default is cubic meters / hour
resolution (str) – String of the form [int][str] giving the temporal resolution on which charges are assessed, the str portion corresponds to numpy.timedelta64 types for example ‘15m’ specifying demand charges that are applied to 15-minute intervals of electricity consumption
prev_demand_dict (dict) – Nested dictionary previous maximmum demand charges with an entry of the form {“cost” : float, “demand” : float} for each charge. Default is None, which results in an a prev_demand and prev_demand_cost of zero for all charges.
prev_consumption_dict (dict) – Dictionary of previous total energy consumption with a key for each charge to be used when starting the cost calculation partway into a billing period (e.g., while using a moving horizon that is shorter than a month). Default is None, resulting in an a prev_consumption of zero for all charges.
consumption_estimate (float, array, dict) – Estimate of the total monthly demand or energy consumption from baseline data. Only used when consumption_data is cvxpy.Expression or pyomo.environ.Var for convex relaxation of tiered charges, while numpy.ndarray consumption_data will use actual consumption and ignore the estimate. If consumption estimate is a float, int, it is assumed to carry units of kWh, therms OR m3. If consumption estimate is array-like it is assumed to carry units of kW, therms/hr OR m3/hr. If consumption estimate is a dict, it should have keys matching the charge dict.
desired_charge_type (list or str) – Name of desired charge type for itemized costs. Either ‘customer’, ‘energy’, ‘demand’, ‘export’, or a list of charge types. Default is None, meaning that all costs will be summed together.
desired_utility (list or str) – Name of desired utility for itemized costs. Either ‘electric’, ‘gas’, or a list of utilities (e.g., [‘electric’, ‘gas’]). Default is None, meaning that all costs will be summed together.
demand_scale_factor (float) – Optional factor for scaling demand charges relative to energy charges when the optimization/simulation period is not a full billing cycle. Applied to monthly charges where end_date - start_date > 1 day. Default is 1
fixed_scale_factor (float) – Optional factor for scaling fixed (customer) charges relative to energy charges when the optimization/simulation period is not a full billing cycle. Applied to the whole customer charge, which is otherwise billed in full regardless of horizon length. Default is 1
model (pyomo.Model) – The model object associated with the problem. Only used in the case of Pyomo, so None by default.
decomposition_type ({“absolute_value”, “binary_big_M”, “linear”, None}) – Type of decomposition to use for consumption data. - “absolute_value”: Uses max(x, 0) constraints. Creates nonlinear problem
for Pyomo due to abs() constraint.
“binary_big_M”: Uses binary indicator with Big-M constraints. Creates a MILP (mixed-integer linear program) for Pyomo or CVXPY.
“linear”: Plain LP split into non-negative imports and exports for Pyomo or CVXPY. Exact only when export charge <= energy charge and energy/demand charges are non-negative (warns otherwise).
None (default): No decomposition, treats all consumption as imports
varstr_alias_func (function) – Function to generate variable name for pyomo, should take in a 6 inputs and generate a string output. The function will receive following six inputs:
utility: str
charge_type: str
name: str
start_date: str
end_date: str
charge_limit: str
- Examples of functions:
f_no_dates=lambda utility, charge_type, name, start_date, end_date, charge_limit: f”{utility}_{charge_type}_{name}_{charge_limit}”
- Raises:
ValueError – When invalid utility, charge_type, or assessed is provided in charge_arrays
ValueError – If numeric imports and exports in consumption_data_dict are both positive in the same timestep
- Returns:
First entry: float, cvxpy Expression, or pyomo Var representing energy charge costs in USD for the given charge_array and consumption_data
Second entry: pyomo ConcreteModel (pyomo path), list of cvxpy constraints from decomposition (cvxpy + decomposition_type path), or None otherwise
- Return type:
- Warns:
UserWarning – When decomposition_type=”linear” and an export charge exceeds the energy charge, since the LP split may then import and export simultaneously
- eeco.costs.calculate_demand_cost(charge_array, consumption_data, limit=0, next_limit=inf, prev_demand=0, prev_demand_cost=0, consumption_estimate=0, scale_factor=1, model=None, varstr='')[source]
Calculates the cost of given demand charges for the given billing rate structure, utility, and consumption information
- Parameters:
charge_array (array) – Array of charge cost (in $/kW)
consumption_data (numpy.ndarray, cvxpy.Expression, or pyomo.environ.Var) – Baseline electrical or gas usage data as an optimization variable object
limit (float) – The total consumption, or limit, that this charge came into effect. Default is 0
next_limit (float) – The total consumption, or limit, that the next charge comes into effect. Default is float(‘inf’) indicating that there is no higher tier
prev_demand (float) – The previous maximum demand for this charge during the same billing period. Only used for optimizing on a horizon shorter than the billing period, so the default is 0
prev_demand_cost (float) – The previous cost for this demand charge during the same billing period. Only used for optimizing on a horizon shorter than the billing period, so the default is 0
consumption_estimate (float, array) – Estimate of the total consumption from baseline data in kW, therms/hr OR m3/hr. Only used when consumption_data is cvxpy.Expression or pyomo.environ.Var for convex relaxation of tiered charges, while numpy.ndarray consumption_data will use actual consumption and ignore the estimate.
scale_factor (float) – Optional factor for scaling demand charges relative to energy charges when the optimization/simulation period is not a full billing cycle. Applied to monthly charges where end_date - start_date > 1 day. Default is 1.
model (pyomo.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
- Returns:
tuple with the first entry being a float, cvxpy Expression, or pyomo Var representing demand charge costs in USD for the given charge_array and consumption_data and the second entry being the pyomo model object (or None)
- Return type:
(cvxpy.Expression, pyomo.environ.Var, or float), pyomo.Model
- eeco.costs.calculate_energy_cost(charge_array, consumption_data, n_per_hour, limit=0, next_limit=inf, prev_consumption=0, consumption_estimate=0, model=None, varstr='')[source]
Calculates the cost of given energy charges for the given billing rate structure, utility, and consumption information.
- Parameters:
charge_array (numpy.ndarray) – Array of the charges in $/kWh for electric and $/cubic meter for gas
consumption_data (numpy.ndarray cvxpy.Expression, or pyomo.environ.Var) – Baseline electrical or gas usage data as an optimization variable object
n_per_hour (int) – Divisor for the indexed consumption data elements, based on the timeseries resolution
limit (float) – The total consumption, or limit, that this charge came into effect. Default is 0
next_limit (float) – The total consumption, or limit, that the next charge comes into effect. Default is float(‘inf’) indicating that there is no higher tier
prev_consumption (float) – Consumption from within this billing period but outside the horizon window (e.g., previously in the month). Necessary for moving-horizon optimization. Default is 0
consumption_estimate (float, array) – Estimate of the total monthly energy consumption from baseline data in kWh, therms OR cubic meters. Only used when consumption_data is cvxpy.Expression or pyomo.environ.Var for convex relaxation of tiered charges, while numpy.ndarray consumption_data will use actual consumption and ignore the estimate.
model (pyomo.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:
ValueError – When invalid utility, charge_type, or assessed is provided in charge_arrays
- Returns:
tuple with the first entry being a float, cvxpy Expression, or pyomo Var representing energy charge costs in USD for the given charge_array and consumption_data and the second entry being the pyomo model object (or None)
- Return type:
(cvxpy.Expression, pyomo.environ.Var, or float), pyomo.Model
- eeco.costs.calculate_export_revenue(charge_array, consumption_data, n_per_hour, model=None, varstr='')[source]
Calculates the export revenues for the given billing rate structure, utility, and consumption information.
Only flat rates for exports are supported (in $ / kWh). Returns positive revenue values that should be subtracted from total cost.
- Parameters:
charge_array (numpy.ndarray) – array with price per kWh sold back to the grid
consumption_data (numpy.ndarray, cvxpy.Expression, or pyomo.environ.Var) – Magnitude of exported electrical or gas usage data as an optimization variable object. Should be positive values.
n_per_hour (int) – Divisor for the indexed consumption data elements, based on the timeseries resolution
model (pyomo.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:
ValueError – When invalid utility, charge_type, or assessed is provided in charge_arrays
- Returns:
tuple with the first entry being a float, cvxpy Expression, or pyomo Var representing export revenues in USD for the given charge_array and export_data and the second entry being the pyomo model object (or None)
- Return type:
(cvxpy.Expression, pyomo.environ.Var, or float), pyomo.Model
- eeco.costs.calculate_itemized_cost(charge_dict, consumption_data_dict, electric_consumption_units=Unit("kilowatt"), gas_consumption_units=Unit("meter ** 3 / hour"), resolution='15m', prev_demand_dict=None, prev_consumption_dict=None, consumption_estimate=0, desired_utility=None, demand_scale_factor=1, fixed_scale_factor=1, model=None, decomposition_type='linear', big_m=1000000.0, by_charge_key=False, varstr_alias_func=<function default_varstr_alias_func>)[source]
Calculates itemized costs as a nested dictionary
- Parameters:
charge_dict (dict) – dictionary of arrays with keys of the form utility`_`charge_type`_`name`_`start_date`_`end_date`_`charge_limit and values being the $ per kW (electric demand), kWh (electric energy/export), cubic meter / hour (gas demand), cubic meter (gas energy), or $ / month (customer)
consumption_data_dict (dict) – Baseline electrical and gas usage data as an optimization variable object with keys “electric” and “gas”. Values of the dictionary must be of type numpy.ndarray, cvxpy.Expression, or pyomo.environ.Var Positive values represent energy imports (consumption from the grid) Negative values represent energy exports (generation sent to the grid)
electric_consumption_units (pint.Unit) – Units for the electricity consumption data. Default is kW
gas_consumption_units (pint.Unit) – Units for the natural gas consumption data. Default is cubic meters / hour
resolution (str) – String of the form [int][str] giving the temporal resolution on which charges are assessed, the str portion corresponds to numpy.timedelta64 types for example ‘15m’ specifying demand charges that are applied to 15-minute intervals of electricity consumption
prev_demand_dict (dict) – Nested dictionary previous maximmum demand charges with an entry of the form {“cost” : float, “demand” : float} for each charge. Default is None, which results in an a prev_demand and prev_demand_cost of zero for all charges.
prev_consumption_dict (dict) – Dictionary of previous total energy consumption with a key for each charge to be used when starting the cost calculation partway into a billing period (e.g., while using a moving horizon that is shorter than a month). Default is None, resulting in an a prev_consumption of zero for all charges.
consumption_estimate (float) – Estimate of the total monthly demand or energy consumption from baseline data. Only used when consumption_data is cvxpy.Expression for convex relaxation of tiered charges, while numpy.ndarray consumption_data will use actual consumption and ignore the estimate.
demand_scale_factor (float) – Optional factor for scaling demand charges relative to energy charges when the optimization/simulation period is not a full billing cycle. Applied to monthly charges where end_date - start_date > 1 day. Default is 1
fixed_scale_factor (float) – Optional factor for scaling fixed (customer) charges relative to energy charges when the optimization/simulation period is not a full billing cycle. Applied to the whole customer charge, which is otherwise billed in full regardless of horizon length. Default is 1
model (pyomo.Model) – The model object associated with the problem. Only used in the case of Pyomo, so None by default.
decomposition_type ({“absolute_value”, “binary_big_M”, “linear”, None}) – Type of decomposition to use for consumption data. - “absolute_value”: Linear problem using absolute value - “binary_big_M”: Uses binary indicator with Big-M constraints.
Creates a MILP (mixed-integer linear program) for Pyomo or CVXPY.
“linear”: Plain LP split into non-negative imports and exports for Pyomo or CVXPY. Exact only when export charge <= energy charge and energy/demand charges are non-negative (warns otherwise).
None (default): No decomposition, treats all consumption as imports
by_charge_key (bool) – Whether to further itemize the results by charge key. Default is False.
- Returns:
dict –
{
“electric”: {
“customer”: float or dict (key -> cost) if by_charge_key
”energy”: float or dict (key -> cost) if by_charge_key
”demand”: float or dict (key -> cost) if by_charge_key
”export”: float or dict (key -> cost) if by_charge_key
”total”: float or dict (key -> cost) if by_charge_key
}
”gas”: {
“customer”: float or dict (key -> cost) if by_charge_key
”energy”: float or dict (key -> cost) if by_charge_key
”demand”: float or dict (key -> cost) if by_charge_key
”export”: float or dict (key -> cost) if by_charge_key
”total”: float or dict (key -> cost) if by_charge_key
}
”total”: float or dict (key -> cost) if by_charge_key
}
model_objects (pyomo ConcreteModel, list of cvxpy constraints, or None) – Same as the second return value of calculate_cost.
- Warns:
UserWarning – When decomposition_type=”linear” and an export charge exceeds the energy charge, since the LP split may then import and export simultaneously
- eeco.costs.check_import_export_dict(consumption_data_dict)[source]
Raise if user-provided imports and exports are both nonzero in a timestep.
Only utilities already given as
{"imports": ..., "exports": ...}with numeric array values are checked; symbolic (cvxpy/pyomo) values are skipped.- Parameters:
consumption_data_dict (dict) – Consumption data as passed to calculate_cost
- Raises:
ValueError – If any timestep has both imports and exports greater than zero
- eeco.costs.check_linear_decomposition_dict(charge_dict)[source]
Warn if charges break the conditions under which a linear split is exact.
With decomposition_type=”linear”, importing and exporting in the same timestep is only suboptimal when export charge <= energy charge and energy and demand charges are non-negative. Only numpy charge arrays are checked.
- Parameters:
charge_dict (dict) – Charge dictionary as passed to calculate_cost
- eeco.costs.create_charge_array(charge, datetime, effective_start_date, effective_end_date, utility='electric')[source]
Creates a single charge array based on the given parameters.
- Parameters:
charge (pandas.DataFrame) – data for the charge including columns month_start, month_end, weekday_start, weekday_end, hour_start, hour_end, and charge
datetime (pandas.DataFrame, pandas.Series, or numpy.ndarray) – If a pandas Series, it must be of type datetime. If a DataFrame it must have a column “DateTime” and row for each timestep
effective_start_date (datetime.datetime) – date on which this charge becomes effective
effective_end_date (datetime.datetime) – date at which this charge is no longer in effect (i.e., this day is excluded)
- Raises:
TypeError – When datetime is not pandas.DataFrame, pandas.Series, or numpy.ndarray
- Returns:
timeseries of the cost of the charge with irrelevant timesteps zeroed out
- Return type:
panda.Series
- eeco.costs.default_varstr_alias_func(utility, charge_type, name, start_date, end_date, charge_limit)[source]
Default function for creating the variable name strings for each charge in the tariff sheet. Can be overwritten in the function call to calculate_cost to customize variable names.
- Parameters:
utility (str) – Name of the utility (‘electric’ or ‘gas’)
charge_type (str) – Name of the charge_type (‘demand’, ‘energy’, or ‘customer’)
name (str) – The name of the period for this charge (e.g., ‘all-day’ or ‘on-peak’)
start_date (str) – The inclusive start date for this charge
end_date (str) – The exclusive end date for this charge
charge_limit (str) – The consumption limit for this tier of charges converted to a string
- Returns:
Variable name of the form utility`_`charge_type`_`name`_`start_date`_`end_date`_`charge_limit
- Return type:
- eeco.costs.detect_charge_periods(rate_data, charge_type, month, weekday, resolution_minutes=30)[source]
Categorize charges into charge periods (peak, half-peak, off-peak, super-off-peak) for a particular month, weekday and charge_type.
- Parameters:
rate_data (pandas.DataFrame) – Tariff data with required columns
charge_type (str) – Type of charge (ENERGY or DEMAND)
month (int) – Month (1-12)
weekday (int) – Weekday (0-6)
resolution_minutes (int) – Time resolution in minutes for checking full day coverage. Default 30
- Returns:
period_categories: dict with period classifications for each row index: - PEAK: highest charge periods - HALF_PEAK: periods adjacent to peak - OFF_PEAK: average charge periods - SUPER_OFF_PEAK: below average charge periods
base_charge: the most frequent charge value
has_overlapping: the most frequent charge value
- Return type:
tuple with
- eeco.costs.get_billing_period_scale_factor(start_dt, end_dt)[source]
Fraction of a monthly billing period covered by the analysis horizon.
The horizon’s overlap with each calendar month it touches is summed, so horizons spanning several months are handled correctly.
- Parameters:
start_dt (datetime-like (see
get_timesteps())) – first timestep to be included in the cost analysisend_dt (datetime-like (see
get_timesteps())) – end of the cost analysis, exclusive: the horizon runs up to but does not include end_dt
- Returns:
the horizon’s length as a fraction of a monthly billing period
- Return type:
- eeco.costs.get_charge_array_duration(key)[source]
Parse a charge array key to determine the duration of the charge period in days.
- Parameters:
key (str) – Charge key of form utility_charge_type_name_start_date_end_date_charge_limit where start_date and end_date are in YYYYMMDD or YYYY-MM-DD format
- Returns:
Duration of the charge period in days
- Return type:
- Raises:
ValueError – If the key format is invalid or dates cannot be parsed
- eeco.costs.get_charge_array_length(charge_array)[source]
Number of timesteps in a charge array for np and cvxpy objects.
- Parameters:
charge_array (numpy.ndarray or cvxpy.Expression) – array of charges per timestep
- Returns:
number of timesteps in charge_array
- Return type:
- eeco.costs.get_charge_df(start_dt, end_dt, rate_data, resolution='15m', keep_fixed_charges=True, scale_fixed_charges=True, scale_demand_charges=False)[source]
Creates a dictionary where the values are charge arrays and keys are of the form {utility}_{type}_{name}_{start_date}_{end_date}_{limit}
- Parameters:
start_dt (datetime-like (see
get_timesteps())) – first timestep to be included in the cost analysisend_dt (datetime-like (see
get_timesteps())) – end of the cost analysis, exclusive: the horizon runs up to but does not include end_dtrate_data (pandas.DataFrame) – tariff data with required columns utility, type, basic_charge_limit, name, month_start, month_end, weekday_start, weekday_end, hour_start, hour_end, and charge and optional columns assessed (default “monthly”), effective_start_date, and effective_end_date
resolution (str) – granularity of each timestep in string form with default value of “15m”
keep_fixed_charges (bool) – Whether to discard fixed (i.e., customer) charges or keep them. Default is True, which returns fixed (and all other) charges.
scale_fixed_charges (bool) – If True, fixed charges will be divided amongst all time steps and scaled by the horizon’s fraction of a billing period. If False, they will not be scaled but included in the first timestep only. Default is True.
scale_demand_charges (bool)
- Returns:
DataFrame of charge arrays
- Return type:
- eeco.costs.get_charge_dict(start_dt, end_dt, rate_data, resolution='15m')[source]
Creates a dictionary where the values are charge arrays and keys are of the form {utility}_{type}_{name}_{start_date}_{end_date}_{limit}
- Parameters:
start_dt (datetime-like (see
get_timesteps())) – first timestep to be included in the cost analysisend_dt (datetime-like (see
get_timesteps())) – end of the cost analysis, exclusive: the horizon runs up to but does not include end_dtrate_data (pandas.DataFrame) – tariff data with required columns utility, type, basic_charge_limit, name, month_start, month_end, weekday_start, weekday_end, hour_start, hour_end, and charge and optional columns assessed (default “monthly”), effective_start_date, and effective_end_date
resolution (str) – granularity of each timestep in string form with default value of “15m”
- Returns:
dictionary of charge arrays
- Return type:
- eeco.costs.get_charge_name(charge, index=None)[source]
Get a unique row name for each row of charge df.
- Parameters:
charge (dict or pandas.Series) – The charge row data containing NAME and PERIOD fields
index (int, optional) – Index to use if name is empty or None
- Returns:
A unique name with underscores converted to dashes
- Return type:
- eeco.costs.get_charge_records(model)[source]
Handles on the Pyomo components built for each charge.
Keyed the same way as prev_demand_dict by the original charge_dict key, so a caller never has to rebuild a variable name that varstr_alias_func may have changed.
- Parameters:
model (pyomo.environ.Model) – A model that calculate_cost has already built costs on
- Raises:
ValueError – When no charges have been recorded on model
- Returns:
Keyed by charge_dict key. Each entry holds the varstr and charge_type strings alongside the limit, max, and max_pos components named in CHARGE_COMPONENT_SUFFIXES, which are None for charges that built none
- Return type:
- eeco.costs.get_charge_window(charge_array, model=None)[source]
Timesteps at which a charge is actually assessed and nonzero.
- Parameters:
charge_array (numpy.ndarray) – Array of charges in $/kWh, $/kW, $/therm, or $/m3
model (pyomo.environ.Model) – The model object associated with the problem. Default is None, in which case positions into charge_array are returned rather than index values.
- Returns:
Positions into charge_array where the charge is nonzero, or the corresponding model._var_index values when a Pyomo model is given
- Return type:
- eeco.costs.get_conversion_factors(electric_consumption_units, gas_consumption_units)[source]
Calculate conversion factors for electric and gas utilities.
- Parameters:
electric_consumption_units (pint.Unit) – Units for the electricity consumption data
gas_consumption_units (pint.Unit) – Units for the gas consumption data
- Returns:
Dictionary with conversion factors for each utility type
- Return type:
- eeco.costs.get_converted_consumption_data(consumption_data_dict, conversion_factors, decomposition_type, model=None, big_m=1000000.0)[source]
Ensure consumption_data_dict has imports/exports structure with proper unit conversion.
- Parameters:
consumption_data_dict (dict) – Dictionary with utility keys and consumption data values
conversion_factors (dict) – Dictionary with conversion factors for each utility type
decomposition_type ({“absolute_value”, “binary_big_M”, “linear”, None}) – Type of decomposition to apply
model (pyomo.Model, optional) – Pyomo model object for optimization variables
- Returns:
consumption_data_dict with imports/exports structure
pyomo ConcreteModel, list of cvxpy constraints, or None
- Return type:
- eeco.costs.get_next_limit(key_substr, current_limit, keys)[source]
Finds the next charge limit for the charge represented by key
- Parameters:
key_substr (str) – The beginnging of the key for which we want to get the next limit (i.e., {utility}_{type}_{name}_{start_date}_{end_date})
current_limit (int) – The limit for the current tier
keys (list of str) – List of all the keys in the charge dictionary
- Returns:
limit in the tier after key, which is inf if there is no higher tier
- Return type:
- eeco.costs.get_prev_demand_dict(charge_dict, usage_data, start_dt, billing_period_starts, prev_dict=None)[source]
Compute a new or updated previous max demand charge dict for use in costing.
For each charge in charge_dict, resets the tracked maximum to zero at the start of the relevant timeframe. Then accumulates the running maximum.
- Parameters:
charge_dict (dict) – Maps charge key strings to charge arrays (numpy arrays or cp.Expression).
usage_data (numpy.ndarray) – Array of consumption values for the current timestep window.
start_dt (datetime-like (see
get_timesteps())) – Start datetime of the current optimization window.billing_period_starts (list) – List of datetimes marking the start of each billing period.
prev_dict (dict, optional) – Existing previous-max dict to update. Defaults to empty dict.
- Returns:
Mapping of charge key to {“demand”: running peak demand, “cost”: running max of usage * charge}
- Return type:
- eeco.costs.get_timesteps(start_dt, end_dt, resolution='15m')[source]
Number of timesteps in the horizon and the corresponding datetime column.
- Parameters:
start_dt (datetime-like) – first timestep to be included in the cost analysis. Accepts datetime.datetime, numpy.datetime64, and ISO-8601 strings
end_dt (datetime-like) – end timestep of the cost analysis, exclusive. The last timestep returned is one resolution before end_dt. Accepts datetime.datetime, numpy.datetime64, and ISO-8601 strings
resolution (str) – granularity of each timestep in string form with default value of “15m”
- Returns:
the number of timesteps and a single-column DataFrame of their datetimes
- Return type:
tuple of (int, pandas.DataFrame)
- Warns:
UserWarning – when the horizon is not a whole multiple of resolution, since the trailing partial timestep is dropped from the returned timeseries but still counted when prorating fixed charges
- eeco.costs.parametrize_charge_dict(start_dt, end_dt, rate_data, variants=None)[source]
Takes in an existing charge_dict and varies it parametrically to create alternative rate structures. Calls parametrize_rate_data to parametrize the billing csv file, then calls it on the dates specified.
- Parameters:
start_dt (datetime-like (see
get_timesteps())) – first timestep to be included in the cost analysisend_dt (datetime-like (see
get_timesteps())) – end of the cost analysis, exclusive: the horizon runs up to but does not include end_dtrate_data (pandas.DataFrame) – tariff data with required columns
variants (list[dict]) – List of dictionaries containing variation parameters with keys: - percent_change_dict: dict for charge scaling (see parametrize_rate_data) - shift_peak_hours_before: float to shift peak start, in hours - shift_peak_hours_after (float) : shift peak end, in hours - variant_name (str, optional) : variant name
- Returns:
dictionary of charge_dicts with different variations
- Return type:
- Raises:
UserWarning – If global scaling overrides individual ratios in any variant (inherited from parametrize_rate_data)
- eeco.costs.parametrize_rate_data(rate_data, percent_change_dict={}, shift_peak_hours_before=0, shift_peak_hours_after=0, variant_name=None)[source]
Parametrize rate data by charge periods (peak, half-peak, off-peak, super-off-peak) or exact charge keys. Applies scaling and window shifting to create alternative rate structures.
- Parameters:
rate_data (pandas.DataFrame) – Tariff data with required columns
percent_change_dict (dict, optional) – Dictionary for charge scaling. Can be one of three formats:
Format 1 - Nested dictionary with structure for charge scaling:
{
‘demand’: {
‘peak’: float, ‘half_peak’: float, ‘off_peak’: float, ‘super_off_peak’: float
},
‘energy’: {
‘peak’: float, ‘half_peak’: float, ‘off_peak’: float, ‘super_off_peak’: float
}
}
Format 2 - Dictionary with exact charge key prefixes based on csv:
{
‘electric_demand_peak-summer’: float, ‘electric_energy_0’: float, ‘electric_demand_all-day’: float, …
}
Format 3 - Global scaling for all charges of each type:
{
‘demand’: float, # scales all demand charges ‘energy’: float, # scales all energy charges
}
If None, all ratios default to 1.0
shift_peak_hours_before (float, optional) – Hours to shift peak window start (negative=earlier, positive=later). Must be multiple of 0.25 hours. Default 0
shift_peak_hours_after (float, optional) – Hours to shift peak window end (negative=earlier, positive=later). Must be multiple of 0.25 hours. Default 0
variant_name (str, optional) – Name for this variant. Default None
- Returns:
Updated rate_data dataframe with parametrized charges and windows
- Return type:
- Raises:
ValueError – If percent_change_dict contains both period-based scaling and individual charge scaling for the same charge type
UserWarning – If percent_change_dict contains exact charge keys that are not found in the data
- eeco.costs.parse_charge_key(key)[source]
Splits a charge key into its fields, inverting default_varstr_alias_func.
- Parameters:
key (str) – Charge key of the form utility`_`charge_type`_`name`_`start_date`_`end_date`_`charge_limit
- Raises:
ValueError – When key has fewer than six underscore-separated fields
- Returns:
utility, charge_type, name, start_date, end_date, charge_limit
- Return type:
eeco.demandresponse module
Calculate incentive-based demand response revenue.
See demandresponse for a description of the module.
- class eeco.demandresponse.BaselineMethod(resolution=None)[source]
Bases:
ABCAbstract base for demand response baseline methods.
Subclasses implement calculate_event_baseline. Use replace to derive a variant with some settings changed.
- Parameters:
resolution (str or None) – Settlement interval width (e.g., “15m”, “1h”). None infers it from the data or model index.
- abstract calculate_event_baseline(historical_power_kW, event, *, model=None, model_power_kW=None, model_datetime_index=None, varstr=None, adjustment_factor=None)[source]
Calculate the per-interval baseline power for a single event.
- Parameters:
historical_power_kW (pandas.Series) – Historical power consumption in kW, indexed by timestamp.
event (dict) – Single event dict. See add_event for the keys.
model (pyomo.environ.Model or pyomo.environ.Block or None) – Model to add baseline components to. None for ex-post use.
model_power_kW (pyomo.environ.Var or None) – Power decision variable over the optimization horizon.
model_datetime_index (pandas.DatetimeIndex or None) – Timestamp of each entry of model_power_kW.
varstr (str or None) – Name prefix for components created on model.
adjustment_factor (float or None) – Day-of adjustment factor to apply as-is, for methods that use one.
- Returns:
(baseline_kW, model).
- Return type:
- replace(**changes)[source]
Return a new instance with some settings changed.
- Parameters:
**changes – Constructor arguments to override. Unspecified settings keep this instance’s values.
- Returns:
New instance of the same class; self is unchanged.
- Return type:
- Raises:
TypeError – If a key is not a constructor argument.
ValueError – If the resulting settings fail constructor validation.
- class eeco.demandresponse.CapacityEnergyPayment(regions, energy_price, **payment_kwargs)[source]
Bases:
PaymentStructurePiecewise-linear capacity payment plus a flat payment per kWh curtailed.
- Parameters:
regions (list of dict or None) – Capacity payment schedule, as for PaymentStructure.
energy_price (float) – Energy payment rate in $/kWh.
**payment_kwargs – Keyword arguments passed to PaymentStructure.
- build_expression(event, reduction_kW, region_x1=None, model=None, varstr='')[source]
Build the capacity and energy revenue expression for an event.
- Parameters:
event (dict) – Single event dict. See add_event for the keys.
reduction_kW (float, numpy.ndarray, cvxpy.Expression, or pyomo.environ.Var) – Load reduction in kW, as a realized value or a decision-variable expression, per interval or as a window mean. A list or tuple of pyomo expressions is also accepted.
region_x1 (float, list of float, or None) – x1 bound of the region to fix. Required for cvxpy.
model (pyomo.environ.Model or pyomo.environ.Block or None) – Model to add components to. Required for pyomo.
varstr (str) – Name prefix for pyomo components created on model.
- Raises:
ValueError – In the cases listed for PaymentStructure.build_expression, or if event has no “duration_hours”.
TypeError – If reduction_kW is not a supported type.
- Returns:
(revenue, model) for numpy or scalar reduction_kW, (total_revenue_var, model) for pyomo, or (revenue_expr, constraints) for cvxpy.
- Return type:
- evaluate(event, reduction_kW)[source]
Calculate realized capacity and energy revenue for a known reduction.
- Parameters:
event (dict) – Single event dict. See add_event for the keys.
reduction_kW (float or numpy.ndarray) – Load reduction in kW, as a window mean or per interval.
- Raises:
ValueError – In the cases listed for PaymentStructure.evaluate, or if event has no “duration_hours”.
- Returns:
Revenue (positive) or penalty (negative) in USD.
- Return type:
- class eeco.demandresponse.FixedLevelBaseline(firm_level_kW, resolution=None)[source]
Bases:
BaselineMethodBaseline fixed at a contracted firm service level.
- Parameters:
firm_level_kW (float) – Contracted firm demand level in kW.
resolution (str or None) – Settlement interval width (e.g., “15m”, “1h”). None infers it from the data or model index.
- Raises:
ValueError – If firm_level_kW is negative.
- calculate_event_baseline(historical_power_kW, event, *, model=None, model_power_kW=None, model_datetime_index=None, varstr=None, adjustment_factor=None)[source]
Return the firm service level as a flat per-interval baseline.
- Parameters:
historical_power_kW (pandas.Series) – Historical power consumption in kW. Only its index is used, to infer the interval width.
event (dict) – Single event dict. See add_event for the keys.
model (pyomo.environ.Model or pyomo.environ.Block or None) – Returned unchanged. No components are added.
model_power_kW (pyomo.environ.Var or None) – Unused.
model_datetime_index (pandas.DatetimeIndex or None) – Used only to infer the interval width.
varstr (str or None) – Unused.
adjustment_factor (float or None) – Unused.
- Returns:
(baseline_kW, model), where baseline_kW is firm_level_kW repeated once per interval.
- Return type:
- class eeco.demandresponse.MarketIndexedPayment(regions, price_lookup, **payment_kwargs)[source]
Bases:
PaymentStructurePiecewise-linear capacity payment priced from a market index.
- Parameters:
regions (list of dict or None) – Payment schedule, as for PaymentStructure.
price_lookup (callable) – Function price_lookup(event) -> float returning the capacity price in $/kW for an event.
**payment_kwargs – Keyword arguments passed to PaymentStructure.
- build_expression(event, reduction_kW, region_x1=None, model=None, varstr='')[source]
Build the revenue expression for an event at the market price.
- Parameters:
event (dict) – Single event dict. See add_event for the keys.
reduction_kW (float, numpy.ndarray, cvxpy.Expression, or pyomo.environ.Var) – Load reduction in kW, as a realized value or a decision-variable expression, per interval or as a window mean. A list or tuple of pyomo expressions is also accepted.
region_x1 (float, list of float, or None) – x1 bound of the region to fix. Required for cvxpy.
model (pyomo.environ.Model or pyomo.environ.Block or None) – Model to add components to. Required for pyomo.
varstr (str) – Name prefix for pyomo components created on model.
- Raises:
ValueError – In the cases listed for PaymentStructure.build_expression.
TypeError – If reduction_kW is not a supported type.
- Returns:
As for PaymentStructure.build_expression.
- Return type:
- evaluate(event, reduction_kW)[source]
Calculate realized revenue at the market price for a known reduction.
- Parameters:
event (dict) – Single event dict. See add_event for the keys.
reduction_kW (float or numpy.ndarray) – Load reduction in kW, as a window mean or per interval.
- Raises:
ValueError – In the cases listed for PaymentStructure.evaluate.
- Returns:
Revenue (positive) or penalty (negative) in USD.
- Return type:
- class eeco.demandresponse.PaymentStructure(regions, settlement='interval', payment_basis='per_event', payout=0.0, payout_basis='per_event')[source]
Bases:
objectPiecewise-linear capacity payment with an optional flat payout.
- Parameters:
regions (list of dict or None) – Payment schedule. Each dict has float values under the keys “x1”, “x2” (delivered ratio bounds) and “y1”, “y2” (payment ratios at those bounds). Bounds may be “Infinity”/”-Infinity” strings; a region with an infinite bound pays a flat ratio from its finite end. Regions whose lowest x1 is finite cannot cover a negative delivered ratio, and in optimization they force reduction >= x1 * bid. None or [] means no capacity payment.
settlement (str) – “interval” (default) or “average”.
payment_basis (str) – “per_event” (default), “per_hour”, or “monthly_share”. With “monthly_share”, the capacity price is $/kW-month and each event is paid its share bid_capacity_kW * duration_hours / monthly_called_capacity_kWh of the monthly payment.
payout (float) – Flat participation payment in $/kW of bid capacity.
payout_basis (str) – “per_event” (default), “per_hour”, or “monthly_share”.
- Raises:
ValueError – If settlement, payment_basis, or payout_basis is not a supported value.
- build_expression(event, reduction_kW, region_x1=None, model=None, varstr='')[source]
Build the revenue expression for an event.
- Parameters:
event (dict) – Single event dict. See add_event for the keys.
reduction_kW (float, numpy.ndarray, cvxpy.Expression, or pyomo.environ.Var) – Load reduction in kW, as a realized value or a decision-variable expression, per interval or as a window mean. A list or tuple of pyomo expressions is also accepted.
region_x1 (float, list of float, or None) – x1 bound of the region to fix. Required for cvxpy. Optional for pyomo, where None lets the solver choose.
model (pyomo.environ.Model or pyomo.environ.Block or None) – Model to add components to. Required for pyomo.
varstr (str) – Name prefix for pyomo components created on model.
- Raises:
ValueError – If reduction_kW is cvxpy and region_x1 matches no region, if reduction_kW is pyomo and model is None or a given region_x1 matches no region.
TypeError – If reduction_kW is not a supported type.
- Warns:
UserWarning – If model already holds revenue built from a different payment structure.
- Returns:
(revenue, model) for numpy or scalar reduction_kW, (revenue_var, model) for pyomo, or (revenue_expr, constraints) for cvxpy.
- Return type:
- evaluate(event, reduction_kW)[source]
Calculate realized revenue for a known reduction.
- Parameters:
event (dict) – Single event dict. See add_event for the keys.
reduction_kW (float or numpy.ndarray) – Load reduction in kW, as a window mean or per interval.
- Raises:
ValueError – If event[“bid_capacity_kW”] is not positive, if no region contains a resulting delivered ratio, or if a “per_hour” basis is used and event has no “duration_hours”.
- Returns:
Revenue (positive) or penalty (negative) in USD.
- Return type:
- find_region(delivered_ratio=None, region_x1=None)[source]
Look up a payment region by delivered ratio or by its x1 bound.
- Parameters:
delivered_ratio (float or None) – Delivered ratio contained in the region.
region_x1 (float or None) – x1 bound of the region.
- Raises:
ValueError – If neither argument is given, if both are given and delivered_ratio is outside the region identified by region_x1, if no region matches, or if there are no regions.
- Returns:
The matching region.
- Return type:
- class eeco.demandresponse.SimilarDaysBaseline(n_baseline_days=10, adjustment_offset_hours=4, adjustment_duration_hours=3, adjustment_clip=(0.8, 1.2), exclude_weekends=True, exclude_holidays=True, holiday_country='US', holiday_subdiv=None, holiday_dates=None, adjustment_in_model=False, resolution=None)[source]
Bases:
BaselineMethodAverage-of-similar-days baseline with an optional day-of adjustment.
- Parameters:
n_baseline_days (int) – Number of eligible baseline days to average. 0 disables baselining and yields an all-zero baseline.
adjustment_offset_hours (int or None) – Hours before the event start at which the day-of adjustment window begins. None disables the day-of adjustment.
adjustment_duration_hours (int) – Length of the day-of adjustment window in hours. Ignored when adjustment_offset_hours is None.
adjustment_clip (tuple of float) – (low, high) bounds on the day-of adjustment factor.
exclude_weekends (bool) – If True, drop Saturdays and Sundays from the candidate baseline days.
exclude_holidays (bool) – If True, drop holidays from the candidate baseline days.
holiday_country (str or None) – ISO 3166-1 country code passed to holidays.country_holidays. Defaults to “US”, as in PG&E’s CBP. None uses only holiday_dates.
holiday_subdiv (str or None) – Subdivision code (e.g., “CA”) passed to holidays.country_holidays.
holiday_dates (list or None) – Additional dates to treat as holidays.
adjustment_in_model (bool) – If True and a model is given to calculate_event_baseline, add the day-of adjustment factor to the model as a fixed pyomo.environ.Var.
resolution (str or None) – Settlement interval width (e.g., “15m”, “1h”). None infers it from the data or model index.
- Raises:
ValueError – If n_baseline_days is negative, or if adjustment_offset_hours is not None and adjustment_duration_hours is not positive or exceeds adjustment_offset_hours.
- calculate_event_baseline(historical_power_kW, event, *, model=None, model_power_kW=None, model_datetime_index=None, varstr=None, adjustment_factor=None)[source]
Calculate the per-interval baseline power for a single event.
- Parameters:
historical_power_kW (pandas.Series) – Historical power consumption in kW, indexed by timestamp.
event (dict) – Single event dict. See add_event for the keys.
model (pyomo.environ.Model or pyomo.environ.Block or None) – Model to add baseline components to. None for ex-post use.
model_power_kW (pyomo.environ.Var or None) – Power decision variable over the optimization horizon. Required when model is given.
model_datetime_index (pandas.DatetimeIndex or None) – Timestamp of each entry of model_power_kW. Required when model is given.
varstr (str or None) – Name of the baseline Var created on model. Required when model is given.
adjustment_factor (float or None) – Day-of adjustment factor to apply as-is. None uses event[“adjustment_factor”] if set, otherwise calculates it with _adjustment_factor.
- Raises:
ValueError – If model is given without model_power_kW, model_datetime_index, and varstr, if a selected baseline day has missing data, or if adjustment_factor is not positive or differs from event[“adjustment_factor”].
- Returns:
(baseline_kW, model), where baseline_kW is the per-interval baseline in kW as a numpy.ndarray or an indexed pyomo.environ.Var, and model is None ex-post.
- Return type:
- select_days(candidate_days, historical_power_kW, event)[source]
Select the baseline days to average for an event.
- Parameters:
candidate_days (list of pandas.Timestamp) – Days proposed for this event’s baseline.
historical_power_kW (pandas.Series) – Historical power consumption in kW, indexed by timestamp.
event (dict) – Single event dict. See add_event for the keys.
- Raises:
ValueError – If no eligible days remain after filtering.
- Warns:
UserWarning – If fewer eligible days remain than n_baseline_days.
- Returns:
At most n_baseline_days days, most preferred first.
- Return type:
- class eeco.demandresponse.TopUsageDaysBaseline(n_baseline_days=10, adjustment_offset_hours=4, adjustment_duration_hours=3, adjustment_clip=(0.8, 1.2), exclude_weekends=True, exclude_holidays=True, holiday_country='US', holiday_subdiv=None, holiday_dates=None, adjustment_in_model=False, resolution=None)[source]
Bases:
SimilarDaysBaselineBaseline that averages the highest-usage eligible days.
Takes the same parameters as SimilarDaysBaseline.
- class eeco.demandresponse.UnilateralInterruptionBaseline(interruption_level_kW=0.0, resolution=None)[source]
Bases:
BaselineMethodUtility-controlled interruption enforced as an upper bound on power.
- Parameters:
interruption_level_kW (float) – Power level in kW the load is held at or below during an event.
resolution (str or None) – Settlement interval width (e.g., “15m”, “1h”). None infers it from the model index.
- Raises:
ValueError – If interruption_level_kW is negative.
- calculate_event_baseline(historical_power_kW, event, *, model=None, model_power_kW=None, model_datetime_index=None, varstr=None, adjustment_factor=None)[source]
Constrain modeled power to the interruption level during an event.
- Parameters:
historical_power_kW (pandas.Series) – Unused.
event (dict) – Single event dict. See add_event for the keys.
model (pyomo.environ.Model or pyomo.environ.Block) – Model to add the interruption constraint to.
model_power_kW (pyomo.environ.Var) – Power decision variable over the optimization horizon.
model_datetime_index (pandas.DatetimeIndex) – Timestamp of each entry of model_power_kW.
varstr (str) – Name prefix for the constraint created on model.
adjustment_factor (float or None) – Unused.
- Raises:
NotImplementedError – If model is None.
ValueError – If model_power_kW, model_datetime_index, or varstr is missing, or if the event window matches no entries of model_datetime_index.
- Returns:
(baseline_kW, model), where baseline_kW is interruption_level_kW repeated once per interval.
- Return type:
- eeco.demandresponse.add_event(events, event_date, start_hour, duration_hours, notification_hours, baseline_days, bid_capacity_kW, capacity_price, adjustment_factor=None, monthly_called_capacity_kWh=None)[source]
Append a demand response event to an events list.
- Parameters:
events (list of dict or None) – Events list to append to. None starts a new list.
event_date (datetime.date, datetime.datetime, or str) – Calendar date of the event, in local time. A tz-aware value keeps its local wall-clock date and drops the time zone.
start_hour (float) – Hour of day (0-24) the event begins, in local wall-clock time.
duration_hours (float) – Length of the event in hours.
notification_hours (float) – Advance notice before the event in hours.
baseline_days (list) – Candidate baseline days for the event, in local time.
bid_capacity_kW (float) – Bid capacity in kW.
capacity_price (float) – Capacity price in $/kW.
adjustment_factor (float or None) – Day-of adjustment factor to apply as-is. None calculates it from historical data.
monthly_called_capacity_kWh (float or None) – Sum of called capacity in kWh over every event hour in the event’s month, used by the “monthly_share” basis. None sums it over the events passed to events_to_dataframe and the entry points.
- Raises:
ValueError – If duration_hours, bid_capacity_kW, or a given adjustment_factor or monthly_called_capacity_kWh is not positive, notification_hours is negative, or baseline_days is empty.
- Warns:
UserWarning – If capacity_price is zero.
- Returns:
New list with the event appended. Each event dict has the keys
”event_date” : pandas.Timestamp, tz-naive
”start_hour” : float
”duration_hours” : float
”notification_hours” : float
”baseline_days” : list
”bid_capacity_kW” : float
”capacity_price” : float
”adjustment_factor” : float or None
”monthly_called_capacity_kWh” : float or None
- Return type:
- eeco.demandresponse.build_event_revenue(power_kW, event, baseline_kW, payment_function, region_x1=None, model=None, varstr='')[source]
Calculate or build the demand response revenue for a single event.
- Parameters:
power_kW (numpy.ndarray, cvxpy.Expression, cvxpy.Variable, or pyomo.environ.Var) – Power consumption in kW during the event window only.
event (dict) – Single event dict with the keys
“event_date” : pandas.Timestamp
“start_hour” : float
“duration_hours” : float
“notification_hours” : float
“baseline_days” : list
“bid_capacity_kW” : float
“capacity_price” : float
“adjustment_factor” : float or None
“monthly_called_capacity_kWh” : float or None
as returned by add_event.
baseline_kW (float, numpy.ndarray, or pyomo.environ.Var) – Baseline power in kW, as a single value or one value per interval.
payment_function (PaymentStructure) – Payment structure used to price the delivered reduction.
region_x1 (float, list of float, or None) – x1 bound of the region to fix. Required for cvxpy. Optional for pyomo, where None lets the solver choose.
model (pyomo.environ.Model or pyomo.environ.Block or None) – Model to add components to. Required for pyomo.
varstr (str) – Name prefix for pyomo components created on model.
- Raises:
ValueError – If power_kW is cvxpy and region_x1 is None, or if the length of baseline_kW does not match power_kW.
TypeError – If power_kW is not a supported type.
- Returns:
(revenue, model) for numpy power_kW, (revenue_var, model) for pyomo, or (revenue_expr, constraints) for cvxpy.
- Return type:
- eeco.demandresponse.build_pyomo_dr_revenue(power_kW, datetime_index, events, historical_power_kW, baseline_method, model, payment_function, region_x1s=None, varstr_prefix='dr_event')[source]
Build demand response revenue on a pyomo model and net it into the model’s active objective.
Revenue is subtracted from a minimization objective and added to a maximization objective, whatever the objective is named. If the model has no active objective, a minimization objective of -total_revenue is added as model.objective (or a unique variant of that name if taken).
- Parameters:
power_kW (pyomo.environ.Var) – Power decision variable over the optimization horizon.
datetime_index (pandas.DatetimeIndex) – Timestamp of each entry of power_kW.
events (list of dict or pandas.DataFrame) – Events from add_event.
historical_power_kW (pandas.Series) – Historical power consumption in kW, indexed by timestamp.
baseline_method (BaselineMethod) – Baseline method, e.g. SimilarDaysBaseline().
model (pyomo.environ.Model or pyomo.environ.Block) – Model to add components to.
payment_function (PaymentStructure) – Payment structure used to price the delivered reduction.
region_x1s (dict or None) – x1 bound of the region to fix for each event, keyed by event date (e.g., {“2024-01-08”: 0.6}). Events not in the dict let the solver choose.
varstr_prefix (str) – Name prefix for pyomo components created on model.
- Raises:
ValueError – If an event window matches no entries of datetime_index, if model already has a component this call would create (e.g., from an earlier call with the same varstr_prefix), or if model has more than one active objective.
- Returns:
(total_revenue, model), where total_revenue is a pyomo expression.
- Return type:
- eeco.demandresponse.calculate_dr_revenue(power_kW, events, baseline_method, payment_function, historical_power_kW=None, datetime_index=None, model=None, region_x1s=None, varstr_prefix='dr_event')[source]
Calculate or build demand response revenue across all events.
- Parameters:
power_kW (pandas.Series, numpy.ndarray, or pyomo.environ.Var) – Power consumption in kW, as realized data or a decision variable.
events (list of dict or pandas.DataFrame) – Events from add_event.
baseline_method (BaselineMethod) – Baseline method, e.g. SimilarDaysBaseline().
payment_function (PaymentStructure) – Payment structure used to price the delivered reduction.
historical_power_kW (pandas.Series or None) – Historical power consumption in kW, indexed by timestamp. Required for pyomo.
datetime_index (pandas.DatetimeIndex or None) – Timestamp of each entry of power_kW. Required for pyomo and for a numpy.ndarray power_kW.
model (pyomo.environ.Model or pyomo.environ.Block or None) – Model to add components to. Required for pyomo.
region_x1s (dict or None) – x1 bound of the region to fix for each event, keyed by event date (e.g., {“2024-01-08”: 0.6}). Events not in the dict let the solver choose. Only used for pyomo.
varstr_prefix (str) – Name prefix for pyomo components created on model.
- Raises:
NotImplementedError – If power_kW is a cvxpy type.
ValueError – For pyomo, if datetime_index, historical_power_kW, or model is missing, or if an event window matches no entries of datetime_index.
TypeError – If power_kW is not a supported type.
- Returns:
(total_revenue, model), where total_revenue is a float in USD for realized data or a pyomo expression for a decision variable.
- Return type:
- eeco.demandresponse.calculate_event_revenue(historical_power_kW, event, baseline_method, payment_function)[source]
Calculate realized demand response revenue for a single event.
- Parameters:
historical_power_kW (pandas.Series) – Power consumption in kW, indexed by timestamp, covering the event and its baseline days.
event (dict) – Single event dict with the keys “event_date” (pandas.Timestamp), “start_hour” (float), “duration_hours” (float), “notification_hours” (float), “baseline_days” (list), “bid_capacity_kW” (float), “capacity_price” (float), “adjustment_factor” (float or None), and “monthly_called_capacity_kWh” (float or None), as returned by add_event.
baseline_method (BaselineMethod) – Baseline method, e.g. SimilarDaysBaseline().
payment_function (PaymentStructure) – Payment structure used to price the delivered reduction.
- Raises:
ValueError – If any settlement interval of the event window has no data in historical_power_kW.
- Returns:
Event results with the keys
”event_date” : pandas.Timestamp
”baseline_kW” : float, event-window mean
”actual_kW” : float, event-window mean
”reduction_kW” : float, event-window mean
”delivered_ratio” : float
”revenue” : float, in USD
”baseline_profile_kW” : numpy.ndarray, per interval
”actual_profile_kW” : numpy.ndarray, per interval
”reduction_profile_kW” : numpy.ndarray, per interval
”interval_datetime” : pandas.DatetimeIndex, in the time zone of historical_power_kW.index
- Return type:
- eeco.demandresponse.calculate_itemized_dr_revenue(power_kW, events, baseline_method, payment_function, datetime_index=None)[source]
Calculate realized demand response revenue for each event.
- Parameters:
power_kW (pandas.Series or numpy.ndarray) – Power consumption in kW.
events (list of dict or pandas.DataFrame) – Events from add_event.
baseline_method (BaselineMethod) – Baseline method, e.g. SimilarDaysBaseline().
payment_function (PaymentStructure) – Payment structure used to price the delivered reduction.
datetime_index (pandas.DatetimeIndex or None) – Timestamp of each entry of power_kW. Required when power_kW is a numpy.ndarray.
- Raises:
ValueError – If datetime_index is missing or mismatched for a numpy.ndarray power_kW, or if an event window has no data.
- Returns:
(per_event_df, total_revenue), where per_event_df has one row per event with the columns returned by calculate_event_revenue and total_revenue is in USD.
- Return type:
- eeco.demandresponse.events_to_dataframe(events)[source]
Convert an events list into a DataFrame sorted by event date.
- Parameters:
events (list of dict or pandas.DataFrame) – Events from add_event.
- Raises:
ValueError – If two events in the same month give different “monthly_called_capacity_kWh” values.
- Returns:
One row per event, sorted by tz-naive local “event_date”, with missing “monthly_called_capacity_kWh” values filled in by _fill_monthly_called_capacity.
- Return type:
eeco.emissions module
Functions to calculate emissions from electricity consumption data.
- eeco.emissions.calculate_grid_emissions(carbon_intensity, consumption_data, emissions_units=Unit('kilogram / megawatt_hour'), consumption_units=Unit('kilowatt'), resolution='15m', model=None, varstr='')[source]
Calculates the emissions for the given consumption information as a cvxpy object carbon intensity of electricity generation structure as a DataFrame.
- Parameters:
carbon_intensity (array) – numpy array with kg of CO2 per kWh
consumption_data (numpy.Array, cvxpy.Variable, or pyomo.environ.Var) – Baseline electrical or gas usage data as a Pyomo Var
emissions_units (pint.Unit) – Units for the emissions data. Default is kg / MWh
consumption_units (pint.Unit) – Units for the electricity consumption data. Default is kW
resolution (str) – granularity of each timestep in string form with default value of “15m”
model (pyomo.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
- Returns:
tuple of pyomo Var representing emissions in kg of CO2 for the given consumption_data and carbon_intensity and the accompanying model object. The model object is only used for Pyomo, so by default it is None
- Return type:
(pint.Quantity, cvxpy.Expression, or pyomo.environ.Var), pyomo.Model
- eeco.emissions.get_carbon_intensity(start_dt, end_dt, emissions_data, emissions_units=Unit('kilogram / megawatt_hour'), resolution='15m', ei_varname='co2_eq_kg_per_MWh')[source]
Computes the emissions (as kilograms of CO2) of a horizon of data
- Parameters:
start_dt (datetime.datetime or numpy.datetime64) – Start datetime to gather rate information.
end_dt (datetime.datetime or numpy.datetime64) – End datetime to gather rate information. This end_dt is excluded to be consistent with Python syntax.
emissions_data (DataFrame) – Electric grid emissions information. Only one of datetime_local and month/day/hour are required.
datetime_local
local datetime to estimate the marginal emissions
month
month for which the emissions data was averaged
day
day for which the emissions data was averaged
hour
hour for which the emissions data was averaged
co2_eq_kg_per_MWh
emissions in kg of CO2 per MWh of grid electricity
emissions_units (pint.Unit) – Units for the emissions data. Default is kg / MWh
resolution (str) – a string of the form [int][str] giving the temporal resolution on which charges are assessed. The str portion corresponds to numpy timedelta64 types. For example ‘15m’ specifying demand charges that are applied to 15-minute intervals of electricity consumption
ei_varname (str) – column name for the Scope 2 emissions factor. Default is EI_VARNAME=”co2_eq_kg_per_MWh”
- Returns:
emissions from start_dt to end_dt in kg CO2 / kWh
- Return type:
pint.Quantity
eeco.metrics module
Functions to estimate flexibility metrics from power consumption trajectories.
- eeco.metrics.energy_capacity(baseline_kW, flexible_kW, timestep=0.25, ec_type='discharging', relative=True)[source]
Calculate the energy capacity of a virtual battery system. This approach implicitly assumes the system has completed a round-trip.
- Parameters:
baseline_kW (array-like) – The baseline power consumption of the facility in kW.
flexible_kW (array-like) – The flexible power consumption of the facility in kW.
timestep (float) – The time step of the data in hours. Default is 0.25 hours (15 minutes).
ec_type (str) – The type of energy capacity to calculate. Options are ‘average’, ‘charging’, ‘discharging’
relative (bool) – If True, return the fractional energy capacity. If False, return the absolute energy capacity.
- Raises:
ValueError – If ec_type is not one of the expected values (‘average’, ‘charging’, ‘discharging’).
- Returns:
The energy capacity of the virtual battery system in either relative or absolute terms.
- Return type:
- eeco.metrics.net_present_value(capital_cost=0, electricity_savings=0, maintenance_diff=0, ancillary_service_benefit=0, service_curtailment=0, service_price=1.0, timestep=0.25, simulation_years=1, upgrade_lifetime=30, interest_rate=0.03)[source]
Calculate the net present value of flexibility of a virtual battery system.
- Parameters:
capital_cost (float) – The capital cost of the virtual battery system in $.
electricity_savings (float) – The electricity savings from the flexible operation in $.
maintenance_diff (float) – The difference in maintenance costs between the baseline and flexible operation in $.
ancillary_service_benefit (float) – The benefit from providing ancillary services in $.
service_curtailment (float) – The amount of service curtailment. If the virtual battery system produces a product, this may be in units of volume or mass (e.g., m^3 or kg).
service_price (float) – The marginal price of curtailed service $/amount. Amount here may refer to units of volume or mass (e.g., $/m^3 or $/kg).
timestep (float) – The time step of the data in hours. Default is 0.25 hours (15 minutes).
simulation_years (int) – The number of years in which the electricity savings or ancillary service benefits are calculated for. Default is 1 year.
upgrade_lifetime (int) – The number of years of operation left for the upgrade. Default is 30 years.
interest_rate (float) – The interest rate used to discount future cash flows. Default is 0.03.
- Raises:
Warning – If the capital cost is less than 0
ValueError – If the upgrade lifetime is less than or equal to 0
ValueError – If the interest rate is less than 0.
ValueError – if the timestep is less than or equal to 0.
- Returns:
The net present value benefit of the virtual battery system in $.
- Return type:
- eeco.metrics.power_capacity(baseline_kW, flexible_kW, timestep=0.25, pc_type='average', relative=True)[source]
Calculate the power capacity of a virtual battery system. This approach implicitly assumes the system has completed a round-trip.
- Parameters:
baseline_kW (array-like) – The baseline power consumption of the facility in kW.
flexible_kW (array-like) – The flexible power consumption of the facility in kW.
timestep (float) – The time step of the data in hours. Default is 0.25 hours (15 minutes).
pc_type (str) – The type of power capacity to calculate. Options are ‘average’, ‘charging’, ‘discharging’, ‘maximum’
relative (bool) – If True, return the fractional power capacity. If False, return the absolute power capacity.
- Raises:
ValueError – If pc_type is not one of the expected values (‘average’, ‘charging’, ‘discharging’, ‘maximum’).
- Returns:
The power capacity of the virtual battery system in either relative or absolute terms.
- Return type:
- eeco.metrics.roundtrip_efficiency(baseline_kW, flexible_kW)[source]
Calculate the round-trip efficiency of a flexibly operating power trajectory relative to a baseline.
- Parameters:
baseline_kW (list or np.ndarray) – power consumption data of the baseline system in units of kW
flexible_kW (list or np.ndarray) – power consumption data of the flexibly operating or cost-optimized system in units of kW.
- Raises:
TypeError – When baseline_kW and flexible_kW are not an acceptable type (e.g., list vs. np.ndarray).
ValueError – When baseline_kW and flexible_kW are not of the same length
Warnings – When baseline_kW and flexible_kW contain negative values, which may indicate an error in the data.
ValueError – When baseline_kW and flexible_kW contain missing values.
Warnings – When rte is calculated to be greater than 1. This may indicate an error in the assumptions behind the data.
- Returns:
The round-trip efficiency [0,1] of the flexible power trajectory relative to the baseline.
- Return type:
eeco.units module
eeco.utils module
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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]
Module contents
Main package for Electric Emissions & Cost Optimizer (EECO).