# Complete Optimization Problem and Solution: voter_1

## 1. Problem Context and Goals

### Context  
In this voting competition, contestants aim to maximize their votes across different states by strategically allocating a limited promotional budget. The decision-making process involves determining how much promotional budget to allocate to each contestant in each state, ensuring that the total spending does not exceed the available budget and that state-specific spending limits are respected. The promotional budget directly influences the number of votes received, with a fixed conversion rate that translates budget allocation into votes. The total available budget for promotional activities is set at 150,000 units, and the maximum promotional budget allowed per state is capped at 25,000 units. The conversion rate of promotional budget to votes is 0.6, meaning that every unit of promotional budget spent in a state generates 0.6 votes for the contestant. The goal is to allocate the budget in a way that maximizes the total votes received across all contestants and states, while adhering to these operational constraints.

### Goals  
The primary goal of this optimization problem is to maximize the total number of votes received by all contestants across all states. This is achieved by determining the optimal allocation of the promotional budget to each contestant in each state, ensuring that the total spending does not exceed the available budget and that state-specific spending limits are respected. Success is measured by the total votes received, which is directly influenced by the promotional budget allocation and the fixed conversion rate. The optimization process ensures that the budget is allocated efficiently and fairly, maximizing the overall impact of the promotional activities.

## 2. Constraints    

The optimization problem is subject to the following constraints:  
1. **Total Budget Constraint**: The sum of the promotional budgets allocated to all contestants across all states must not exceed the total available budget of 150,000 units. This ensures that the overall spending remains within the financial limits of the competition.  
2. **State-Level Budget Constraint**: The promotional budget allocated to any contestant in a single state must not exceed the maximum allowed budget per state, which is set at 25,000 units. This ensures that no single state receives an excessive share of the promotional resources, promoting fairness and balance in the competition.  

These constraints ensure that the promotional budget is allocated in a way that respects both the overall financial limits and the state-specific spending caps, leading to a fair and efficient distribution of resources.

## 3. Available Data  

### Database Schema  
```sql
-- Iteration 1 Database Schema
-- Objective: Schema changes include creating new tables for decision variables and constraints, moving scalar parameters to business_configuration_logic.json, and updating the data dictionary to reflect optimization mappings.

CREATE TABLE PROMOTIONAL_BUDGET (
  contestant_number INTEGER,
  state STRING,
  budget FLOAT
);

CREATE TABLE VOTES_RECEIVED (
  contestant_number INTEGER,
  state STRING,
  votes INTEGER
);


```

### Data Dictionary  
- **PROMOTIONAL_BUDGET**: This table contains the promotional budget allocated to each contestant in each state.  
  - **contestant_number**: A unique identifier for each contestant.  
  - **state**: The state where the promotional budget is allocated.  
  - **budget**: The amount of promotional budget allocated to the contestant in the specified state.  

- **VOTES_RECEIVED**: This table contains the number of votes received by each contestant in each state.  
  - **contestant_number**: A unique identifier for each contestant.  
  - **state**: The state where the votes were received.  
  - **votes**: The number of votes received by the contestant in the specified state.  

### Current Stored Values  
```sql
-- Iteration 1 Realistic Data
-- Generated by triple expert (business + data + optimization)
-- Values were determined based on realistic promotional budgets, conversion rates, and state-specific constraints, ensuring the optimization problem is meaningful and solvable.

-- Realistic data for PROMOTIONAL_BUDGET
INSERT INTO PROMOTIONAL_BUDGET (contestant_number, state, budget) VALUES (1, 'CA', 15000.0);
INSERT INTO PROMOTIONAL_BUDGET (contestant_number, state, budget) VALUES (1, 'TX', 10000.0);
INSERT INTO PROMOTIONAL_BUDGET (contestant_number, state, budget) VALUES (1, 'NY', 20000.0);
INSERT INTO PROMOTIONAL_BUDGET (contestant_number, state, budget) VALUES (2, 'CA', 12000.0);
INSERT INTO PROMOTIONAL_BUDGET (contestant_number, state, budget) VALUES (2, 'TX', 15000.0);
INSERT INTO PROMOTIONAL_BUDGET (contestant_number, state, budget) VALUES (2, 'NY', 18000.0);
INSERT INTO PROMOTIONAL_BUDGET (contestant_number, state, budget) VALUES (3, 'CA', 20000.0);
INSERT INTO PROMOTIONAL_BUDGET (contestant_number, state, budget) VALUES (3, 'TX', 8000.0);
INSERT INTO PROMOTIONAL_BUDGET (contestant_number, state, budget) VALUES (3, 'NY', 12000.0);

-- Realistic data for VOTES_RECEIVED
INSERT INTO VOTES_RECEIVED (contestant_number, state, votes) VALUES (1, 'CA', 7500);
INSERT INTO VOTES_RECEIVED (contestant_number, state, votes) VALUES (1, 'TX', 5000);
INSERT INTO VOTES_RECEIVED (contestant_number, state, votes) VALUES (1, 'NY', 10000);
INSERT INTO VOTES_RECEIVED (contestant_number, state, votes) VALUES (2, 'CA', 6000);
INSERT INTO VOTES_RECEIVED (contestant_number, state, votes) VALUES (2, 'TX', 7500);
INSERT INTO VOTES_RECEIVED (contestant_number, state, votes) VALUES (2, 'NY', 9000);
INSERT INTO VOTES_RECEIVED (contestant_number, state, votes) VALUES (3, 'CA', 10000);
INSERT INTO VOTES_RECEIVED (contestant_number, state, votes) VALUES (3, 'TX', 4000);
INSERT INTO VOTES_RECEIVED (contestant_number, state, votes) VALUES (3, 'NY', 6000);


```

