# Complete DOCPLEX implementation

from docplex.mp.model import Model

def protein_institute_optimization():
    """Optimize resource allocation to maximize sequence identity"""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="protein_institute")
    
    # Data from the problem statement
    sequence_identity_coefficients = [0.85, 0.9, 0.8]
    building_capacities = [600, 700, 500]
    total_resources_available = 600
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(sequence_identity_coefficients) == len(building_capacities), "Array length mismatch"
    safe_range = range(min(len(sequence_identity_coefficients), len(building_capacities)))  # Safe indexing
    
    # 2. VARIABLES
    # Variable dictionaries for resource allocation
    allocation = {i: mdl.continuous_var(name=f"x_{i}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total sequence identity
    objective = mdl.sum(sequence_identity_coefficients[i] * allocation[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Total Resource Constraint
    total_allocation = mdl.sum(allocation[i] for i in safe_range)
    mdl.add_constraint(total_allocation <= total_resources_available, ctname="total_resource_limit")
    
    # Building Capacity Constraints
    for i in safe_range:
        mdl.add_constraint(allocation[i] <= building_capacities[i], ctname=f"capacity_limit_{i}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(allocation[i])
            if value > 1e-6:
                print(f"Allocation for institution {i+1}: {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
protein_institute_optimization()