# Complete PYOMO implementation

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

def protein_institute_optimization():
    """Optimize resource allocation to maximize sequence identity"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    n_institutions = 3
    sequence_identity_coefficients = [0.85, 0.9, 0.8]
    building_capacities = [600, 700, 500]
    total_resources_available = 600
    
    # CRITICAL: Validate array lengths before indexing
    assert len(sequence_identity_coefficients) == len(building_capacities) == n_institutions, "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.RangeSet(1, n_institutions)  # 1-based indexing
    
    # 4. PARAMETERS
    model.sequence_identity_coefficient = pyo.Param(model.I, initialize={i+1: sequence_identity_coefficients[i] for i in range(n_institutions)})
    model.building_capacity = pyo.Param(model.I, initialize={i+1: building_capacities[i] for i in range(n_institutions)})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.sequence_identity_coefficient[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Total Resource Constraint
    def total_resource_constraint_rule(model):
        return sum(model.x[i] for i in model.I) <= total_resources_available
    model.total_resource_constraint = pyo.Constraint(rule=total_resource_constraint_rule)
    
    # Building Capacity Constraints
    def building_capacity_rule(model, i):
        return model.x[i] <= model.building_capacity[i]
    model.building_capacity_constraint = pyo.Constraint(model.I, rule=building_capacity_rule)
    
    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')
    
    # Solve the model
    results = solver.solve(model, tee=True)
    
    # 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):.3f}")
        
        # Extract variable values
        print("\nVariable values:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"x[{i}] = {x_val:.3f}")
        
    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
protein_institute_optimization()