# Complete Optimization Problem and Solution: mountain_photos

## 1. Problem Context and Goals

### Context  
A photography company is tasked with selecting the most cost-effective camera lenses for photographing a set of mountains. Each mountain has specific requirements for the minimum focal length and aperture of the lenses used to capture high-quality images. The company must decide which lenses to assign to each mountain, ensuring that the selected lenses meet these technical requirements while minimizing the total cost of the lenses used.  

The decision involves choosing whether to assign a specific lens to a specific mountain, represented as a binary choice (selected or not selected). The company has operational constraints: each mountain must be assigned at least one lens, but no more than three lenses, to balance flexibility and cost efficiency. These constraints are defined by the business configuration parameters, which specify the minimum and maximum number of lenses that can be used per mountain.  

The cost of each lens is a key factor in the decision-making process, as the company aims to minimize the total expenditure on lenses while ensuring that all technical requirements are met. The focal length and aperture of each lens must be equal to or greater than the minimum requirements specified for each mountain.  

### Goals  
The primary goal of this optimization problem is to minimize the total cost of the lenses selected for photographing the mountains. This is achieved by carefully choosing which lenses to assign to each mountain, ensuring that the selected lenses meet the technical requirements and that the total number of lenses used per mountain falls within the specified bounds. Success is measured by the ability to achieve the lowest possible total cost while adhering to all operational and technical constraints.  

## 2. Constraints  

The optimization problem is subject to the following constraints:  
1. **Minimum Lenses per Mountain**: Each mountain must be assigned at least one lens to ensure that the photography requirements are met.  
2. **Maximum Lenses per Mountain**: No mountain can be assigned more than three lenses to prevent excessive costs and maintain operational efficiency.  
3. **Focal Length Requirement**: For each lens assigned to a mountain, the focal length of the lens must be equal to or greater than the minimum focal length required for that mountain.  
4. **Aperture Requirement**: For each lens assigned to a mountain, the maximum aperture of the lens must be equal to or greater than the minimum aperture required for that mountain.  

These constraints ensure that the lens selection process is both technically feasible and operationally efficient, aligning with the company’s goal of minimizing costs while meeting all photography requirements.  

## 3. Available Data  

### Database Schema  
```sql
-- Iteration 2 Database Schema
-- Objective: Refined schema to include a new table for lens-mountain selection, updated business configuration logic, and ensured proper mapping for decision variables.

CREATE TABLE lenses (
  lens_id INTEGER,
  cost FLOAT,
  focal_length_mm INTEGER,
  max_aperture FLOAT
);

CREATE TABLE mountains (
  mountain_id INTEGER,
  minimum_focal_length INTEGER,
  minimum_aperture FLOAT
);

CREATE TABLE lens_mountain_selection (
  lens_id INTEGER,
  mountain_id INTEGER,
  selected BOOLEAN
);
```

### Data Dictionary  
- **Lenses Table**:  
  - **lens_id**: Unique identifier for each camera lens.  
  - **cost**: The cost of the lens, used to calculate the total expenditure in the optimization objective.  
  - **focal_length_mm**: The focal length of the lens in millimeters, used to ensure it meets the minimum requirement for each mountain.  
  - **max_aperture**: The maximum aperture of the lens, used to ensure it meets the minimum requirement for each mountain.  

- **Mountains Table**:  
  - **mountain_id**: Unique identifier for each mountain.  
  - **minimum_focal_length**: The minimum focal length required for photographing the mountain.  
  - **minimum_aperture**: The minimum aperture required for photographing the mountain.  

- **Lens-Mountain Selection Table**:  
  - **lens_id**: Identifier for the lens being considered for selection.  
  - **mountain_id**: Identifier for the mountain to which the lens is being assigned.  
  - **selected**: A binary indicator (True/False) representing whether the lens is selected for the mountain.  

### Current Stored Values  
```sql
-- Iteration 2 Realistic Data
-- Generated by triple expert (business + data + optimization)
-- Values were determined based on realistic photography equipment specifications, mountain characteristics, and business constraints to ensure a meaningful and solvable optimization problem.

-- Realistic data for lenses
INSERT INTO lenses (lens_id, cost, focal_length_mm, max_aperture) VALUES (1, 500.0, 24, 1.8);
INSERT INTO lenses (lens_id, cost, focal_length_mm, max_aperture) VALUES (2, 750.0, 50, 2.8);
INSERT INTO lenses (lens_id, cost, focal_length_mm, max_aperture) VALUES (3, 1000.0, 85, 4.0);

-- Realistic data for mountains
INSERT INTO mountains (mountain_id, minimum_focal_length, minimum_aperture) VALUES (1, 24, 1.8);
INSERT INTO mountains (mountain_id, minimum_focal_length, minimum_aperture) VALUES (2, 50, 2.8);
INSERT INTO mountains (mountain_id, minimum_focal_length, minimum_aperture) VALUES (3, 85, 4.0);

-- Realistic data for lens_mountain_selection
INSERT INTO lens_mountain_selection (lens_id, mountain_id, selected) VALUES (1, 1, True);
INSERT INTO lens_mountain_selection (lens_id, mountain_id, selected) VALUES (2, 2, True);
INSERT INTO lens_mountain_selection (lens_id, mountain_id, selected) VALUES (3, 3, True);
```

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