# Complete Optimization Problem and Solution: news_report

## 1. Problem Context and Goals

### Context  
A news agency is tasked with optimizing the assignment of journalists to events to maximize the overall quality of coverage. The quality of coverage is determined by the journalist's years of experience and the attendance of the event they are assigned to. Each event must be covered by at least one journalist, and no journalist can be assigned to more than a specified number of events, as defined by the business configuration. The decision to assign a journalist to an event is represented as a binary choice, ensuring a clear and linear relationship between the decision variables and the objective. The coverage quality is calculated as the product of the journalist's years of experience and the event's attendance, which directly contributes to the linear objective function. This setup ensures that the optimization problem remains linear, avoiding any nonlinear relationships such as variable products or divisions.

### Goals  
The primary goal of this optimization problem is to maximize the total coverage quality across all events. This is achieved by strategically assigning journalists to events in a way that leverages their experience and the significance of the event, as measured by attendance. Success is measured by the sum of the coverage quality scores for all assignments, where each score is the product of the journalist's years of experience and the event's attendance. The optimization process ensures that the assignments are made within the constraints of each journalist's maximum allowable number of event assignments, maintaining a balanced and efficient allocation of resources.

## 2. Constraints    

1. **Event Coverage Requirement**: Each event must be covered by at least one journalist. This ensures that all events receive adequate coverage, and no event is left unattended.  
2. **Journalist Assignment Limit**: No journalist can be assigned to more than the maximum number of events specified in the business configuration. This prevents overburdening journalists and ensures a fair distribution of assignments.  

These constraints are designed to maintain operational feasibility while aligning with the linear structure of the optimization problem. They ensure that the assignments are both comprehensive and balanced, without introducing any nonlinear complexities.

## 3. Available Data  

### Database Schema  
```sql
-- Iteration 1 Database Schema
-- Objective: Schema changes include creating a new table for journalist-event assignments and adding a column for maximum assignments per journalist. Configuration logic updates include adding scalar parameters for maximum assignments and a formula for coverage quality calculation.

CREATE TABLE journalist (
  Years_working INTEGER,
  max_assignments INTEGER
);

CREATE TABLE event (
  Event_Attendance INTEGER
);

CREATE TABLE journalist_event_assignment (
  assignment BOOLEAN
);
```

### Data Dictionary  
- **Journalist Table**:  
  - **Years_working**: Represents the number of years a journalist has been working. This value is used to calculate the coverage quality score.  
  - **max_assignments**: Specifies the maximum number of events a journalist can be assigned to, ensuring balanced workloads.  

- **Event Table**:  
  - **Event_Attendance**: Represents the number of attendees at an event. This value is used to calculate the coverage quality score.  

- **Journalist_Event_Assignment Table**:  
  - **assignment**: A binary indicator (0 or 1) that determines whether a journalist is assigned to a specific event. This is the decision variable in the optimization problem.  

### Current Stored Values  
```sql
-- Iteration 1 Realistic Data
-- Generated by triple expert (business + data + optimization)
-- Values were determined based on realistic business scenarios, considering journalist experience levels, event attendance ranges, and assignment constraints to ensure a meaningful and solvable optimization problem.

-- Realistic data for journalist
INSERT INTO journalist (Years_working, max_assignments) VALUES (5, 3);
INSERT INTO journalist (Years_working, max_assignments) VALUES (10, 4);
INSERT INTO journalist (Years_working, max_assignments) VALUES (15, 5);

-- Realistic data for event
INSERT INTO event (Event_Attendance) VALUES (100);
INSERT INTO event (Event_Attendance) VALUES (200);
INSERT INTO event (Event_Attendance) VALUES (300);

-- Realistic data for journalist_event_assignment
INSERT INTO journalist_event_assignment (assignment) VALUES (0);
INSERT INTO journalist_event_assignment (assignment) VALUES (1);
INSERT INTO journalist_event_assignment (assignment) VALUES (0);
```

## 4. Mathematical Optimization Formulation

#### Decision Variables
- Let \( x_{ij} \) be a binary decision variable where:
  - \( x_{ij} = 1 \) if journalist \( i \) is assigned to event \( j \)
  - \( x_{ij} = 0 \) otherwise

