-
Notifications
You must be signed in to change notification settings - Fork 4
Fix #232: Add PartitionIntoTriangles model #609
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
6c25bca
feat: add PartitionIntoTriangles model (#232)
zazabap 96c1e67
Merge origin/main into issue-232-partition-into-triangles
GiggleLiu 68b137e
Address Copilot review: optimize evaluate() and validate CLI input
GiggleLiu e901e06
Fix clippy needless_range_loop warning in evaluate()
GiggleLiu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,160 @@ | ||
| //! Partition Into Triangles problem implementation. | ||
| //! | ||
| //! Given a graph G = (V, E) where |V| = 3q, determine whether V can be | ||
| //! partitioned into q triples, each forming a triangle (K3) in G. | ||
|
|
||
| use crate::registry::{FieldInfo, ProblemSchemaEntry}; | ||
| use crate::topology::{Graph, SimpleGraph}; | ||
| use crate::traits::{Problem, SatisfactionProblem}; | ||
| use crate::variant::VariantParam; | ||
| use serde::{Deserialize, Serialize}; | ||
|
|
||
| inventory::submit! { | ||
| ProblemSchemaEntry { | ||
| name: "PartitionIntoTriangles", | ||
| module_path: module_path!(), | ||
| description: "Partition vertices into triangles (K3 subgraphs)", | ||
| fields: &[ | ||
| FieldInfo { name: "graph", type_name: "G", description: "The underlying graph G=(V,E) with |V| divisible by 3" }, | ||
| ], | ||
| } | ||
| } | ||
|
|
||
| /// The Partition Into Triangles problem. | ||
| /// | ||
| /// Given a graph G = (V, E) where |V| = 3q, determine whether V can be | ||
| /// partitioned into q triples, each forming a triangle (K3) in G. | ||
| /// | ||
| /// # Type Parameters | ||
| /// | ||
| /// * `G` - Graph type (e.g., SimpleGraph) | ||
| /// | ||
| /// # Example | ||
| /// | ||
| /// ``` | ||
| /// use problemreductions::models::graph::PartitionIntoTriangles; | ||
| /// use problemreductions::topology::SimpleGraph; | ||
| /// use problemreductions::{Problem, Solver, BruteForce}; | ||
| /// | ||
| /// // Triangle graph: 3 vertices forming a single triangle | ||
| /// let graph = SimpleGraph::new(3, vec![(0, 1), (1, 2), (0, 2)]); | ||
| /// let problem = PartitionIntoTriangles::new(graph); | ||
| /// | ||
| /// let solver = BruteForce::new(); | ||
| /// let solution = solver.find_satisfying(&problem); | ||
| /// assert!(solution.is_some()); | ||
| /// ``` | ||
| #[derive(Debug, Clone, Serialize, Deserialize)] | ||
| #[serde(bound(deserialize = "G: serde::Deserialize<'de>"))] | ||
| pub struct PartitionIntoTriangles<G> { | ||
| /// The underlying graph. | ||
| graph: G, | ||
| } | ||
|
|
||
| impl<G: Graph> PartitionIntoTriangles<G> { | ||
| /// Create a new Partition Into Triangles problem from a graph. | ||
| /// | ||
| /// # Panics | ||
| /// Panics if the number of vertices is not divisible by 3. | ||
| pub fn new(graph: G) -> Self { | ||
| assert!( | ||
| graph.num_vertices().is_multiple_of(3), | ||
| "Number of vertices ({}) must be divisible by 3", | ||
| graph.num_vertices() | ||
| ); | ||
| Self { graph } | ||
| } | ||
|
|
||
| /// Get a reference to the underlying graph. | ||
| pub fn graph(&self) -> &G { | ||
| &self.graph | ||
| } | ||
|
|
||
| /// Get the number of vertices in the underlying graph. | ||
| pub fn num_vertices(&self) -> usize { | ||
| self.graph.num_vertices() | ||
| } | ||
|
|
||
| /// Get the number of edges in the underlying graph. | ||
| pub fn num_edges(&self) -> usize { | ||
| self.graph.num_edges() | ||
| } | ||
| } | ||
|
|
||
| impl<G> Problem for PartitionIntoTriangles<G> | ||
| where | ||
| G: Graph + VariantParam, | ||
| { | ||
| const NAME: &'static str = "PartitionIntoTriangles"; | ||
| type Metric = bool; | ||
|
|
||
| fn variant() -> Vec<(&'static str, &'static str)> { | ||
| crate::variant_params![G] | ||
| } | ||
|
|
||
| fn dims(&self) -> Vec<usize> { | ||
| let q = self.graph.num_vertices() / 3; | ||
| vec![q; self.graph.num_vertices()] | ||
| } | ||
|
|
||
| fn evaluate(&self, config: &[usize]) -> bool { | ||
| let n = self.graph.num_vertices(); | ||
| let q = n / 3; | ||
|
|
||
| // Check config length | ||
| if config.len() != n { | ||
| return false; | ||
| } | ||
|
|
||
| // Check all values are in range [0, q) | ||
| if config.iter().any(|&c| c >= q) { | ||
| return false; | ||
| } | ||
|
|
||
| // Count vertices per group | ||
| let mut counts = vec![0usize; q]; | ||
| for &c in config { | ||
| counts[c] += 1; | ||
| } | ||
|
|
||
| // Each group must have exactly 3 vertices | ||
| if counts.iter().any(|&c| c != 3) { | ||
| return false; | ||
| } | ||
|
|
||
| // Build per-group vertex lists in a single pass over config. | ||
| let mut group_verts = vec![[0usize; 3]; q]; | ||
| let mut group_pos = vec![0usize; q]; | ||
|
|
||
| for (v, &g) in config.iter().enumerate() { | ||
| let pos = group_pos[g]; | ||
| group_verts[g][pos] = v; | ||
| group_pos[g] = pos + 1; | ||
| } | ||
|
|
||
| // Check each group forms a triangle | ||
| for verts in &group_verts { | ||
| if !self.graph.has_edge(verts[0], verts[1]) { | ||
| return false; | ||
| } | ||
| if !self.graph.has_edge(verts[0], verts[2]) { | ||
| return false; | ||
| } | ||
| if !self.graph.has_edge(verts[1], verts[2]) { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| true | ||
| } | ||
| } | ||
|
|
||
| impl<G: Graph + VariantParam> SatisfactionProblem for PartitionIntoTriangles<G> {} | ||
|
|
||
| crate::declare_variants! { | ||
| PartitionIntoTriangles<SimpleGraph> => "2^num_vertices", | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| #[path = "../../unit_tests/models/graph/partition_into_triangles.rs"] | ||
| mod tests; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
127 changes: 127 additions & 0 deletions
127
src/unit_tests/models/graph/partition_into_triangles.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,127 @@ | ||
| use super::*; | ||
| use crate::solvers::{BruteForce, Solver}; | ||
| use crate::topology::SimpleGraph; | ||
|
|
||
| #[test] | ||
| fn test_partitionintotriangles_basic() { | ||
| use crate::traits::Problem; | ||
|
|
||
| // 9-vertex YES instance: three disjoint triangles | ||
| // Triangle 1: 0-1-2, Triangle 2: 3-4-5, Triangle 3: 6-7-8 | ||
| let graph = SimpleGraph::new( | ||
| 9, | ||
| vec![ | ||
| (0, 1), | ||
| (1, 2), | ||
| (0, 2), | ||
| (3, 4), | ||
| (4, 5), | ||
| (3, 5), | ||
| (6, 7), | ||
| (7, 8), | ||
| (6, 8), | ||
| ], | ||
| ); | ||
| let problem = PartitionIntoTriangles::new(graph); | ||
|
|
||
| assert_eq!(problem.num_vertices(), 9); | ||
| assert_eq!(problem.num_edges(), 9); | ||
| assert_eq!(problem.dims(), vec![3; 9]); | ||
|
|
||
| // Valid partition: vertices 0,1,2 in group 0; 3,4,5 in group 1; 6,7,8 in group 2 | ||
| assert!(problem.evaluate(&[0, 0, 0, 1, 1, 1, 2, 2, 2])); | ||
|
|
||
| // Invalid: wrong grouping (vertices 0,1,3 are not a triangle) | ||
| assert!(!problem.evaluate(&[0, 0, 1, 0, 1, 1, 2, 2, 2])); | ||
|
|
||
| // Invalid: group sizes wrong (4 in group 0, 2 in group 1) | ||
| assert!(!problem.evaluate(&[0, 0, 0, 0, 1, 1, 2, 2, 2])); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_partitionintotriangles_no_solution() { | ||
| use crate::traits::Problem; | ||
|
|
||
| // 6-vertex NO instance: path graph has no triangles at all | ||
| let graph = SimpleGraph::new(6, vec![(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]); | ||
| let problem = PartitionIntoTriangles::new(graph); | ||
|
|
||
| assert_eq!(problem.num_vertices(), 6); | ||
| assert_eq!(problem.dims(), vec![2; 6]); | ||
|
|
||
| // No valid partition exists since there are no triangles | ||
| let solver = BruteForce::new(); | ||
| let solution = solver.find_satisfying(&problem); | ||
| assert!(solution.is_none()); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_partitionintotriangles_solver() { | ||
| use crate::traits::Problem; | ||
|
|
||
| // Single triangle | ||
| let graph = SimpleGraph::new(3, vec![(0, 1), (1, 2), (0, 2)]); | ||
| let problem = PartitionIntoTriangles::new(graph); | ||
|
|
||
| let solver = BruteForce::new(); | ||
| let solution = solver.find_satisfying(&problem); | ||
| assert!(solution.is_some()); | ||
| let sol = solution.unwrap(); | ||
| assert!(problem.evaluate(&sol)); | ||
|
|
||
| // All solutions should be valid | ||
| let all = solver.find_all_satisfying(&problem); | ||
| assert!(!all.is_empty()); | ||
| for s in &all { | ||
| assert!(problem.evaluate(s)); | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_partitionintotriangles_serialization() { | ||
| let graph = SimpleGraph::new(3, vec![(0, 1), (1, 2), (0, 2)]); | ||
| let problem = PartitionIntoTriangles::new(graph); | ||
|
|
||
| let json = serde_json::to_string(&problem).unwrap(); | ||
| let deserialized: PartitionIntoTriangles<SimpleGraph> = serde_json::from_str(&json).unwrap(); | ||
|
|
||
| assert_eq!(deserialized.num_vertices(), 3); | ||
| assert_eq!(deserialized.num_edges(), 3); | ||
| } | ||
|
|
||
| #[test] | ||
| #[should_panic(expected = "must be divisible by 3")] | ||
| fn test_partitionintotriangles_invalid_vertex_count() { | ||
| let graph = SimpleGraph::new(4, vec![(0, 1), (1, 2), (2, 3)]); | ||
| let _ = PartitionIntoTriangles::new(graph); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_partitionintotriangles_config_out_of_range() { | ||
| use crate::traits::Problem; | ||
|
|
||
| let graph = SimpleGraph::new(3, vec![(0, 1), (1, 2), (0, 2)]); | ||
| let problem = PartitionIntoTriangles::new(graph); | ||
|
|
||
| // q = 1, so only group 0 is valid; group 1 is out of range | ||
| assert!(!problem.evaluate(&[0, 0, 1])); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_partitionintotriangles_wrong_config_length() { | ||
| use crate::traits::Problem; | ||
|
|
||
| let graph = SimpleGraph::new(3, vec![(0, 1), (1, 2), (0, 2)]); | ||
| let problem = PartitionIntoTriangles::new(graph); | ||
|
|
||
| assert!(!problem.evaluate(&[0, 0])); | ||
| assert!(!problem.evaluate(&[0, 0, 0, 0])); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_partitionintotriangles_size_getters() { | ||
| let graph = SimpleGraph::new(6, vec![(0, 1), (1, 2), (0, 2), (3, 4), (4, 5), (3, 5)]); | ||
| let problem = PartitionIntoTriangles::new(graph); | ||
| assert_eq!(problem.num_vertices(), 6); | ||
| assert_eq!(problem.num_edges(), 6); | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The CLI
createpath callsPartitionIntoTriangles::new(graph), which asserts (panics) when the vertex count is not divisible by 3. That will crash the CLI with a panic backtrace instead of returning a user-facing error. Consider validatinggraph.num_vertices() % 3 == 0here andbail!with a clear message/usage hint (or otherwise converting the precondition failure into aResult).