Skip to content
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

Fix pickle/deepcopy node hole handling #888

Merged
merged 5 commits into from
Jun 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
fixes:
- |
Fixed an issue with several :class:`~.PyDiGraph` and :class:`~.PyGraph`
methods that removed nodes where previously when calling
these methods the :attr:`.PyDiGraph.node_removed` attribute would not be
updated to reflect that nodes were removed.
83 changes: 20 additions & 63 deletions src/digraph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use rustworkx_core::dictmap::*;
use pyo3::exceptions::PyIndexError;
use pyo3::gc::PyVisit;
use pyo3::prelude::*;
use pyo3::types::{PyBool, PyDict, PyList, PyLong, PyString, PyTuple};
use pyo3::types::{PyBool, PyDict, PyList, PyString, PyTuple};
use pyo3::PyTraverseError;
use pyo3::Python;

Expand All @@ -44,7 +44,7 @@ use petgraph::prelude::*;

use petgraph::visit::{
EdgeIndexable, GraphBase, IntoEdgeReferences, IntoNodeReferences, NodeCount, NodeFiltered,
Visitable,
NodeIndexable, Visitable,
};

use super::dot_utils::build_dot;
Expand Down Expand Up @@ -318,7 +318,6 @@ impl PyDiGraph {
};
edges.push(edge);
}

