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