# Complete Optimization Problem and Solution: candidate_poll

## 1. Problem Context and Goals

### Context  
In the dynamic environment of a political campaign, strategic allocation of resources is crucial to maximize support across various poll sources. The campaign team is tasked with deciding how much effort to allocate to each poll source. These decisions are represented by the variable effort[i], which is continuous for each poll source i. The primary objective is to maximize the overall support rate, which is achieved by effectively distributing the available resources. The total support rate is calculated by summing the product of the effort allocated to each poll source and its respective support rate. The campaign operates under a fixed budget, which serves as a constraint on the total resources that can be allocated. This budget is a scalar parameter, ensuring that the allocation strategy remains within the financial limits of the campaign. The business configuration includes this total resource availability, which is a critical factor in the decision-making process. The campaign must adhere to linear constraints, ensuring that the allocation of effort does not exceed the available resources and that each poll source receives an effort within its specified minimum and maximum limits.

### Goals  
The primary goal of the optimization process is to maximize the total support rate for the campaign. This involves strategically allocating resources to various poll sources to achieve the highest possible support rate. The success of this optimization is measured by the total support rate, which is the sum of the products of effort and support rate for each poll source. The objective is clearly defined in linear terms, focusing on maximizing the overall support rate without involving complex mathematical operations.

## 2. Constraints    

The optimization process is subject to several linear constraints that ensure the feasibility and effectiveness of the resource allocation strategy. The total effort allocated across all poll sources must not exceed the total available resources, which is a fixed budget constraint. Additionally, each poll source has specific minimum and maximum effort limits that must be respected. These constraints ensure that the allocation strategy is both practical and aligned with the campaign's operational capabilities. The constraints are expressed in straightforward business terms, emphasizing the linear nature of the relationships involved.

## 3. Available Data  

### Database Schema  
```sql
-- Iteration 2 Database Schema
-- Objective: Schema changes include creating a new table for objective coefficients, modifying existing tables to fill mapping gaps, and updating business configuration logic for scalar parameters and formulas.

CREATE TABLE EffortAllocation (
  poll_source_id INTEGER,
  effort FLOAT
);

CREATE TABLE PollConstraints (
  poll_source_id INTEGER,
  min_effort FLOAT,
  max_effort FLOAT
);

CREATE TABLE PollSupportRates (
  poll_source_id INTEGER,
  support_rate FLOAT
);
```

### Data Dictionary  
The data dictionary provides a comprehensive overview of the tables and columns used in the optimization process, highlighting their business purposes and roles in the optimization model:

- **EffortAllocation**: This table captures the level of effort allocated to each poll source. It plays a crucial role as the decision variable in the optimization model.
  - **poll_source_id**: Serves as the identifier for each poll source, linking effort to specific sources.
  - **effort**: Represents the level of effort allocated to the poll source, acting as the decision variable.

- **PollConstraints**: This table defines the constraints for effort allocation to poll sources, ensuring that allocations remain within feasible limits.
  - **poll_source_id**: Identifies each poll source, linking constraints to specific sources.
  - **min_effort**: Specifies the minimum effort required for each poll source, serving as a lower bound constraint.
  - **max_effort**: Specifies the maximum effort allowed for each poll source, serving as an upper bound constraint.

- **PollSupportRates**: This table stores the support rate coefficient for each poll source, which is used in calculating the total support rate.
  - **poll_source_id**: Identifies each poll source, linking support rates to specific sources.
  - **support_rate**: Represents the support rate coefficient for the poll source, acting as an objective coefficient in the optimization model.

