# Complete PYOMO implementation

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

def voter_2_optimization():
    """Optimization model for maximizing student participation in elections."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    majors = ['Computer Science', 'Biology', 'History']
    expected_votes = {'Computer Science': 150, 'Biology': 100, 'History': 80}
    students = {'Computer Science': 200, 'Biology': 150, 'History': 100}
    
    # Validate array lengths before indexing
    assert len(majors) == len(expected_votes) == len(students), "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.Set(initialize=majors)
    
    # 4. PARAMETERS
    model.expected_votes = pyo.Param(model.I, initialize=expected_votes)
    model.students = pyo.Param(model.I, initialize=students)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeIntegers)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.expected_votes[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    # Total Budget Constraint
    def budget_rule(model):
        return sum(model.x[i] for i in model.I) <= 50000
    model.budget_constraint = pyo.Constraint(rule=budget_rule)
    
    # Minimum Resource Allocation Constraint
    def min_allocation_rule(model, i):
        return model.x[i] >= 500
    model.min_allocation_constraint = pyo.Constraint(model.I, rule=min_allocation_rule)
    
    # Maximum Resource Allocation Constraint
    def max_allocation_rule(model, i):
        return model.x[i] <= 5000
    model.max_allocation_constraint = pyo.Constraint(model.I, rule=max_allocation_rule)
    
    # Proportional Resource Allocation Constraint
    def proportional_allocation_rule(model, i):
        return model.x[i] <= 10 * model.students[i]
    model.proportional_allocation_constraint = pyo.Constraint(model.I, rule=proportional_allocation_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("\nResource Allocation:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            print(f"{i}: {x_val} units")
        
    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

# Execute the optimization
if __name__ == "__main__":
    voter_2_optimization()