# Complete PYOMO implementation - Retry Attempt 3

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

def scientist_assignment_optimization():
    """Optimize the assignment of scientists to projects to minimize total project hours."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Projects data
    projects_hours = [120, 150, 100]
    project_max_hours = [200, 250, 180]
    
    # Number of scientists and projects
    n_scientists = 3
    n_projects = len(projects_hours)
    
    # Validate array lengths
    assert len(projects_hours) == len(project_max_hours) == n_projects, "Array length mismatch in projects data"
    
    # 3. SETS
    model.S = pyo.RangeSet(1, n_scientists)  # Scientists
    model.P = pyo.RangeSet(1, n_projects)    # Projects
    
    # 4. PARAMETERS
    model.hours = pyo.Param(model.P, initialize={j: projects_hours[j-1] for j in model.P})
    model.max_hours = pyo.Param(model.P, initialize={j: project_max_hours[j-1] for j in model.P})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.S, model.P, within=pyo.Binary)  # Binary decision variable
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.hours[j] * model.x[i, j] for i in model.S for j in model.P)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    
    # Scientist Assignment Constraint: Each scientist must be assigned to at least one project
    def scientist_assignment_rule(model, i):
        return sum(model.x[i, j] for j in model.P) >= 1
    model.scientist_assignment = pyo.Constraint(model.S, rule=scientist_assignment_rule)
    
    # Project Hours Constraint: Total hours assigned to a project must not exceed its maximum allowed hours
    def project_hours_rule(model, j):
        return sum(model.hours[j] * model.x[i, j] for i in model.S) <= model.max_hours[j]
    model.project_hours = pyo.Constraint(model.P, rule=project_hours_rule)
    
    # Project Assignment Constraint: Each project must have at least one scientist assigned to it
    def project_assignment_rule(model, j):
        return sum(model.x[i, j] for i in model.S) >= 1
    model.project_assignment = pyo.Constraint(model.P, rule=project_assignment_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(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nAssignment details:")
        for i in model.S:
            for j in model.P:
                if pyo.value(model.x[i, j]) > 0.5:  # Only print assignments
                    print(f"Scientist {i} assigned to Project {j}")
        
    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__":
    scientist_assignment_optimization()