Skip to content

Fix #534: Add PartiallyOrderedKnapsack model#631

Open
zazabap wants to merge 8 commits intomainfrom
issue-534-partially-ordered-knapsack
Open

Fix #534: Add PartiallyOrderedKnapsack model#631
zazabap wants to merge 8 commits intomainfrom
issue-534-partially-ordered-knapsack

Conversation

@zazabap
Copy link
Collaborator

@zazabap zazabap commented Mar 13, 2026

Summary

Add the PartiallyOrderedKnapsack problem model — a knapsack variant where items are subject to a partial order (precedence constraints). Including an item requires including all its predecessors (downward-closed set). Modeled as an optimization problem (maximize total value subject to precedence + capacity).

Fixes #534

zazabap and others added 3 commits March 13, 2026 09:03
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- New optimization problem model in src/models/misc/
- Precedence-constrained knapsack with downward-closure check
- Full CLI support (dispatch, alias, create)
- 17 unit tests covering evaluation, solver, serialization
- Paper documentation with problem definition and references

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@zazabap
Copy link
Collaborator Author

zazabap commented Mar 13, 2026

Implementation Summary

Changes

  • src/models/misc/partially_ordered_knapsack.rs — New model: struct, constructor with validation, getters (sizes, values, precedences, capacity, num_items, num_precedences), Problem and OptimizationProblem trait impls with downward-closure feasibility check via Floyd-Warshall transitive closure, declare_variants! with 2^num_items complexity
  • src/models/misc/mod.rs — Register module and re-export
  • src/models/mod.rs — Add to misc re-export line
  • src/unit_tests/models/misc/partially_ordered_knapsack.rs — 17 tests: basic, evaluate (valid, precedence violation, transitive violation, overweight, empty, single root, chain, wrong length, invalid value), brute force solver, empty instance, no-precedences (standard knapsack behavior), zero capacity, serialization round-trip, constructor panics
  • problemreductions-cli/src/dispatch.rsload_problem and serialize_any_problem arms
  • problemreductions-cli/src/problem_name.rs — Lowercase alias mapping
  • problemreductions-cli/src/commands/create.rs — CLI creation with --sizes, --values, --capacity, --item-precedences
  • problemreductions-cli/src/cli.rs — New --values and --item-precedences flags, help table entry
  • docs/paper/reductions.typ — Problem definition entry with display name
  • docs/paper/references.bib — Added Johnson & Niemi 1983 and Kolliopoulos & Steiner 2007

Deviations from Plan

  • Used --item-precedences instead of --precedences to avoid conflicts with other potential flag names
  • Modeled as optimization (maximize value) per check-issue recommendation, consistent with existing Knapsack

Open Questions

  • None

@codecov
Copy link

codecov bot commented Mar 13, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.87%. Comparing base (d34477e) to head (460f58b).

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #631      +/-   ##
==========================================
+ Coverage   96.86%   96.87%   +0.01%     
==========================================
  Files         264      266       +2     
  Lines       35196    35447     +251     
==========================================
+ Hits        34091    34341     +250     
- Misses       1105     1106       +1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds a new optimization model, PartiallyOrderedKnapsack, extending the library and CLI to support knapsack instances with precedence (downward-closure) constraints, and updates the paper docs accordingly.

Changes:

  • Introduces PartiallyOrderedKnapsack model with schema registration, evaluation logic, and variant declaration.
  • Adds unit tests covering evaluation edge-cases, brute-force optimality, and serde roundtrip.
  • Integrates the model into the CLI (alias/dispatch/create flags) and paper documentation (+references).

