## 4. Mathematical Optimization Formulation

#### Decision Variables
- Let \( x_1, x_2, x_3 \) be the production quantities for products 1, 2, and 3, respectively. These are continuous decision variables representing the number of units to produce for each product.

#### Objective Function
Maximize total revenue:
\[ \text{Maximize } Z = 12.99x_1 + 18.49x_2 + 22.00x_3 \]

Data Source Verification:
- Coefficients 12.99, 18.49, and 22.00 are derived from `Products.Price`.

#### Constraints
1. Total production capacity constraint:
   \[ x_1 + x_2 + x_3 \leq 5000 + 7000 + 8000 = 20000 \]

2. Manufacturer-specific capacity constraints:
   - For Manufacturer 1:
     \[ x_1 \leq 5000 \]
   - For Manufacturer 2:
     \[ x_2 \leq 7000 \]
   - For Manufacturer 3:
     \[ x_3 \leq 8000 \]

Data Source Verification:
- The total production capacity constraint is derived from the sum of `Manufacturers.Capacity`.
- Individual manufacturer capacity constraints are derived from `Manufacturers.Capacity` for each respective manufacturer.

This linear model is immediately solvable using standard linear programming techniques, ensuring that the production quantities are optimized to maximize revenue while respecting the capacity constraints of each manufacturer.

## 5. Gurobipy Implementation

```python
# Complete GUROBIPY implementation

import gurobipy as gp
from gurobipy import GRB

def optimize_production():
    """Optimize production quantities to maximize revenue"""

    # 1. MODEL & DATA SETUP
    model = gp.Model("manufactory_1")
    
    # Prices and capacities from the database
    prices = [12.99, 18.49, 22.00]
    manufacturer_capacities = [5000, 7000, 8000]
    total_capacity = sum(manufacturer_capacities)
    
    # CRITICAL: Validate array lengths before loops
    n_products = len(prices)
    assert len(manufacturer_capacities) == n_products, "Array length mismatch"
    
    # 2. VARIABLES
    # Variable dictionaries for production quantities
    x = {i: model.addVar(vtype=GRB.CONTINUOUS, name=f"x_{i+1}", lb=0) 
         for i in range(n_products)}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total revenue
    model.setObjective(gp.quicksum(prices[i] * x[i] for i in range(n_products)), GRB.MAXIMIZE)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Total production capacity constraint
    model.addConstr(gp.quicksum(x[i] for i in range(n_products)) <= total_capacity, name="total_capacity")
    
    # Manufacturer-specific capacity constraints
    for i in range(n_products):
        model.addConstr(x[i] <= manufacturer_capacities[i], name=f"capacity_{i+1}")
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in range(n_products):
            if x[i].x > 1e-6:
                print(f"x[{i+1}] = {x[i].x:.3f}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

# Run the optimization
optimize_production()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 370380.0
**Execution Time**: 2.49 seconds
**Reliability**: high
**Analysis**: Gurobipy found an optimal solution quickly with a reliable execution time, indicating high efficiency and accuracy.

## 6. DOCplex Implementation

```python
# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_production():
    """Optimize production quantities to maximize revenue"""

    # 1. MODEL & DATA SETUP
    mdl = Model(name="manufactory_1")
    
    # Data from the problem context
    prices = [12.99, 18.49, 22.00]
    capacities = [5000, 7000, 8000]
    total_capacity = sum(capacities)
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(prices) == len(capacities) == 3, "Array length mismatch"
    safe_range = range(min(len(prices), len(capacities)))  # Safe indexing
    
    # 2. VARIABLES
    # Variable dictionaries for production quantities
    x = {i: mdl.continuous_var(name=f"x_{i+1}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total revenue
    objective = mdl.sum(prices[i] * x[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Total production capacity constraint
    total_production = mdl.sum(x[i] for i in safe_range)
    mdl.add_constraint(total_production <= total_capacity, ctname="total_capacity")
    
    # Manufacturer-specific capacity constraints
    for i in safe_range:
        mdl.add_constraint(x[i] <= capacities[i], ctname=f"capacity_{i+1}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value:.2f}")
        for i in safe_range:
            value = solution.get_value(x[i])
            if value > 1e-6:
                print(f"x[{i+1}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
optimize_production()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 370380.0
**Execution Time**: 6.98 seconds
**Reliability**: high
**Analysis**: DOCplex also found the optimal solution, albeit with a longer execution time compared to Gurobipy, but still reliable.

## 7. Pyomo Implementation

```python
# Complete PYOMO implementation

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

def optimize_production():
    """Optimize production quantities to maximize revenue"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Prices and capacities from the database
    prices = [12.99, 18.49, 22.00]
    capacities = [5000, 7000, 8000]
    total_capacity = sum(capacities)
    
    # CRITICAL: Validate array lengths before indexing
    n_products = len(prices)
    assert len(capacities) == n_products, "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.RangeSet(1, n_products)  # 1-based indexing
    
    # 4. PARAMETERS
    model.price = pyo.Param(model.I, initialize={i+1: prices[i] for i in range(n_products)})
    model.capacity = pyo.Param(model.I, initialize={i+1: capacities[i] for i in range(n_products)})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.price[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Total production capacity constraint
    def total_capacity_rule(model):
        return sum(model.x[i] for i in model.I) <= total_capacity
    model.total_capacity_constraint = pyo.Constraint(rule=total_capacity_rule)
    
    # Manufacturer-specific capacity constraints
    def capacity_rule(model, i):
        return model.x[i] <= model.capacity[i]
    model.capacity_constraint = pyo.Constraint(model.I, rule=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):.2f}")
        
        # Extract variable values
        print("\nVariable values:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"x[{i}] = {x_val:.3f}")
        
    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
optimize_production()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 370380.0
**Execution Time**: 6.74 seconds
**Reliability**: high
**Analysis**: Pyomo achieved the optimal solution with a similar execution time to DOCplex, confirming the solution's reliability.

## 8. Cross-Solver Analysis and Final Recommendation

### Solver Results Comparison

| Solver | Status | Optimal Value | Execution Time | Decision Variables | Retry Attempt |
|--------|--------|---------------|----------------|-------------------|---------------|
| Gurobipy | OPTIMAL | 370380.00 | 2.49s | N/A | N/A |
| Docplex | OPTIMAL | 370380.00 | 6.98s | N/A | N/A |
| Pyomo | OPTIMAL | 370380.00 | 6.74s | N/A | N/A |

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

### Final Recommendation
**Recommended Optimal Value**: 370380.0
**Confidence Level**: HIGH
**Preferred Solver(s)**: gurobipy
**Reasoning**: Gurobipy is preferred due to its faster execution time while maintaining accuracy and reliability.

### Optimal Decision Variables
- **x_1** = 5000.000
  - *Business Meaning*: Produce 7000 units of product 2, fully utilizing Manufacturer 2's capacity.
- **x_2** = 7000.000
  - *Business Meaning*: Produce 8000 units of product 3, fully utilizing Manufacturer 3's capacity.
- **x_3** = 8000.000
  - *Business Meaning*: Resource allocation for x_3

### Business Interpretation
**Overall Strategy**: The optimal production plan maximizes revenue by fully utilizing each manufacturer's capacity.
**Objective Value Meaning**: The optimal objective value of 370380.0 represents the maximum achievable revenue given the production constraints.
**Resource Allocation Summary**: All available manufacturing capacity is utilized to achieve maximum revenue.
**Implementation Recommendations**: Implement the production plan by coordinating with each manufacturer to ensure full capacity utilization and timely production.