raphtory 0.17.0

raphtory, a temporal graph library
Documentation
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
//! The API for querying a view of the graph in a read-only state
use crate::{
    db::{
        api::{
            properties::{Metadata, Properties},
            view::{
                filter_ops::Filter,
                internal::{
                    DynamicGraph, InternalFilter, IntoDynHop, IntoDynamic, MaterializedGraph,
                },
                LayerOps, StaticGraphViewOps,
            },
        },
        graph::{
            edge::EdgeView,
            edges::Edges,
            graph::graph_equal,
            node::NodeView,
            nodes::Nodes,
            views::{
                cached_view::CachedView,
                filter::{
                    edge_property_filtered_graph::EdgePropertyFilteredGraph,
                    exploded_edge_property_filter::ExplodedEdgePropertyFilteredGraph,
                },
                layer_graph::LayeredGraph,
                node_subgraph::NodeSubgraph,
                valid_graph::ValidGraph,
                window_graph::WindowedGraph,
            },
        },
    },
    errors::GraphError,
    prelude::*,
    python::{
        filter::filter_expr::PyFilterExpr,
        graph::{edge::PyEdge, node::PyNode},
        types::repr::{Repr, StructReprBuilder},
        utils::PyNodeRef,
    },
};
use pyo3::prelude::*;
use raphtory_api::{core::storage::arc_str::ArcStr, python::timeindex::PyOptionalEventTime};
use rayon::prelude::*;
use std::collections::HashMap;

impl<'py> IntoPyObject<'py> for MaterializedGraph {
    type Target = PyAny;
    type Output = Bound<'py, Self::Target>;
    type Error = PyErr;

    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
        match self {
            MaterializedGraph::EventGraph(g) => g.into_pyobject(py).map(|b| b.into_any()),
            MaterializedGraph::PersistentGraph(g) => g.into_pyobject(py).map(|b| b.into_any()),
        }
    }
}

impl<'py> IntoPyObject<'py> for DynamicGraph {
    type Target = PyGraphView;
    type Output = <Self::Target as IntoPyObject<'py>>::Output;
    type Error = <Self::Target as IntoPyObject<'py>>::Error;

    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
        PyGraphView::from(self).into_pyobject(py)
    }
}

impl<'source> FromPyObject<'source> for DynamicGraph {
    fn extract_bound(ob: &Bound<'source, PyAny>) -> PyResult<Self> {
        ob.extract::<PyRef<PyGraphView>>().map(|g| g.graph.clone())
    }
}
/// Graph view is a read-only version of a graph at a certain point in time.

#[pyclass(name = "GraphView", frozen, subclass, module = "raphtory")]
#[derive(Clone)]
#[repr(C)]
pub struct PyGraphView {
    pub graph: DynamicGraph,
}

impl_timeops!(PyGraphView, graph, DynamicGraph, "GraphView");
impl_filter_ops!(PyGraphView<DynamicGraph>, graph, "GraphView");
impl_layerops!(PyGraphView, graph, DynamicGraph, "GraphView");

/// Graph view is a read-only version of a graph at a certain point in time.
impl<G: StaticGraphViewOps + IntoDynamic> From<G> for PyGraphView {
    fn from(value: G) -> Self {
        PyGraphView {
            graph: value.into_dynamic(),
        }
    }
}

impl<'py, G: StaticGraphViewOps + IntoDynamic> IntoPyObject<'py> for WindowedGraph<G> {
    type Target = PyGraphView;
    type Output = <Self::Target as IntoPyObject<'py>>::Output;
    type Error = <Self::Target as IntoPyObject<'py>>::Error;

    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
        PyGraphView::from(self).into_pyobject(py)
    }
}

impl<'py, G: StaticGraphViewOps + IntoDynamic> IntoPyObject<'py> for LayeredGraph<G> {
    type Target = PyGraphView;
    type Output = <Self::Target as IntoPyObject<'py>>::Output;
    type Error = <Self::Target as IntoPyObject<'py>>::Error;

    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
        PyGraphView::from(self).into_pyobject(py)
    }
}

impl<'py, G: StaticGraphViewOps + IntoDynamic> IntoPyObject<'py> for NodeSubgraph<G> {
    type Target = PyGraphView;
    type Output = <Self::Target as IntoPyObject<'py>>::Output;
    type Error = <Self::Target as IntoPyObject<'py>>::Error;

    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
        PyGraphView::from(self).into_pyobject(py)
    }
}

impl<'py, G: StaticGraphViewOps + IntoDynamic> IntoPyObject<'py> for CachedView<G> {
    type Target = PyGraphView;
    type Output = <Self::Target as IntoPyObject<'py>>::Output;
    type Error = <Self::Target as IntoPyObject<'py>>::Error;

    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
        PyGraphView::from(self).into_pyobject(py)
    }
}

impl<'py, G: StaticGraphViewOps + IntoDynamic> IntoPyObject<'py> for EdgePropertyFilteredGraph<G> {
    type Target = PyGraphView;
    type Output = <Self::Target as IntoPyObject<'py>>::Output;
    type Error = <Self::Target as IntoPyObject<'py>>::Error;

    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
        PyGraphView::from(self).into_pyobject(py)
    }
}