## 4. Mathematical Optimization Formulation

#### Decision Variables
Let \( x_{i,j} \) be the promotional budget allocated to contestant \( i \) in state \( j \), where:
- \( i \in \{1, 2, 3\} \) (contestants)
- \( j \in \{\text{CA}, \text{TX}, \text{NY}\} \) (states)

#### Objective Function
Maximize the total votes received across all contestants and states:
\[
\text{Maximize } Z = \sum_{i} \sum_{j} 0.6 \cdot x_{i,j}
\]
- **Coefficient Source**: The coefficient \( 0.6 \) is derived from the fixed conversion rate of promotional budget to votes, as specified in the business problem description.

#### Constraints
1. **Total Budget Constraint**:
\[
\sum_{i} \sum_{j} x_{i,j} \leq 150,000
\]
- **Coefficient Source**: The right-hand-side value \( 150,000 \) is the total available budget, as specified in the business problem description.

2. **State-Level Budget Constraint**:
\[
x_{i,j} \leq 25,000 \quad \forall i, j
\]
- **Coefficient Source**: The right-hand-side value \( 25,000 \) is the maximum allowed budget per state, as specified in the business problem description.

#### Data Source Verification
- **Objective Function Coefficient (0.6)**: Derived from the fixed conversion rate of promotional budget to votes, as specified in the business problem description.
- **Total Budget Constraint (150,000)**: Derived from the total available budget, as specified in the business problem description.
- **State-Level Budget Constraint (25,000)**: Derived from the maximum allowed budget per state, as specified in the business problem description.

This formulation provides a complete, immediately solvable LINEAR mathematical model with all numerical coefficients explicitly mapped to their respective data sources.

## 5. Gurobipy Implementation

```python
#!/usr/bin/env python3
"""
Gurobipy 12.0.2 Implementation for Voter Optimization Problem
"""

import gurobipy as gp
from gurobipy import GRB

def voter_optimization():
    """Optimize promotional budget allocation to maximize votes."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("voter_optimization")
    
    # Contestants and states
    contestants = [1, 2, 3]
    states = ['CA', 'TX', 'NY']
    
    # Conversion rate
    conversion_rate = 0.6
    
    # Total budget and state-level budget limit
    total_budget = 150000
    state_budget_limit = 25000
    
    # 2. VARIABLES
    # Decision variable: promotional budget allocated to each contestant in each state
    x = model.addVars(contestants, states, vtype=GRB.CONTINUOUS, name="x", lb=0)
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total votes received
    model.setObjective(gp.quicksum(conversion_rate * x[i, j] for i in contestants for j in states), GRB.MAXIMIZE)
    
    # 4. CONSTRAINTS
    
    # Total Budget Constraint
    model.addConstr(gp.quicksum(x[i, j] for i in contestants for j in states) <= total_budget, name="total_budget")
    
    # State-Level Budget Constraint
    for i in contestants:
        for j in states:
            model.addConstr(x[i, j] <= state_budget_limit, name=f"state_budget_{i}_{j}")
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in contestants:
            for j in states:
                if x[i, j].x > 1e-6:
                    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
if __name__ == "__main__":
    voter_optimization()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 90000.0
**Execution Time**: 0.21 seconds
**Reliability**: high
**Analysis**: Gurobipy achieved the optimal solution efficiently with the fastest execution time.

## 6. DOCplex Implementation

```python
#!/usr/bin/env python3
"""
DOCPLEX implementation for the voter_1 optimization problem
"""

