## 4. Mathematical Optimization Formulation

#### Decision Variables
- \( r_i \): The rate charged for reservation \( i \). This is a continuous decision variable representing the price per night for each reservation.

#### Objective Function
Maximize the total revenue from all reservations:

\[
\text{Maximize } Z = \sum_{i} (r_i \times \text{LengthOfStay}_i)
\]

Where:
- \( \text{LengthOfStay}_i \) is the length of stay for reservation \( i \), sourced from the `ReservationDurations` table.

#### Constraints
1. **Minimum Rate Constraint**: Ensure that the rate charged for each reservation does not fall below a specified minimum rate.
   \[
   r_i \geq \text{MinimumRate} \quad \forall i
   \]

   Data Source Verification:
   - \(\text{MinimumRate}\) is a business configuration parameter.

2. **Room Capacity Constraint**: Ensure that the number of people occupying a room does not exceed its capacity. Assuming each reservation corresponds to a single room and the capacity is a known parameter:
   \[
   \text{Occupancy}_i \leq \text{RoomCapacity} \quad \forall i
   \]

   Data Source Verification:
   - \(\text{RoomCapacity}\) is a business configuration parameter.

3. **Reservation Mapping Constraint**: Ensure each reservation is mapped to a room.
   \[
   \text{RoomId}_i \text{ is valid for each } i
   \]

   Data Source Verification:
   - \(\text{RoomId}_i\) is sourced from the `Reservations` table.

#### Data Source Verification
- \( r_i \) is sourced from the `Reservations.Rate` column.
- \(\text{LengthOfStay}_i\) is sourced from the `ReservationDurations.LengthOfStay` column.
- \(\text{RoomId}_i\) is sourced from the `Reservations.RoomId` column.

This linear optimization model is designed to maximize revenue by adjusting room rates while adhering to constraints on minimum pricing and room capacity. The model uses data from the provided tables to ensure all constraints and objectives are grounded in the current operational context.

## 5. Gurobipy Implementation

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

import gurobipy as gp
from gurobipy import GRB

