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

Rjf/expose graph ops #65

Merged
merged 9 commits into from
Dec 8, 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
63 changes: 63 additions & 0 deletions python/nrel/routee/compass/compass_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,69 @@ def run(self, query: Union[Query, List[Query]]) -> Result:
return results[0]
return results

def graph_edge_origin(self, edge_id: int) -> int:
"""
get the origin vertex id for some edge

Args:
edge_id (int): the id of the edge

Returns:
int: the vertex id at the source of the edge
"""
return self._app.graph_edge_origin(edge_id)

def graph_edge_destination(self, edge_id: int) -> int:
"""
get the destination vertex id for some edge

Args:
edge_id (int): the id of the edge

Returns:
int: the vertex id at the destination of the edge
"""
return self._app.graph_edge_destination(edge_id)

def graph_edge_distance(
self, edge_id: int, distance_unit: Optional[str] = None
) -> float:
"""
get the distance for some edge

Args:
edge_id (int): the id of the edge
distance_unit (Optional[str]): distance unit, by default meters

Returns:
int: the distance covered by traversing the edge
"""
return self._app.graph_edge_distance(edge_id, distance_unit)

def graph_get_out_edge_ids(self, vertex_id: int) -> List[int]:
"""
get the list of edge ids that depart from some vertex

Args:
vertex_id (int): the id of the vertex

Returns:
List[int]: the edge ids of edges departing from this vertex
"""
return self._app.graph_get_out_edge_ids(vertex_id)

def graph_get_in_edge_ids(self, vertex_id: int) -> List[int]:
"""
get the list of edge ids that arrive from some vertex

Args:
vertex_id (int): the id of the vertex

Returns:
List[int]: the edge ids of edges arriving at this vertex
"""
return self._app.graph_get_in_edge_ids(vertex_id)


