Solution#

API Reference > Modeling > Solution

The decision_ai.Solution class stores the results of your optimization problem and provides convenient methods to access variable values.

Purpose:

  • Store optimization results in a structured format

  • Provide easy access to variable values

  • Support solution analysis and reporting

  • Enable solution serialization and persistence

Key Features:

  • Structured Access - Easy retrieval of variable values

  • Multiple Formats - Support for different output formats

  • Validation - Automatic validation of solution feasibility

  • Serialization - Convert solutions to/from various formats

Usage Example#

# After solving your model
solution = model.solve(input_data)

# Check if solution is optimal
if solution.is_optimal():
    print("Optimal solution found!")

    # Access variable values
    print(f"Objective value: {solution.objective_value}")

    # Access specific variables (depends on your variable structure)
    for employee in input_data.employees:
        for day in input_data.days:
            if solution.get_variable_value(f"assign_{employee}_{day}") == 1:
                print(f"{employee} works on {day}")

# Get solution summary
print(solution.to_string())

Accessing Variable Values#

The exact methods for accessing variable values depend on your model’s variable structure:

# For simple variables
total_cost = solution.get_variable_value("total_cost")

# For dictionary-structured variables
# (Access patterns depend on your PulpVariables implementation)
assignments = {}
for emp in employees:
    for day in days:
        var_name = f"assign_{emp}_{day}"
        if solution.get_variable_value(var_name) == 1:
            assignments[emp] = assignments.get(emp, []) + [day]

Solution Analysis#

# Check solution status
if solution.is_optimal():
    print("Found optimal solution")
elif solution.is_feasible():
    print("Found feasible solution (may not be optimal)")
else:
    print("No feasible solution found")

# Get performance metrics
print(f"Objective value: {solution.objective_value}")
print(f"Solution time: {solution.solve_time} seconds")
print(f"Number of variables: {solution.num_variables}")
print(f"Number of constraints: {solution.num_constraints}")

Class Reference#

class decision_ai.Solution(status: Literal['Infeasible', 'Optimal'] | None = None, objective: float | None = None, variables: GenericVariables | None = None, violations: dict[str, dict[str, ConstraintViolation]] | None = None)#

Bases: Generic[GenericVariables]

Solution dataclass for the optimization model.

set_solution(sol: Solution) None#

Set the solution dataclass.

Solution Export#

# Export to different formats
solution_dict = solution.to_dict()
solution_json = solution.to_json()
solution_summary = solution.to_string()

# Save to file
with open("solution.json", "w") as f:
    f.write(solution.to_json())

Best Practices#

  1. Check Solution Status - Always verify if the solution is optimal or feasible

  2. Handle Infeasible Cases - Provide meaningful error handling for infeasible problems

  3. Structure Output - Organize solution output in a user-friendly format

  4. Validate Results - Cross-check critical constraints in your solution

  5. Document Variable Mapping - Make it clear how variables map to business meaning

Common Solution Patterns#

Assignment Problems:

def extract_assignments(solution, employees, tasks):
    assignments = {}
    for emp in employees:
        assignments[emp] = []
        for task in tasks:
            if solution.get_variable_value(f"assign_{emp}_{task}") == 1:
                assignments[emp].append(task)
    return assignments

Flow Problems:

def extract_flows(solution, edges):
    flows = {}
    for from_node, to_node in edges:
        flow_value = solution.get_variable_value(f"flow_{from_node}_{to_node}")
        if flow_value > 0:
            flows[(from_node, to_node)] = flow_value
    return flows

Scheduling Problems:

def extract_schedule(solution, employees, days, shifts):
    schedule = {}
    for day in days:
        schedule[day] = {}
        for shift in shifts:
            schedule[day][shift] = []
            for emp in employees:
                if solution.get_variable_value(f"assign_{emp}_{day}_{shift}") == 1:
                    schedule[day][shift].append(emp)
    return schedule