# Complete Optimization Problem and Solution: architecture

## 1. Problem Context and Goals

### Context  
An architectural firm is focused on optimizing the allocation of its architects to various projects, specifically bridges and mills. The firm aims to make strategic decisions regarding which architects are assigned to which projects, with the decision variables being binary indicators: x_ij for bridge assignments and y_ik for mill assignments. The operational goal is to maximize the total length of bridges constructed and the number of mills designed. This is achieved by leveraging the firm's resources efficiently, ensuring that each architect does not exceed their capacity to handle projects. The business configuration includes a maximum number of projects an architect can handle, which serves as a constraint to ensure workload balance. Additionally, the total number of mills being designed is considered to align with the firm's strategic focus on mill projects. The firm uses current operational data to inform these decisions, ensuring that the optimization process is grounded in realistic business scenarios. The constraints are linear, focusing on resource limitations and project assignments, avoiding any nonlinear relationships.

### Goals  
The primary goal of the optimization process is to maximize the firm's output in terms of bridge lengths and mill designs. The metric for optimization is the combined total of the lengths of bridges and the number of mills designed, weighted by their respective decision variables. Success is measured by the ability to allocate architects in a way that maximizes these outputs, using the available data and business configuration parameters. The optimization goal is clearly defined in linear terms, focusing on maximizing the sum of the lengths of bridges and the number of mills designed, without involving complex mathematical expressions.

## 2. Constraints    

The optimization process is subject to several key constraints that ensure the feasibility and efficiency of project assignments:

- Each architect can handle a limited number of projects, with the total number of bridge and mill assignments for each architect not exceeding the maximum capacity defined in the business configuration.
- Every bridge project must be assigned to exactly one architect, ensuring that all bridge projects are covered without overlap.
- Similarly, each mill project must be assigned to exactly one architect, guaranteeing that all mill projects are adequately managed.

These constraints are expressed in straightforward business terms, aligning with the linear mathematical formulation required for the optimization process.

## 3. Available Data  

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

CREATE TABLE bridge (
  bridge_id INTEGER,
  length_meters FLOAT,
  architect_id INTEGER
);

CREATE TABLE architect_assignments (
  architect_id INTEGER,
  bridge_id INTEGER,
  mill_id INTEGER
);

CREATE TABLE mills (
  mill_id INTEGER,
  designed BOOLEAN
);
```

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

- **Bridge Table**: This table stores information about each bridge project, including its unique identifier, length in meters, and the architect assigned to it. The length of the bridge serves as a coefficient in the objective function, contributing to the optimization goal of maximizing bridge lengths.

- **Architect Assignments Table**: This table tracks the assignments of architects to both bridge and mill projects. It includes identifiers for architects, bridges, and mills, serving as the basis for the decision variables in the optimization model. The binary nature of these assignments aligns with the decision variables x_ij and y_ik.

- **Mills Table**: This table contains information about mill projects, specifically whether a mill has been designed. The designed status acts as an indicator in the objective function, contributing to the optimization goal of maximizing the number of mills designed.

### Current Stored Values  
```sql
-- Iteration 1 Realistic Data
-- Generated by triple expert (business + data + optimization)
-- Values were determined based on typical project sizes and architect workloads in the industry, ensuring a balance between bridge lengths and mill designs to maximize the objective function.

-- Realistic data for bridge
INSERT INTO bridge (bridge_id, length_meters, architect_id) VALUES (1, 150.0, 1);
INSERT INTO bridge (bridge_id, length_meters, architect_id) VALUES (2, 250.0, 2);
INSERT INTO bridge (bridge_id, length_meters, architect_id) VALUES (3, 180.0, 3);

-- Realistic data for architect_assignments
INSERT INTO architect_assignments (architect_id, bridge_id, mill_id) VALUES (1, 1, 1);
INSERT INTO architect_assignments (architect_id, bridge_id, mill_id) VALUES (2, 2, 2);
INSERT INTO architect_assignments (architect_id, bridge_id, mill_id) VALUES (3, 3, 3);

