# Complete Optimization Problem and Solution: manufactory_1

## 1. Problem Context and Goals

### Context  
The manufacturing company is focused on optimizing its production strategy to maximize revenue from product sales. The primary decision involves determining the optimal number of units to produce for each product, which is directly linked to the production quantities stored in the database. The operational parameters are aligned with the goal of maximizing total revenue, calculated as the sum of the product of each product's price and its production quantity. The business configuration includes the total production capacity available across all manufacturers, which serves as a constraint in the optimization model. Additionally, each manufacturer has a specific maximum production capacity that must be respected. The context is framed to ensure that all business decisions and constraints naturally lead to a linear optimization formulation, avoiding any nonlinear relationships such as variable products or divisions. The business configuration parameters, including scalar values and logic formulas, are integrated into the decision-making process to ensure consistency and flexibility in production planning.

### Goals  
The primary goal of the optimization process is to maximize the total revenue generated from product sales. This is achieved by optimizing the production quantities for each product, ensuring that the total revenue, calculated as the sum of the product of each product's price and its production quantity, is maximized. Success is measured by the alignment of the optimization process with the expected coefficient sources, ensuring that the revenue is maximized within the given constraints. The goal is articulated in natural language to emphasize the linear nature of the optimization objective.

## 2. Constraints    

The optimization process is subject to several key constraints that ensure the feasibility of the production plan. The total production capacity available across all manufacturers is a critical constraint, ensuring that the combined production does not exceed the overall capacity. Each manufacturer also has a specific maximum production capacity, which must be adhered to in order to prevent overburdening any single manufacturer. These constraints are described in business terms that naturally lead to linear mathematical forms, ensuring that the optimization problem remains solvable within the defined parameters.

## 3. Available Data  

### Database Schema  
```sql
-- Iteration 1 Database Schema
-- Objective: Schema changes include creating new tables for missing optimization data and updating configuration logic for scalar parameters and formulas.

CREATE TABLE Products (
  Price FLOAT,
  ProductionQuantity FLOAT
);

CREATE TABLE ProductionQuantities (
  ProductID INTEGER,
  Quantity FLOAT
);

CREATE TABLE Manufacturers (
  ManufacturerID INTEGER,
  Capacity INTEGER
);
```

### Data Dictionary  
The data dictionary provides a comprehensive mapping of tables and columns to their business purposes and optimization roles. The "Products" table stores information about each product, including its price and the number of units to produce. This table plays a crucial role in determining the objective coefficients for revenue calculation. The "ProductionQuantities" table links each product to its production quantity, serving as a decision variable in the optimization process. The "Manufacturers" table contains data about each manufacturer's production capacity, which is used as a constraint bound in the optimization model. This business-oriented description ensures a clear connection to the expected linear mathematical formulation.

### Current Stored Values  
```sql
-- Iteration 1 Realistic Data
-- Generated by triple expert (business + data + optimization)
-- Values were determined based on typical manufacturing capacities and product pricing strategies to ensure a realistic and solvable optimization problem.

-- Realistic data for Products
INSERT INTO Products (Price, ProductionQuantity) VALUES (12.99, 150);
INSERT INTO Products (Price, ProductionQuantity) VALUES (18.49, 250);
INSERT INTO Products (Price, ProductionQuantity) VALUES (22.0, 200);

-- Realistic data for ProductionQuantities
INSERT INTO ProductionQuantities (ProductID, Quantity) VALUES (1, 150);
INSERT INTO ProductionQuantities (ProductID, Quantity) VALUES (2, 250);
INSERT INTO ProductionQuantities (ProductID, Quantity) VALUES (3, 200);

-- Realistic data for Manufacturers
INSERT INTO Manufacturers (ManufacturerID, Capacity) VALUES (1, 5000);
INSERT INTO Manufacturers (ManufacturerID, Capacity) VALUES (2, 7000);
INSERT INTO Manufacturers (ManufacturerID, Capacity) VALUES (3, 8000);
```

## 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.