#### Objective Function
Maximize the total coverage quality:
\[
\text{Maximize } Z = \sum_{i} \sum_{j} (\text{Years\_working}_i \times \text{Event\_Attendance}_j) \times x_{ij}
\]
Where:
- \( \text{Years\_working}_i \) is the number of years journalist \( i \) has been working (from journalist.Years_working)
- \( \text{Event\_Attendance}_j \) is the attendance of event \( j \) (from event.Event_Attendance)

#### Constraints
1. **Event Coverage Requirement**: Each event must be covered by at least one journalist:
\[
\sum_{i} x_{ij} \geq 1 \quad \forall j
\]
2. **Journalist Assignment Limit**: No journalist can be assigned to more than their maximum number of events:
\[
\sum_{j} x_{ij} \leq \text{max\_assignments}_i \quad \forall i
\]
Where:
- \( \text{max\_assignments}_i \) is the maximum number of events journalist \( i \) can be assigned to (from journalist.max_assignments)

#### Data Source Verification
- \( \text{Years\_working}_i \): journalist.Years_working
- \( \text{Event\_Attendance}_j \): event.Event_Attendance
- \( \text{max\_assignments}_i \): journalist.max_assignments

### Complete Numerical Model
Using the provided data:

#### Decision Variables
- \( x_{11}, x_{12}, x_{13} \): Assignment of journalist 1 to events 1, 2, 3
- \( x_{21}, x_{22}, x_{23} \): Assignment of journalist 2 to events 1, 2, 3
- \( x_{31}, x_{32}, x_{33} \): Assignment of journalist 3 to events 1, 2, 3

#### Objective Function
\[
\text{Maximize } Z = 5 \times 100 \times x_{11} + 5 \times 200 \times x_{12} + 5 \times 300 \times x_{13} + 10 \times 100 \times x_{21} + 10 \times 200 \times x_{22} + 10 \times 300 \times x_{23} + 15 \times 100 \times x_{31} + 15 \times 200 \times x_{32} + 15 \times 300 \times x_{33}
\]
\[
\text{Maximize } Z = 500x_{11} + 1000x_{12} + 1500x_{13} + 1000x_{21} + 2000x_{22} + 3000x_{23} + 1500x_{31} + 3000x_{32} + 4500x_{33}
\]

#### Constraints
1. **Event Coverage Requirement**:
\[
x_{11} + x_{21} + x_{31} \geq 1 \quad \text{(Event 1)}
\]
\[
x_{12} + x_{22} + x_{32} \geq 1 \quad \text{(Event 2)}
\]
\[
x_{13} + x_{23} + x_{33} \geq 1 \quad \text{(Event 3)}
\]
2. **Journalist Assignment Limit**:
\[
x_{11} + x_{12} + x_{13} \leq 3 \quad \text{(Journalist 1)}
\]
\[
x_{21} + x_{22} + x_{23} \leq 4 \quad \text{(Journalist 2)}
\]
\[
x_{31} + x_{32} + x_{33} \leq 5 \quad \text{(Journalist 3)}
\]

This is a complete, immediately solvable linear programming model.

## 5. Gurobipy Implementation

