# Complete PYOMO implementation

import pyomo.environ as pyo
from pyomo.opt import SolverFactory

def dormitory_assignment_optimization():
    """Optimize student dormitory assignments to minimize allergy penalties."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data based on the provided problem context
    students = [101, 102, 103]
    dormitories = [1, 2, 3]
    
    # Penalty values for assigning students to dormitories
    penalty_values = {
        (101, 2): 20.0,
        (102, 2): 25.0,
        (103, 2): 15.0
    }
    
    # Dormitory capacities
    capacities = {
        1: 50,
        2: 100,
        3: 150
    }
    
    # Allergy-friendly status of dormitories
    allergy_friendly = {
        1: True,
        2: False,
        3: True
    }
    
    # 3. SETS
    model.I = pyo.Set(initialize=students)
    model.J = pyo.Set(initialize=dormitories)
    
    # 4. PARAMETERS
    model.penalty_value = pyo.Param(model.I, model.J, initialize=penalty_values, default=0.0)
    model.capacity = pyo.Param(model.J, initialize=capacities)
    model.is_allergy_friendly = pyo.Param(model.J, initialize=allergy_friendly)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, model.J, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.penalty_value[i, j] * model.x[i, j] for i in model.I for j in model.J)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    
    # Each student must be assigned to exactly one dormitory
    def student_assignment_rule(model, i):
        return sum(model.x[i, j] for j in model.J) == 1
    model.student_assignment_constraint = pyo.Constraint(model.I, rule=student_assignment_rule)
    
    # The number of students assigned to a dormitory cannot exceed its capacity
    def capacity_rule(model, j):
        return sum(model.x[i, j] for i in model.I) <= model.capacity[j]
    model.capacity_constraint = pyo.Constraint(model.J, rule=capacity_rule)
    
    # Students with allergies cannot be assigned to non-allergy-friendly dormitories
    def allergy_constraint_rule(model, i, j):
        if not model.is_allergy_friendly[j]:
            return model.x[i, j] == 0
        return pyo.Constraint.Skip
    model.allergy_constraint = pyo.Constraint(model.I, model.J, rule=allergy_constraint_rule)
    
    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')
    
    # Optional: Set solver options
    solver.options['TimeLimit'] = 300  # 5 minutes
    solver.options['MIPGap'] = 0.01    # 1% gap
    
    # Solve the model
    results = solver.solve(model, tee=True)  # tee=True shows solver output
    
    # 9. RESULT PROCESSING
    # Check solver status
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nAssignment values:")
        for i in model.I:
            for j in model.J:
                x_val = pyo.value(model.x[i, j])
                if x_val > 1e-6:  # Only print non-zero values
                    print(f"Student {i} assigned to Dormitory {j}: {int(x_val)}")
        
    elif results.solver.termination_condition == pyo.TerminationCondition.infeasible:
        print("Problem is infeasible")
    elif results.solver.termination_condition == pyo.TerminationCondition.unbounded:
        print("Problem is unbounded")
    else:
        print(f"Solver terminated with condition: {results.solver.termination_condition}")
    
    return model

# Run the optimization
dormitory_assignment_optimization()