# Complete Optimization Problem and Solution: election

## 1. Problem Context and Goals

### Context  
In the context of an upcoming election, the political party aims to strategically allocate campaign resources across various counties to maximize the number of votes received. The decision-making process involves determining the amount of resources to allocate to each county, represented by the decision variable `resource_allocation[i]`, which is continuous for each county `i`. The objective is to maximize the expected votes, which is a linear function of the resources allocated, weighted by the expected votes gained per unit of resource for each county.

The operational parameters guiding this allocation include a total budget constraint, ensuring that the sum of resources allocated does not exceed the available budget. Additionally, there are minimum and maximum resource allocation constraints for each county to ensure a balanced and effective distribution of resources. The total budget available for resource allocation acts as an upper bound, while the minimum and maximum allocations per county serve as lower and upper bounds, respectively. These constraints are designed to maintain a strategic and feasible allocation of resources across all counties.

### Goals  
The primary goal of this optimization problem is to maximize the total expected votes for the political party. This is achieved by optimizing the allocation of resources across counties, where the metric to optimize is the sum of the product of the expected votes per resource unit and the resources allocated to each county. The success of this optimization is measured by the alignment of resource allocation with the expected vote coefficients, ensuring that resources are distributed in a manner that maximizes the overall vote count. The optimization goal is clearly defined in linear terms, focusing on maximizing the linear combination of resource allocations and vote coefficients.

## 2. Constraints    

The optimization problem is subject to several linear constraints that ensure the feasibility and strategic distribution of resources:

- The total resources allocated across all counties must not exceed the total budget available. This constraint ensures that the allocation remains within the financial limits set for the campaign.
- Each county must receive a minimum amount of resources, ensuring that every county has enough resources to make a meaningful impact on the election outcome.
- The resources allocated to each county must not exceed a specified maximum, preventing over-investment in any single county and promoting a balanced distribution of resources.

These constraints are expressed in business terms that naturally lead to linear mathematical forms, ensuring that the optimization problem remains linear and solvable using standard linear optimization techniques.

## 3. Available Data  

### Database Schema  
```sql
-- Iteration 1 Database Schema
-- Objective: Schema changes include creating new tables for objective coefficients, constraint bounds, and decision variables. Business configuration logic is updated to include scalar parameters and formulas for optimization constraints and objectives.

CREATE TABLE ObjectiveCoefficients (
  county_id INTEGER,
  votes_coefficient FLOAT
);

CREATE TABLE DecisionVariables (
  county_id INTEGER,
  resource_allocation FLOAT
);
```

### Data Dictionary  
The data used in this optimization problem is organized into tables that serve specific business purposes and optimization roles:

- **ObjectiveCoefficients Table**: This table stores the coefficients used in the objective function, representing the expected votes gained per unit of resource for each county. The `county_id` column uniquely identifies each county, linking the coefficients to specific counties. The `votes_coefficient` column provides the expected votes per resource unit, serving as a key component in the objective function.

- **DecisionVariables Table**: This table contains the decision variables representing the amount of resources allocated to each county. The `county_id` column uniquely identifies each county, linking the decision variables to specific counties. The `resource_allocation` column indicates the amount of resources allocated, serving as the decision variable in the optimization model.

### Current Stored Values  
```sql
-- Iteration 1 Realistic Data
-- Generated by triple expert (business + data + optimization)
-- Values were determined based on typical campaign resource allocation scenarios, ensuring that the budget and allocation constraints are realistic and align with common political campaign strategies.

-- Realistic data for ObjectiveCoefficients
INSERT INTO ObjectiveCoefficients (county_id, votes_coefficient) VALUES (1, 0.6);
INSERT INTO ObjectiveCoefficients (county_id, votes_coefficient) VALUES (2, 1.5);
INSERT INTO ObjectiveCoefficients (county_id, votes_coefficient) VALUES (3, 0.9);

-- Realistic data for DecisionVariables
INSERT INTO DecisionVariables (county_id, resource_allocation) VALUES (1, 800);
INSERT INTO DecisionVariables (county_id, resource_allocation) VALUES (2, 1500);
INSERT INTO DecisionVariables (county_id, resource_allocation) VALUES (3, 700);
```

## 4. Mathematical Optimization Formulation

