# Complete Optimization Problem and Solution: body_builder

## 1. Problem Context and Goals

### Context  
A bodybuilding competition organizer is tasked with selecting a team of bodybuilders to compete in an upcoming event. The goal is to assemble a team that maximizes the total performance score based on the bodybuilders' Snatch and Clean & Jerk scores. The selection process must adhere to specific operational constraints to ensure the team meets diversity and physical criteria.  

The organizer must decide which bodybuilders to include in the team, represented by a binary decision for each individual. The total number of bodybuilders in the team cannot exceed a predefined limit, ensuring the team remains manageable and diverse. Additionally, the team must meet a minimum average height requirement of 170 cm and a maximum average weight requirement of 100 kg. These constraints ensure the team aligns with the competition's physical standards.  

The performance scores for each bodybuilder are derived from their Snatch and Clean & Jerk results, which are stored in the database. The physical attributes of height and weight are also recorded and used to enforce the team's physical criteria. The business configuration includes a maximum team size limit of 5 bodybuilders, a minimum average height requirement, and a maximum average weight requirement, all of which are critical to the selection process.  

### Goals  
The primary goal of this optimization problem is to maximize the total performance score of the selected team. This score is calculated as the sum of the Snatch and Clean & Jerk scores of the chosen bodybuilders. Success is measured by achieving the highest possible total score while adhering to the constraints on team size, average height, and average weight.  

## 2. Constraints  

The selection of bodybuilders for the team must respect the following constraints:  
1. **Team Size Limit**: The total number of bodybuilders selected for the team must not exceed the predefined limit of 5. This ensures the team remains manageable and diverse.  
2. **Minimum Average Height**: The average height of the selected bodybuilders must be at least 170 cm. This ensures the team meets the competition's physical standards for height.  
3. **Maximum Average Weight**: The average weight of the selected bodybuilders must not exceed 100 kg. This ensures the team aligns with the competition's physical standards for weight.  

These constraints are designed to ensure the team is both competitive and compliant with the competition's requirements.  

## 3. Available Data  

### Database Schema  
```sql
-- Iteration 1 Database Schema
-- Objective: Schema changes include adding a table for decision variables and updating configuration logic to handle team size constraints and business metrics.

CREATE TABLE body_builder (
  Snatch FLOAT,
  Clean_Jerk FLOAT
);

CREATE TABLE people (
  Height FLOAT,
  Weight FLOAT
);

CREATE TABLE team_selection (
  is_selected BOOLEAN
);
```

### Data Dictionary  
- **body_builder Table**:  
  - **Snatch**: The Snatch score of a bodybuilder, used to calculate the total performance score.  
  - **Clean_Jerk**: The Clean & Jerk score of a bodybuilder, used to calculate the total performance score.  

- **people Table**:  
  - **Height**: The height of a bodybuilder in centimeters, used to enforce the minimum average height constraint.  
  - **Weight**: The weight of a bodybuilder in kilograms, used to enforce the maximum average weight constraint.  

- **team_selection Table**:  
  - **is_selected**: A binary indicator of whether a bodybuilder is selected for the team, representing the decision variable in the optimization model.  

### Current Stored Values  
```sql
-- Iteration 1 Realistic Data
-- Generated by triple expert (business + data + optimization)
-- Values were determined based on typical bodybuilding competition data, ensuring realistic performance scores and physical attributes. The data was generated to respect the constraints and enable a meaningful optimization problem.

-- Realistic data for body_builder
INSERT INTO body_builder (Snatch, Clean_Jerk) VALUES (150.5, 200.0);
INSERT INTO body_builder (Snatch, Clean_Jerk) VALUES (160.0, 210.5);
INSERT INTO body_builder (Snatch, Clean_Jerk) VALUES (170.5, 220.0);

-- Realistic data for people
INSERT INTO people (Height, Weight) VALUES (175.0, 90.0);
INSERT INTO people (Height, Weight) VALUES (180.0, 95.0);
INSERT INTO people (Height, Weight) VALUES (185.0, 100.0);

-- Realistic data for team_selection
INSERT INTO team_selection (is_selected) VALUES (True);
INSERT INTO team_selection (is_selected) VALUES (False);
INSERT INTO team_selection (is_selected) VALUES (True);
```

## 4. Mathematical Optimization Formulation

#### Decision Variables
- Let \( x_i \) be a binary decision variable where:
  - \( x_i = 1 \) if bodybuilder \( i \) is selected for the team.
  - \( x_i = 0 \) otherwise.
  
  Here, \( i = 1, 2, 3 \) corresponds to the three bodybuilders in the database.

#### Objective Function
Maximize the total performance score:
\[
\text{Maximize } Z = 150.5x_1 + 160.0x_2 + 170.5x_3 + 200.0x_1 + 210.5x_2 + 220.0x_3
\]
Simplifying:
\[
\text{Maximize } Z = 350.5x_1 + 370.5x_2 + 390.5x_3
\]

