Models¶
Optimization¶
Pyomo¶
The following functions are tools made to work with optimization models created with the pyomo library.
- mango.models.pyomo.is_feasible(status)¶
Check if a solver status indicates a feasible solution.
Determines whether the given status represents a feasible solution by checking if it corresponds to optimal or maximum time limit termination conditions.
- Parameters:
status (Union[str, TerminationCondition]) – Solver status (string or pyomo object)
- Returns:
True if the status indicates a feasible solution
- Return type:
bool
- Example:
>>> result = solver.solve(model) >>> if is_feasible(result.solver.termination_condition): ... print("Solution is feasible")
- mango.models.pyomo.safe_value(x)¶
Safely extract the value from a Pyomo variable.
Pyomo’s value() function generates an error if the variable has not been used in the model. This function provides a safe alternative that returns 0 for unused or None variables.
- Parameters:
x (Union[Var, None]) – Pyomo variable to extract value from
- Returns:
Value of the variable, or 0 if variable is None or unused
- Return type:
float
- Raises:
Exception – Handles any Pyomo value extraction errors gracefully
- Example:
>>> var = model.x[1, 2] >>> val = safe_value(var) # Returns 0 if var was not used
- mango.models.pyomo.var_to_sdict(variable, clean=False, rounding=2)¶
Transform a Pyomo variable into a SuperDict with indices and values.
Converts a Pyomo variable into a dictionary-like structure containing all variable indices and their corresponding values. Optionally filters out zero values and rounds the results.
- Parameters:
variable (Var) – Pyomo variable to convert
clean (bool) – If True, only return non-zero values
rounding (int) – Number of decimal places to round values
- Returns:
SuperDict containing variable indices and values
- Return type:
SuperDict
- Example:
>>> var = model.x # Pyomo variable with indices (1,2), (2,3) >>> result = var_to_sdict(var, clean=True, rounding=3) >>> print(result) # {(1,2): 1.234, (2,3): 5.678}
- mango.models.pyomo.var_to_table(variable, keys, clean=False, rounding=2)¶
Generate a Table object from a Pyomo variable.
Converts a Pyomo variable into a Table structure with named columns for indices and values. Automatically generates column names if not provided.
- Parameters:
variable (Var) – Pyomo variable to convert
keys (Optional[List[str]]) – Names for the index columns (None for auto-generation)
clean (bool) – If True, only return non-zero values
rounding (int) – Number of decimal places to round values
- Returns:
Table object with variable data
- Return type:
- Example:
>>> var = model.x # Pyomo variable with indices (i, j) >>> table = var_to_table(var, keys=['i', 'j'], clean=True) >>> print(table) # [{'i': 1, 'j': 2, 'Value': 1.23}, ...]
- mango.models.pyomo.get_status(result)¶
Extract the termination condition status from a Pyomo solver result.
Retrieves the termination condition from the solver result object and returns it as a string representation.
- Parameters:
result (SolverResults) – Pyomo solver result object
- Returns:
String representation of the termination condition
- Return type:
str
- Example:
>>> result = solver.solve(model) >>> status = get_status(result) >>> print(f"Solver status: {status}")
- mango.models.pyomo.get_gap(result)¶
Calculate the relative optimality gap from a Pyomo solver result.
Computes the relative gap between the upper and lower bounds of the solution, handling both minimization and maximization problems. Returns the absolute value of the gap as a percentage.
- Parameters:
result (SolverResults) – Pyomo solver result object
- Returns:
Relative optimality gap as a percentage
- Return type:
float
- Example:
>>> result = solver.solve(model) >>> gap = get_gap(result) >>> print(f"Optimality gap: {gap}%")
- mango.models.pyomo.write_cbc_warmstart_file(filename, instance, opt)¶
Write a warmstart file for the CBC solver.
Creates a warmstart file that can be used by the CBC solver to initialize the solution process. This function is necessary due to a bug in CBC that prevents reading warmstart files with absolute paths on Windows systems.
- Parameters:
filename (str) – Path where the warmstart file should be written
instance (ConcreteModel) – Pyomo model instance (created with create_instance)
opt (SolverFactory) – Solver instance (created with solver factory)
- Returns:
None
- Example:
>>> opt = SolverFactory('cbc') >>> write_cbc_warmstart_file('warmstart.sol', model, opt)
- mango.models.pyomo.variables_to_excel(model_solution, path, file_name='variables.xlsx', clean=True, rounding=6)¶
Export all Pyomo variable values to an Excel file.
Saves all variables from a Pyomo model solution to an Excel file with each variable as a separate worksheet. Optionally filters out zero values and rounds the results.
- Parameters:
model_solution (ConcreteModel) – Pyomo model solution object
path (str) – Directory path where the file should be saved
file_name (str) – Name of the Excel file to create
clean (bool) – If True, discard variables with zero values
rounding (int) – Number of decimal places to round values
- Returns:
None
- Raises:
IOError – If file cannot be written
- Example:
>>> variables_to_excel( ... model, 'output/', 'solution.xlsx', clean=True, rounding=4 ... )
- mango.models.pyomo.variables_to_json(model_solution, path, file_name='variables.json', clean=True)¶
Export all Pyomo variable values to a JSON file.
Saves all variables from a Pyomo model solution to a JSON file with structured data. Optionally filters out zero values.
- Parameters:
model_solution (ConcreteModel) – Pyomo model solution object
path (str) – Directory path where the file should be saved
file_name (str) – Name of the JSON file to create
clean (bool) – If True, discard variables with zero values
- Returns:
None
- Raises:
IOError – If file cannot be written
- Example:
>>> variables_to_json(model, 'output/', 'solution.json', clean=True)
- mango.models.pyomo.instance_from_excel(instance, path, file_name='variables.xlsx')¶
Load Pyomo model instance data from an Excel file.
Reads variable values from an Excel file and loads them into a Pyomo model instance. The Excel file should contain worksheets with variable data in the format created by variables_to_excel.
- Parameters:
instance (ConcreteModel) – Pyomo model instance to load data into
path (str) – Directory path containing the Excel file
file_name (str) – Name of the Excel file to load
- Returns:
Model instance with loaded variable values
- Return type:
ConcreteModel
- Raises:
IOError – If file cannot be read
- Example:
>>> model = instance_from_excel(model, 'data/', 'initial_values.xlsx')
- mango.models.pyomo.instance_from_json(instance, path, file_name='variables.json', **kwargs)¶
Load Pyomo model instance data from a JSON file.
Reads variable values from a JSON file and loads them into a Pyomo model instance. The JSON file should contain structured data in the format created by variables_to_json.
- Parameters:
instance (ConcreteModel) – Pyomo model instance to load data into
path (str) – Directory path containing the JSON file
file_name (str) – Name of the JSON file to load
kwargs – Additional keyword arguments for load_json
- Returns:
Model instance with loaded variable values
- Return type:
ConcreteModel
- Raises:
IOError – If file cannot be read
- Example:
>>> model = instance_from_json(model, 'data/', 'initial_values.json')
- mango.models.pyomo.instance_from_dict(instance, data)¶
Load Pyomo model instance data from a dictionary containing tables.
Processes a dictionary containing table data and loads the values into the corresponding variables in a Pyomo model instance. Each table should have index columns and a ‘Value’ column.
- Parameters:
instance (ConcreteModel) – Pyomo model instance to load data into
data (Dict[str, List[Dict]]) – Dictionary containing table data for variables
- Returns:
Model instance with loaded variable values
- Return type:
ConcreteModel
- Example:
>>> data = {'x': [{'i': 1, 'j': 2, 'Value': 1.5}]} >>> model = instance_from_dict(model, data)
- mango.models.pyomo.load_variable(instance, var_name, value)¶
Load values into a specific variable in a Pyomo model instance.
Assigns values to a named variable in the model instance using the provided value dictionary with index-value pairs.
- Parameters:
instance (ConcreteModel) – Pyomo model instance containing the variable
var_name (str) – Name of the variable to load values into
value (Dict[tuple, float]) – Dictionary mapping variable indices to values
- Returns:
None
- Raises:
KeyError – If variable name is not found in the instance
- Example:
>>> values = {(1, 2): 1.5, (2, 3): 2.0} >>> load_variable(model, 'x', values)
- mango.models.pyomo.model_data_to_excel(model_data, path, file_name='model_data.xlsx')¶
Export Pyomo model data to an Excel file.
Saves model data (parameters, sets, etc.) to an Excel file with each data component as a separate worksheet. Handles both indexed and scalar data appropriately.
- Parameters:
model_data (Dict[str, Any]) – Dictionary containing model data for Pyomo model
path (str) – Directory path where the file should be saved
file_name (str) – Name of the Excel file to create
- Returns:
None
- Raises:
IOError – If file cannot be written
- Example:
>>> data = {'demand': {(1,): 100, (2,): 200}, 'capacity': 1000} >>> model_data_to_excel(data, 'output/', 'model_data.xlsx')
- mango.models.pyomo.solver_result_to_json(result, path)¶
Export Pyomo solver result to a JSON file.
Saves a Pyomo solver result object to a JSON file, converting Pyomo-specific objects to JSON-serializable formats. Handles special Pyomo data types and status objects.
- Parameters:
result (SolverResults) – Pyomo solver result object
path (str) – File path where the JSON should be saved
- Returns:
None
- Raises:
IOError – If file cannot be written
- Example:
>>> result = solver.solve(model) >>> solver_result_to_json(result, 'output/solution_result.json')
- mango.models.pyomo.solver_result_from_json(path, **kwargs)¶
Load a Pyomo solver result object from a JSON file.
Reconstructs a Pyomo SolverResults object from data previously saved using solver_result_to_json. Restores the original structure and data types where possible.
- Parameters:
path (str) – File path to the JSON file containing result data
kwargs – Additional keyword arguments for load_json
- Returns:
Reconstructed Pyomo solver result object
- Return type:
SolverResults
- Raises:
IOError – If file cannot be read
- Example:
>>> result = solver_result_from_json('output/solution_result.json') >>> print(f"Solver status: {result.solver.termination_condition}")