```python
#!/usr/bin/env python3
"""
Gurobipy Implementation for News Report Optimization Problem
"""

import gurobipy as gp
from gurobipy import GRB

def optimize_news_report():
    """Optimize the assignment of journalists to events to maximize coverage quality."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("news_report_optimization")
    
    # Data from the problem
    journalists = [
        {"Years_working": 5, "max_assignments": 3},
        {"Years_working": 10, "max_assignments": 4},
        {"Years_working": 15, "max_assignments": 5}
    ]
    
    events = [
        {"Event_Attendance": 100},
        {"Event_Attendance": 200},
        {"Event_Attendance": 300}
    ]
    
    n_journalists = len(journalists)
    n_events = len(events)
    
    # CRITICAL: Validate array lengths before loops
    assert n_journalists > 0 and n_events > 0, "Array length mismatch"
    
    # 2. VARIABLES
    # Binary decision variables: x[i][j] = 1 if journalist i is assigned to event j
    x = model.addVars(n_journalists, n_events, vtype=GRB.BINARY, name="x")
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total coverage quality
    model.setObjective(
        gp.quicksum(
            journalists[i]["Years_working"] * events[j]["Event_Attendance"] * x[i, j]
            for i in range(n_journalists)
            for j in range(n_events)
        ),
        GRB.MAXIMIZE
    )
    
    # 4. CONSTRAINTS
    
    # Event Coverage Requirement: Each event must be covered by at least one journalist
    for j in range(n_events):
        model.addConstr(
            gp.quicksum(x[i, j] for i in range(n_journalists)) >= 1,
            name=f"event_coverage_{j}"
        )
    
    # Journalist Assignment Limit: No journalist can be assigned to more than their max_assignments
    for i in range(n_journalists):
        model.addConstr(
            gp.quicksum(x[i, j] for j in range(n_events)) <= journalists[i]["max_assignments"],
            name=f"journalist_limit_{i}"
        )
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in range(n_journalists):
            for j in range(n_events):
                if x[i, j].x > 0.5:  # Check if assignment is made
                    print(f"Journalist {i} assigned to Event {j}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

# Run the optimization
if __name__ == "__main__":
    optimize_news_report()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 18000.0
**Execution Time**: 0.19 seconds
**Reliability**: high
**Analysis**: Gurobipy found the optimal solution quickly with an execution time of 0.189 seconds, indicating high efficiency and reliability.

## 6. DOCplex Implementation

```python
#!/usr/bin/env python3
"""
DOCplex implementation for news agency journalist assignment optimization
"""

from docplex.mp.model import Model

