Math Modeling Problem Solver
Use this skill when the user asks to solve a mathematical modeling competition problem, especially multi-part problems like the Huazhong Cup or CUMCM.
Workflow
Phase 1: Understand the Problem
- Read all problem descriptions and data files — Identify each sub-problem, its constraints, objectives, and how it differs from other parts
- Load and inspect data files — Check Excel/CSV contents, understand column meanings, identify data types (coordinates, time windows, orders, distance matrices)
- Extract all model parameters — List every constant, coefficient, and constraint from the problem statement (speeds, penalty rates, emission factors, etc.)
Phase 2: Design the Solution Architecture
- Define the directory structure:
problem_A/code/ ← solver scripts
problem_A/data/ ← input data (xlsx, csv)
problem_A/figures/ ← visualizations
problem_B/... ← same pattern for each sub-problem
- Choose the modeling approach — e.g., Mixed Integer Programming, heuristic algorithms, dynamic programming
- Design the solver pipeline:
- Data loading and preprocessing (load Excel → normalize → index)
- Initial solution construction (greedy, insertion heuristics)
- Solution improvement (local search: 2-opt, swap, relocate)
- Constraint checking (capacity, time windows, special restrictions)
- Cost calculation (multi-component: startup + fuel + carbon + penalty)
- Plan output format — JSON for structured results + TXT for human-readable reports
Phase 3: Implement the Solver
- Use Python with pandas, numpy — Load Excel data, build distance matrices
- Build cost functions carefully:
- Time-varying speeds → time-dependent travel times
- U-shaped energy curves → speed-dependent fuel/kWh consumption
- Load-dependent adjustments → linear interpolation between empty and full
- Soft time windows → early/late penalty with different rates
- Carbon pricing → fuel-to-CO₂ conversion × carbon price
- Implement greedy construction — Sort customers by priority (time window start), insert at minimum marginal cost position
- Implement 2-opt local search — Iterate until no improvement; check all possible 2-opt swaps
- Add fleet management — Track vehicle counts by type, enforce fleet limits
- For multi-problem progression — Reuse previous problem's solver as baseline, add new constraints incrementally
Phase 4: Validate and Debug
- Run and check for constraint violations — Verify capacity, time windows, special restrictions are all satisfied
- If violations found — Write targeted fix functions, not universal hacks:
- Identify violating routes precisely
- Understand root cause (timing calculation, boundary condition, etc.)
- Fix the specific issue in cost/check functions
- Re-run and verify all violations resolved
- Compare to baselines — Check if results are reasonable relative to simpler models
Phase 5: Analyze Results
- Generate structured output — Save full results as JSON (routes, costs, details per route)
- Print human-readable summary — Route-by-route breakdown with per-route costs
- Compute aggregate statistics — Total cost, distance, CO₂, vehicle counts by type, load rates
- Cross-problem comparison — Compare metrics across sub-problems to identify trends
Key Patterns
Data structure pattern
info = {
'nodes': dict, # node_id → {kg, m3, cid, tw_start, tw_end, priority}
'ntw': dict, # node_id → (tw_start, tw_end)
'nd': 2D array, # distance matrix (n+1 × n+1)
'coords': dict, # node_id → (x, y)
'gz': set, # green zone customer IDs
'c2n': dict, # customer_id → [node_ids]
'agg': dict, # customer_id → {total_kg, total_m3}
'nn': list, # node IDs sorted by distance from depot
}
Cost function pattern
def route_cost(route, vehicle_type, info):
total = vehicle_type['startup_cost']
t = 480.0 # start time in minutes from midnight
has_violation = False
for each segment (i→j) in route:
speed = get_speed(t) # time-dependent
travel_time = distance / speed * 60
arrival = t + travel_time
energy = fpk(speed) * distance / 100 * load_factor
carbon = energy * emission_factor
carbon_cost = carbon * carbon_price
tw_penalty = compute_penalty(arrival, time_window)
total += energy_cost + carbon_cost + tw_penalty
return total, has_violation
Greedy insertion pattern
for each customer (sorted by time window start):
best_cost_increase = INF
best_vehicle = None
best_position = None
for each vehicle:
for each insertion position in vehicle.route:
cost_delta = marginal_cost_of_insertion(customer, position)
if cost_delta < best_cost_increase and constraints_satisfied:
best = (vehicle, position, cost_delta)
if best found:
insert customer into best vehicle at best position
else:
create new vehicle for this customer
Violation fix pattern
def find_violations(routes, info):
violations = []
for each route:
simulate arrival times (exactly matching route_cost logic)
if any constraint violated:
violations.append(detailed_violation_info)
return violations
def fix_violations(routes, violations, info):
for v in violations:
try: reassign to EV, adjust timing, or re-optimize
if unfixable: flag for manual review
Sub-problem progression for multi-part problems
When each sub-problem builds on the previous:
- Problem N → solve independently
- Problem N+1 → start from Problem N baseline, add new constraints, run and compare
- Problem N+2 → start from Problem N+1 baseline, add dynamic event handling, compare to static
Save each problem's results separately, then generate cross-problem comparison analysis.
Deliverables
For each problem, produce:
problemX_solver.py — Self-contained solver script
problemX_result.json — Machine-readable results
problemX_result.txt — Human-readable summary
figures/*.png — Visualizations (route maps, cost breakdowns)
Cross-problem:
5. Comprehensive comparison report (DOCX + TXT)
6. Paper template (DOCX)
7. All summary figures
1---2name: math-modeling-solver3description: Solve math modeling competition problems (Huazhong Cup, CUMCM, etc.) with a systematic workflow — data exploration, model building, algorithm implementation, result analysis.4---56# Math Modeling Problem Solver78Use this skill when the user asks to solve a mathematical modeling competition problem, especially multi-part problems like the Huazhong Cup or CUMCM.910## Workflow1112### Phase 1: Understand the Problem13141. **Read all problem descriptions and data files** — Identify each sub-problem, its constraints, objectives, and how it differs from other parts152. **Load and inspect data files** — Check Excel/CSV contents, understand column meanings, identify data types (coordinates, time windows, orders, distance matrices)163. **Extract all model parameters** — List every constant, coefficient, and constraint from the problem statement (speeds, penalty rates, emission factors, etc.)1718### Phase 2: Design the Solution Architecture19201. **Define the directory structure**:21 ```22 problem_A/code/ ← solver scripts23 problem_A/data/ ← input data (xlsx, csv)24 problem_A/figures/ ← visualizations25 problem_B/... ← same pattern for each sub-problem26 ```272. **Choose the modeling approach** — e.g., Mixed Integer Programming, heuristic algorithms, dynamic programming283. **Design the solver pipeline**:29 - Data loading and preprocessing (load Excel → normalize → index)30 - Initial solution construction (greedy, insertion heuristics)31 - Solution improvement (local search: 2-opt, swap, relocate)32 - Constraint checking (capacity, time windows, special restrictions)33 - Cost calculation (multi-component: startup + fuel + carbon + penalty)344. **Plan output format** — JSON for structured results + TXT for human-readable reports3536### Phase 3: Implement the Solver37381. **Use Python with pandas, numpy** — Load Excel data, build distance matrices392. **Build cost functions carefully**:40 - Time-varying speeds → time-dependent travel times41 - U-shaped energy curves → speed-dependent fuel/kWh consumption42 - Load-dependent adjustments → linear interpolation between empty and full43 - Soft time windows → early/late penalty with different rates44 - Carbon pricing → fuel-to-CO₂ conversion × carbon price453. **Implement greedy construction** — Sort customers by priority (time window start), insert at minimum marginal cost position464. **Implement 2-opt local search** — Iterate until no improvement; check all possible 2-opt swaps475. **Add fleet management** — Track vehicle counts by type, enforce fleet limits486. **For multi-problem progression** — Reuse previous problem's solver as baseline, add new constraints incrementally4950### Phase 4: Validate and Debug51521. **Run and check for constraint violations** — Verify capacity, time windows, special restrictions are all satisfied532. **If violations found** — Write targeted fix functions, not universal hacks:54 - Identify violating routes precisely55 - Understand root cause (timing calculation, boundary condition, etc.)56 - Fix the specific issue in cost/check functions57 - Re-run and verify all violations resolved583. **Compare to baselines** — Check if results are reasonable relative to simpler models5960### Phase 5: Analyze Results61621. **Generate structured output** — Save full results as JSON (routes, costs, details per route)632. **Print human-readable summary** — Route-by-route breakdown with per-route costs643. **Compute aggregate statistics** — Total cost, distance, CO₂, vehicle counts by type, load rates654. **Cross-problem comparison** — Compare metrics across sub-problems to identify trends6667## Key Patterns6869### Data structure pattern70```python71info = {72 'nodes': dict, # node_id → {kg, m3, cid, tw_start, tw_end, priority}73 'ntw': dict, # node_id → (tw_start, tw_end)74 'nd': 2D array, # distance matrix (n+1 × n+1)75 'coords': dict, # node_id → (x, y)76 'gz': set, # green zone customer IDs77 'c2n': dict, # customer_id → [node_ids]78 'agg': dict, # customer_id → {total_kg, total_m3}79 'nn': list, # node IDs sorted by distance from depot80}81```8283### Cost function pattern84```python85def route_cost(route, vehicle_type, info):86 total = vehicle_type['startup_cost']87 t = 480.0 # start time in minutes from midnight88 has_violation = False89 for each segment (i→j) in route:90 speed = get_speed(t) # time-dependent91 travel_time = distance / speed * 6092 arrival = t + travel_time93 energy = fpk(speed) * distance / 100 * load_factor94 carbon = energy * emission_factor95 carbon_cost = carbon * carbon_price96 tw_penalty = compute_penalty(arrival, time_window)97 total += energy_cost + carbon_cost + tw_penalty98 return total, has_violation99```100101### Greedy insertion pattern102```python103for each customer (sorted by time window start):104 best_cost_increase = INF105 best_vehicle = None106 best_position = None107 for each vehicle:108 for each insertion position in vehicle.route:109 cost_delta = marginal_cost_of_insertion(customer, position)110 if cost_delta < best_cost_increase and constraints_satisfied:111 best = (vehicle, position, cost_delta)112 if best found:113 insert customer into best vehicle at best position114 else:115 create new vehicle for this customer116```117118### Violation fix pattern119```python120def find_violations(routes, info):121 violations = []122 for each route:123 simulate arrival times (exactly matching route_cost logic)124 if any constraint violated:125 violations.append(detailed_violation_info)126 return violations127128def fix_violations(routes, violations, info):129 for v in violations:130 try: reassign to EV, adjust timing, or re-optimize131 if unfixable: flag for manual review132```133134## Sub-problem progression for multi-part problems135136When each sub-problem builds on the previous:137- **Problem N** → solve independently138- **Problem N+1** → start from Problem N baseline, add new constraints, run and compare139- **Problem N+2** → start from Problem N+1 baseline, add dynamic event handling, compare to static140141Save each problem's results separately, then generate cross-problem comparison analysis.142143## Deliverables144145For each problem, produce:1461. `problemX_solver.py` — Self-contained solver script1472. `problemX_result.json` — Machine-readable results1483. `problemX_result.txt` — Human-readable summary1494. `figures/*.png` — Visualizations (route maps, cost breakdowns)150151Cross-problem:1525. Comprehensive comparison report (DOCX + TXT)1536. Paper template (DOCX)1547. All summary figures