-- Realistic data for mills
INSERT INTO mills (mill_id, designed) VALUES (1, True);
INSERT INTO mills (mill_id, designed) VALUES (2, True);
INSERT INTO mills (mill_id, designed) VALUES (3, False);
```

## 4. Mathematical Optimization Formulation

#### Decision Variables
- \( x_{ij} \): Binary variable indicating whether architect \( i \) is assigned to bridge project \( j \). \( x_{ij} = 1 \) if assigned, 0 otherwise.
- \( y_{ik} \): Binary variable indicating whether architect \( i \) is assigned to mill project \( k \). \( y_{ik} = 1 \) if assigned, 0 otherwise.

#### Objective Function
Maximize the total output, which is the sum of the lengths of bridges and the number of mills designed:

\[
\text{Maximize } Z = \sum_{j} \text{length\_meters}_j \times x_{ij} + \sum_{k} \text{designed}_k \times y_{ik}
\]

Where:
- \(\text{length\_meters}_j\) is the length of bridge \( j \) from the `bridge` table.
- \(\text{designed}_k\) is a binary indicator from the `mills` table, where 1 indicates the mill is designed.

#### Constraints
1. **Architect Capacity Constraint**: Each architect can handle a limited number of projects (both bridges and mills combined). Let \( C_i \) be the maximum number of projects architect \( i \) can handle.

   \[
   \sum_{j} x_{ij} + \sum_{k} y_{ik} \leq C_i \quad \forall i
   \]

2. **Bridge Assignment Constraint**: Each bridge project must be assigned to exactly one architect.

   \[
   \sum_{i} x_{ij} = 1 \quad \forall j
   \]

3. **Mill Assignment Constraint**: Each mill project must be assigned to exactly one architect.

   \[
   \sum_{i} y_{ik} = 1 \quad \forall k
   \]

Data Source Verification:
- \(\text{length\_meters}_j\) is sourced from `bridge.length_meters`.
- \(\text{designed}_k\) is sourced from `mills.designed`.
- Architect capacity \( C_i \) is a business configuration parameter not explicitly provided in the data but assumed to be known from the firm's operational guidelines.

This formulation provides a complete linear model that can be solved using standard LP/MIP solvers to determine the optimal assignment of architects to projects, maximizing the firm's output in terms of bridge lengths and mill designs.

## 5. Gurobipy Implementation

```python
# Complete GUROBIPY implementation

import gurobipy as gp
from gurobipy import GRB

