# Complete Optimization Problem and Solution: network_2

## 1. Problem Context and Goals

### Context  
A social network company is focused on enhancing its marketing campaign's effectiveness by strategically selecting individuals within the network to target. The primary decision involves determining which individuals should be targeted to maximize the spread of influence throughout the network. Each individual has an associated influence potential, and the goal is to maximize the total influence by targeting the right people. The company operates under a budget constraint, which limits the total cost of targeting individuals. The decision to target an individual is represented by a binary variable, where each person can either be targeted or not. The influence potential of each person is quantified and used to guide the targeting decisions. The total budget available for this campaign is a critical parameter, ensuring that the targeting strategy remains financially viable.

### Goals  
The optimization goal is to maximize the total influence spread across the network. This involves selecting individuals whose influence potential, when targeted, contributes the most to the overall influence. The success of the campaign is measured by the total influence achieved, which is directly linked to the influence potential of the targeted individuals. The objective is to make these decisions in a way that maximizes the total influence while adhering to the budget constraint.

## 2. Constraints    

The campaign is subject to several constraints to ensure feasibility and alignment with business objectives. The primary constraint is the budget limitation, which dictates that the total cost of targeting individuals must not exceed the available budget. Each individual has a specific cost associated with targeting them, and the sum of these costs for all targeted individuals must remain within the budget. Additionally, the decision to target an individual is binary, meaning each person can either be targeted or not, with no partial targeting allowed. These constraints ensure that the optimization problem remains linear and manageable.

## 3. Available Data  

### Database Schema  
```sql
-- Iteration 1 Database Schema
-- Objective: Schema changes include creating new tables for influence coefficients and costs, modifying existing tables for better mapping, and updating configuration logic for budget management.

CREATE TABLE InfluenceCoefficients (
  person_id INTEGER,
  influence_value FLOAT
);

CREATE TABLE TargetingCosts (
  person_id INTEGER,
  cost_value FLOAT
);

CREATE TABLE Person (
  name STRING,
  target BOOLEAN
);
```

### Data Dictionary  
The data used in this optimization problem is organized into three main tables, each serving a distinct purpose in the decision-making process:

- **InfluenceCoefficients**: This table captures the influence potential of each individual in the network. Each entry links a person to their influence value, which is a measure of their ability to spread influence if targeted. This data is crucial for determining the potential impact of targeting each individual.

- **TargetingCosts**: This table details the cost associated with targeting each person. Each entry connects a person to their targeting cost, which is used to ensure that the total cost of the campaign does not exceed the budget. This information is essential for maintaining financial feasibility.

- **Person**: This table stores information about individuals in the network, including their names and whether they are targeted in the campaign. The target column is a binary indicator used as a decision variable in the optimization model, representing the decision to target or not target each person.

### Current Stored Values  
```sql
-- Iteration 1 Realistic Data
-- Generated by triple expert (business + data + optimization)
-- Values were determined based on typical social network influence metrics and marketing budget constraints, ensuring a balance between influence potential and targeting costs.

-- Realistic data for InfluenceCoefficients
INSERT INTO InfluenceCoefficients (person_id, influence_value) VALUES (1, 1.5);
INSERT INTO InfluenceCoefficients (person_id, influence_value) VALUES (2, 0.9);
INSERT INTO InfluenceCoefficients (person_id, influence_value) VALUES (3, 1.2);

-- Realistic data for TargetingCosts
INSERT INTO TargetingCosts (person_id, cost_value) VALUES (1, 300.0);
INSERT INTO TargetingCosts (person_id, cost_value) VALUES (2, 150.0);
INSERT INTO TargetingCosts (person_id, cost_value) VALUES (3, 250.0);

-- Realistic data for Person
INSERT INTO Person (name, target) VALUES ('Alice', False);
INSERT INTO Person (name, target) VALUES ('Bob', True);
INSERT INTO Person (name, target) VALUES ('Charlie', False);
```

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