# Complete Optimization Problem and Solution: allergy_1

## 1. Problem Context and Goals

### Context  
A university is tasked with providing allergy accommodations to its students across various cities. The goal is to ensure that all students with allergies receive the necessary support while minimizing the total cost of these accommodations. The cost of providing accommodations varies depending on the type of allergy and the city where the student resides. The university has a fixed budget allocated for this purpose, and there is a minimum requirement for the amount of resources that must be allocated to each allergy type in each city. 

The decision variables in this problem represent the amount of resources allocated to students based on their allergy type and city. These resources are continuous, meaning they can take any value within the allowed range. The operational parameters include the cost of providing accommodations for each allergy type in each city, the total budget available, and the minimum required resources for each allergy type in each city. These parameters are used to ensure that the solution is both cost-effective and meets the necessary support requirements.

The business configuration includes a total budget of 500,000 units, which serves as the upper limit for the total resources allocated. Additionally, there is a minimum requirement of 5 units of resources for each allergy type in each city, ensuring that all students receive at least the necessary support. These constraints are designed to align with the linear nature of the optimization problem, avoiding any nonlinear relationships such as variable products or divisions.

### Goals  
The primary goal of this optimization problem is to minimize the total cost of providing allergy accommodations to students. This is achieved by determining the optimal allocation of resources for each allergy type in each city, ensuring that the total cost is as low as possible while still meeting the minimum resource requirements and staying within the budget. 

Success is measured by the ability to provide the necessary support to all students with allergies at the lowest possible cost. The cost of accommodations for each allergy type in each city serves as the key metric in this optimization, guiding the allocation of resources to achieve the most cost-effective solution. The goal is to ensure that the university can meet its obligations to students without exceeding its financial constraints.

## 2. Constraints    

The optimization problem is subject to two main constraints, both of which are linear in nature:

1. **Budget Constraint**: The total amount of resources allocated across all allergy types and cities must not exceed the total budget available for allergy accommodations. This ensures that the university does not overspend on providing support to students.

2. **Minimum Resource Requirement**: For each allergy type in each city, the amount of resources allocated must be at least the minimum required level. This ensures that all students with allergies receive the necessary support, regardless of the city they reside in.

These constraints are designed to ensure that the solution is both financially feasible and meets the university's obligations to its students. They are expressed in a way that naturally leads to a linear optimization formulation, avoiding any nonlinear relationships.

## 3. Available Data  

### Database Schema  
```sql
-- Iteration 1 Database Schema
-- Objective: Schema changes include creating tables for cost, budget, and required resources, and updating business configuration logic with scalar parameters and formulas.

CREATE TABLE cost (
  AllergyType STRING,
  city_code STRING,
  cost FLOAT,
  resource FLOAT
);


```

### Data Dictionary  
The **cost** table contains information about the cost of providing allergy accommodations and the resources allocated for each allergy type in each city. The columns in this table are:

- **AllergyType**: Represents the type of allergy (e.g., peanut, dairy, gluten). This is used to identify the specific allergy for which accommodations are being provided.
- **city_code**: Represents the city where the student resides (e.g., NYC, LA, CHI). This is used to identify the location where the accommodations are needed.
- **cost**: Represents the cost of providing accommodations for the specific allergy type in the city. This value is used as a coefficient in the objective function to calculate the total cost.
- **resource**: Represents the amount of resources allocated to the specific allergy type in the city. This is the decision variable in the optimization problem, determining how much support is provided.

### Current Stored Values  
```sql
-- Iteration 1 Realistic Data
-- Generated by triple expert (business + data + optimization)
-- Values were determined based on realistic cost estimates for allergy accommodations in major cities, considering factors like local cost of living and resource availability. The budget and required resources were set to ensure the problem is solvable while reflecting real-world constraints.

-- Realistic data for cost
INSERT INTO cost (AllergyType, city_code, cost, resource) VALUES ('peanut', 'NYC', 120.0, 12.0);
INSERT INTO cost (AllergyType, city_code, cost, resource) VALUES ('dairy', 'LA', 100.0, 10.0);
INSERT INTO cost (AllergyType, city_code, cost, resource) VALUES ('gluten', 'CHI', 90.0, 9.0);


```

## 4. Mathematical Optimization Formulation

#### Decision Variables
Let \( x_{i,j} \) represent the amount of resources allocated to students with allergy type \( i \) in city \( j \).  
Here, \( i \in \{\text{peanut}, \text{dairy}, \text{gluten}\} \) and \( j \in \{\text{NYC}, \text{LA}, \text{CHI}\} \).  
\( x_{i,j} \) is a continuous variable.

#### Objective Function
Minimize the total cost of providing allergy accommodations:  
\[
\text{Minimize } Z = 120x_{\text{peanut},\text{NYC}} + 100x_{\text{dairy},\text{LA}} + 90x_{\text{gluten},\text{CHI}}
\]

#### Constraints
1. **Budget Constraint**: The total cost must not exceed the budget of 500,000 units:  
\[
120x_{\text{peanut},\text{NYC}} + 100x_{\text{dairy},\text{LA}} + 90x_{\text{gluten},\text{CHI}} \leq 500000
\]