impl<'py, G: StaticGraphViewOps + IntoDynamic> IntoPyObject<'py>
    for ExplodedEdgePropertyFilteredGraph<G>
{
    type Target = PyGraphView;
    type Output = <Self::Target as IntoPyObject<'py>>::Output;
    type Error = <Self::Target as IntoPyObject<'py>>::Error;

    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
        PyGraphView::from(self).into_pyobject(py)
    }
}

impl<'py, G: StaticGraphViewOps + IntoDynamic> IntoPyObject<'py> for ValidGraph<G> {
    type Target = PyGraphView;
    type Output = <Self::Target as IntoPyObject<'py>>::Output;
    type Error = <Self::Target as IntoPyObject<'py>>::Error;

    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
        PyGraphView::from(self).into_pyobject(py)
    }
}

/// The API for querying a view of the graph in a read-only state
#[pymethods]
impl PyGraphView {
    /// Return all the layer ids in the graph
    ///
    /// Returns:
    ///     list[str]: the names of all layers in the graph
    #[getter]
    pub fn unique_layers(&self) -> Vec<ArcStr> {
        self.graph.unique_layers().collect()
    }

    //******  Metrics APIs ******//

    /// Time entry of the earliest activity in the graph
    ///
    /// Returns:
    ///     OptionalEventTime: the time entry of the earliest activity in the graph
    #[getter]
    pub fn earliest_time(&self) -> PyOptionalEventTime {
        self.graph.earliest_time().into()
    }

    /// Time entry of the latest activity in the graph
    ///
    /// Returns:
    ///     OptionalEventTime: the time entry of the latest activity in the graph
    #[getter]
    pub fn latest_time(&self) -> PyOptionalEventTime {
        self.graph.latest_time().into()
    }

    /// Number of edges in the graph
    ///
    /// Returns:
    ///    int: the number of edges in the graph
    pub fn count_edges(&self) -> usize {
        self.graph.count_edges()
    }

    /// Number of edges in the graph
    ///
    /// Returns:
    ///    int: the number of temporal edges in the graph
    pub fn count_temporal_edges(&self) -> usize {
        self.graph.count_temporal_edges()
    }

    /// Number of nodes in the graph
    ///
    /// Returns:
    ///   int: the number of nodes in the graph
    pub fn count_nodes(&self) -> usize {
        self.graph.count_nodes()
    }

    /// Returns true if the graph contains the specified node
    ///
    /// Arguments:
    ///    id (NodeInput): the node id
    ///
    /// Returns:
    ///   bool: true if the graph contains the specified node, false otherwise
    pub fn has_node(&self, id: PyNodeRef) -> bool {
        self.graph.has_node(id)
    }

    /// Returns true if the graph contains the specified edge
    ///
    /// Arguments:
    ///   src (NodeInput): the source node id
    ///   dst (NodeInput): the destination node id
    ///
    /// Returns:
    ///     bool: true if the graph contains the specified edge, false otherwise
    #[pyo3(signature = (src, dst))]
    pub fn has_edge(&self, src: PyNodeRef, dst: PyNodeRef) -> bool {
        self.graph.has_edge(src, dst)
    }

    //******  Getter APIs ******//

