zen_garden.preprocess.unit_handling¶
File which contains the unit handling and scaling class.
Classes
|
This class scales the optimization model before solving it and rescales the solution. |
|
A class for managing and converting units in an energy system model. |
- class zen_garden.preprocess.unit_handling.Scaling(model, algorithm=None, include_rhs=True)¶
This class scales the optimization model before solving it and rescales the solution.
- __init__(model, algorithm=None, include_rhs=True)¶
Initializes scaling instance.
- Parameters:
model – optimization model
algorithm – list of scaling algorithms
include_rhs – bool whether to include the right hand side in the scaling
- adjust_int_variables()¶
Adjusts the column scaling factors corresponding to binary and integer variables. These columns are skipped in the scaling process since scaling is solely valid for continuous variables.
- adjust_scaling_factors_of_skipped_rows(name)¶
Adjusts the column scaling factors corresponding to variables that are part of rows that are skipped. If the scaling factors are not adjusted, the problem cannot be rescaled to the original problem.
- Parameters:
name – name of the constraint for which the scaling factors are adjusted
- adjust_upper_lower_bounds_variables()¶
Adjusts the upper and lower bounds of the variables whose coefficients are scaled. If the bounds are not scaled, the problem might get infeasible.
- analyze_numerics()¶
Analyzes the numerics of the optimization model.
- generate_numerics_string(label, index=None, A_matrix=None, var=None, is_rhs=False)¶
Generates a string for log-outputs during scaling.
- Parameters:
label – label of the constraint
index – index of the A matrix
A_matrix – A matrix of the optimization model
var – variable of the optimization model
is_rhs – bool whether the string is computed for the right hand side
- Returns:
string for log-outputs
- get_full_geom(A_matrix, axis)¶
Gets the full geometric mean of each column or row of the A matrix. Note, this funtcion is very slow and is not yet ready to be used in the scaling process.
- Parameters:
A_matrix – A matrix of the optimization model (scipy.sparse.csr_matrix)
axis – axis along which the geometric mean is calculated
- Returns:
geometric mean of each column or row
- get_min(A_matrix)¶
Gets the minimum values each column or row of the A matrix.
- Parameters:
A_matrix – A matrix of the optimization model (scipy.sparse.csr_matrix)
- Returns:
Minimum values of each column or row
- Return type:
np.array
- initiate_A_matrix()¶
Constructs the A matrix and the right hand side of the constraints.
- iter_scaling()¶
Generates the row and column scaling factors.
- overwrite_problem()¶
Overwrites the optimization problem with the scaled data.
- print_numerics(i, no_scaling=False, benchmarking_output=False)¶
Prints the numerics of the optimization model.
- Parameters:
i – iteration of the scaling process
no_scaling – bool whether no scaling is activated. Then only numerics are printed.
benchmarking_output – bool whether data for benchmarking is collected
cond_number – bool whether the condition number of the A matrix is computed
- Returns:
- numerical range of the A matrix and the right hand side as well as
the condition number of the A matrix (if benchmarking_output is True
- print_numerics_of_last_iteration()¶
Prints the numerics of the last iteration of the scaling process.
- re_scale()¶
Rescales the solution of the optimization model.
- replace_data(name)¶
Replaces the data (coefficients) of the lhs and rhs of the constraint with the scaled data.
- Parameters:
name – name of the constraint for which the data is replaced with the scaled data
- run_scaling()¶
Runs the scaling algorithm. Function called in runner.py.
- update_A(vector, axis)¶
Updates the A matrix with the current scaling vector. This function does not overwrite the original optimization model but is used for the scaling process.
- Parameters:
vector – vector to update current scaling vectors
axis – axis for which the scaling vector is updated (0 for rows, 1 for columns)
- class zen_garden.preprocess.unit_handling.UnitHandling(folder_path, rounding_decimal_points_units)¶
A class for managing and converting units in an energy system model.
This class facilitates unit consistency checks, dimensionality analysis, and unit conversions in energy systems models, particularly those that involve energy carriers, technologies, and conversion processes. It helps in defining and converting units across various parameters and ensures that unit definitions are consistent across the entire system.
- Key functionalities:
Loading and extracting base units for the system.
Converting input units into a unified system of base units.
Checking for dimensional consistency between input units and base units.
Redefining and verifying the dimensional matrix of the system.
Ensuring that unit conversions and combinations are performed accurately.
- __init__(folder_path, rounding_decimal_points_units)¶
Initializes an instance of the UnitHandling class.
This constructor processes and stores the system’s base unit definitions and other configurations. It also defines the rounding tolerance for unit conversions.
- Parameters:
folder_path (str or Path) – The path to the folder containing system specifications (e.g., “unit_definitions.txt”, “base_units.csv”).
rounding_decimal_points_units (int) – The number of decimal points to which units should be rounded during conversion and consistency checks.
- assert_unit_consistency(elements, energy_quantity_units, energy_quantity_units_check, item, optimization_setup, reference_carrier_name, unit_dict)¶
Asserts that the units of the attributes of an element are consistent with the system’s dimensional framework.
This method checks if the units of attributes defined in the input files (or the optimization setup) are consistent with each other and with the base units. It verifies that all the parameters’ units conform to dimensional analysis and resolves any inconsistencies.
- Parameters:
elements (list) – List of all elements in the system.
energy_quantity_units (dict) – Dictionary of attribute names and their corresponding energy quantity units.
energy_quantity_units_check (dict) – Dictionary of energy quantity units in base units for consistency checking.
item – The specific element or energy system being checked.
optimization_setup (OptimizationSetup) – The optimization setup containing all system parameters.
reference_carrier_name (str) – The name of the reference carrier associated with the element (if applicable).
unit_dict (dict) – Dictionary of unit specifications for attributes.
- Raises:
AssertionError – If inconsistencies are found in the units of the attributes.
- calculate_combined_unit(input_unit, return_combination=False)¶
Represents the input unit as a combination of base units.
This method constructs a combined unit by converting an input unit into a set of base units. It first checks the dimensionality of the input unit and constructs the appropriate combined unit through dimensional analysis. It then checks for unit consistency with the base units and returns the combined unit.
- Parameters:
input_unit (str) – The input unit to be converted (e.g.,
kg,m/s).return_combination (bool) – If True, also returns the base unit combination, in addition to the combined unit.
- Returns:
The combined unit represented as a
pint.Quantity. Ifreturn_combination=True, returns a tuple containing the combined unit and the base unit combination.- Return type:
pint.Quantity or tuple
- Raises:
AssertionError – If the dimensionality of the input unit cannot be matched with base units.
- check_if_invalid_hourstring(input_unit)¶
Checks if “h” in the input unit refers to the Planck constant.
This method ensures that the string “h” is not mistaken for the Planck constant when specifying time units in the system. It will raise an error if “h” is used incorrectly.
- Parameters:
input_unit (str) – The unit string to be checked.
- static check_pos_neg_boolean(array, axis=None)¶
Checks if array contains only positive or negative booleans (-1, 0, 1).
This method verifies if the input array contains values that are either positive or negative booleans, which is often used to check binary states in the optimization.
- Parameters:
array (numpy.ndarray) – The numeric array to be checked.
axis (int, optional) – The axis of the dataframe along which the check is applied.
- Returns:
Returns True if the array contains only positive or negative booleans, otherwise returns False.
- Return type:
bool
- consistency_checks_input_units(optimization_setup)¶
Performs unit consistency checks on the input data.
This method checks whether the units of the parameters defined in the input CSV files are consistent with the system’s dimensional framework. It compares units across elements and technologies and ensures that the units match the expected dimensional definitions. The check also includes units for conversion factors, retrofit flow coupling factors, and other related parameters.
- Parameters:
optimization_setup (OptimizationSetup) – The setup object containing information about the optimization problem, including elements, technologies, and carriers.
- Raises:
AssertionError – If unit inconsistencies are found in the input files or optimization setup.
- convert_unit_into_base_units(input_unit, get_multiplier=False, attribute_name=None, path=None)¶
Converts an input unit into base units.
This method converts an input unit into the equivalent base units, following the dimensional analysis process to express the input_unit as a combination of base units. Additionally, it can return the multiplier that scales the input unit into the base units, depending on the value of get_multiplier.
- Parameters:
input_unit (str) – The unit to be converted (e.g., “kg”, “m/s”).
attribute_name (str, optional) – The name of the attribute corresponding to the unit.
path (str, optional) – The file path of the attribute for logging purposes.
get_multiplier (bool, optional) – Whether to return the multiplier for the conversion. If False, returns the base unit combination.
- Returns:
If get_multiplier is False, returns the input_unit converted to base units as a pint.Quantity. If get_multiplier is True, returns the multiplier as a float and the base units as a pint.Quantity.
- Return type:
pint.Quantity or tuple
- define_ton_as_metric()¶
Redefines the “ton” as a metric ton.
This method redefines the unit “ton” to represent the metric ton, ensuring consistency across the system when dealing with mass units.
- extract_base_units()¶
Extracts the base units from either a CSV or JSON file.
If the CSV file (
base_units.csv) is not found, the method will fall back on a JSON file (base_units.json) to load the base units. Ifhouris not found in the list of base units, a warning will be raised. This method provides the list of all base units that will be used for further calculations and unit consistency checks.- Returns:
A list of base units defined in the system.
- Return type:
list
- Raises:
UserWarning – If the hour unit is not found in the base unit
definitions. –
- get_base_units()¶
Extracts and initializes the base units of the energy system.
This method loads unit definitions, processes them to extract base units, and constructs the dimensionality matrix for the system. It also checks for duplicates and verifies that no unit can be constructed from other base units. Additionally, it ensures that all base units have a valid dimensionality and that no linear dependencies exist between them.
- Raises:
KeyError – If there are multiple base units defined for the same dimensionality.
AssertionError – If there are linear dependencies between base units that can’t be resolved.
- get_most_often_appearing_energy_unit(energy_units)¶
Finds the most commonly appearing energy unit for a carrier’s attributes.
This method identifies the most frequently used energy unit across the attributes of a given carrier, which is assumed to be the correct one.
- Parameters:
energy_units (dict) – Dictionary containing attribute names and their energy quantity terms.
- Returns:
The energy unit that appears most frequently across the attributes of the carrier.
- Return type:
str
- get_unit_multiplier(input_unit, attribute_name, path=None, combined_unit=None)¶
Calculates the multiplier for converting an input unit into the base units.
This method computes the scaling factor (multiplier) needed to convert the given input_unit into a base unit. If the input_unit is already a base unit, the multiplier is 1. If the input_unit is not in base units, it computes the conversion using dimensional analysis and ensures that the resulting multiplier meets the rounding tolerance.
- Parameters:
input_unit (str) – The unit to be converted (e.g., “kg”, “m/s”).
attribute_name (str) – The name of the attribute that this unit corresponds to.
path (str, optional) – The file path associated with the unit (for logging purposes).
combined_unit (pint.Quantity, optional) – The combined unit in base units. If provided, skips recomputing the combined unit.
- Returns:
The multiplier that scales the input_unit into the base units.
- Return type:
float
- Raises:
AssertionError – If the multiplier is smaller than the rounding tolerance.
- redefine_standard_units()¶
Redefines standard units required in the system.
This method sets up standard units such as “Euro”, “year”, and “ton”, and ensures that the system handles leap years correctly.
- save_carrier_energy_quantities(optimization_setup)¶
Saves energy quantity units of carriers after consistency checks.
This method stores the energy quantities of the carriers after they have been verified for unit consistency. It ensures that the units of the carrier’s attributes are properly assigned to variables for later use in calculations.
- Parameters:
optimization_setup (OptimizationSetup) – The optimization setup containing system parameters.
- Returns:
A dictionary containing the carrier units.
- Return type:
dict
- set_attribute_values(df_output, attribute)¶
Saves the values of an attribute from a dataframe output.
This method stores the values of a given attribute from a dataframe into the class’ internal dictionary for future use.
- Parameters:
df_output (DataFrame) – The dataframe containing the output values for attributes.
attribute (str) – The name of the attribute whose values are being saved.
- set_base_unit_combination(input_unit, attribute)¶
Converts the input unit to the corresponding base unit.
This method takes an input unit and converts it to its base unit equivalent, which can be used for further unit analysis. It also handles special cases where the input unit is NaN or dimensionless.
- Parameters:
input_unit (str or Quantity) – The unit to be converted to base units.
attribute (str) – The name of the attribute that uses the unit.