#### Constraints
1. **Team Size Limit**:
\[
x_1 + x_2 + x_3 \leq 5
\]
2. **Minimum Average Height**:
\[
175.0x_1 + 180.0x_2 + 185.0x_3 \geq 170(x_1 + x_2 + x_3)
\]
Simplifying:
\[
5.0x_1 + 10.0x_2 + 15.0x_3 \geq 0
\]
3. **Maximum Average Weight**:
\[
90.0x_1 + 95.0x_2 + 100.0x_3 \leq 100(x_1 + x_2 + x_3)
\]
Simplifying:
\[
-10.0x_1 - 5.0x_2 + 0.0x_3 \leq 0
\]

#### Data Source Verification
- **Objective Function Coefficients**:
  - \( 150.5, 160.0, 170.5 \) from `body_builder.Snatch`.
  - \( 200.0, 210.5, 220.0 \) from `body_builder.Clean_Jerk`.
  
- **Constraint Coefficients**:
  - **Height**: \( 175.0, 180.0, 185.0 \) from `people.Height`.
  - **Weight**: \( 90.0, 95.0, 100.0 \) from `people.Weight`.
  
- **Team Size Limit**: The constant \( 5 \) is derived from the business configuration.

This formulation is a complete, immediately solvable Linear Programming (LP) model with all numerical coefficients derived from the provided data.

## 5. Gurobipy Implementation

```python
#!/usr/bin/env python3
"""
Gurobipy 12.0.2 Implementation for Bodybuilder Team Selection Problem
"""

import gurobipy as gp
from gurobipy import GRB

def bodybuilder_optimization():
    """Optimization model for selecting bodybuilders to maximize performance score."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("bodybuilder_selection")
    
    # Data from the database
    snatch_scores = [150.5, 160.0, 170.5]
    clean_jerk_scores = [200.0, 210.5, 220.0]
    heights = [175.0, 180.0, 185.0]
    weights = [90.0, 95.0, 100.0]
    
    # Number of bodybuilders
    n_bodybuilders = len(snatch_scores)
    
    # CRITICAL: Validate array lengths before loops
    assert len(snatch_scores) == len(clean_jerk_scores) == len(heights) == len(weights) == n_bodybuilders, "Array length mismatch"
    
    # 2. VARIABLES
    # Binary decision variables for selecting bodybuilders
    x = {i: model.addVar(vtype=GRB.BINARY, name=f"x_{i}") for i in range(n_bodybuilders)}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the total performance score
    total_score = gp.quicksum((snatch_scores[i] + clean_jerk_scores[i]) * x[i] for i in range(n_bodybuilders))
    model.setObjective(total_score, GRB.MAXIMIZE)
    
    # 4. CONSTRAINTS
    
    # Team Size Limit: Total number of bodybuilders selected <= 5
    model.addConstr(gp.quicksum(x[i] for i in range(n_bodybuilders)) <= 5, name="team_size_limit")
    
    # Minimum Average Height: Average height of selected bodybuilders >= 170 cm
    model.addConstr(gp.quicksum(heights[i] * x[i] for i in range(n_bodybuilders)) >= 170 * gp.quicksum(x[i] for i in range(n_bodybuilders)), name="min_avg_height")
    
    # Maximum Average Weight: Average weight of selected bodybuilders <= 100 kg
    model.addConstr(gp.quicksum(weights[i] * x[i] for i in range(n_bodybuilders)) <= 100 * gp.quicksum(x[i] for i in range(n_bodybuilders)), name="max_avg_weight")
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in range(n_bodybuilders):
            if x[i].x > 0.5:
                print(f"Bodybuilder {i} is selected.")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

# Execute the optimization
if __name__ == "__main__":
    bodybuilder_optimization()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 1111.5
**Execution Time**: 0.17 seconds
**Reliability**: high
**Analysis**: Gurobipy achieved the optimal solution efficiently with the fastest execution time.

## 6. DOCplex Implementation

```python
#!/usr/bin/env python3
"""
DOCPLEX Implementation for Bodybuilder Team Selection Problem
"""

from docplex.mp.model import Model

def bodybuilder_team_selection():
    """Optimization model to select a team of bodybuilders maximizing performance score."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="bodybuilder_team_selection")
    
    # Data from the database
    snatch_scores = [150.5, 160.0, 170.5]
    clean_jerk_scores = [200.0, 210.5, 220.0]
    heights = [175.0, 180.0, 185.0]
    weights = [90.0, 95.0, 100.0]
    
    # Business configuration
    max_team_size = 5
    min_avg_height = 170.0
    max_avg_weight = 100.0
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(snatch_scores) == len(clean_jerk_scores) == len(heights) == len(weights), "Array length mismatch"
    safe_range = range(min(len(snatch_scores), len(clean_jerk_scores), len(heights), len(weights)))  # Safe indexing
    
    # 2. VARIABLES
    # Binary decision variables for each bodybuilder
    x = {i: mdl.binary_var(name=f"x_{i}") for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the total performance score
    total_score = mdl.sum((snatch_scores[i] + clean_jerk_scores[i]) * x[i] for i in safe_range)
    mdl.maximize(total_score)
    
    # 4. CONSTRAINTS
    
    # Team Size Limit
    team_size = mdl.sum(x[i] for i in safe_range)
    mdl.add_constraint(team_size <= max_team_size, ctname="team_size_limit")
    
    # Minimum Average Height
    total_height = mdl.sum(heights[i] * x[i] for i in safe_range)
    mdl.add_constraint(total_height >= min_avg_height * team_size, ctname="min_avg_height")
    
    # Maximum Average Weight
    total_weight = mdl.sum(weights[i] * x[i] for i in safe_range)
    mdl.add_constraint(total_weight <= max_avg_weight * team_size, ctname="max_avg_weight")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(x[i])
            if value > 1e-6:
                print(f"Bodybuilder {i} selected: {value:.0f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Execute the optimization model
if __name__ == "__main__":
    bodybuilder_team_selection()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 1111.5
**Execution Time**: 1.06 seconds
**Reliability**: high
**Analysis**: DOCplex also achieved the optimal solution but with a longer execution time compared to Gurobipy.

## 7. Pyomo Implementation

```python
#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Bodybuilder Team Selection Problem
"""

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