def optimize_journalist_assignments():
    """Optimize journalist assignments to maximize coverage quality"""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="news_report_optimization")
    
    # Journalist data
    journalists = [
        {"Years_working": 5, "max_assignments": 3},
        {"Years_working": 10, "max_assignments": 4},
        {"Years_working": 15, "max_assignments": 5}
    ]
    
    # Event data
    events = [
        {"Event_Attendance": 100},
        {"Event_Attendance": 200},
        {"Event_Attendance": 300}
    ]
    
    # CRITICAL: Validate array lengths
    n_journalists = len(journalists)
    n_events = len(events)
    assert n_journalists > 0 and n_events > 0, "Empty data arrays"
    
    # Safe indexing range
    safe_journalists = range(n_journalists)
    safe_events = range(n_events)
    
    # 2. VARIABLES
    # Binary decision variables: x[i][j] = 1 if journalist i is assigned to event j
    x = {(i, j): mdl.binary_var(name=f"x_{i}_{j}") 
         for i in safe_journalists for j in safe_events}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total coverage quality
    coverage_quality = mdl.sum(
        journalists[i]["Years_working"] * events[j]["Event_Attendance"] * x[(i, j)]
        for i in safe_journalists for j in safe_events
    )
    mdl.maximize(coverage_quality)
    
    # 4. CONSTRAINTS
    
    # Event Coverage Requirement: Each event must be covered by at least one journalist
    for j in safe_events:
        mdl.add_constraint(
            mdl.sum(x[(i, j)] for i in safe_journalists) >= 1,
            ctname=f"event_coverage_{j}"
        )
    
    # Journalist Assignment Limit: No journalist can be assigned to more than max_assignments
    for i in safe_journalists:
        mdl.add_constraint(
            mdl.sum(x[(i, j)] for j in safe_events) <= journalists[i]["max_assignments"],
            ctname=f"journalist_limit_{i}"
        )
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_journalists:
            for j in safe_events:
                if solution.get_value(x[(i, j)]) > 0.5:  # Binary variable threshold
                    print(f"Journalist {i} assigned to Event {j}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
if __name__ == "__main__":
    optimize_journalist_assignments()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 18000.0
**Execution Time**: 1.17 seconds
**Reliability**: high
**Analysis**: DOCplex also found the optimal solution but took longer (1.169 seconds) compared to Gurobipy, suggesting slightly lower efficiency.

## 7. Pyomo Implementation

```python
#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for News Agency Optimization Problem
"""

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

def news_agency_optimization():
    """Optimize journalist assignments to events to maximize coverage quality."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Journalist data: Years_working and max_assignments
    journalists = {
        1: {'Years_working': 5, 'max_assignments': 3},
        2: {'Years_working': 10, 'max_assignments': 4},
        3: {'Years_working': 15, 'max_assignments': 5}
    }
    
    # Event data: Event_Attendance
    events = {
        1: {'Event_Attendance': 100},
        2: {'Event_Attendance': 200},
        3: {'Event_Attendance': 300}
    }
    
    # CRITICAL: Validate array lengths before indexing
    assert len(journalists) > 0 and len(events) > 0, "Data arrays must not be empty"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.Set(initialize=journalists.keys())  # Journalists
    model.J = pyo.Set(initialize=events.keys())      # Events
    
    # 4. PARAMETERS (data containers)
    model.Years_working = pyo.Param(model.I, initialize={i: journalists[i]['Years_working'] for i in model.I})
    model.max_assignments = pyo.Param(model.I, initialize={i: journalists[i]['max_assignments'] for i in model.I})
    model.Event_Attendance = pyo.Param(model.J, initialize={j: events[j]['Event_Attendance'] for j in model.J})
    
    # 5. VARIABLES
    # Binary decision variables: x[i,j] = 1 if journalist i is assigned to event j
    model.x = pyo.Var(model.I, model.J, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    # Maximize total coverage quality
    def obj_rule(model):
        return sum(model.Years_working[i] * model.Event_Attendance[j] * model.x[i,j] for i in model.I for j in model.J)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Event Coverage Requirement: Each event must be covered by at least one journalist
    def event_coverage_rule(model, j):
        return sum(model.x[i,j] for i in model.I) >= 1
    model.event_coverage = pyo.Constraint(model.J, rule=event_coverage_rule)
    
    # Journalist Assignment Limit: No journalist can be assigned to more than their max_assignments
    def journalist_limit_rule(model, i):
        return sum(model.x[i,j] for j in model.J) <= model.max_assignments[i]
    model.journalist_limit = pyo.Constraint(model.I, rule=journalist_limit_rule)
    
    # 8. SOLVING WITH GUROBI (your available solver)
    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(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nAssignment details:")
        for i in model.I:
            for j in model.J:
                if pyo.value(model.x[i,j]) > 0.5:  # Only print assignments
                    print(f"Journalist {i} assigned to Event {j}")
        
    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

# Execute the optimization
if __name__ == "__main__":
    news_agency_optimization()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 18000.0
**Execution Time**: 0.76 seconds
**Reliability**: high
**Analysis**: Pyomo found the optimal solution with an execution time of 0.756 seconds, which is intermediate between Gurobipy and DOCplex.

## 8. Cross-Solver Analysis and Final Recommendation

### Solver Results Comparison

| Solver | Status | Optimal Value | Execution Time | Decision Variables | Retry Attempt |
|--------|--------|---------------|----------------|-------------------|---------------|
| Gurobipy | OPTIMAL | 18000.00 | 0.19s | N/A | N/A |
| Docplex | OPTIMAL | 18000.00 | 1.17s | N/A | N/A |
| Pyomo | OPTIMAL | 18000.00 | 0.76s | N/A | N/A |

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

### Final Recommendation
**Recommended Optimal Value**: 18000.0
**Confidence Level**: HIGH
**Preferred Solver(s)**: gurobipy
**Reasoning**: Gurobipy is recommended due to its fastest execution time while still providing the optimal solution, indicating higher efficiency and reliability.

### Business Interpretation
**Overall Strategy**: The optimal total coverage quality of 18000 indicates the best possible assignment of journalists to events based on their experience and event attendance.
**Objective Value Meaning**: The optimal objective value of 18000 represents the maximum total coverage quality achievable given the constraints.
**Resource Allocation Summary**: Journalists should be assigned to events in a way that maximizes their experience and the event attendance, ensuring all events are covered and no journalist is over-assigned.
**Implementation Recommendations**: Implement the assignments as per the optimal solution, ensuring that each event is covered by at least one journalist and no journalist exceeds their maximum assignment limit.