2. **Minimum Resource Requirement**: Each allergy type in each city must receive at least 5 units of resources:  
\[
x_{\text{peanut},\text{NYC}} \geq 5  
x_{\text{dairy},\text{LA}} \geq 5  
x_{\text{gluten},\text{CHI}} \geq 5
\]

#### Data Source Verification
- Coefficients in the objective function and budget constraint:  
  - \( 120 \): `cost.cost` for `AllergyType = 'peanut'` and `city_code = 'NYC'`  
  - \( 100 \): `cost.cost` for `AllergyType = 'dairy'` and `city_code = 'LA'`  
  - \( 90 \): `cost.cost` for `AllergyType = 'gluten'` and `city_code = 'CHI'`  
- Budget limit: Business configuration parameter (500,000 units).  
- Minimum resource requirement: Business configuration parameter (5 units).  

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

## 5. Gurobipy Implementation

```python
# Complete GUROBIPY implementation - Retry Attempt 4

import gurobipy as gp
from gurobipy import GRB

def allergy_accommodation_optimization():
    # 1. MODEL & DATA SETUP
    model = gp.Model("allergy_accommodation")
    
    # Define allergy types and cities
    allergy_types = ['peanut', 'dairy', 'gluten']
    cities = ['NYC', 'LA', 'CHI']
    
    # Cost data for each allergy type and city
    costs = {
        ('peanut', 'NYC'): 120.0,
        ('dairy', 'LA'): 100.0,
        ('gluten', 'CHI'): 90.0
    }
    
    # Validate that all allergy-city pairs have cost data
    for i in allergy_types:
        for j in cities:
            if (i, j) not in costs:
                raise ValueError(f"Missing cost data for {i} in {j}")
    
    # Budget and minimum resource requirement
    budget = 500000
    min_resource = 5
    
    # 2. VARIABLES
    x = model.addVars(allergy_types, cities, vtype=GRB.CONTINUOUS, name="x", lb=min_resource)
    
    # 3. OBJECTIVE FUNCTION
    model.setObjective(gp.quicksum(costs[i, j] * x[i, j] for i in allergy_types for j in cities), GRB.MINIMIZE)
    
    # 4. CONSTRAINTS
    # Budget constraint
    model.addConstr(gp.quicksum(costs[i, j] * x[i, j] for i in allergy_types for j in cities) <= budget, name="budget_constraint")
    
    # Minimum resource requirement (already handled by variable lower bounds)
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in allergy_types:
            for j in cities:
                print(f"x[{i}, {j}] = {x[i, j].x:.3f}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

# Execute the optimization
allergy_accommodation_optimization()
```

### Execution Results
**Status**: ERROR
**Error**: Traceback (most recent call last):
  File "/tmp/tmpfzj9u69g.py", line 59, in <module>
    allergy_accommodation_optimization()
  File "/tmp/tmpfzj9u69g.py", line 25, in allergy_accommodation_optimization
    raise ValueError(f"Missing cost data for {i} in {j}")
ValueError: Missing cost data for peanut in LA

**Analysis**: Gurobipy encountered an error due to missing cost data for peanut in LA. This suggests a potential issue with the data input or model formulation.

## 6. DOCplex Implementation

```python
# Complete DOCPLEX implementation - Retry Attempt 4

from docplex.mp.model import Model

def allergy_accommodation_optimization():
    # 1. MODEL & DATA SETUP
    mdl = Model(name="allergy_accommodation_optimization")
    
    # Data from the problem
    allergy_types = ['peanut', 'dairy', 'gluten']
    cities = ['NYC', 'LA', 'CHI']
    
    # Cost data from the database
    costs = {
        ('peanut', 'NYC'): 120.0,
        ('dairy', 'LA'): 100.0,
        ('gluten', 'CHI'): 90.0
    }
    
    # Budget and minimum resource requirement
    total_budget = 500000
    min_resource = 5
    
    # 2. VARIABLES
    # Decision variables: resources allocated for each allergy type in each city
    x = {(i, j): mdl.continuous_var(name=f"x_{i}_{j}", lb=0) for i in allergy_types for j in cities}
    
    # 3. OBJECTIVE FUNCTION
    # Minimize the total cost of providing allergy accommodations
    objective = mdl.sum(costs.get((i, j), 0) * x[i, j] for i in allergy_types for j in cities)
    mdl.minimize(objective)
    
    # 4. CONSTRAINTS
    
    # Budget Constraint: Total cost must not exceed the budget
    budget_constraint = mdl.sum(costs.get((i, j), 0) * x[i, j] for i in allergy_types for j in cities) <= total_budget
    mdl.add_constraint(budget_constraint, ctname="budget_constraint")
    
    # Minimum Resource Requirement: Each allergy type in each city must receive at least min_resource units
    for i in allergy_types:
        for j in cities:
            if (i, j) in costs:
                min_resource_constraint = x[i, j] >= min_resource
                mdl.add_constraint(min_resource_constraint, ctname=f"min_resource_{i}_{j}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in allergy_types:
            for j in cities:
                if (i, j) in costs:
                    value = solution.get_value(x[i, j])
                    print(f"x[{i}, {j}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Execute the optimization
allergy_accommodation_optimization()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 1550.0
**Execution Time**: 1.15 seconds
**Reliability**: high
**Retry Attempt**: 4
**Analysis**: DOCplex successfully solved the problem, providing an optimal value of 1550.0. The decision variables meet the minimum resource requirements and stay within the budget.

## 7. Pyomo Implementation

```python
# Complete PYOMO implementation - Retry Attempt 4

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