def bodybuilder_optimization():
    """Optimization model for selecting bodybuilders to maximize performance score."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Performance scores (Snatch + Clean & Jerk)
    performance_scores = [350.5, 370.5, 390.5]
    
    # Physical attributes
    heights = [175.0, 180.0, 185.0]
    weights = [90.0, 95.0, 100.0]
    
    # Number of bodybuilders
    n_bodybuilders = len(performance_scores)
    
    # CRITICAL: Validate array lengths before indexing
    assert len(performance_scores) == len(heights) == len(weights) == n_bodybuilders, "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.RangeSet(1, n_bodybuilders)  # 1-based indexing
    
    # 4. PARAMETERS (data containers)
    model.performance = pyo.Param(model.I, initialize={i+1: performance_scores[i] for i in range(n_bodybuilders)})
    model.height = pyo.Param(model.I, initialize={i+1: heights[i] for i in range(n_bodybuilders)})
    model.weight = pyo.Param(model.I, initialize={i+1: weights[i] for i in range(n_bodybuilders)})
    
    # 5. VARIABLES
    # Binary decision variables
    model.x = pyo.Var(model.I, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.performance[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Team Size Limit
    def team_size_rule(model):
        return sum(model.x[i] for i in model.I) <= 5
    model.team_size_constraint = pyo.Constraint(rule=team_size_rule)
    
    # Minimum Average Height
    def min_height_rule(model):
        return sum(model.height[i] * model.x[i] for i in model.I) >= 170 * sum(model.x[i] for i in model.I)
    model.min_height_constraint = pyo.Constraint(rule=min_height_rule)
    
    # Maximum Average Weight
    def max_weight_rule(model):
        return sum(model.weight[i] * model.x[i] for i in model.I) <= 100 * sum(model.x[i] for i in model.I)
    model.max_weight_constraint = pyo.Constraint(rule=max_weight_rule)
    
    # 8. SOLVING WITH GUROBI (your available solver)
    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("\nSelected bodybuilders:")
        for i in model.I:
            if pyo.value(model.x[i]) > 0.5:  # Only print selected bodybuilders
                print(f"Bodybuilder {i} is selected.")
        
    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__":
    bodybuilder_optimization()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 1111.5
**Execution Time**: 0.78 seconds
**Reliability**: high
**Analysis**: Pyomo achieved the optimal solution with an execution time between Gurobipy and DOCplex.

## 8. Cross-Solver Analysis and Final Recommendation

### Solver Results Comparison

| Solver | Status | Optimal Value | Execution Time | Decision Variables | Retry Attempt |
|--------|--------|---------------|----------------|-------------------|---------------|
| Gurobipy | OPTIMAL | 1111.50 | 0.17s | N/A | N/A |
| Docplex | OPTIMAL | 1111.50 | 1.06s | N/A | N/A |
| Pyomo | OPTIMAL | 1111.50 | 0.78s | N/A | N/A |

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

### Final Recommendation
**Recommended Optimal Value**: 1111.5
**Confidence Level**: HIGH
**Preferred Solver(s)**: gurobipy
**Reasoning**: Gurobipy is recommended due to its fastest execution time while achieving the same optimal solution as the other solvers.

### Optimal Decision Variables
- **x_1** = 1.000
  - *Business Meaning*: Bodybuilder 1 is selected for the team, contributing 350.5 to the total performance score.
- **x_2** = 1.000
  - *Business Meaning*: Bodybuilder 2 is selected for the team, contributing 370.5 to the total performance score.
- **x_3** = 1.000
  - *Business Meaning*: Bodybuilder 3 is selected for the team, contributing 390.5 to the total performance score.

### Business Interpretation
**Overall Strategy**: The optimal team includes all three bodybuilders, maximizing the total performance score while satisfying all constraints.
**Objective Value Meaning**: The total performance score of 1111.5 represents the maximum achievable performance given the constraints.
**Resource Allocation Summary**: All three bodybuilders should be selected for the team to maximize performance.
**Implementation Recommendations**: Proceed with selecting all three bodybuilders for the team. Ensure that the team size, height, and weight constraints are satisfied during implementation.