# Complete Optimization Problem and Solution: inn_1

## 1. Problem Context and Goals

### Context  
The inn is focused on maximizing its revenue by strategically setting room rates while ensuring that room occupancy does not exceed the established capacity and all reservations are fulfilled. The primary decision variable in this optimization is the rate charged for each reservation, which is directly linked to the reservation details stored in the system. The operational objective is to maximize the total revenue, calculated as the sum of the product of the rate charged for each reservation and the length of stay for that reservation. 

The business configuration includes key parameters such as the maximum number of people that can occupy a room, which serves as a constraint to ensure that room capacity is not exceeded. Additionally, there is a minimum rate that can be charged for a room, ensuring that the inn remains competitive while covering basic costs. The length of stay for each reservation is calculated based on the check-in and check-out dates, and this information is used in the revenue calculation. 

The data presented reflects current operational information, focusing on precise decision-making that aligns with linear optimization formulations. The constraints are designed to match expected linear relationships, avoiding any scenarios that would require nonlinear calculations. Specific operational parameters are clearly mapped to their respective coefficient sources, ensuring consistency and clarity in the optimization model.

### Goals  
The primary goal of this optimization problem is to maximize the total revenue generated from room bookings. This is achieved by adjusting the room rates while adhering to the constraints of room occupancy and minimum pricing. The success of this optimization is measured by the total revenue, which is calculated as the sum of the rate charged for each reservation multiplied by the length of stay for that reservation. The optimization goal is clearly defined in natural language, focusing on maximizing revenue through linear relationships without the use of mathematical formulas or symbolic notation.

## 2. Constraints    

The optimization model includes constraints that ensure the business operates within its defined parameters. One key constraint is the maximum occupancy for each room, which ensures that the number of people occupying a room does not exceed its capacity. This constraint is directly linked to the business configuration logic and is crucial for maintaining operational efficiency and customer satisfaction.

Another important constraint is the base price for each reservation, which ensures that the rate charged does not fall below a specified minimum. This constraint is essential for maintaining profitability and competitiveness in the market. Both constraints are described in business terms that naturally lead to linear mathematical forms, avoiding any nonlinear relationships such as variable products or divisions.

## 3. Available Data  

### Database Schema  
```sql
-- Iteration 1 Database Schema
-- Objective: Schema changes include adding a new table for reservation durations and modifying existing tables to ensure all reservations are mapped to rooms. Configuration logic updated for scalar parameters and formulas.

CREATE TABLE Reservations (
  ReservationId INTEGER,
  Rate FLOAT,
  RoomId INTEGER
);

CREATE TABLE ReservationDurations (
  ReservationId INTEGER,
  LengthOfStay INTEGER
);
```

### Data Dictionary  
The data dictionary provides a comprehensive mapping of tables and columns to their business purposes and optimization roles. 

- **Reservations Table**: This table stores details about each reservation, including the rate charged and the room assigned. The primary role of this table in the optimization model is to define the decision variables, specifically the rate charged for each reservation. The columns include:
  - **ReservationId**: A unique identifier for each reservation, used to link reservation details in the optimization model.
  - **Rate**: The rate charged for the reservation, serving as a decision variable for revenue maximization.
  - **RoomId**: An identifier for the room assigned to the reservation, ensuring that each reservation is mapped to a room.

- **ReservationDurations Table**: This table records the length of stay for each reservation, which is crucial for calculating revenue. The columns include:
  - **ReservationId**: A unique identifier for each reservation, linking the duration to the reservation.
  - **LengthOfStay**: The number of days for the reservation, used in the revenue calculation.

### Current Stored Values  
```sql
-- Iteration 1 Realistic Data
-- Generated by triple expert (business + data + optimization)
-- Values were determined based on typical room rates and occupancy patterns in a mid-range inn, ensuring that the rates are competitive yet profitable, and that the length of stay reflects common booking durations.

-- Realistic data for Reservations
INSERT INTO Reservations (ReservationId, Rate, RoomId) VALUES (1, 120.0, 101);
INSERT INTO Reservations (ReservationId, Rate, RoomId) VALUES (2, 150.0, 102);
INSERT INTO Reservations (ReservationId, Rate, RoomId) VALUES (3, 200.0, 103);

-- Realistic data for ReservationDurations
INSERT INTO ReservationDurations (ReservationId, LengthOfStay) VALUES (1, 2);
INSERT INTO ReservationDurations (ReservationId, LengthOfStay) VALUES (2, 3);
INSERT INTO ReservationDurations (ReservationId, LengthOfStay) VALUES (3, 5);
```

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