# Complete Optimization Problem and Solution: sports_competition

## 1. Problem Context and Goals

### Context  
In a competitive sports league, the objective is to strategically allocate players to various clubs to maximize the overall points scored by all clubs. Each player has a specific number of points they can contribute, and they are allowed to apply to a limited number of clubs. Clubs, on the other hand, have a maximum capacity for the number of players they can accommodate. The decision-making process involves determining whether a player is assigned to a club, represented by a binary decision variable. The goal is to maximize the total points scored by all clubs, which is achieved by summing the points of players assigned to clubs. The business configuration includes a parameter that limits the number of applications a player can make, ensuring that the optimization respects these constraints. This setup naturally leads to a linear optimization problem, where the focus is on maximizing the total points while adhering to the constraints of player applications and club capacities.

### Goals  
The primary goal of this optimization problem is to maximize the total points scored by all clubs in the league. This is achieved by strategically assigning players to clubs in a way that maximizes the sum of the points contributed by each player assigned to a club. The success of this optimization is measured by the total points accumulated, which directly correlates with the points each player can contribute when assigned to a club. The objective is clearly defined in linear terms, focusing on maximizing the total points without involving any complex mathematical operations beyond addition.

## 2. Constraints    

The optimization problem is subject to several constraints that ensure the feasibility and practicality of the player assignments:

- Each player can apply to a limited number of clubs, which is defined by the maximum number of applications they can make. This constraint ensures that the number of clubs a player is assigned to does not exceed their application limit.
- Each club has a capacity limit, which dictates the maximum number of players it can accommodate. This constraint ensures that the total number of players assigned to a club does not exceed its capacity.
- The assignment of players to clubs is represented by a binary decision variable, indicating whether a player is assigned to a club or not. This constraint ensures that each assignment decision is binary, reflecting the reality of player assignments.

These constraints are expressed in linear terms, aligning with the business requirements and ensuring that the optimization problem remains linear.

## 3. Available Data  

### Database Schema  
```sql
-- Iteration 1 Database Schema
-- Objective: Schema changes include creating new tables for club capacities and player applications, modifying existing tables to include missing mappings, and updating business configuration logic for scalar parameters and formulas.

CREATE TABLE Player (
  PlayerID INTEGER,
  Points INTEGER,
  MaxApps INTEGER
);

CREATE TABLE ClubCapacity (
  ClubID INTEGER,
  Capacity INTEGER
);

CREATE TABLE PlayerClubAssignment (
  PlayerID INTEGER,
  ClubID INTEGER,
  Assigned BOOLEAN
);

CREATE TABLE PlayerApplications (
  id INTEGER PRIMARY KEY,
  value NUMBER
);
```

### Data Dictionary  
The data dictionary provides a comprehensive overview of the tables and columns used in the optimization problem, highlighting their business purposes and roles in the optimization process:

- **Player Table**: This table stores information about each player, including their unique identifier, the points they can contribute, and the maximum number of applications they can make. The points are used as coefficients in the optimization objective, while the application limit serves as a constraint.

- **ClubCapacity Table**: This table contains information about each club's capacity, specifying the maximum number of players each club can accommodate. This capacity serves as a constraint in the optimization problem.

- **PlayerClubAssignment Table**: This table tracks the assignment of players to clubs, using a binary variable to indicate whether a player is assigned to a club. This assignment is the primary decision variable in the optimization problem.

### Current Stored Values  
```sql
-- Iteration 1 Realistic Data
-- Generated by triple expert (business + data + optimization)
-- Values were determined based on typical sports league structures, ensuring a balance between player applications and club capacities to allow for meaningful optimization.

-- Realistic data for Player
INSERT INTO Player (PlayerID, Points, MaxApps) VALUES (1, 15, 3);
INSERT INTO Player (PlayerID, Points, MaxApps) VALUES (2, 25, 4);
INSERT INTO Player (PlayerID, Points, MaxApps) VALUES (3, 10, 2);

-- Realistic data for ClubCapacity
INSERT INTO ClubCapacity (ClubID, Capacity) VALUES (1, 5);
INSERT INTO ClubCapacity (ClubID, Capacity) VALUES (2, 10);
INSERT INTO ClubCapacity (ClubID, Capacity) VALUES (3, 8);

-- Realistic data for PlayerClubAssignment
INSERT INTO PlayerClubAssignment (PlayerID, ClubID, Assigned) VALUES (1, 1, False);
INSERT INTO PlayerClubAssignment (PlayerID, ClubID, Assigned) VALUES (2, 2, True);
INSERT INTO PlayerClubAssignment (PlayerID, ClubID, Assigned) VALUES (3, 3, False);
```

