## 4. Mathematical Optimization Formulation

#### Decision Variables
- Let \( x_i \) be a binary decision variable for each person \( i \), where \( x_i = 1 \) if person \( i \) is targeted, and \( x_i = 0 \) otherwise.

#### Objective Function
Maximize the total influence spread across the network:

\[
\text{Maximize } Z = 1.5x_1 + 0.9x_2 + 1.2x_3
\]

Data Source Verification:
- Coefficients for the objective function are derived from the `InfluenceCoefficients.influence_value` column.

#### Constraints
1. Budget Constraint: The total cost of targeting individuals must not exceed the available budget.

\[
300x_1 + 150x_2 + 250x_3 \leq \text{Budget}
\]

Assuming a budget of 500 (as an example):

\[
300x_1 + 150x_2 + 250x_3 \leq 500
\]

Data Source Verification:
- Coefficients for the budget constraint are derived from the `TargetingCosts.cost_value` column.

2. Binary Decision Variables: Each person can either be targeted or not.

\[
x_i \in \{0, 1\} \quad \forall i \in \{1, 2, 3\}
\]

This formulation provides a complete and immediately solvable linear mathematical model using the provided data. The objective is to maximize the total influence while adhering to the budget constraint, with decision variables representing whether each individual is targeted.

## 5. Gurobipy Implementation

```python
# Complete GUROBIPY implementation

import gurobipy as gp
from gurobipy import GRB

def optimize_social_network_influence():
    """Optimize the targeting strategy for maximum influence spread within budget constraints."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("network_2")
    
    # Data: Influence values and costs for each person
    influence_values = [1.5, 0.9, 1.2]
    targeting_costs = [300.0, 150.0, 250.0]
    budget = 500.0
    n_people = len(influence_values)
    
    # CRITICAL: Validate array lengths before loops
    assert len(influence_values) == len(targeting_costs) == n_people, "Array length mismatch"
    
    # 2. VARIABLES
    # Binary decision variables for targeting each person
    x = {i: model.addVar(vtype=GRB.BINARY, name=f"x_{i}") for i in range(n_people)}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total influence
    model.setObjective(gp.quicksum(influence_values[i] * x[i] for i in range(n_people)), GRB.MAXIMIZE)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Budget constraint
    model.addConstr(gp.quicksum(targeting_costs[i] * x[i] for i in range(n_people)) <= budget, name="budget_constraint")
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in range(n_people):
            if x[i].x > 1e-6:
                print(f"Person {i+1} is targeted.")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

# Run the optimization
optimize_social_network_influence()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 2.4
**Execution Time**: 1.39 seconds
**Reliability**: high
**Analysis**: Gurobipy found an optimal solution quickly with the lowest execution time, indicating efficient performance and reliability.

## 6. DOCplex Implementation

```python
# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_social_network_campaign():
    """Optimize the targeting strategy for a social network marketing campaign."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="network_2")
    
    # Data from the problem statement
    influence_values = [1.5, 0.9, 1.2]
    targeting_costs = [300.0, 150.0, 250.0]
    budget = 500.0
    
    # Validate array lengths to prevent IndexError
    assert len(influence_values) == len(targeting_costs), "Array length mismatch"
    safe_range = range(len(influence_values))  # Safe indexing
    
    # 2. VARIABLES
    # Binary decision variables for targeting individuals
    x = {i: mdl.binary_var(name=f"x_{i}") for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the total influence spread across the network
    objective = mdl.sum(influence_values[i] * x[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    # Budget constraint: Total cost of targeting must not exceed the budget
    total_cost = mdl.sum(targeting_costs[i] * x[i] for i in safe_range)
    mdl.add_constraint(total_cost <= budget, ctname="budget_constraint")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(x[i])
            if value > 1e-6:
                print(f"x[{i}] = {value:.0f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
optimize_social_network_campaign()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 2.4
**Execution Time**: 5.02 seconds
**Reliability**: high
**Analysis**: DOCplex also found an optimal solution, though with a longer execution time compared to Gurobipy, but still reliable.

## 7. Pyomo Implementation

```python
# Complete PYOMO implementation

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

def network_optimization():
    """Optimization for maximizing influence in a social network under budget constraints"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Data from the problem statement
    influence_values = [1.5, 0.9, 1.2]
    targeting_costs = [300.0, 150.0, 250.0]
    budget = 500.0
    
    # Validate array lengths
    n_people = len(influence_values)
    assert len(targeting_costs) == n_people, "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.RangeSet(1, n_people)  # 1-based indexing
    
    # 4. PARAMETERS
    model.influence = pyo.Param(model.I, initialize={i+1: influence_values[i] for i in range(n_people)})
    model.cost = pyo.Param(model.I, initialize={i+1: targeting_costs[i] for i in range(n_people)})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.influence[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    def budget_constraint_rule(model):
        return sum(model.cost[i] * model.x[i] for i in model.I) <= budget
    model.budget_constraint = pyo.Constraint(rule=budget_constraint_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)}")
        
        # Extract variable values
        print("\nVariable values:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"x[{i}] = {int(x_val)}")
        
    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
network_optimization()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 2.4
**Execution Time**: 10.88 seconds
**Reliability**: medium
**Analysis**: Pyomo achieved the optimal solution but took significantly longer, suggesting less efficiency compared to the other solvers.

## 8. Cross-Solver Analysis and Final Recommendation

### Solver Results Comparison

| Solver | Status | Optimal Value | Execution Time | Decision Variables | Retry Attempt |
|--------|--------|---------------|----------------|-------------------|---------------|
| Gurobipy | OPTIMAL | 2.40 | 1.39s | N/A | N/A |
| Docplex | OPTIMAL | 2.40 | 5.02s | N/A | N/A |
| Pyomo | OPTIMAL | 2.40 | 10.88s | N/A | N/A |

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

### Final Recommendation
**Recommended Optimal Value**: 2.4
**Confidence Level**: HIGH
**Preferred Solver(s)**: gurobipy
**Reasoning**: Gurobipy is preferred due to its high reliability and efficiency, providing the optimal solution in the shortest time.

### Optimal Decision Variables
- **x_1** = 1.000
  - *Business Meaning*: Targeting person 2, who has a moderate influence coefficient, is optimal.
- **x_2** = 1.000
  - *Business Meaning*: Not targeting person 3, as it does not fit within the budget while maximizing influence.
- **x_3** = 0.000
  - *Business Meaning*: Resource allocation for x_3

### Business Interpretation
**Overall Strategy**: Targeting individuals 1 and 2 maximizes influence within the budget constraints.
**Objective Value Meaning**: The optimal objective value of 2.4 represents the maximum achievable influence spread within the given budget.
**Resource Allocation Summary**: Allocate resources to target individuals 1 and 2, ensuring the budget constraint is respected.
**Implementation Recommendations**: Implement a strategy to engage individuals 1 and 2 effectively to maximize influence spread.