1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
//! Defines the `Graph` struct, which represents a raphtory graph in memory.
//!
//! This is the base class used to create a temporal graph, add vertices and edges,
//! create windows, and query the graph with a variety of algorithms.
//! It is a wrapper around a set of shards, which are the actual graph data structures.
//! In Python, this class wraps around the rust graph.

use crate::graph_view::PyGraphView;
use crate::utils::{adapt_result, extract_input_vertex, extract_into_time, InputVertexBox};
use crate::wrappers::prop::Prop;
use itertools::Itertools;
use pyo3::exceptions::PyException;
use pyo3::prelude::*;
use raphtory::core as dbc;
use raphtory::db::graph::Graph;
use std::collections::HashMap;
use std::fmt::{Debug, Formatter};
use std::path::{Display, Path, PathBuf};

/// A temporal graph.
#[derive(Clone)]
#[pyclass(name="Graph", extends=PyGraphView)]
pub struct PyGraph {
    pub(crate) graph: Graph,
}

impl Debug for PyGraph {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.graph)
    }
}

impl From<Graph> for PyGraph {
    fn from(value: Graph) -> Self {
        Self { graph: value }
    }
}

impl PyGraph {
    pub fn py_from_db_graph(db_graph: Graph) -> PyResult<Py<PyGraph>> {
        Python::with_gil(|py| {
            Py::new(
                py,
                (PyGraph::from(db_graph.clone()), PyGraphView::from(db_graph)),
            )
        })
    }
}

/// A temporal graph.
#[pymethods]
impl PyGraph {
    #[new]
    #[pyo3(signature = (nr_shards=1))]
    pub fn py_new(nr_shards: usize) -> (Self, PyGraphView) {
        let graph = Graph::new(nr_shards);
        (
            Self {
                graph: graph.clone(),
            },
            PyGraphView::from(graph),
        )
    }

    /// Adds a new vertex with the given id and properties to the graph.
    ///
    /// Arguments:
    ///    timestamp (int): The timestamp of the vertex.
    ///    id (str or int): The id of the vertex.
    ///    properties (dict): The properties of the vertex.
    ///
    /// Returns:
    ///   None
    #[pyo3(signature = (timestamp, id, properties=None))]
    pub fn add_vertex(
        &self,
        timestamp: i64,
        id: &PyAny,
        properties: Option<HashMap<String, Prop>>,
    ) -> PyResult<()> {
        let v = Self::extract_id(id)?;
        let result = self
            .graph
            .add_vertex(timestamp, v, &Self::transform_props(properties));
        adapt_result(result)
    }

    /// Adds properties to an existing vertex.
    ///
    /// Arguments:
    ///     id (str or int): The id of the vertex.
    ///     properties (dict): The properties of the vertex.
    ///
    /// Returns:
    ///    None
    pub fn add_vertex_properties(
        &self,
        id: &PyAny,
        properties: HashMap<String, Prop>,
    ) -> PyResult<()> {
        let v = Self::extract_id(id)?;
        let result = self
            .graph
            .add_vertex_properties(v, &Self::transform_props(Some(properties)));
        adapt_result(result)
    }

    /// Adds a new edge with the given source and destination vertices and properties to the graph.
    ///
    /// Arguments:
    ///    timestamp (int): The timestamp of the edge.
    ///    src (str or int): The id of the source vertex.
    ///    dst (str or int): The id of the destination vertex.
    ///    properties (dict): The properties of the edge, as a dict of string and properties
    ///    layer (str): The layer of the edge.
    ///
    /// Returns:
    ///   None
    #[pyo3(signature = (timestamp, src, dst, properties=None, layer=None))]
    pub fn add_edge(
        &self,
        timestamp: &PyAny,
        src: &PyAny,
        dst: &PyAny,
        properties: Option<HashMap<String, Prop>>,
        layer: Option<&str>,
    ) -> PyResult<()> {
        let time = extract_into_time(timestamp)?;
        let src = Self::extract_id(src)?;
        let dst = Self::extract_id(dst)?;
        adapt_result(
            self.graph
                .add_edge(time, src, dst, &Self::transform_props(properties), layer),
        )
    }

    /// Adds properties to an existing edge.
    ///
    /// Arguments:
    ///    src (str or int): The id of the source vertex.
    ///    dst (str or int): The id of the destination vertex.
    ///    properties (dict): The properties of the edge, as a dict of string and properties
    ///    layer (str): The layer of the edge.
    ///
    /// Returns:
    ///  None
    #[pyo3(signature = (src, dst, properties, layer=None))]
    pub fn add_edge_properties(
        &self,
        src: &PyAny,
        dst: &PyAny,
        properties: HashMap<String, Prop>,
        layer: Option<&str>,
    ) -> PyResult<()> {
        let src = Self::extract_id(src)?;
        let dst = Self::extract_id(dst)?;
        let result = self.graph.add_edge_properties(
            src,
            dst,
            &Self::transform_props(Some(properties)),
            layer,
        );
        adapt_result(result)
    }

    //******  Saving And Loading  ******//

    // Alternative constructors are tricky, see: https://gist.github.com/redshiftzero/648e4feeff3843ffd9924f13625f839c

    /// Loads a graph from the given path.
    ///
    /// Arguments:
    ///   path (str): The path to the graph.
    ///
    /// Returns:
    ///  Graph: The loaded graph.
    #[staticmethod]
    pub fn load_from_file(path: String) -> PyResult<Py<PyGraph>> {
        let file_path: PathBuf = [env!("CARGO_MANIFEST_DIR"), &path].iter().collect();

        match Graph::load_from_file(file_path) {
            Ok(g) => Self::py_from_db_graph(g),
            Err(e) => Err(PyException::new_err(format!(
                "Failed to load graph from the files. Reason: {}",
                e
            ))),
        }
    }

    /// Saves the graph to the given path.
    ///
    /// Arguments:
    ///  path (str): The path to the graph.
    ///
    /// Returns:
    /// None
    pub fn save_to_file(&self, path: String) -> PyResult<()> {
        match self.graph.save_to_file(Path::new(&path)) {
            Ok(()) => Ok(()),
            Err(e) => Err(PyException::new_err(format!(
                "Failed to save graph to the files. Reason: {}",
                e
            ))),
        }
    }
}

impl PyGraph {
    fn transform_props(props: Option<HashMap<String, Prop>>) -> Vec<(String, dbc::Prop)> {
        props
            .unwrap_or_default()
            .into_iter()
            .map(|(key, value)| (key, value.into()))
            .collect_vec()
    }

    /// Extracts the id from the given python vertex
    ///
    /// Arguments:
    ///     id (str or int): The id of the vertex.
    pub(crate) fn extract_id(id: &PyAny) -> PyResult<InputVertexBox> {
        extract_input_vertex(id)
    }
}