## 4. Mathematical Optimization Formulation

#### Decision Variables
- \( x_{l,m} \): Binary decision variable indicating whether lens \( l \) is assigned to mountain \( m \).  
  \( x_{l,m} \in \{0, 1\} \) for all \( l \in L \), \( m \in M \).  

#### Objective Function
Minimize the total cost of selected lenses:  
\[
\text{Minimize } \sum_{l \in L} \sum_{m \in M} \text{cost}_l \cdot x_{l,m}
\]  
**Data Source Verification**:  
- \( \text{cost}_l \): `lenses.cost`  

#### Constraints
1. **Minimum Lenses per Mountain**: Each mountain must be assigned at least one lens.  
\[
\sum_{l \in L} x_{l,m} \geq 1 \quad \forall m \in M
\]  

2. **Maximum Lenses per Mountain**: No mountain can be assigned more than three lenses.  
\[
\sum_{l \in L} x_{l,m} \leq 3 \quad \forall m \in M
\]  

3. **Focal Length Requirement**: For each lens assigned to a mountain, the focal length must meet the minimum requirement.  
\[
\text{focal\_length}_l \cdot x_{l,m} \geq \text{minimum\_focal\_length}_m \cdot x_{l,m} \quad \forall l \in L, m \in M
\]  
**Data Source Verification**:  
- \( \text{focal\_length}_l \): `lenses.focal_length_mm`  
- \( \text{minimum\_focal\_length}_m \): `mountains.minimum_focal_length`  

4. **Aperture Requirement**: For each lens assigned to a mountain, the maximum aperture must meet the minimum requirement.  
\[
\text{max\_aperture}_l \cdot x_{l,m} \geq \text{minimum\_aperture}_m \cdot x_{l,m} \quad \forall l \in L, m \in M
\]  
**Data Source Verification**:  
- \( \text{max\_aperture}_l \): `lenses.max_aperture`  
- \( \text{minimum\_aperture}_m \): `mountains.minimum_aperture`  

#### Data Source Verification for Decision Variables
- \( x_{l,m} \): `lens_mountain_selection.selected`  

This formulation is a complete, immediately solvable LINEAR mathematical model with all numerical coefficients derived from the provided data.

## 5. Gurobipy Implementation

```python
#!/usr/bin/env python3
"""
Gurobipy implementation for the mountain_photos optimization problem.
"""

import gurobipy as gp
from gurobipy import GRB

def mountain_photos_optimization():
    """Optimize lens selection for photographing mountains."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("mountain_photos")
    
    # Data from the database schema
    lenses = [
        {'lens_id': 1, 'cost': 500.0, 'focal_length_mm': 24, 'max_aperture': 1.8},
        {'lens_id': 2, 'cost': 750.0, 'focal_length_mm': 50, 'max_aperture': 2.8},
        {'lens_id': 3, 'cost': 1000.0, 'focal_length_mm': 85, 'max_aperture': 4.0}
    ]
    
    mountains = [
        {'mountain_id': 1, 'minimum_focal_length': 24, 'minimum_aperture': 1.8},
        {'mountain_id': 2, 'minimum_focal_length': 50, 'minimum_aperture': 2.8},
        {'mountain_id': 3, 'minimum_focal_length': 85, 'minimum_aperture': 4.0}
    ]
    
    # CRITICAL: Validate array lengths before loops
    assert len(lenses) > 0, "No lenses provided"
    assert len(mountains) > 0, "No mountains provided"
    
    # 2. VARIABLES
    # Binary decision variables: x[l][m] = 1 if lens l is assigned to mountain m
    x = model.addVars(len(lenses), len(mountains), vtype=GRB.BINARY, name="x")
    
    # 3. OBJECTIVE FUNCTION
    # Minimize the total cost of selected lenses
    model.setObjective(
        gp.quicksum(lenses[l]['cost'] * x[l, m] for l in range(len(lenses)) for m in range(len(mountains))),
        GRB.MINIMIZE
    )
    
    # 4. CONSTRAINTS
    
    # Constraint 1: Minimum Lenses per Mountain
    for m in range(len(mountains)):
        model.addConstr(
            gp.quicksum(x[l, m] for l in range(len(lenses))) >= 1,
            name=f"min_lenses_mountain_{m+1}"
        )
    
    # Constraint 2: Maximum Lenses per Mountain
    for m in range(len(mountains)):
        model.addConstr(
            gp.quicksum(x[l, m] for l in range(len(lenses))) <= 3,
            name=f"max_lenses_mountain_{m+1}"
        )
    
    # Constraint 3: Focal Length Requirement
    for l in range(len(lenses)):
        for m in range(len(mountains)):
            model.addConstr(
                lenses[l]['focal_length_mm'] * x[l, m] >= mountains[m]['minimum_focal_length'] * x[l, m],
                name=f"focal_length_lens_{l+1}_mountain_{m+1}"
            )
    
    # Constraint 4: Aperture Requirement
    for l in range(len(lenses)):
        for m in range(len(mountains)):
            model.addConstr(
                lenses[l]['max_aperture'] * x[l, m] >= mountains[m]['minimum_aperture'] * x[l, m],
                name=f"aperture_lens_{l+1}_mountain_{m+1}"
            )
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for l in range(len(lenses)):
            for m in range(len(mountains)):
                if x[l, m].x > 0.5:
                    print(f"Lens {lenses[l]['lens_id']} assigned to Mountain {mountains[m]['mountain_id']}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

# Run the optimization
if __name__ == "__main__":
    mountain_photos_optimization()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 2250.0
**Execution Time**: 0.19 seconds
**Reliability**: high
**Analysis**: Gurobipy achieved the optimal solution with the fastest execution time, indicating high efficiency and reliability.

## 6. DOCplex Implementation

```python
#!/usr/bin/env python3
"""
DOCPLEX implementation for the mountain photography lens selection problem.
"""