def optimize_inn_revenue():
    # 1. MODEL & DATA SETUP
    model = gp.Model("inn_1")
    
    # Data from the problem context
    reservation_ids = [1, 2, 3]
    rates = [120.0, 150.0, 200.0]
    lengths_of_stay = [2, 3, 5]
    minimum_rate = 100.0  # Example minimum rate
    room_capacity = 4  # Example room capacity
    occupancies = [2, 3, 4]  # Example occupancies for each reservation
    
    # Validate array lengths
    assert len(reservation_ids) == len(rates) == len(lengths_of_stay) == len(occupancies), "Array length mismatch"
    
    # 2. VARIABLES
    # Decision variables for rates
    r = {i: model.addVar(vtype=GRB.CONTINUOUS, name=f"rate_{i}", lb=minimum_rate) 
         for i in reservation_ids}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total revenue
    model.setObjective(gp.quicksum(r[i] * lengths_of_stay[i-1] for i in reservation_ids), GRB.MAXIMIZE)
    
    # 4. CONSTRAINTS
    # Minimum rate constraint
    model.addConstrs((r[i] >= minimum_rate for i in reservation_ids), name="min_rate")
    
    # Room capacity constraint
    model.addConstrs((occupancies[i-1] <= room_capacity for i in reservation_ids), name="room_capacity")
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in reservation_ids:
            print(f"Rate for reservation {i}: {r[i].x:.2f}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    else:
        print("Optimization ended with status", model.status)

# Run the optimization
optimize_inn_revenue()
```

### Execution Results
**Status**: INFEASIBLE
**Error**: Problem is infeasible
**Analysis**: Gurobipy consistently reports the problem as infeasible, indicating a potential issue with the constraints or data.

## 6. DOCplex Implementation

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

from docplex.mp.model import Model

def optimize_inn_revenue():
    # 1. MODEL & DATA SETUP
    mdl = Model(name="inn_revenue_optimization")
    
    # Data from the problem statement
    reservation_ids = [1, 2, 3]
    rates = [120.0, 150.0, 200.0]
    lengths_of_stay = [2, 3, 5]
    minimum_rate = 100.0  # Example minimum rate
    room_capacity = 4     # Example room capacity (not used directly in this model)
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(reservation_ids) == len(rates) == len(lengths_of_stay), "Array length mismatch"
    safe_range = range(len(reservation_ids))  # Safe indexing
    
    # 2. VARIABLES
    # Decision variables for rates
    r = {i: mdl.continuous_var(name=f"rate_{reservation_ids[i]}", lb=minimum_rate) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total revenue
    total_revenue = mdl.sum(r[i] * lengths_of_stay[i] for i in safe_range)
    mdl.maximize(total_revenue)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Minimum rate constraint
    for i in safe_range:
        mdl.add_constraint(r[i] >= minimum_rate, ctname=f"min_rate_{reservation_ids[i]}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(r[i])
            print(f"Rate for reservation {reservation_ids[i]}: {value:.2f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")

# Run the optimization
optimize_inn_revenue()
```

### Execution Results
**Status**: INFEASIBLE
**Error**: Problem is infeasible
**Analysis**: DOCplex also reports infeasibility, suggesting that the problem formulation or data constraints are not satisfiable.

## 7. Pyomo Implementation

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

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

def optimize_inn_revenue():
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()

    # 2. DATA SETUP
    # Assuming these are the given parameters
    reservation_ids = [1, 2, 3]
    rates = {1: 120.0, 2: 150.0, 3: 200.0}
    lengths_of_stay = {1: 2, 2: 3, 3: 5}
    minimum_rate = 100.0
    room_capacity = 4  # Assuming a fixed capacity for simplicity

    # 3. SETS
    model.I = pyo.Set(initialize=reservation_ids)

    # 4. PARAMETERS
    model.rate = pyo.Param(model.I, initialize=rates)
    model.length_of_stay = pyo.Param(model.I, initialize=lengths_of_stay)

    # 5. VARIABLES
    model.r = pyo.Var(model.I, within=pyo.NonNegativeReals, bounds=(minimum_rate, None))

    # 6. OBJECTIVE FUNCTION
    def revenue_rule(model):
        return sum(model.r[i] * model.length_of_stay[i] for i in model.I)
    model.objective = pyo.Objective(rule=revenue_rule, sense=pyo.maximize)

    # 7. CONSTRAINTS
    # Minimum Rate Constraint
    def min_rate_rule(model, i):
        return model.r[i] >= minimum_rate
    model.min_rate_constraint = pyo.Constraint(model.I, rule=min_rate_rule)

    # Room Capacity Constraint
    # Assuming each reservation corresponds to a single room and the capacity is a known parameter
    def capacity_rule(model, i):
        # This constraint is a placeholder as the problem statement does not provide occupancy data
        # Assuming occupancy is always within capacity for this example
        return pyo.Constraint.Feasible
    model.capacity_constraint = pyo.Constraint(model.I, rule=capacity_rule)

    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')

    # 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("\nVariable values:")
        for i in model.I:
            r_val = pyo.value(model.r[i])
            print(f"Rate for reservation {i} = {r_val:.2f}")
        
    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
optimize_inn_revenue()
```

### Execution Results
**Status**: INFEASIBLE
**Error**: Problem is infeasible
**Analysis**: Pyomo's infeasibility result aligns with the other solvers, reinforcing the likelihood of an issue with the model or data.

## 8. Cross-Solver Analysis and Final Recommendation

### Solver Results Comparison

| Solver | Status | Optimal Value | Execution Time | Decision Variables | Retry Attempt |
|--------|--------|---------------|----------------|-------------------|---------------|
| Gurobipy | INFEASIBLE | N/A | 0.51s | N/A | 4 |
| Docplex | INFEASIBLE | N/A | 3.96s | N/A | 4 |
| Pyomo | INFEASIBLE | N/A | 3.68s | N/A | 4 |

### Solver Consistency Analysis
**Result**: All solvers produced consistent results ✓
**Consistent Solvers**: gurobipy, docplex, pyomo
**Solver Retry Summary**: gurobipy: 4 attempts, docplex: 4 attempts, pyomo: 4 attempts

### Final Recommendation
**Confidence Level**: HIGH
**Preferred Solver(s)**: multiple
**Reasoning**: All solvers consistently report infeasibility, suggesting a need to review the model and data rather than solver-specific issues.

### Business Interpretation
**Overall Strategy**: The current model setup cannot find a feasible solution, indicating that the business constraints may be too restrictive or incorrectly specified.
**Objective Value Meaning**: The optimal objective value represents the maximum possible revenue, which is currently unattainable due to infeasibility.
**Resource Allocation Summary**: Review and adjust constraints such as minimum rates and room capacities to ensure feasibility.
**Implementation Recommendations**: Verify data accuracy, especially minimum rates and room capacities. Consider relaxing constraints or revising the model to better reflect business realities.