Reviewed changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
src/models/misc/partially_ordered_knapsack.rs New model implementation + schema registration + variants + test module hook.
src/unit_tests/models/misc/partially_ordered_knapsack.rs Unit tests for correctness, solver integration, and serialization.
src/models/misc/mod.rs Registers and re-exports the new misc model.
src/models/mod.rs Re-exports the new model at the top-level models module.
problemreductions-cli/src/problem_name.rs Adds alias resolution for the new problem name.
problemreductions-cli/src/dispatch.rs Enables load/serialize dispatch for the new model.
problemreductions-cli/src/commands/create.rs Adds pred create PartiallyOrderedKnapsack ... support and parsing.
problemreductions-cli/src/cli.rs Adds new CLI flags (--values, --item-precedences) and help text line.
docs/paper/references.bib Adds bibliography entries used by the new paper section.
docs/paper/reductions.typ Adds problem definition section and display-name mapping for the paper.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +131 to +160
/// Uses the transitive closure of the precedence relation: if item `b` is
/// selected and `a` is a (transitive) predecessor of `b`, then `a` must
/// also be selected.
fn is_downward_closed(&self, config: &[usize]) -> bool {
let n = self.num_items();
// Build adjacency matrix for transitive closure
let mut reachable = vec![vec![false; n]; n];
for &(a, b) in &self.precedences {
reachable[a][b] = true;
}
// Floyd-Warshall for transitive closure
for k in 0..n {
for i in 0..n {
for j in 0..n {
if reachable[i][k] && reachable[k][j] {
reachable[i][j] = true;
}
}
}
}
// Check: for every selected item b, all predecessors must be selected
for b in 0..n {
if config[b] == 1 {
for a in 0..n {
if reachable[a][b] && config[a] != 1 {
return false;
}
}
}
}
Comment on lines +12 to +24
inventory::submit! {
ProblemSchemaEntry {
name: "PartiallyOrderedKnapsack",
module_path: module_path!(),
description: "Select items to maximize total value subject to precedence constraints and weight capacity",
fields: &[
FieldInfo { name: "sizes", type_name: "Vec<i64>", description: "Item sizes s(u) for each item" },
FieldInfo { name: "values", type_name: "Vec<i64>", description: "Item values v(u) for each item" },
FieldInfo { name: "precedences", type_name: "Vec<(usize, usize)>", description: "Precedence pairs (a, b) meaning a must be included before b" },
FieldInfo { name: "capacity", type_name: "i64", description: "Knapsack capacity B" },
],
}
}
#[arg(long)]
pub values: Option<String>,
/// Precedence pairs (e.g., "0>2,0>3,1>4") for PartiallyOrderedKnapsack
#[arg(long)]
Comment on lines +518 to +519
"PartiallyOrderedKnapsack requires --sizes, --values, --capacity, and --item-precedences\n\n\
Usage: pred create PartiallyOrderedKnapsack --sizes 2,3,4,1,2,3 --values 3,2,5,4,3,8 --item-precedences \"0>2,0>3,1>4,3>5,4>5\" --capacity 11"
#problem-def("PartiallyOrderedKnapsack")[
Given a finite set $U$ with $|U| = n$ items, a partial order $<$ on $U$ (given by its cover relations), for each $u in U$ a size $s(u) in ZZ^+$ and a value $v(u) in ZZ^+$, and a capacity $B in ZZ^+$, find a downward-closed subset $U' subset.eq U$ (i.e., if $u in U'$ and $u' < u$ then $u' in U'$) maximizing $sum_(u in U') v(u)$ subject to $sum_(u in U') s(u) lt.eq B$.
][
Garey and Johnson's problem A6 MP12 @garey1979. Unlike standard Knapsack, the partial order constraint makes the problem _strongly_ NP-complete --- it remains NP-complete even when $s(u) = v(u)$ for all $u$, so no pseudo-polynomial algorithm exists unless $P = "NP"$. The problem arises in manufacturing scheduling, project selection, and mining operations. For tree partial orders, Johnson and Niemi @johnson1983 gave pseudo-polynomial $O(n dot B)$ tree DP and an FPTAS. Kolliopoulos and Steiner @kolliopoulos2007 extended the FPTAS to 2-dimensional partial orders with $O(n^4 slash epsilon)$ running time.
zazabap and others added 5 commits March 15, 2026 07:53
…rdered-knapsack

# Conflicts:
#	docs/paper/reductions.typ
#	docs/paper/references.bib
#	problemreductions-cli/src/cli.rs
#	problemreductions-cli/src/commands/create.rs
#	problemreductions-cli/src/dispatch.rs
#	problemreductions-cli/src/problem_name.rs
#	src/models/misc/mod.rs
#	src/models/mod.rs
- Precompute transitive predecessors in constructor instead of recomputing
  Floyd-Warshall on every evaluate() call
- Custom Serialize/Deserialize to rebuild predecessors on deserialization
- Rename CLI flag --item-precedences to --precedences (with alias for compat)
- Fix error message to reflect --precedences is optional
- Fix Typst $P = "NP"$ to $P = N P$ for correct math typography
- Add missing schema fields (display_name, aliases, dimensions)
- Add opt keyword to declare_variants!
- Regenerate problem_schemas.json and reduction_graph.json

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Add canonical model example builder for PartiallyOrderedKnapsack
- Add PartiallyOrderedKnapsack to trait_consistency tests
- Add nonnegative validation for sizes and capacity
- Add cycle detection in precedence graph
- Fix corrupted reduction_graph.json (was mixing stdout/JSON)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@zazabap
Copy link
Collaborator Author

zazabap commented Mar 15, 2026

Review Pipeline Report

Check Result
Merge with main Resolved 8 file conflicts
Copilot comments 5 fixed (precompute predecessors, fix CLI flag name, fix error message, fix Typst math, add missing schema fields)
Issue/human comments 2 checked, 0 actionable
Structural review 18/18 passed (added canonical example, trait_consistency entry)
Quality review Fixed corrupted reduction_graph.json, added nonneg validation, added cycle detection
CI green (2 attempts, fixed clippy needless_range_loop)
Agentic test passed (pred list/show/create all work)
Board Review pool → Under review → Final review

🤖 Generated by review-pipeline

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Model] PartiallyOrderedKnapsack

2 participants