from docplex.mp.model import Model

def mountain_photos_optimization():
    """Optimize lens selection for mountain photography."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="mountain_photos")
    
    # Data from the database
    lenses = [
        {"lens_id": 1, "cost": 500.0, "focal_length_mm": 24, "max_aperture": 1.8},
        {"lens_id": 2, "cost": 750.0, "focal_length_mm": 50, "max_aperture": 2.8},
        {"lens_id": 3, "cost": 1000.0, "focal_length_mm": 85, "max_aperture": 4.0}
    ]
    
    mountains = [
        {"mountain_id": 1, "minimum_focal_length": 24, "minimum_aperture": 1.8},
        {"mountain_id": 2, "minimum_focal_length": 50, "minimum_aperture": 2.8},
        {"mountain_id": 3, "minimum_focal_length": 85, "minimum_aperture": 4.0}
    ]
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(lenses) > 0 and len(mountains) > 0, "Empty data arrays"
    
    # 2. VARIABLES
    # Binary decision variables: x[l][m] = 1 if lens l is assigned to mountain m
    x = {(l["lens_id"], m["mountain_id"]): mdl.binary_var(name=f"x_{l['lens_id']}_{m['mountain_id']}")
         for l in lenses for m in mountains}
    
    # 3. OBJECTIVE FUNCTION
    # Minimize the total cost of selected lenses
    objective = mdl.sum(l["cost"] * x[(l["lens_id"], m["mountain_id"])]
                        for l in lenses for m in mountains)
    mdl.minimize(objective)
    
    # 4. CONSTRAINTS
    
    # Constraint 1: Minimum Lenses per Mountain
    for m in mountains:
        mdl.add_constraint(mdl.sum(x[(l["lens_id"], m["mountain_id"])] for l in lenses) >= 1,
                           ctname=f"min_lenses_{m['mountain_id']}")
    
    # Constraint 2: Maximum Lenses per Mountain
    for m in mountains:
        mdl.add_constraint(mdl.sum(x[(l["lens_id"], m["mountain_id"])] for l in lenses) <= 3,
                           ctname=f"max_lenses_{m['mountain_id']}")
    
    # Constraint 3: Focal Length Requirement
    for l in lenses:
        for m in mountains:
            mdl.add_constraint(l["focal_length_mm"] * x[(l["lens_id"], m["mountain_id"])] >= m["minimum_focal_length"] * x[(l["lens_id"], m["mountain_id"])],
                               ctname=f"focal_length_{l['lens_id']}_{m['mountain_id']}")
    
    # Constraint 4: Aperture Requirement
    for l in lenses:
        for m in mountains:
            mdl.add_constraint(l["max_aperture"] * x[(l["lens_id"], m["mountain_id"])] >= m["minimum_aperture"] * x[(l["lens_id"], m["mountain_id"])],
                               ctname=f"aperture_{l['lens_id']}_{m['mountain_id']}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for (lens_id, mountain_id), var in x.items():
            if solution.get_value(var) > 0:
                print(f"Lens {lens_id} assigned to Mountain {mountain_id}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

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

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

## 7. Pyomo Implementation

```python
# Complete PYOMO implementation

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

def mountain_photos_optimization():
    """Optimization model for selecting camera lenses for photographing mountains."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Lenses data
    lenses_data = {
        1: {'cost': 500.0, 'focal_length_mm': 24, 'max_aperture': 1.8},
        2: {'cost': 750.0, 'focal_length_mm': 50, 'max_aperture': 2.8},
        3: {'cost': 1000.0, 'focal_length_mm': 85, 'max_aperture': 4.0}
    }
    
    # Mountains data
    mountains_data = {
        1: {'minimum_focal_length': 24, 'minimum_aperture': 1.8},
        2: {'minimum_focal_length': 50, 'minimum_aperture': 2.8},
        3: {'minimum_focal_length': 85, 'minimum_aperture': 4.0}
    }
    
    # Validate data lengths
    assert len(lenses_data) > 0, "Lenses data is empty"
    assert len(mountains_data) > 0, "Mountains data is empty"
    
    # 3. SETS
    model.L = pyo.Set(initialize=lenses_data.keys())  # Set of lenses
    model.M = pyo.Set(initialize=mountains_data.keys())  # Set of mountains
    
    # 4. PARAMETERS
    model.cost = pyo.Param(model.L, initialize={l: lenses_data[l]['cost'] for l in model.L})
    model.focal_length = pyo.Param(model.L, initialize={l: lenses_data[l]['focal_length_mm'] for l in model.L})
    model.max_aperture = pyo.Param(model.L, initialize={l: lenses_data[l]['max_aperture'] for l in model.L})
    
    model.min_focal_length = pyo.Param(model.M, initialize={m: mountains_data[m]['minimum_focal_length'] for m in model.M})
    model.min_aperture = pyo.Param(model.M, initialize={m: mountains_data[m]['minimum_aperture'] for m in model.M})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.L, model.M, within=pyo.Binary)  # Binary decision variable
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.cost[l] * model.x[l, m] for l in model.L for m in model.M)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    # Minimum Lenses per Mountain
    def min_lenses_rule(model, m):
        return sum(model.x[l, m] for l in model.L) >= 1
    model.min_lenses_constraint = pyo.Constraint(model.M, rule=min_lenses_rule)
    
    # Maximum Lenses per Mountain
    def max_lenses_rule(model, m):
        return sum(model.x[l, m] for l in model.L) <= 3
    model.max_lenses_constraint = pyo.Constraint(model.M, rule=max_lenses_rule)
    
    # Focal Length Requirement
    def focal_length_rule(model, l, m):
        return model.focal_length[l] * model.x[l, m] >= model.min_focal_length[m] * model.x[l, m]
    model.focal_length_constraint = pyo.Constraint(model.L, model.M, rule=focal_length_rule)
    
    # Aperture Requirement
    def aperture_rule(model, l, m):
        return model.max_aperture[l] * model.x[l, m] >= model.min_aperture[m] * model.x[l, m]
    model.aperture_constraint = pyo.Constraint(model.L, model.M, rule=aperture_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(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nSelected lenses for each mountain:")
        for m in model.M:
            print(f"Mountain {m}:")
            for l in model.L:
                if pyo.value(model.x[l, m]) > 0.5:  # Only print selected lenses
                    print(f"  Lens {l} 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__":
    mountain_photos_optimization()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 2250.0
**Execution Time**: 0.90 seconds
**Reliability**: high
**Analysis**: Pyomo achieved the optimal solution with an execution time between Gurobipy and DOCplex, indicating good reliability but lower efficiency.

## 8. Cross-Solver Analysis and Final Recommendation

### Solver Results Comparison

| Solver | Status | Optimal Value | Execution Time | Decision Variables | Retry Attempt |
|--------|--------|---------------|----------------|-------------------|---------------|
| Gurobipy | OPTIMAL | 2250.00 | 0.19s | N/A | N/A |
| Docplex | OPTIMAL | 2250.00 | 1.15s | N/A | N/A |
| Pyomo | OPTIMAL | 2250.00 | 0.90s | N/A | N/A |

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

### Final Recommendation
**Recommended Optimal Value**: 2250.0
**Confidence Level**: HIGH
**Preferred Solver(s)**: gurobipy
**Reasoning**: Gurobipy is recommended due to its optimal solution and the fastest execution time, indicating higher efficiency and reliability.

### Business Interpretation
**Overall Strategy**: The optimal solution suggests a total cost of 2250.0 for assigning lenses to mountains, ensuring all constraints are met.
**Objective Value Meaning**: The optimal objective value of 2250.0 represents the minimum total cost for assigning lenses to mountains while meeting all constraints.
**Resource Allocation Summary**: Resources should be allocated such that each mountain is assigned at least one lens and no more than three lenses, with focal length and aperture requirements met.
**Implementation Recommendations**: Implement the solution by assigning lenses to mountains as per the optimal decision variables, ensuring all constraints are satisfied and the total cost is minimized.