from docplex.mp.model import Model

def voter_optimization():
    """Optimize promotional budget allocation to maximize votes"""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="voter_optimization")
    
    # Contestants and states
    contestants = [1, 2, 3]
    states = ['CA', 'TX', 'NY']
    
    # Parameters
    total_budget = 150000
    max_budget_per_state = 25000
    conversion_rate = 0.6
    
    # 2. VARIABLES
    # Decision variable: promotional budget allocated to each contestant in each state
    x = {(i, j): mdl.continuous_var(name=f"x_{i}_{j}", lb=0) for i in contestants for j in states}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total votes received across all contestants and states
    objective = mdl.sum(conversion_rate * x[i, j] for i in contestants for j in states)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    
    # Total Budget Constraint
    total_budget_expr = mdl.sum(x[i, j] for i in contestants for j in states)
    mdl.add_constraint(total_budget_expr <= total_budget, ctname="total_budget")
    
    # State-Level Budget Constraint
    for i in contestants:
        for j in states:
            mdl.add_constraint(x[i, j] <= max_budget_per_state, ctname=f"state_budget_{i}_{j}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in contestants:
            for j in states:
                value = solution.get_value(x[i, j])
                if value > 1e-6:
                    print(f"x[{i}, {j}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

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

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

## 7. Pyomo Implementation

```python
#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Voter Optimization Problem
"""

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

def voter_optimization():
    """Optimize promotional budget allocation to maximize votes."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    contestants = [1, 2, 3]
    states = ['CA', 'TX', 'NY']
    total_budget = 150000
    max_state_budget = 25000
    conversion_rate = 0.6
    
    # 3. SETS
    model.contestants = pyo.Set(initialize=contestants)
    model.states = pyo.Set(initialize=states)
    
    # 4. VARIABLES
    model.x = pyo.Var(model.contestants, model.states, within=pyo.NonNegativeReals, bounds=(0, max_state_budget))
    
    # 5. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(conversion_rate * model.x[i, j] for i in model.contestants for j in model.states)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 6. CONSTRAINTS
    
    # Total Budget Constraint
    def total_budget_rule(model):
        return sum(model.x[i, j] for i in model.contestants for j in model.states) <= total_budget
    model.total_budget_constraint = pyo.Constraint(rule=total_budget_rule)
    
    # State-Level Budget Constraint
    def state_budget_rule(model, i, j):
        return model.x[i, j] <= max_state_budget
    model.state_budget_constraint = pyo.Constraint(model.contestants, model.states, rule=state_budget_rule)
    
    # 7. 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
    
    # 8. 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("\nPromotional Budget Allocation:")
        for i in model.contestants:
            for j in model.states:
                x_val = pyo.value(model.x[i, j])
                if x_val > 1e-6:  # Only print non-zero values
                    print(f"Contestant {i}, State {j}: {x_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
if __name__ == "__main__":
    voter_optimization()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 90000.0
**Execution Time**: 0.82 seconds
**Reliability**: high
**Analysis**: Pyomo achieved the optimal solution with an execution time comparable to DOCplex.

## 8. Cross-Solver Analysis and Final Recommendation

### Solver Results Comparison

| Solver | Status | Optimal Value | Execution Time | Decision Variables | Retry Attempt |
|--------|--------|---------------|----------------|-------------------|---------------|
| Gurobipy | OPTIMAL | 90000.00 | 0.21s | N/A | N/A |
| Docplex | OPTIMAL | 90000.00 | 0.89s | N/A | N/A |
| Pyomo | OPTIMAL | 90000.00 | 0.82s | N/A | N/A |

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

### Final Recommendation
**Recommended Optimal Value**: 90000.0
**Confidence Level**: HIGH
**Preferred Solver(s)**: gurobipy
**Reasoning**: Gurobipy is recommended due to its fastest execution time while achieving the same optimal value as the other solvers.

### Business Interpretation
**Overall Strategy**: The optimal solution suggests that the maximum total votes achievable is 90,000, given the budget constraints.
**Objective Value Meaning**: The optimal objective value of 90,000 represents the maximum total votes that can be obtained by optimally allocating the promotional budget across contestants and states.
**Resource Allocation Summary**: The total budget of $150,000 should be allocated in such a way that no more than $25,000 is spent in any single state for any contestant, ensuring the maximum votes are achieved.
**Implementation Recommendations**: Allocate the promotional budget evenly across states and contestants, ensuring no state exceeds the $25,000 limit per contestant. Monitor the conversion rate to ensure the expected votes are realized.