let out_dict = PyDict::new(py);
let nodes_lst: PyObject = PyList::new(py, nodes).into();
let edges_lst: PyObject = PyList::new(py, edges).into();
Expand Down Expand Up @@ -398,55 +397,22 @@ impl PyDiGraph {
.downcast::<PyTuple>()
.unwrap();

// use a pointer to iter the node list
let mut pointer = 0;
let mut next_node_idx: usize = nodes_lst
.get_item(pointer)
.unwrap()
.downcast::<PyTuple>()
.unwrap()
.get_item(0)
.unwrap()
.downcast::<PyLong>()
.unwrap()
.extract()
.unwrap();

// list of temporary nodes that will be removed later to re-create holes
let node_bound_1: usize = last_item.get_item(0).unwrap().extract().unwrap();
let mut tmp_nodes: Vec<NodeIndex> =
Vec::with_capacity(node_bound_1 + 1 - nodes_lst.len());

for i in 0..nodes_lst.len() + 1 {
if i < next_node_idx {
for item in nodes_lst {
let item = item.downcast::<PyTuple>().unwrap();
let next_index: usize = item.get_item(0).unwrap().extract().unwrap();
let weight: PyObject = item.get_item(1).unwrap().extract().unwrap();
while next_index > self.graph.node_bound() {
// node does not exist
let tmp_node = self.graph.add_node(py.None());
tmp_nodes.push(tmp_node);
} else {
// add node to the graph, and update the next available node index
let item = nodes_lst
.get_item(pointer)
.unwrap()
.downcast::<PyTuple>()
.unwrap();

let node_w = item.get_item(1).unwrap().extract().unwrap();
self.graph.add_node(node_w);
pointer += 1;
if pointer < nodes_lst.len() {
next_node_idx = nodes_lst
.get_item(pointer)
.unwrap()
.downcast::<PyTuple>()
.unwrap()
.get_item(0)
.unwrap()
.downcast::<PyLong>()
.unwrap()
.extract()
.unwrap();
}
}
// add node to the graph, and update the next available node index
self.graph.add_node(weight);
}
// Remove any temporary nodes we added
for tmp_node in tmp_nodes {
Expand All @@ -463,20 +429,8 @@ impl PyDiGraph {
self.graph.add_edge(tmp_node, tmp_node, py.None());
} else {
let triple = item.downcast::<PyTuple>().unwrap();
let edge_p: usize = triple
.get_item(0)
.unwrap()
.downcast::<PyLong>()
.unwrap()
.extract()
.unwrap();
let edge_c: usize = triple
.get_item(1)
.unwrap()
.downcast::<PyLong>()
.unwrap()
.extract()
.unwrap();
let edge_p: usize = triple.get_item(0).unwrap().extract().unwrap();
let edge_c: usize = triple.get_item(1).unwrap().extract().unwrap();
let edge_w = triple.get_item(2).unwrap().extract().unwrap();
self.graph
.add_edge(NodeIndex::new(edge_p), NodeIndex::new(edge_c), edge_w);
Expand Down Expand Up @@ -1760,8 +1714,8 @@ impl PyDiGraph {
/// the graph.
#[pyo3(text_signature = "(self, index_list, /)")]
pub fn remove_nodes_from(&mut self, index_list: Vec<usize>) -> PyResult<()> {
for node in index_list.iter().map(|x| NodeIndex::new(*x)) {
self.graph.remove_node(node);
for node in index_list {
self.remove_node(node)?;
}
Ok(())
}
Expand Down Expand Up @@ -2389,7 +2343,7 @@ impl PyDiGraph {
// If no nodes are copied bail here since there is nothing left
// to do.
if out_map.is_empty() {
self.graph.remove_node(node_index);
self.remove_node(node_index.index())?;
// Return a new empty map to clear allocation from out_map
return Ok(NodeMap {
node_map: DictMap::new(),
Expand Down Expand Up @@ -2450,7 +2404,7 @@ impl PyDiGraph {
self._add_edge(source_out, target, weight)?;
}
// Remove node
self.graph.remove_node(node_index);
self.remove_node(node_index.index())?;
Ok(NodeMap { node_map: out_map })
}

Expand Down Expand Up @@ -2559,7 +2513,7 @@ impl PyDiGraph {

// Remove nodes that will be replaced.
for index in indices_to_remove {
self.graph.remove_node(index);
self.remove_node(index.index())?;
}

// If `weight_combo_fn` was specified, merge edges according
Expand Down Expand Up @@ -2912,7 +2866,10 @@ impl PyDiGraph {

fn __delitem__(&mut self, idx: usize) -> PyResult<()> {
match self.graph.remove_node(NodeIndex::new(idx)) {
Some(_) => Ok(()),
Some(_) => {
self.node_removed = true;
Ok(())
}
None => Err(PyIndexError::new_err("No node found for index")),
}
}
Expand Down
78 changes: 19 additions & 59 deletions src/graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use rustworkx_core::dictmap::*;
use pyo3::exceptions::PyIndexError;
use pyo3::gc::PyVisit;
use pyo3::prelude::*;
use pyo3::types::{PyBool, PyDict, PyList, PyLong, PyString, PyTuple};
use pyo3::types::{PyBool, PyDict, PyList, PyString, PyTuple};
use pyo3::PyTraverseError;
use pyo3::Python;

Expand All @@ -47,6 +47,7 @@ use petgraph::graph::{EdgeIndex, NodeIndex};
use petgraph::prelude::*;
use petgraph::visit::{
EdgeIndexable, GraphBase, IntoEdgeReferences, IntoNodeReferences, NodeCount, NodeFiltered,
NodeIndexable,
};

/// A class for creating undirected graphs
Expand Down Expand Up @@ -284,56 +285,24 @@ impl PyGraph {
.downcast::<PyTuple>()
.unwrap();

// use a pointer to iter the node list
let mut pointer = 0;
let mut next_node_idx: usize = nodes_lst
.get_item(pointer)
.unwrap()
.downcast::<PyTuple>()
.unwrap()
.get_item(0)
.unwrap()
.downcast::<PyLong>()
.unwrap()
.extract()
.unwrap();

// list of temporary nodes that will be removed later to re-create holes
let node_bound_1: usize = last_item.get_item(0).unwrap().extract().unwrap();
let mut tmp_nodes: Vec<NodeIndex> =
Vec::with_capacity(node_bound_1 + 1 - nodes_lst.len());

for i in 0..nodes_lst.len() + 1 {
if i < next_node_idx {
for item in nodes_lst {
let item = item.downcast::<PyTuple>().unwrap();
let next_index: usize = item.get_item(0).unwrap().extract().unwrap();
let weight: PyObject = item.get_item(1).unwrap().extract().unwrap();
while next_index > self.graph.node_bound() {
enavarro51 marked this conversation as resolved.
Show resolved Hide resolved
// node does not exist
let tmp_node = self.graph.add_node(py.None());
tmp_nodes.push(tmp_node);
} else {
// add node to the graph, and update the next available node index
let item = nodes_lst
.get_item(pointer)
.unwrap()
.downcast::<PyTuple>()
.unwrap();

let node_w = item.get_item(1).unwrap().extract().unwrap();
self.graph.add_node(node_w);
pointer += 1;
if pointer < nodes_lst.len() {
next_node_idx = nodes_lst
.get_item(pointer)
.unwrap()
.downcast::<PyTuple>()
.unwrap()
.get_item(0)
.unwrap()
.downcast::<PyLong>()
.unwrap()
.extract()
.unwrap();
}
}
// add node to the graph, and update the next available node index
self.graph.add_node(weight);
}
// Remove any temporary nodes we added
for tmp_node in tmp_nodes {
self.graph.remove_node(tmp_node);
}
Expand All @@ -348,20 +317,8 @@ impl PyGraph {
self.graph.add_edge(tmp_node, tmp_node, py.None());
} else {
let triple = item.downcast::<PyTuple>().unwrap();
let edge_p: usize = triple
.get_item(0)
.unwrap()
.downcast::<PyLong>()
.unwrap()
.extract()
.unwrap();
let edge_c: usize = triple
.get_item(1)
.unwrap()
.downcast::<PyLong>()
.unwrap()
.extract()
.unwrap();
let edge_p: usize = triple.get_item(0).unwrap().extract().unwrap();
let edge_c: usize = triple.get_item(1).unwrap().extract().unwrap();
let edge_w = triple.get_item(2).unwrap().extract().unwrap();
self.graph
.add_edge(NodeIndex::new(edge_p), NodeIndex::new(edge_c), edge_w);
Expand Down Expand Up @@ -1062,8 +1019,8 @@ impl PyGraph {
/// the graph
#[pyo3(text_signature = "(self, index_list, /)")]
pub fn remove_nodes_from(&mut self, index_list: Vec<usize>) -> PyResult<()> {
for node in index_list.iter().map(|x| NodeIndex::new(*x)) {
self.graph.remove_node(node);
for node in index_list {
self.remove_node(node)?;
enavarro51 marked this conversation as resolved.
Show resolved Hide resolved
}
Ok(())
}
Expand Down Expand Up @@ -1695,7 +1652,7 @@ impl PyGraph {

// Remove nodes that will be replaced.
for index in indices_to_remove {
self.graph.remove_node(index);
self.remove_node(index.index())?;
}

// If `weight_combo_fn` was specified, merge edges according
Expand Down Expand Up @@ -1846,7 +1803,10 @@ impl PyGraph {

fn __delitem__(&mut self, idx: usize) -> PyResult<()> {
match self.graph.remove_node(NodeIndex::new(idx)) {
Some(_) => Ok(()),
Some(_) => {
self.node_removed = true;
Ok(())
}
enavarro51 marked this conversation as resolved.
Show resolved Hide resolved
None => Err(PyIndexError::new_err("No node found for index")),
}
}
Expand Down
26 changes: 26 additions & 0 deletions tests/rustworkx_tests/digraph/test_deepcopy.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,29 @@ def test_deepcopy_different_objects(self):
self.assertIsNot(
graph_a.get_edge_data(node_a, node_b), graph_b.get_edge_data(node_a, node_b)
)

def test_deepcopy_multinode_hole_in_middle(self):
graph = rustworkx.PyDiGraph()
graph.add_nodes_from(range(20))
graph.remove_nodes_from([10, 11, 12, 13, 14])
graph.add_edges_from_no_data(
[
(4, 5),
(16, 18),
(2, 19),
(0, 15),
(15, 16),
(16, 17),
(6, 17),
(8, 18),
(17, 1),
(17, 7),
(18, 3),
(18, 9),
(19, 16),
]
)
copied_graph = copy.deepcopy(graph)
self.assertEqual(
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 15, 16, 17, 18, 19], copied_graph.node_indices()
)
26 changes: 26 additions & 0 deletions tests/rustworkx_tests/graph/test_deepcopy.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,29 @@ def test_deepcopy_attrs(self):
graph = rustworkx.PyGraph(attrs="abc")
graph_copy = copy.deepcopy(graph)
self.assertEqual(graph.attrs, graph_copy.attrs)

def test_deepcopy_multinode_hole_in_middle(self):
graph = rustworkx.PyGraph()
graph.add_nodes_from(range(20))
graph.remove_nodes_from([10, 11, 12, 13, 14])
graph.add_edges_from_no_data(
[
(4, 5),
(16, 18),
(2, 19),
(0, 15),
(15, 16),
(16, 17),
(6, 17),
(8, 18),
(17, 1),
(17, 7),
(18, 3),
(18, 9),
(19, 16),
]
)
copied_graph = copy.deepcopy(graph)
self.assertEqual(
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 15, 16, 17, 18, 19], copied_graph.node_indices()
)