def allergy_accommodation_optimization():
    """Optimization model for allergy accommodation problem."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Define sets for allergy types and cities
    allergy_types = ['peanut', 'dairy', 'gluten']
    cities = ['NYC', 'LA', 'CHI']
    
    # Define cost data
    cost_data = {
        ('peanut', 'NYC'): 120.0,
        ('dairy', 'LA'): 100.0,
        ('gluten', 'CHI'): 90.0
    }
    
    # Validate cost data for all combinations
    for i in allergy_types:
        for j in cities:
            if (i, j) not in cost_data:
                raise ValueError(f"Missing cost data for {i} in {j}")
    
    # 3. SETS
    model.allergy_types = pyo.Set(initialize=allergy_types)
    model.cities = pyo.Set(initialize=cities)
    
    # 4. PARAMETERS
    model.cost = pyo.Param(model.allergy_types, model.cities, initialize=cost_data)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.allergy_types, model.cities, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.cost[i, j] * model.x[i, j] for i in model.allergy_types for j in model.cities)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    # Budget Constraint
    def budget_rule(model):
        return sum(model.cost[i, j] * model.x[i, j] for i in model.allergy_types for j in model.cities) <= 500000
    model.budget_constraint = pyo.Constraint(rule=budget_rule)
    
    # Minimum Resource Requirement
    def min_resource_rule(model, i, j):
        return model.x[i, j] >= 5
    model.min_resource_constraint = pyo.Constraint(model.allergy_types, model.cities, rule=min_resource_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)}")
        
        # Extract variable values
        print("\nVariable values:")
        for i in model.allergy_types:
            for j in model.cities:
                x_val = pyo.value(model.x[i, j])
                if x_val > 1e-6:  # Only print non-zero values
                    print(f"x[{i}, {j}] = {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

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

### Execution Results
**Status**: ERROR
**Error**: Traceback (most recent call last):
  File "/tmp/tmppbnlu_yk.py", line 91, in <module>
    allergy_accommodation_optimization()
  File "/tmp/tmppbnlu_yk.py", line 28, in allergy_accommodation_optimization
    raise ValueError(f"Missing cost data for {i} in {j}")
ValueError: Missing cost data for peanut in LA

**Analysis**: Pyomo also encountered an error due to missing cost data for peanut in LA, similar to Gurobipy. This indicates a consistent issue with the data or model setup.

## 8. Cross-Solver Analysis and Final Recommendation

### Solver Results Comparison

| Solver | Status | Optimal Value | Execution Time | Decision Variables | Retry Attempt |
|--------|--------|---------------|----------------|-------------------|---------------|
| Gurobipy | ERROR | N/A | 0.15s | N/A | 4 |
| Docplex | OPTIMAL | 1550.00 | 1.15s | N/A | 4 |
| Pyomo | ERROR | N/A | 0.75s | N/A | 4 |

### Solver Consistency Analysis
**Result**: Solvers produced inconsistent results
**Consistent Solvers**: docplex
**Inconsistent Solvers**: gurobipy, pyomo
**Potential Issues**:
- Missing cost data for peanut in LA
- Potential data input errors
- Model formulation issues
**Solver Retry Summary**: gurobipy: 4 attempts, docplex: 4 attempts, pyomo: 4 attempts

### Final Recommendation
**Recommended Optimal Value**: 1550.0
**Confidence Level**: HIGH
**Preferred Solver(s)**: docplex
**Reasoning**: DOCplex is the only solver that successfully solved the problem without errors, providing a reliable and optimal solution.

### Optimal Decision Variables
- **x_peanut_NYC** = 5.000
  - *Business Meaning*: Amount of resources allocated to students with peanut allergy in NYC, optimally set to 5 units.
- **x_dairy_LA** = 5.000
  - *Business Meaning*: Amount of resources allocated to students with dairy allergy in LA, optimally set to 5 units.
- **x_gluten_CHI** = 5.000
  - *Business Meaning*: Amount of resources allocated to students with gluten allergy in Chicago, optimally set to 5 units.

### Business Interpretation
**Overall Strategy**: The optimal solution suggests allocating the minimum required resources to each allergy type in their respective cities, resulting in a total cost of 1550 units, well within the budget.
**Objective Value Meaning**: The total cost of providing allergy accommodations is minimized to 1550 units, ensuring efficient use of the budget.
**Resource Allocation Summary**: Resources should be allocated at the minimum required levels of 5 units for each allergy type in their respective cities.
**Implementation Recommendations**: Ensure the minimum resource requirements are met for each allergy type in NYC, LA, and Chicago. Verify the cost data for all allergy types and cities to prevent future errors.