-
Notifications
You must be signed in to change notification settings - Fork 162
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add custom iterator class for BFS successors return (#185)
* Add custom iterator class for BFS successors return This commit changes the return type of the bfs_successors function to be a custom class BFSSuccessors. This new return class implements both the sequence protocol and iterator protocol. This means that aside from explicit type checking it should be backwards compatible with the list being previously returned. It can be used with either index based access or iterated over. This should be more efficient for large graphs because instead of doing the copy and type conversion and iterating over the entire nested Vec of results it instead does it per access (either via __getitem__ or __next__). It does add a small amount of overhead for smaller graphs but it is minimal since the function returns in microseconds in such cases so a 10-20% overhead is not a big deal. It's worth noting while this defers the type conversion, it does not defer execution like most python iterators normally do. When bfs_successors is called it will still always fully traverse the graph. However, in practice the bottleneck for the bfs_successor function wasn't actually the graph traversal, but instead the type conversion. Related to #71 * Only implement sequence protocol Using the sequence protocol we can still get an implicit iterator by just casting it on the python side. This will still get us the lazy type conversion but simplify the api and also make the behavior more consistent. At the same time to ensure we're handling negative indices correctly a test method is added to verify that a negative index access to the sequence works as expected. * Update src/lib.rs Co-authored-by: Kevin Krsulich <[email protected]>
- Loading branch information
Showing
4 changed files
with
175 additions
and
11 deletions.
There are no files selected for viewing
This file contains 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 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,63 @@ | ||
// Licensed under the Apache License, Version 2.0 (the "License"); you may | ||
// not use this file except in compliance with the License. You may obtain | ||
// a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT | ||
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the | ||
// License for the specific language governing permissions and limitations | ||
// under the License. | ||
|
||
use std::convert::TryInto; | ||
|
||
use pyo3::class::PySequenceProtocol; | ||
use pyo3::exceptions::PyIndexError; | ||
use pyo3::prelude::*; | ||
|
||
/// A custom class for the return from :func:`retworkx.bfs_successors` | ||
/// | ||
/// This class is a container class for the results of the | ||
/// :func:`retworkx.bfs_successors` function. It implements the Python | ||
/// sequence protocol. So you can treat the return as read-only | ||
/// sequence/list that is integer indexed. If you want to use it as an | ||
/// iterator you can by wrapping it in an ``iter()`` that will yield the | ||
/// results in order. | ||
/// | ||
/// For example:: | ||
/// | ||
/// import retworkx | ||
/// | ||
/// graph = retworkx.generators.directed_path_graph(5) | ||
/// bfs_succ = retworkx.bfs_successors(0) | ||
/// # Index based access | ||
/// third_element = bfs_succ[2] | ||
/// # Use as iterator | ||
/// bfs_iter = iter(bfs_succ) | ||
/// first_element = next(bfs_iter) | ||
/// second_element = nex(bfs_iter) | ||
/// | ||
#[pyclass(module = "retworkx")] | ||
pub struct BFSSuccessors { | ||
pub bfs_successors: Vec<(PyObject, Vec<PyObject>)>, | ||
pub index: usize, | ||
} | ||
|
||
#[pyproto] | ||
impl PySequenceProtocol for BFSSuccessors { | ||
fn __len__(&self) -> PyResult<usize> { | ||
Ok(self.bfs_successors.len()) | ||
} | ||
|
||
fn __getitem__( | ||
&'p self, | ||
idx: isize, | ||
) -> PyResult<(PyObject, Vec<PyObject>)> { | ||
if idx >= self.bfs_successors.len().try_into().unwrap() { | ||
Err(PyIndexError::new_err(format!("Invalid index, {}", idx))) | ||
} else { | ||
Ok(self.bfs_successors[idx as usize].clone()) | ||
} | ||
} | ||
} |
This file contains 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 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