# Complete PYOMO implementation

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

def scientist_optimization():
    """Optimization model for assigning scientists to projects"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Data from the database
    projects_data = {1: 15.0, 2: 25.0, 3: 35.0}
    assigned_to_data = [
        (101, 1, True), (101, 2, True),
        (102, 2, True), (102, 3, True),
        (103, 3, True)
    ]
    constraint_bounds_data = {
        'scientist': 2,
        'project': 1
    }
    
    # Extract unique scientist and project IDs
    scientist_ids = set(scientist for scientist, _, _ in assigned_to_data)
    project_ids = set(project for _, project, _ in assigned_to_data)
    
    # 3. SETS
    model.I = pyo.Set(initialize=scientist_ids)
    model.J = pyo.Set(initialize=project_ids)
    
    # 4. PARAMETERS
    model.hours = pyo.Param(model.J, initialize=projects_data)
    model.min_assignments_scientist = pyo.Param(initialize=constraint_bounds_data['scientist'])
    model.min_assignments_project = pyo.Param(initialize=constraint_bounds_data['project'])
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, model.J, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.hours[j] * model.x[i, j] for i in model.I for j in model.J)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Minimum Projects per Scientist
    def min_projects_per_scientist_rule(model, i):
        return sum(model.x[i, j] for j in model.J) >= model.min_assignments_scientist
    model.min_projects_per_scientist = pyo.Constraint(model.I, rule=min_projects_per_scientist_rule)
    
    # Minimum Scientists per Project
    def min_scientists_per_project_rule(model, j):
        return sum(model.x[i, j] for i in model.I) >= model.min_assignments_project
    model.min_scientists_per_project = pyo.Constraint(model.J, rule=min_scientists_per_project_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 of scientists to projects:")
        for i in model.I:
            for j in model.J:
                x_val = pyo.value(model.x[i, j])
                if x_val > 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

# Run the optimization
scientist_optimization()