## 4. Mathematical Optimization Formulation

#### Decision Variables
- Let \( x_{ij} \) be a binary decision variable where \( x_{ij} = 1 \) if player \( i \) is assigned to club \( j \), and \( x_{ij} = 0 \) otherwise.

#### Objective Function
Maximize the total points scored by all clubs:
\[ \text{Maximize } \sum_{i} \sum_{j} \text{Player.Points}[i] \times x_{ij} \]

Data Source Verification:
- Coefficients for the objective function are derived from the `Player.Points` column.

#### Constraints
1. **Player Application Limit**: Each player can apply to a limited number of clubs.
   \[
   \sum_{j} x_{ij} \leq \text{Player.MaxApps}[i] \quad \forall i
   \]

2. **Club Capacity Limit**: Each club has a capacity limit for the number of players.
   \[
   \sum_{i} x_{ij} \leq \text{ClubCapacity.Capacity}[j] \quad \forall j
   \]

3. **Binary Assignment**: The assignment of players to clubs is binary.
   \[
   x_{ij} \in \{0, 1\} \quad \forall i, j
   \]

Data Source Verification:
- The constraint coefficients for player application limits are from `Player.MaxApps`.
- The constraint coefficients for club capacities are from `ClubCapacity.Capacity`.

This formulation provides a complete and immediately solvable linear mathematical model using the provided data, ensuring that all constraints and the objective function are expressed in linear terms.

## 5. Gurobipy Implementation

```python
# Complete GUROBIPY implementation

import gurobipy as gp
from gurobipy import GRB

def sports_competition_optimization():
    """Optimize player assignments to clubs to maximize total points."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("sports_competition")
    
    # Data from the problem context
    players = [1, 2, 3]
    clubs = [1, 2, 3]
    points = {1: 15, 2: 25, 3: 10}
    max_apps = {1: 3, 2: 4, 3: 2}
    capacities = {1: 5, 2: 10, 3: 8}
    
    # CRITICAL: Validate array lengths before loops
    assert len(players) == len(points) == len(max_apps), "Player data length mismatch"
    assert len(clubs) == len(capacities), "Club data length mismatch"
    
    # 2. VARIABLES
    # Binary decision variables for player-club assignments
    x = model.addVars(players, clubs, vtype=GRB.BINARY, name="x")
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total points scored by all clubs
    model.setObjective(gp.quicksum(points[i] * x[i, j] for i in players for j in clubs), GRB.MAXIMIZE)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Player application limit constraints
    model.addConstrs((gp.quicksum(x[i, j] for j in clubs) <= max_apps[i] for i in players), name="player_app_limit")
    
    # Club capacity limit constraints
    model.addConstrs((gp.quicksum(x[i, j] for i in players) <= capacities[j] for j in clubs), name="club_capacity_limit")
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in players:
            for j in clubs:
                if x[i, j].x > 1e-6:
                    print(f"Player {i} assigned to Club {j}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

# Run the optimization
sports_competition_optimization()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 140.0
**Execution Time**: 0.74 seconds
**Reliability**: high
**Analysis**: Gurobipy found an optimal solution quickly with the shortest execution time, indicating efficient performance and reliability.

## 6. DOCplex Implementation

```python
# Complete DOCPLEX implementation

from docplex.mp.model import Model