#### Decision Variables
- Let \( x_i \) be the amount of resources allocated to county \( i \).
- \( x_i \) is a continuous decision variable representing the resource allocation for each county.

#### Objective Function
Maximize the total expected votes:
\[ \text{Maximize } Z = 0.6x_1 + 1.5x_2 + 0.9x_3 \]

#### Constraints
1. Total budget constraint:
   \[ x_1 + x_2 + x_3 \leq \text{Total Budget} \]

2. Minimum resource allocation for each county:
   \[ x_1 \geq \text{Minimum Allocation for County 1} \]
   \[ x_2 \geq \text{Minimum Allocation for County 2} \]
   \[ x_3 \geq \text{Minimum Allocation for County 3} \]

3. Maximum resource allocation for each county:
   \[ x_1 \leq \text{Maximum Allocation for County 1} \]
   \[ x_2 \leq \text{Maximum Allocation for County 2} \]
   \[ x_3 \leq \text{Maximum Allocation for County 3} \]

Data Source Verification:
- Objective function coefficients are sourced from `ObjectiveCoefficients.votes_coefficient`.
- Decision variables \( x_i \) correspond to `DecisionVariables.resource_allocation`.
- Total budget, minimum, and maximum allocations are assumed to be provided as parameters in the business configuration, though specific values are not detailed in the provided data.

## 5. Gurobipy Implementation

```python
# Complete GUROBIPY implementation

import gurobipy as gp
from gurobipy import GRB

def election_optimization():
    """Optimize resource allocation for maximizing votes in an election"""

    # 1. MODEL & DATA SETUP
    model = gp.Model("election_optimization")

    # Data: Coefficients and constraints
    counties = [1, 2, 3]
    votes_coefficient = {1: 0.6, 2: 1.5, 3: 0.9}
    total_budget = 3000
    min_allocation = {1: 500, 2: 1000, 3: 600}
    max_allocation = {1: 1000, 2: 2000, 3: 1200}

    # CRITICAL: Validate array lengths before loops
    assert len(votes_coefficient) == len(min_allocation) == len(max_allocation) == len(counties), "Array length mismatch"

    # 2. VARIABLES
    # Variable dictionaries for resource allocation
    resource_allocation = {i: model.addVar(vtype=GRB.CONTINUOUS, name=f"x_{i}", lb=0) for i in counties}

    # 3. OBJECTIVE FUNCTION
    # Maximize total expected votes
    model.setObjective(gp.quicksum(votes_coefficient[i] * resource_allocation[i] for i in counties), GRB.MAXIMIZE)

    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS

    # Total budget constraint
    model.addConstr(gp.quicksum(resource_allocation[i] for i in counties) <= total_budget, name="total_budget")

    # Minimum and maximum resource allocation constraints for each county
    for i in counties:
        model.addConstr(resource_allocation[i] >= min_allocation[i], name=f"min_allocation_{i}")
        model.addConstr(resource_allocation[i] <= max_allocation[i], name=f"max_allocation_{i}")

    # 5. SOLVING & RESULTS
    model.optimize()

    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in counties:
            if resource_allocation[i].x > 1e-6:
                print(f"Resource allocation for county {i}: {resource_allocation[i].x:.3f}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")

    return model

# Run the optimization
election_optimization()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 3690.0
**Execution Time**: 1.51 seconds
**Reliability**: high
**Analysis**: Gurobipy found an optimal solution quickly with a reliable status and no errors.

## 6. DOCplex Implementation

```python
# Complete DOCPLEX implementation

from docplex.mp.model import Model

def election_optimization():
    """Optimize resource allocation for maximizing votes in an election"""

    # 1. MODEL & DATA SETUP
    mdl = Model(name="election_optimization")

    # Data: Coefficients and constraints
    votes_coefficients = [0.6, 1.5, 0.9]
    min_allocations = [500, 1000, 600]
    max_allocations = [1000, 2000, 1200]
    total_budget = 3000

    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(votes_coefficients) == len(min_allocations) == len(max_allocations), "Array length mismatch"
    safe_range = range(len(votes_coefficients))  # Safe indexing

    # 2. VARIABLES
    # Variable dictionaries (most common)
    resource_allocation = {i: mdl.continuous_var(name=f"x_{i}", lb=min_allocations[i], ub=max_allocations[i]) for i in safe_range}

    # 3. OBJECTIVE FUNCTION
    # Use mdl.sum() for summations (DOCplex specific)
    objective = mdl.sum(votes_coefficients[i] * resource_allocation[i] for i in safe_range)
    mdl.maximize(objective)

    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS

    # Total budget constraint
    total_usage = mdl.sum(resource_allocation[i] for i in safe_range)
    mdl.add_constraint(total_usage <= total_budget, ctname="total_budget")

    # 5. SOLVING & RESULTS
    solution = mdl.solve()

    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(resource_allocation[i])
            print(f"Resource allocation for county {i+1}: {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")

    return mdl