    /// Gets the node with the specified id
    ///
    /// Arguments:
    ///   id (NodeInput): the node id
    ///
    /// Returns:
    ///     Optional[Node]: the node with the specified id, or None if the node does not exist
    pub fn node(&self, id: PyNodeRef) -> Option<NodeView<'static, DynamicGraph>> {
        self.graph.node(id)
    }

    /// Get the nodes that match the properties name and value
    /// Arguments:
    ///     properties_dict (dict[str, PropValue]): the properties name and value
    /// Returns:
    ///    list[Node]: the nodes that match the properties name and value
    #[pyo3(signature = (properties_dict))]
    pub fn find_nodes(&self, properties_dict: HashMap<String, Prop>) -> Vec<PyNode> {
        let iter = self.nodes().into_iter().par_bridge();
        let out = iter
            .filter(|n| {
                let props = n.properties();
                properties_dict.iter().all(|(k, v)| {
                    if let Some(prop) = props.get(k) {
                        &prop == v
                    } else {
                        false
                    }
                })
            })
            .map(PyNode::from)
            .collect::<Vec<_>>();

        out
    }

    /// Gets the nodes in the graph
    ///
    /// Returns:
    ///   Nodes: the nodes in the graph
    #[getter]
    pub fn nodes(&self) -> Nodes<'static, DynamicGraph> {
        self.graph.nodes()
    }

    /// Gets the edge with the specified source and destination nodes
    ///
    /// Arguments:
    ///     src (NodeInput): the source node id
    ///     dst (NodeInput): the destination node id
    ///
    /// Returns:
    ///     Optional[Edge]: the edge with the specified source and destination nodes, or None if the edge does not exist
    #[pyo3(signature = (src, dst))]
    pub fn edge(&self, src: PyNodeRef, dst: PyNodeRef) -> Option<EdgeView<DynamicGraph>> {
        self.graph.edge(src, dst)
    }

    /// Get the edges that match the properties name and value
    /// Arguments:
    ///     properties_dict (dict[str, PropValue]): the properties name and value
    /// Returns:
    ///    list[Edge]: the edges that match the properties name and value
    #[pyo3(signature = (properties_dict))]
    pub fn find_edges(&self, properties_dict: HashMap<String, Prop>) -> Vec<PyEdge> {
        let iter = self.edges().into_iter().par_bridge();
        let out = iter
            .filter(|e| {
                let props = e.properties();
                properties_dict.iter().all(|(k, v)| {
                    if let Some(prop) = props.get(k) {
                        &prop == v
                    } else {
                        false
                    }
                })
            })
            .map(PyEdge::from)
            .collect::<Vec<_>>();

        out
    }

    /// Gets all edges in the graph
    ///
    /// Returns:
    ///   Edges: the edges in the graph
    #[getter]
    pub fn edges(&self) -> Edges<'static, DynamicGraph> {
        self.graph.edges()
    }

    /// Get all graph properties
    ///
    ///
    /// Returns:
    ///     Properties: Properties paired with their names
    #[getter]
    fn properties(&self) -> Properties<DynamicGraph> {
        self.graph.properties()
    }

    /// Get all graph metadata
    ///
    ///
    /// Returns:
    ///     Metadata:
    #[getter]
    fn metadata(&self) -> Metadata<'static, DynamicGraph> {
        self.graph.metadata()
    }

    /// Returns a subgraph given a set of nodes
    ///
    /// Arguments:
    ///   nodes (list[NodeInput]): set of nodes
    ///
    /// Returns:
    ///    GraphView: Returns the subgraph
    fn subgraph(&self, nodes: Vec<PyNodeRef>) -> NodeSubgraph<DynamicGraph> {
        self.graph.subgraph(nodes)
    }

    /// Return a view of the graph that only includes valid edges
    ///
    /// Note:
    ///
    ///     The semantics for `valid` depend on the time semantics of the underlying graph.
    ///     In the case of a persistent graph, an edge is valid if its last update is an addition.
    ///     In the case of an event graph, an edge is valid if it has at least one addition event.
    ///
    /// Returns:
    ///     GraphView: The filtered graph
    fn valid(&self) -> ValidGraph<DynamicGraph> {
        self.graph.valid()
    }

    /// Applies the filters to the graph and retains the node ids and the edge ids
    /// in the graph that satisfy the filters
    /// creates bitsets per layer for nodes and edges
    ///
    /// Returns:
    ///   GraphView: Returns the masked graph
    fn cache_view(&self) -> CachedView<DynamicGraph> {
        self.graph.cache_view()
    }

    /// Returns a subgraph filtered by node types given a set of node types
    ///
    /// Arguments:
    ///   node_types (list[str]): set of node types
    ///
    /// Returns:
    ///    GraphView: Returns the subgraph
    fn subgraph_node_types(&self, node_types: Vec<ArcStr>) -> PyGraphView {
        let subgraph = self.graph.subgraph_node_types(node_types);
        let dyn_graph = subgraph.into_dyn_hop();
        PyGraphView::from(dyn_graph)
    }

    /// Returns a subgraph given a set of nodes that are excluded from the subgraph
    ///
    /// Arguments:
    ///   nodes (list[NodeInput]): set of nodes
    ///
    /// Returns:
    ///    GraphView: Returns the subgraph
    fn exclude_nodes(&self, nodes: Vec<PyNodeRef>) -> NodeSubgraph<DynamicGraph> {
        self.graph.exclude_nodes(nodes)
    }

    /// Returns a 'materialized' clone of the graph view - i.e. a new graph with a copy of the data seen within the view instead of just a mask over the original graph
    ///
    /// Returns:
    ///    GraphView: Returns a graph clone
    fn materialize(&self) -> Result<MaterializedGraph, GraphError> {
        self.graph.materialize()
    }

    /// Displays the graph
    pub fn __repr__(&self) -> String {
        self.repr()
    }

    pub fn __eq__(&self, other: &Self) -> bool {
        graph_equal(&self.graph.clone(), &other.graph.clone())
    }
}

impl Repr for PyGraphView {
    fn repr(&self) -> String {
        if self.properties().is_empty() {
            StructReprBuilder::new("Graph")
                .add_field("number_of_nodes", self.graph.count_nodes())
                .add_field("number_of_edges", self.graph.count_edges())
                .add_field(
                    "number_of_temporal_edges",
                    self.graph.count_temporal_edges(),
                )
                .add_field("earliest_time", self.earliest_time().repr())
                .add_field("latest_time", self.latest_time().repr())
                .finish()
        } else {
            StructReprBuilder::new("Graph")
                .add_field("number_of_nodes", self.graph.count_nodes())
                .add_field("number_of_edges", self.graph.count_edges())
                .add_field(
                    "number_of_temporal_edges",
                    self.graph.count_temporal_edges(),
                )
                .add_field("earliest_time", self.earliest_time().repr())
                .add_field("latest_time", self.latest_time().repr())
                .add_field("properties", self.properties())
                .finish()
        }
    }
}