def sports_competition_optimization():
    """Optimization for assigning players to clubs to maximize total points."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="sports_competition")
    
    # Data from the problem context
    players = [
        {"PlayerID": 1, "Points": 15, "MaxApps": 3},
        {"PlayerID": 2, "Points": 25, "MaxApps": 4},
        {"PlayerID": 3, "Points": 10, "MaxApps": 2}
    ]
    
    clubs = [
        {"ClubID": 1, "Capacity": 5},
        {"ClubID": 2, "Capacity": 10},
        {"ClubID": 3, "Capacity": 8}
    ]
    
    # Extracting data into lists for easier handling
    player_ids = [p["PlayerID"] for p in players]
    player_points = [p["Points"] for p in players]
    player_max_apps = [p["MaxApps"] for p in players]
    
    club_ids = [c["ClubID"] for c in clubs]
    club_capacities = [c["Capacity"] for c in clubs]
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(player_ids) == len(player_points) == len(player_max_apps), "Player data length mismatch"
    assert len(club_ids) == len(club_capacities), "Club data length mismatch"
    
    safe_player_range = range(len(player_ids))
    safe_club_range = range(len(club_ids))
    
    # 2. VARIABLES
    # Binary decision variables for player-club assignments
    x = {(i, j): mdl.binary_var(name=f"x_{i}_{j}") for i in safe_player_range for j in safe_club_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the total points scored by all clubs
    objective = mdl.sum(player_points[i] * x[i, j] for i in safe_player_range for j in safe_club_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    
    # Player Application Limit
    for i in safe_player_range:
        mdl.add_constraint(mdl.sum(x[i, j] for j in safe_club_range) <= player_max_apps[i], ctname=f"player_app_limit_{i}")
    
    # Club Capacity Limit
    for j in safe_club_range:
        mdl.add_constraint(mdl.sum(x[i, j] for i in safe_player_range) <= club_capacities[j], ctname=f"club_capacity_{j}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_player_range:
            for j in safe_club_range:
                value = solution.get_value(x[i, j])
                if value > 1e-6:
                    print(f"Player {player_ids[i]} assigned to Club {club_ids[j]}: {value}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
sports_competition_optimization()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 140.0
**Execution Time**: 5.28 seconds
**Reliability**: high
**Analysis**: DOCplex also found an optimal solution, though it took longer than Gurobipy. The results are consistent, indicating reliability.

## 7. Pyomo Implementation

```python
# Complete PYOMO implementation

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

def sports_competition_optimization():
    """Optimization for sports competition player assignment to clubs"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    players = [1, 2, 3]
    clubs = [1, 2, 3]
    points = {1: 15, 2: 25, 3: 10}
    max_apps = {1: 3, 2: 4, 3: 2}
    capacities = {1: 5, 2: 10, 3: 8}
    
    # CRITICAL: Validate data lengths before indexing
    assert len(points) == len(max_apps) == len(players), "Player data length mismatch"
    assert len(capacities) == len(clubs), "Club data length mismatch"
    
    # 3. SETS
    model.Players = pyo.Set(initialize=players)
    model.Clubs = pyo.Set(initialize=clubs)
    
    # 4. PARAMETERS
    model.Points = pyo.Param(model.Players, initialize=points)
    model.MaxApps = pyo.Param(model.Players, initialize=max_apps)
    model.Capacity = pyo.Param(model.Clubs, initialize=capacities)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.Players, model.Clubs, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.Points[i] * model.x[i, j] for i in model.Players for j in model.Clubs)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Player Application Limit
    def player_app_limit_rule(model, i):
        return sum(model.x[i, j] for j in model.Clubs) <= model.MaxApps[i]
    model.player_app_limit = pyo.Constraint(model.Players, rule=player_app_limit_rule)
    
    # Club Capacity Limit
    def club_capacity_rule(model, j):
        return sum(model.x[i, j] for i in model.Players) <= model.Capacity[j]
    model.club_capacity = pyo.Constraint(model.Clubs, rule=club_capacity_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 players to clubs:")
        for i in model.Players:
            for j in model.Clubs:
                x_val = pyo.value(model.x[i, j])
                if x_val > 0.5:  # Only print assignments
                    print(f"Player {i} assigned to Club {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
sports_competition_optimization()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 140.0
**Execution Time**: 1.84 seconds
**Reliability**: high
**Analysis**: Pyomo achieved an optimal solution with a moderate execution time, consistent with the other solvers, suggesting reliability.

## 8. Cross-Solver Analysis and Final Recommendation

### Solver Results Comparison

| Solver | Status | Optimal Value | Execution Time | Decision Variables | Retry Attempt |
|--------|--------|---------------|----------------|-------------------|---------------|
| Gurobipy | OPTIMAL | 140.00 | 0.74s | N/A | N/A |
| Docplex | OPTIMAL | 140.00 | 5.28s | N/A | N/A |
| Pyomo | OPTIMAL | 140.00 | 1.84s | N/A | N/A |

### Solver Consistency Analysis
**Result**: All solvers produced consistent results ✓
**Consistent Solvers**: gurobipy, docplex, pyomo
**Majority Vote Optimal Value**: 140.0

### Final Recommendation
**Recommended Optimal Value**: 140.0
**Confidence Level**: HIGH
**Preferred Solver(s)**: gurobipy
**Reasoning**: Gurobipy is recommended due to its fastest execution time and consistent results, making it the most efficient choice for this problem.

### Business Interpretation
**Overall Strategy**: The optimal assignment of players to clubs maximizes the total points scored, ensuring the best possible performance for the clubs.
**Objective Value Meaning**: The optimal objective value of 140.0 represents the maximum total points that can be achieved by optimally assigning players to clubs.
**Resource Allocation Summary**: Players should be allocated to clubs in a way that maximizes the total points scored, adhering to player application limits and club capacity constraints.
**Implementation Recommendations**: Implement the solution by assigning players to clubs based on the optimal decision variables, ensuring compliance with all constraints.