def inject_to_disk_plugin(output_file: str, toml_config: dict) -> dict:
"""
Expand Down
5 changes: 4 additions & 1 deletion rust/routee-compass-core/src/algorithm/search/direction.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
#[derive(Copy, Clone)]
use serde::{Deserialize, Serialize};

#[derive(Copy, Clone, Serialize, Deserialize)]
#[serde(rename = "snake_case")]
pub enum Direction {
Forward,
Reverse,
Expand Down
1 change: 1 addition & 0 deletions rust/routee-compass-core/src/util/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ pub mod geo;
pub mod io_utils;
pub mod multiset;
pub mod read_only_lock;
pub mod serde_ops;
pub mod unit;
21 changes: 21 additions & 0 deletions rust/routee-compass-core/src/util/serde_ops.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
use serde::de;

/// hack-ish trick for types which can be deserialized from a string
/// representation, such as enums where all variants have no arguments.
///
/// # Arguments
///
/// * `input` - string to deserialize
///
/// # Returns
///
/// the deserialized value or a deserialization error
pub fn string_deserialize<T>(input: &str) -> Result<T, serde_json::Error>
where
T: de::DeserializeOwned,
{
let mut enquoted = input.to_owned();
enquoted.insert(0, '"');
enquoted.push('"');
serde_json::from_str::<T>(enquoted.as_str())
}
10 changes: 10 additions & 0 deletions rust/routee-compass-core/src/util/unit/distance_unit.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use super::Distance;
use crate::util::serde_ops::string_deserialize;
use serde::{Deserialize, Serialize};
use std::str::FromStr;

#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
#[serde(rename_all = "snake_case")]
Expand Down Expand Up @@ -35,6 +37,14 @@ impl std::fmt::Display for DistanceUnit {
}
}

impl FromStr for DistanceUnit {
type Err = serde_json::Error;

fn from_str(s: &str) -> Result<Self, Self::Err> {
string_deserialize(s)
}
}

#[cfg(test)]
mod test {

Expand Down
10 changes: 10 additions & 0 deletions rust/routee-compass-core/src/util/unit/energy_rate_unit.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use super::{DistanceUnit, EnergyUnit};
use crate::util::serde_ops::string_deserialize;
use serde::{Deserialize, Serialize};
use std::str::FromStr;

#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq, Copy)]
#[serde(rename_all = "snake_case")]
Expand Down Expand Up @@ -47,3 +49,11 @@ impl std::fmt::Display for EnergyRateUnit {
write!(f, "{}", s)
}
}

impl FromStr for EnergyRateUnit {
type Err = serde_json::Error;

fn from_str(s: &str) -> Result<Self, Self::Err> {
string_deserialize(s)
}
}
13 changes: 11 additions & 2 deletions rust/routee-compass-core/src/util/unit/energy_unit.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use serde::{Deserialize, Serialize};

use super::Energy;
use crate::util::serde_ops::string_deserialize;
use serde::{Deserialize, Serialize};
use std::str::FromStr;

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Copy)]
#[serde(rename_all = "snake_case")]
Expand Down Expand Up @@ -36,3 +37,11 @@ impl std::fmt::Display for EnergyUnit {
write!(f, "{}", s)
}
}

impl FromStr for EnergyUnit {
type Err = serde_json::Error;

fn from_str(s: &str) -> Result<Self, Self::Err> {
string_deserialize(s)
}
}
10 changes: 10 additions & 0 deletions rust/routee-compass-core/src/util/unit/grade_unit.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use super::Grade;
use crate::util::serde_ops::string_deserialize;
use serde::{Deserialize, Serialize};
use std::str::FromStr;

#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
#[serde(rename_all = "snake_case")]
Expand Down Expand Up @@ -35,6 +37,14 @@ impl std::fmt::Display for GradeUnit {
}
}

impl FromStr for GradeUnit {
type Err = serde_json::Error;

fn from_str(s: &str) -> Result<Self, Self::Err> {
string_deserialize(s)
}
}

#[cfg(test)]
mod test {

Expand Down
10 changes: 10 additions & 0 deletions rust/routee-compass-core/src/util/unit/speed_unit.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use super::Speed;
use super::{DistanceUnit, TimeUnit};
use crate::util::serde_ops::string_deserialize;
use serde::{Deserialize, Serialize};
use std::str::FromStr;

#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
#[serde(rename_all = "snake_case")]
Expand All @@ -19,6 +21,14 @@ impl std::fmt::Display for SpeedUnit {
}
}

impl FromStr for SpeedUnit {
type Err = serde_json::Error;

fn from_str(s: &str) -> Result<Self, Self::Err> {
string_deserialize(s)
}
}

impl From<(DistanceUnit, TimeUnit)> for SpeedUnit {
fn from(value: (DistanceUnit, TimeUnit)) -> Self {
use DistanceUnit as D;
Expand Down
10 changes: 10 additions & 0 deletions rust/routee-compass-core/src/util/unit/time_unit.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use super::Time;
use crate::util::serde_ops::string_deserialize;
use serde::{Deserialize, Serialize};
use std::str::FromStr;

#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "snake_case")]
Expand Down Expand Up @@ -43,6 +45,14 @@ impl std::fmt::Display for TimeUnit {
}
}

impl FromStr for TimeUnit {
type Err = serde_json::Error;

fn from_str(s: &str) -> Result<Self, Self::Err> {
string_deserialize(s)
}
}

#[cfg(test)]
mod test {

Expand Down
1 change: 1 addition & 0 deletions rust/routee-compass-py/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ documentation = "https://docs.rs/routee-compass"

[dependencies]
routee-compass = { path = "../routee-compass", version = "0.4.0" }
routee-compass-core = { path = "../routee-compass-core", version = "0.4.0" }
pyo3 = { version = "0.20.0", features = ["extension-module"] }
serde_json = { workspace = true }
config = { workspace = true }
Expand Down
95 changes: 95 additions & 0 deletions rust/routee-compass-py/src/app_graph_ops.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
use crate::app_wrapper::CompassAppWrapper;
use pyo3::{exceptions::PyException, PyResult};
use routee_compass::app::search::search_app_graph_ops::SearchAppGraphOps;
use routee_compass_core::{
algorithm::search::direction::Direction,
model::road_network::{edge_id::EdgeId, vertex_id::VertexId},
util::unit::{as_f64::AsF64, DistanceUnit},
};
use std::str::FromStr;

pub fn graph_edge_origin(app: &CompassAppWrapper, edge_id: usize) -> PyResult<usize> {
let edge_id_internal = EdgeId(edge_id);
app.routee_compass
.search_app
.get_edge_origin(edge_id_internal)
.map(|o| o.0)
.map_err(|e| {
PyException::new_err(format!(
"error retrieving edge origin for edge_id {}: {}",
edge_id, e
))
})
}

pub fn graph_edge_destination(app: &CompassAppWrapper, edge_id: usize) -> PyResult<usize> {
let edge_id_internal = EdgeId(edge_id);
app.routee_compass
.search_app
.get_edge_destination(edge_id_internal)
.map(|o| o.0)
.map_err(|e| {
PyException::new_err(format!(
"error retrieving edge destination for edge_id {}: {}",
edge_id, e
))
})
}

pub fn graph_edge_distance(
app: &CompassAppWrapper,
edge_id: usize,
distance_unit: Option<String>,
) -> PyResult<f64> {
let du_internal_result: PyResult<Option<DistanceUnit>> = match distance_unit {
Some(du_str) => {
let du = DistanceUnit::from_str(du_str.as_str()).map_err(|_| {
PyException::new_err(format!("could not deserialize distance unit '{}'", du_str))
})?;

Ok(Some(du))
}

None => Ok(None),
};
let du_internal = du_internal_result?;
let edge_id_internal = EdgeId(edge_id);
app.routee_compass
.search_app
.get_edge_distance(edge_id_internal, du_internal)
.map(|o| o.as_f64())
.map_err(|e| {
PyException::new_err(format!(
"error retrieving edge destination for edge_id {}: {}",
edge_id, e
))
})
}

pub fn get_out_edge_ids(app: &CompassAppWrapper, vertex_id: usize) -> PyResult<Vec<usize>> {
let vertex_id_internal = VertexId(vertex_id);
app.routee_compass
.search_app
.get_incident_edge_ids(vertex_id_internal, Direction::Forward)
.map(|es| es.iter().map(|e| e.0).collect())
.map_err(|e| {
PyException::new_err(format!(
"error retrieving out edges for vertex_id {}: {}",
vertex_id, e
))
})
}

pub fn get_in_edge_ids(app: &CompassAppWrapper, vertex_id: usize) -> PyResult<Vec<usize>> {
let vertex_id_internal = VertexId(vertex_id);
app.routee_compass
.search_app
.get_incident_edge_ids(vertex_id_internal, Direction::Reverse)
.map(|es| es.iter().map(|e| e.0).collect())
.map_err(|e| {
PyException::new_err(format!(
"error retrieving in edges for vertex_id {}: {}",
vertex_id, e
))
})
}
37 changes: 33 additions & 4 deletions rust/routee-compass-py/src/app_wrapper.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,47 @@
use std::path::Path;

use crate::app_graph_ops as ops;
use pyo3::{exceptions::PyException, prelude::*, types::PyType};
use routee_compass::app::compass::{
compass_app::CompassApp, compass_app_ops::read_config_from_string,
config::compass_app_builder::CompassAppBuilder,
use routee_compass::app::{
compass::{
compass_app::CompassApp, compass_app_ops::read_config_from_string,
config::compass_app_builder::CompassAppBuilder,
},
search::search_app_graph_ops::SearchAppGraphOps,
};
use routee_compass_core::model::road_network::edge_id::EdgeId;

#[pyclass]
pub struct CompassAppWrapper {
routee_compass: CompassApp,
pub routee_compass: CompassApp,
}

#[pymethods]
impl CompassAppWrapper {
pub fn graph_edge_origin(&self, edge_id: usize) -> PyResult<usize> {
ops::graph_edge_origin(self, edge_id)
}

pub fn graph_edge_destination(&self, edge_id: usize) -> PyResult<usize> {
ops::graph_edge_destination(self, edge_id)
}

pub fn graph_edge_distance(
&self,
edge_id: usize,
distance_unit: Option<String>,
) -> PyResult<f64> {
ops::graph_edge_distance(self, edge_id, distance_unit)
}

pub fn graph_get_out_edge_ids(&self, vertex_id: usize) -> PyResult<Vec<usize>> {
ops::get_out_edge_ids(self, vertex_id)
}

pub fn graph_get_in_edge_ids(&self, vertex_id: usize) -> PyResult<Vec<usize>> {
ops::get_in_edge_ids(self, vertex_id)
}

#[classmethod]
pub fn _from_config_toml_string(
_cls: &PyType,
Expand Down
Loading