def optimize_architect_assignments():
    """Optimize architect assignments to maximize bridge lengths and mill designs."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("architect_assignment")
    
    # Data from the problem context
    bridge_lengths = [150.0, 250.0, 180.0]  # Lengths of bridges
    mill_designed = [1, 1, 0]  # Binary indicators for mills designed
    max_projects_per_architect = 2  # Example capacity constraint for each architect
    
    n_bridges = len(bridge_lengths)
    n_mills = len(mill_designed)
    n_architects = 3  # Assuming 3 architects based on data
    
    # CRITICAL: Validate array lengths before loops
    assert len(bridge_lengths) == n_bridges, "Bridge lengths array length mismatch"
    assert len(mill_designed) == n_mills, "Mill designed array length mismatch"
    
    # 2. VARIABLES
    # Decision variables for bridge assignments
    x = model.addVars(n_architects, n_bridges, vtype=GRB.BINARY, name="x")
    
    # Decision variables for mill assignments
    y = model.addVars(n_architects, n_mills, vtype=GRB.BINARY, name="y")
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the total output: sum of bridge lengths and number of mills designed
    model.setObjective(
        gp.quicksum(bridge_lengths[j] * x[i, j] for i in range(n_architects) for j in range(n_bridges)) +
        gp.quicksum(mill_designed[k] * y[i, k] for i in range(n_architects) for k in range(n_mills)),
        GRB.MAXIMIZE
    )
    
    # 4. CONSTRAINTS
    
    # Architect capacity constraint
    model.addConstrs(
        (gp.quicksum(x[i, j] for j in range(n_bridges)) + gp.quicksum(y[i, k] for k in range(n_mills)) <= max_projects_per_architect
         for i in range(n_architects)), name="architect_capacity"
    )
    
    # Bridge assignment constraint
    model.addConstrs(
        (gp.quicksum(x[i, j] for i in range(n_architects)) == 1 for j in range(n_bridges)), name="bridge_assignment"
    )
    
    # Mill assignment constraint
    model.addConstrs(
        (gp.quicksum(y[i, k] for i in range(n_architects)) == 1 for k in range(n_mills)), name="mill_assignment"
    )
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in range(n_architects):
            for j in range(n_bridges):
                if x[i, j].x > 1e-6:
                    print(f"x[{i},{j}] = {x[i, j].x:.3f}")
            for k in range(n_mills):
                if y[i, k].x > 1e-6:
                    print(f"y[{i},{k}] = {y[i, k].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_architect_assignments()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 582.0
**Execution Time**: 1.61 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 optimize_architect_assignments():
    # 1. MODEL & DATA SETUP
    mdl = Model(name="architect_assignment")
    
    # Data from the problem context
    bridge_lengths = [150.0, 250.0, 180.0]  # Lengths of bridges
    mill_designed = [1, 1, 0]  # Binary indicator if mill is designed
    architect_capacity = [2, 2, 2]  # Maximum projects each architect can handle
    
    n_bridges = len(bridge_lengths)
    n_mills = len(mill_designed)
    n_architects = len(architect_capacity)
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert n_bridges == n_mills == n_architects, "Array length mismatch"
    safe_range = range(min(n_bridges, n_mills, n_architects))  # Safe indexing
    
    # 2. VARIABLES
    x = {(i, j): mdl.binary_var(name=f"x_{i}_{j}") for i in safe_range for j in safe_range}
    y = {(i, k): mdl.binary_var(name=f"y_{i}_{k}") for i in safe_range for k in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    objective = mdl.sum(bridge_lengths[j] * x[i, j] for i in safe_range for j in safe_range) + \
                mdl.sum(mill_designed[k] * y[i, k] for i in safe_range for k in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    
    # Architect Capacity Constraint
    for i in safe_range:
        mdl.add_constraint(mdl.sum(x[i, j] for j in safe_range) + mdl.sum(y[i, k] for k in safe_range) <= architect_capacity[i], ctname=f"capacity_{i}")
    
    # Bridge Assignment Constraint
    for j in safe_range:
        mdl.add_constraint(mdl.sum(x[i, j] for i in safe_range) == 1, ctname=f"bridge_assignment_{j}")
    
    # Mill Assignment Constraint
    for k in safe_range:
        mdl.add_constraint(mdl.sum(y[i, k] for i in safe_range) == 1, ctname=f"mill_assignment_{k}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            for j in safe_range:
                if solution.get_value(x[i, j]) > 1e-6:
                    print(f"x[{i},{j}] = {solution.get_value(x[i, j]):.3f}")
            for k in safe_range:
                if solution.get_value(y[i, k]) > 1e-6:
                    print(f"y[{i},{k}] = {solution.get_value(y[i, k]):.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")

    return mdl

# Run the optimization
optimize_architect_assignments()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 582.0
**Execution Time**: 8.62 seconds
**Reliability**: high
**Analysis**: DOCplex also found an 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_architect_assignments():
    """Optimize architect assignments to bridge and mill projects"""

    # 1. MODEL CREATION
    model = pyo.ConcreteModel()

    # 2. DATA SETUP
    # Example data based on the problem context
    bridge_lengths = {1: 150.0, 2: 250.0, 3: 180.0}
    mill_designed = {1: 1, 2: 1, 3: 0}
    architect_capacity = {1: 2, 2: 2, 3: 2}  # Example capacities

    # Validate data lengths
    assert len(bridge_lengths) == len(mill_designed), "Data length mismatch"

    # 3. SETS
    model.I = pyo.Set(initialize=[1, 2, 3])  # Architects
    model.J = pyo.Set(initialize=bridge_lengths.keys())  # Bridges
    model.K = pyo.Set(initialize=mill_designed.keys())  # Mills

    # 4. PARAMETERS
    model.length_meters = pyo.Param(model.J, initialize=bridge_lengths)
    model.designed = pyo.Param(model.K, initialize=mill_designed)
    model.capacity = pyo.Param(model.I, initialize=architect_capacity)

    # 5. VARIABLES
    model.x = pyo.Var(model.I, model.J, within=pyo.Binary)
    model.y = pyo.Var(model.I, model.K, within=pyo.Binary)

    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.length_meters[j] * model.x[i, j] for i in model.I for j in model.J) + \
               sum(model.designed[k] * model.y[i, k] for i in model.I for k in model.K)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)

    # 7. CONSTRAINTS

    # Architect Capacity Constraint
    def capacity_rule(model, i):
        return sum(model.x[i, j] for j in model.J) + sum(model.y[i, k] for k in model.K) <= model.capacity[i]
    model.capacity_constraint = pyo.Constraint(model.I, rule=capacity_rule)

    # Bridge Assignment Constraint
    def bridge_assignment_rule(model, j):
        return sum(model.x[i, j] for i in model.I) == 1
    model.bridge_assignment_constraint = pyo.Constraint(model.J, rule=bridge_assignment_rule)

    # Mill Assignment Constraint
    def mill_assignment_rule(model, k):
        return sum(model.y[i, k] for i in model.I) == 1
    model.mill_assignment_constraint = pyo.Constraint(model.K, rule=mill_assignment_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)

    # 9. RESULT PROCESSING
    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 values:")
        for i in model.I:
            for j in model.J:
                x_val = pyo.value(model.x[i, j])
                if x_val > 1e-6:
                    print(f"x[{i},{j}] = {int(x_val)}")
            for k in model.K:
                y_val = pyo.value(model.y[i, k])
                if y_val > 1e-6:
                    print(f"y[{i},{k}] = {int(y_val)}")

    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_architect_assignments()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 582.0
**Execution Time**: 2.53 seconds
**Reliability**: high
**Analysis**: Pyomo achieved the optimal solution with a moderate execution time, demonstrating reliability and consistency with other solvers.

## 8. Cross-Solver Analysis and Final Recommendation

### Solver Results Comparison

| Solver | Status | Optimal Value | Execution Time | Decision Variables | Retry Attempt |
|--------|--------|---------------|----------------|-------------------|---------------|
| Gurobipy | OPTIMAL | 582.00 | 1.61s | N/A | N/A |
| Docplex | OPTIMAL | 582.00 | 8.62s | N/A | N/A |
| Pyomo | OPTIMAL | 582.00 | 2.53s | N/A | N/A |

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

### Final Recommendation
**Recommended Optimal Value**: 582.0
**Confidence Level**: HIGH
**Preferred Solver(s)**: gurobipy
**Reasoning**: Gurobipy is recommended due to its fastest execution time and high reliability, making it suitable for time-sensitive applications.

### Business Interpretation
**Overall Strategy**: The optimal assignment maximizes the total output of bridge lengths and mill designs, ensuring efficient use of architect resources.
**Objective Value Meaning**: The optimal objective value of 582.0 represents the maximum achievable output in terms of total bridge lengths and mill designs, reflecting the firm's capacity to handle projects efficiently.
**Resource Allocation Summary**: Architects are optimally assigned to projects, ensuring each project is handled by exactly one architect while respecting capacity constraints.
**Implementation Recommendations**: Implement the solution by assigning architects to projects as per the optimal decision variables, ensuring adherence to capacity constraints and maximizing project output.