### Current Stored Values  
```sql
-- Iteration 2 Realistic Data
-- Generated by triple expert (business + data + optimization)
-- Values were determined based on typical resource allocation scenarios in political campaigns, ensuring that the support rates and efforts align with realistic campaign strategies.

-- Realistic data for EffortAllocation
INSERT INTO EffortAllocation (poll_source_id, effort) VALUES (1, 15.0);
INSERT INTO EffortAllocation (poll_source_id, effort) VALUES (2, 25.0);
INSERT INTO EffortAllocation (poll_source_id, effort) VALUES (3, 10.0);

-- Realistic data for PollConstraints
INSERT INTO PollConstraints (poll_source_id, min_effort, max_effort) VALUES (1, 5.0, 20.0);
INSERT INTO PollConstraints (poll_source_id, min_effort, max_effort) VALUES (2, 10.0, 30.0);
INSERT INTO PollConstraints (poll_source_id, min_effort, max_effort) VALUES (3, 7.5, 25.0);

-- Realistic data for PollSupportRates
INSERT INTO PollSupportRates (poll_source_id, support_rate) VALUES (1, 0.55);
INSERT INTO PollSupportRates (poll_source_id, support_rate) VALUES (2, 0.75);
INSERT INTO PollSupportRates (poll_source_id, support_rate) VALUES (3, 0.6);
```

## 4. Mathematical Optimization Formulation

#### Decision Variables
- Let \( x_i \) be the effort allocated to poll source \( i \).
- \( x_i \) is a continuous variable representing the level of effort for each poll source.

#### Objective Function
Maximize the total support rate:
\[ \text{Maximize } Z = 0.55x_1 + 0.75x_2 + 0.6x_3 \]

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

2. Minimum and maximum effort constraints for each poll source:
   \[
   \begin{align*}
   5.0 & \leq x_1 \leq 20.0 \\
   10.0 & \leq x_2 \leq 30.0 \\
   7.5 & \leq x_3 \leq 25.0 \\
   \end{align*}
   \]

Data Source Verification:
- Objective coefficients (support rates) are from `PollSupportRates.support_rate`.
- Minimum and maximum effort constraints are from `PollConstraints.min_effort` and `PollConstraints.max_effort`.
- The total budget constraint is a parameter that should be defined based on the campaign's available resources.

## 5. Gurobipy Implementation

```python
# Complete GUROBIPY implementation

import gurobipy as gp
from gurobipy import GRB

def candidate_poll_optimization():
    """Optimize resource allocation for maximizing support rate in a political campaign."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("candidate_poll")
    
    # Data from the problem context
    poll_sources = [1, 2, 3]
    support_rates = {1: 0.55, 2: 0.75, 3: 0.6}
    min_effort = {1: 5.0, 2: 10.0, 3: 7.5}
    max_effort = {1: 20.0, 2: 30.0, 3: 25.0}
    total_budget = 50.0  # Example budget constraint
    
    # CRITICAL: Validate array lengths before loops
    assert len(support_rates) == len(min_effort) == len(max_effort) == len(poll_sources), "Array length mismatch"
    
    # 2. VARIABLES
    effort = {i: model.addVar(vtype=GRB.CONTINUOUS, name=f"effort_{i}", lb=min_effort[i], ub=max_effort[i]) 
              for i in poll_sources}
    
    # 3. OBJECTIVE FUNCTION
    model.setObjective(gp.quicksum(support_rates[i] * effort[i] for i in poll_sources), GRB.MAXIMIZE)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Total effort constraint (budget constraint)
    model.addConstr(gp.quicksum(effort[i] for i in poll_sources) <= total_budget, name="total_budget")
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in poll_sources:
            if effort[i].x > 1e-6:
                print(f"effort[{i}] = {effort[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
candidate_poll_optimization()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 34.25
**Execution Time**: 0.42 seconds
**Reliability**: high
**Analysis**: Gurobipy found an optimal solution quickly with a short execution time, indicating high efficiency and reliability.

## 6. DOCplex Implementation

```python
# Complete DOCPLEX implementation

from docplex.mp.model import Model