# Run the optimization
election_optimization()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 3690.0
**Execution Time**: 10.34 seconds
**Reliability**: high
**Analysis**: DOCplex also found an optimal solution, albeit with a longer execution time compared to Gurobipy.

## 7. Pyomo Implementation

```python
# Complete PYOMO implementation

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

def election_optimization():
    """Election resource allocation optimization using Pyomo"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    counties = [1, 2, 3]
    votes_coefficients = {1: 0.6, 2: 1.5, 3: 0.9}
    min_allocation = {1: 500, 2: 1000, 3: 600}
    max_allocation = {1: 1000, 2: 2000, 3: 1200}
    total_budget = 3000
    
    # CRITICAL: Validate array lengths before indexing
    assert len(votes_coefficients) == len(min_allocation) == len(max_allocation) == len(counties), "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.Set(initialize=counties)
    
    # 4. PARAMETERS (data containers)
    model.votes_coefficient = pyo.Param(model.I, initialize=votes_coefficients)
    model.min_allocation = pyo.Param(model.I, initialize=min_allocation)
    model.max_allocation = pyo.Param(model.I, initialize=max_allocation)
    
    # 5. VARIABLES
    model.resource_allocation = pyo.Var(model.I, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.votes_coefficient[i] * model.resource_allocation[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Total budget constraint
    def budget_constraint_rule(model):
        return sum(model.resource_allocation[i] for i in model.I) <= total_budget
    model.budget_constraint = pyo.Constraint(rule=budget_constraint_rule)
    
    # Minimum and maximum allocation constraints
    def min_allocation_rule(model, i):
        return model.resource_allocation[i] >= model.min_allocation[i]
    model.min_allocation_constraint = pyo.Constraint(model.I, rule=min_allocation_rule)
    
    def max_allocation_rule(model, i):
        return model.resource_allocation[i] <= model.max_allocation[i]
    model.max_allocation_constraint = pyo.Constraint(model.I, rule=max_allocation_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):.3f}")
        
        # Extract variable values
        print("\nResource allocation:")
        for i in model.I:
            allocation_val = pyo.value(model.resource_allocation[i])
            print(f"County {i}: {allocation_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

# Run the optimization
election_optimization()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 3690.0
**Execution Time**: 7.29 seconds
**Reliability**: high
**Analysis**: Pyomo achieved an optimal solution with a moderate execution time, consistent with other solvers.

## 8. Cross-Solver Analysis and Final Recommendation

### Solver Results Comparison

| Solver | Status | Optimal Value | Execution Time | Decision Variables | Retry Attempt |
|--------|--------|---------------|----------------|-------------------|---------------|
| Gurobipy | OPTIMAL | 3690.00 | 1.51s | N/A | N/A |
| Docplex | OPTIMAL | 3690.00 | 10.34s | N/A | N/A |
| Pyomo | OPTIMAL | 3690.00 | 7.29s | N/A | N/A |

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

### Final Recommendation
**Recommended Optimal Value**: 3690.0
**Confidence Level**: HIGH
**Preferred Solver(s)**: gurobipy
**Reasoning**: Gurobipy is recommended due to its fastest execution time and high reliability, making it suitable for time-sensitive decision-making.

### Business Interpretation
**Overall Strategy**: The optimal allocation of resources will maximize the expected votes, achieving the best possible outcome within the given constraints.
**Objective Value Meaning**: The optimal objective value of 3690.0 represents the maximum expected votes achievable with the given resource allocation.
**Resource Allocation Summary**: Resources should be allocated to maximize votes while adhering to budget and allocation constraints for each county.
**Implementation Recommendations**: Implement the solution by allocating resources as per the solver's optimal decision variables, ensuring compliance with all constraints.