def candidate_poll_optimization():
    """Optimization for candidate poll resource allocation"""

    # 1. MODEL & DATA SETUP
    mdl = Model(name="candidate_poll")
    
    # Data from the problem context
    poll_sources = [1, 2, 3]
    support_rates = [0.55, 0.75, 0.6]
    min_efforts = [5.0, 10.0, 7.5]
    max_efforts = [20.0, 30.0, 25.0]
    total_budget = 50.0  # Example budget constraint

    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(poll_sources) == len(support_rates) == len(min_efforts) == len(max_efforts), "Array length mismatch"
    safe_range = range(len(poll_sources))  # Safe indexing

    # 2. VARIABLES
    effort = {i: mdl.continuous_var(name=f"effort_{poll_sources[i]}", lb=min_efforts[i], ub=max_efforts[i]) for i in safe_range}

    # 3. OBJECTIVE FUNCTION
    # Maximize the total support rate
    objective = mdl.sum(support_rates[i] * effort[i] for i in safe_range)
    mdl.maximize(objective)

    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS

    # Total effort constraint (budget constraint)
    total_effort = mdl.sum(effort[i] for i in safe_range)
    mdl.add_constraint(total_effort <= 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(effort[i])
            print(f"effort[{poll_sources[i]}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")

    return mdl

# Run the optimization
candidate_poll_optimization()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 34.25
**Execution Time**: 7.57 seconds
**Reliability**: high
**Analysis**: DOCplex also found an optimal solution, but with a longer execution time compared to Gurobipy, suggesting it is reliable but less efficient.

## 7. Pyomo Implementation

```python
# Complete PYOMO implementation

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

def candidate_poll_optimization():
    """Optimization for candidate poll resource allocation"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    poll_sources = [1, 2, 3]
    support_rates = {1: 0.55, 2: 0.75, 3: 0.6}
    min_efforts = {1: 5.0, 2: 10.0, 3: 7.5}
    max_efforts = {1: 20.0, 2: 30.0, 3: 25.0}
    total_budget = 50.0  # Example budget constraint
    
    # CRITICAL: Validate array lengths before indexing
    assert len(support_rates) == len(min_efforts) == len(max_efforts) == len(poll_sources), "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.Set(initialize=poll_sources)
    
    # 4. PARAMETERS
    model.support_rate = pyo.Param(model.I, initialize=support_rates)
    model.min_effort = pyo.Param(model.I, initialize=min_efforts)
    model.max_effort = pyo.Param(model.I, initialize=max_efforts)
    
    # 5. VARIABLES
    model.effort = pyo.Var(model.I, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.support_rate[i] * model.effort[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.effort[i] for i in model.I) <= total_budget
    model.budget_constraint = pyo.Constraint(rule=budget_constraint_rule)
    
    # Minimum and maximum effort constraints
    def effort_bounds_rule(model, i):
        return (model.min_effort[i], model.effort[i], model.max_effort[i])
    model.effort_bounds = pyo.Constraint(model.I, rule=effort_bounds_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("\nEffort allocation:")
        for i in model.I:
            effort_val = pyo.value(model.effort[i])
            print(f"Effort for poll source {i}: {effort_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
candidate_poll_optimization()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 34.25
**Execution Time**: 3.10 seconds
**Reliability**: high
**Analysis**: Pyomo achieved the optimal solution with a moderate execution time, indicating a balance between efficiency and reliability.

## 8. Cross-Solver Analysis and Final Recommendation

### Solver Results Comparison

| Solver | Status | Optimal Value | Execution Time | Decision Variables | Retry Attempt |
|--------|--------|---------------|----------------|-------------------|---------------|
| Gurobipy | OPTIMAL | 34.25 | 0.42s | N/A | N/A |
| Docplex | OPTIMAL | 34.25 | 7.57s | N/A | N/A |
| Pyomo | OPTIMAL | 34.25 | 3.10s | N/A | N/A |

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

### Final Recommendation
**Recommended Optimal Value**: 34.25
**Confidence Level**: HIGH
**Preferred Solver(s)**: gurobipy
**Reasoning**: Gurobipy is preferred due to its high reliability and the shortest execution time, making it the most efficient choice for this problem.

### Business Interpretation
**Overall Strategy**: The optimal allocation of resources maximizes the total support rate effectively.
**Objective Value Meaning**: The optimal objective value of 34.25 represents the maximum achievable support rate given the constraints.
**Resource Allocation Summary**: Resources should be allocated to maximize the support rate while adhering to budget and effort constraints.
**Implementation Recommendations**: Implement the solution by allocating resources according to the optimal decision variables, ensuring compliance with all constraints.