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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
//! The edge module contains the PyEdge class, which is used to represent edges in the graph and
//! provides access to the edge's properties and vertices.
//!
//! The PyEdge class also provides access to the perspective APIs, which allow the user to view the
//! edge as it existed at a particular point in time, or as it existed over a particular time range.
//!
use crate::dynamic::{DynamicGraph, IntoDynamic};
use crate::types::repr::{iterator_repr, Repr};
use crate::utils::*;
use crate::vertex::{PyVertex, PyVertexIterable};
use crate::wrappers::iterators::{OptionI64Iterable, OptionPropIterable};
use crate::wrappers::prop::Prop;
use chrono::NaiveDateTime;
use itertools::Itertools;
use pyo3::prelude::*;
use pyo3::{pyclass, pymethods, PyAny, PyRef, PyRefMut, PyResult};
use raphtory::db::edge::EdgeView;
use raphtory::db::view_api::*;
use std::collections::HashMap;
use std::sync::Arc;

/// PyEdge is a Python class that represents an edge in the graph.
/// An edge is a directed connection between two vertices.
#[pyclass(name = "Edge")]
pub struct PyEdge {
    pub(crate) edge: EdgeView<DynamicGraph>,
}

impl<G: GraphViewOps + IntoDynamic> From<EdgeView<G>> for PyEdge {
    fn from(value: EdgeView<G>) -> Self {
        Self {
            edge: EdgeView {
                graph: value.graph.clone().into_dynamic(),
                edge: value.edge,
            },
        }
    }
}

impl<G: GraphViewOps + IntoDynamic> IntoPyObject for EdgeView<G> {
    fn into_py_object(self) -> PyObject {
        let py_version: PyEdge = self.into();
        Python::with_gil(|py| py_version.into_py(py))
    }
}

/// PyEdge is a Python class that represents an edge in the graph.
/// An edge is a directed connection between two vertices.
#[pymethods]
impl PyEdge {
    pub fn __getitem__(&self, name: String) -> Option<Prop> {
        self.property(name, Some(true))
    }

    /// Returns the value of the property with the given name.
    /// If the property is not found, None is returned.
    /// If the property is found, the value of the property is returned.
    ///
    /// Arguments:
    ///    name (str): The name of the property to retrieve.
    ///
    /// Returns:
    ///   The value of the property with the given name.
    #[pyo3(signature = (name, include_static = true))]
    pub fn property(&self, name: String, include_static: Option<bool>) -> Option<Prop> {
        let include_static = include_static.unwrap_or(true);
        self.edge
            .property(name, include_static)
            .map(|prop| prop.into())
    }

    /// Returns the value of the property with the given name all times.
    /// If the property is not found, None is returned.
    /// If the property is found, the value of the property is returned.
    ///
    /// Arguments:
    ///   name (str): The name of the property to retrieve.
    ///
    /// Returns:
    ///  The value of the property with the given name.
    #[pyo3(signature = (name))]
    pub fn property_history(&self, name: String) -> Vec<(i64, Prop)> {
        self.edge
            .property_history(name)
            .into_iter()
            .map(|(k, v)| (k, v.into()))
            .collect()
    }

    /// Returns a list of timestamps of when an edge is added or change to an edge is made.
    ///
    /// Returns:
    ///     A list of timestamps.
    ///

    pub fn history(&self) -> Vec<i64> {
        self.edge.history()
    }

    /// Returns a dictionary of all properties on the edge.
    ///
    /// Arguments:
    ///  include_static (bool): Whether to include static properties in the result.
    ///
    /// Returns:
    ///   A dictionary of all properties on the edge.
    #[pyo3(signature = (include_static = true))]
    pub fn properties(&self, include_static: Option<bool>) -> HashMap<String, Prop> {
        let include_static = include_static.unwrap_or(true);
        self.edge
            .properties(include_static)
            .into_iter()
            .map(|(k, v)| (k, v.into()))
            .collect()
    }

    /// Returns a dictionary of all properties on the edge at all times.
    ///
    /// Returns:
    ///   A dictionary of all properties on the edge at all times.
    pub fn property_histories(&self) -> HashMap<String, Vec<(i64, Prop)>> {
        self.edge
            .property_histories()
            .into_iter()
            .map(|(k, v)| (k, v.into_iter().map(|(t, p)| (t, p.into())).collect()))
            .collect()
    }

    /// Returns a list of all property names on the edge.
    ///
    /// Arguments:
    ///   include_static (bool): Whether to include static properties in the result.
    ///
    /// Returns:
    ///   A list of all property names on the edge.
    #[pyo3(signature = (include_static = true))]
    pub fn property_names(&self, include_static: Option<bool>) -> Vec<String> {
        let include_static = include_static.unwrap_or(true);
        self.edge.property_names(include_static)
    }

    /// Check if a property exists with the given name.
    ///
    /// Arguments:
    ///  name (str): The name of the property to check.
    ///  include_static (bool): Whether to include static properties in the result.
    ///
    /// Returns:
    /// True if a property exists with the given name, False otherwise.
    #[pyo3(signature = (name, include_static = true))]
    pub fn has_property(&self, name: String, include_static: Option<bool>) -> bool {
        let include_static = include_static.unwrap_or(true);
        self.edge.has_property(name, include_static)
    }

    /// Check if a static property exists with the given name.
    ///
    /// Arguments:
    ///   name (str): The name of the property to check.
    ///
    /// Returns:
    ///   True if a static property exists with the given name, False otherwise.
    pub fn has_static_property(&self, name: String) -> bool {
        self.edge.has_static_property(name)
    }

    pub fn static_property(&self, name: String) -> Option<Prop> {
        self.edge.static_property(name).map(|prop| prop.into())
    }

    /// Get the source vertex of the Edge.
    ///
    /// Returns:
    ///   The source vertex of the Edge.
    fn src(&self) -> PyVertex {
        self.edge.src().into()
    }

    /// Get the destination vertex of the Edge.
    ///
    /// Returns:
    ///   The destination vertex of the Edge.
    fn dst(&self) -> PyVertex {
        self.edge.dst().into()
    }

    //******  Perspective APIS  ******//

    /// Get the start time of the Edge.
    ///
    /// Returns:
    ///  The start time of the Edge.
    pub fn start(&self) -> Option<i64> {
        self.edge.start()
    }

    /// Get the start datetime of the Edge.
    ///
    /// Returns:
    ///     the start datetime of the Edge.
    pub fn start_date_time(&self) -> Option<NaiveDateTime> {
        let start_time = self.edge.start()?;
        Some(NaiveDateTime::from_timestamp_millis(start_time).unwrap())
    }

    /// Get the end time of the Edge.
    ///
    /// Returns:
    ///   The end time of the Edge.
    pub fn end(&self) -> Option<i64> {
        self.edge.end()
    }

    /// Get the end datetime of the Edge.
    ///
    /// Returns:
    ///    The end datetime of the Edge
    pub fn end_date_time(&self) -> Option<NaiveDateTime> {
        let end_time = self.edge.end()?;
        Some(NaiveDateTime::from_timestamp_millis(end_time).unwrap())
    }

    /// Get the duration of the Edge.
    ///
    /// Arguments:
    ///   step (int): The step size to use when calculating the duration.
    ///
    /// Returns:
    ///   A set of windows containing edges that fall in the time period
    #[pyo3(signature = (step))]
    fn expanding(&self, step: &PyAny) -> PyResult<PyWindowSet> {
        expanding_impl(&self.edge, step)
    }

    /// Get a set of Edge windows for a given window size, step, start time
    /// and end time using rolling window.
    /// A rolling window is a window that moves forward by `step` size at each iteration.
    ///
    /// Arguments:
    ///   window (int): The size of the window.
    ///   step (int): The step size to use when calculating the duration.
    ///   start (int): The start time to use when calculating the duration.
    ///   end (int): The end time to use when calculating the duration.
    ///
    /// Returns:
    ///   A set of windows containing edges that fall in the time period
    fn rolling(&self, window: &PyAny, step: Option<&PyAny>) -> PyResult<PyWindowSet> {
        rolling_impl(&self.edge, window, step)
    }

    /// Get a new Edge with the properties of this Edge within the specified time window.
    ///
    /// Arguments:
    ///   t_start (int): The start time of the window.
    ///   t_end (int): The end time of the window.
    ///
    /// Returns:
    ///   A new Edge with the properties of this Edge within the specified time window.
    #[pyo3(signature = (t_start = None, t_end = None))]
    pub fn window(&self, t_start: Option<&PyAny>, t_end: Option<&PyAny>) -> PyResult<PyEdge> {
        window_impl(&self.edge, t_start, t_end).map(|e| e.into())
    }

    /// Get a new Edge with the properties of this Edge at a specified time.
    ///
    /// Arguments:
    ///   end (int): The time to get the properties at.
    ///
    /// Returns:
    ///   A new Edge with the properties of this Edge at a specified time.
    #[pyo3(signature = (end))]
    pub fn at(&self, end: &PyAny) -> PyResult<PyEdge> {
        at_impl(&self.edge, end).map(|e| e.into())
    }

    /// Explodes an Edge into a list of PyEdges. This is useful when you want to iterate over
    /// the properties of an Edge at every single point in time. This will return a seperate edge
    /// each time a property had been changed.
    ///
    /// Returns:
    ///     A list of PyEdges
    pub fn explode(&self) -> PyEdges {
        let edge = self.edge.clone();
        (move || edge.explode()).into()
    }

    /// Gets the earliest time of an edge.
    ///
    /// Returns:
    ///     (int) The earliest time of an edge
    pub fn earliest_time(&self) -> Option<i64> {
        self.edge.earliest_time()
    }

    /// Gets of earliest datetime of an edge.
    ///
    /// Returns:
    ///     the earliest datetime of an edge
    pub fn earliest_date_time(&self) -> Option<NaiveDateTime> {
        Some(NaiveDateTime::from_timestamp_millis(self.edge.earliest_time()?).unwrap())
    }

    /// Gets the latest time of an edge.
    ///
    /// Returns:
    ///     (int) The latest time of an edge
    pub fn latest_time(&self) -> Option<i64> {
        self.edge.latest_time()
    }

    /// Gets of latest datetime of an edge.
    ///
    /// Returns:
    ///     the latest datetime of an edge
    pub fn latest_date_time(&self) -> Option<NaiveDateTime> {
        let latest_time = self.edge.latest_time()?;
        Some(NaiveDateTime::from_timestamp_millis(latest_time).unwrap())
    }

    /// Gets the time of an exploded edge.
    ///
    /// Returns:
    ///     (int) The time of an exploded edge
    pub fn time(&self) -> Option<i64> {
        self.edge.time()
    }

    /// Gets the name of the layer this edge belongs to
    ///
    /// Returns:
    ///     (str) The name of the layer
    pub fn layer_name(&self) -> String {
        self.edge.layer_name()
    }

    /// Gets the datetime of an exploded edge.
    ///
    /// Returns:
    ///     (datetime) the datetime of an exploded edge
    pub fn date_time(&self) -> Option<NaiveDateTime> {
        let date_time = self.edge.time()?;
        Some(NaiveDateTime::from_timestamp_millis(date_time).unwrap())
    }

    /// Displays the Edge as a string.
    pub fn __repr__(&self) -> String {
        self.repr()
    }
}

impl Repr for PyEdge {
    fn repr(&self) -> String {
        let properties = &self
            .properties(Some(true))
            .iter()
            .map(|(k, v)| k.to_string() + " : " + &v.to_string())
            .join(", ");

        let source = self.edge.src().name();
        let target = self.edge.dst().name();
        let earliest_time = self.edge.earliest_time();
        let latest_time = self.edge.latest_time();
        if properties.is_empty() {
            format!(
                "Edge(source={}, target={}, earliest_time={}, latest_time={})",
                source.trim_matches('"'),
                target.trim_matches('"'),
                earliest_time.unwrap_or(0),
                latest_time.unwrap_or(0),
            )
        } else {
            let property_string: String = "{".to_string() + &properties + "}";
            format!(
                "Edge(source={}, target={}, earliest_time={}, latest_time={}, properties={})",
                source.trim_matches('"'),
                target.trim_matches('"'),
                earliest_time.unwrap_or(0),
                latest_time.unwrap_or(0),
                property_string
            )
        }
    }
}

py_iterator!(PyEdgeIter, EdgeView<DynamicGraph>, PyEdge, "EdgeIter");

/// A list of edges that can be iterated over.
#[pyclass(name = "Edges")]
pub struct PyEdges {
    builder: Arc<dyn Fn() -> BoxedIter<EdgeView<DynamicGraph>> + Send + Sync + 'static>,
}

impl PyEdges {
    /// an iterable that can be used in rust
    fn iter(&self) -> BoxedIter<EdgeView<DynamicGraph>> {
        (self.builder)()
    }

    /// returns an iterable used in python
    fn py_iter(&self) -> BoxedIter<PyEdge> {
        Box::new(self.iter().map(|e| e.into()))
    }
}

#[pymethods]
impl PyEdges {
    fn __iter__(&self) -> PyEdgeIter {
        PyEdgeIter {
            iter: Box::new(self.py_iter()),
        }
    }

    fn __len__(&self) -> usize {
        self.iter().count()
    }

    fn src(&self) -> PyVertexIterable {
        let builder = self.builder.clone();
        (move || builder().src()).into()
    }

    fn dst(&self) -> PyVertexIterable {
        let builder = self.builder.clone();
        (move || builder().dst()).into()
    }

    /// Returns all edges as a list
    fn collect(&self) -> Vec<PyEdge> {
        self.py_iter().collect()
    }

    /// Returns the first edge
    fn first(&self) -> Option<PyEdge> {
        self.py_iter().next()
    }

    /// Returns the number of edges
    fn count(&self) -> usize {
        self.py_iter().count()
    }

    /// Explodes the edges into a list of edges. This is useful when you want to iterate over
    /// the properties of an Edge at every single point in time. This will return a seperate edge
    /// each time a property had been changed.
    fn explode(&self) -> PyEdges {
        let builder = self.builder.clone();
        (move || {
            let iter: BoxedIter<EdgeView<DynamicGraph>> =
                Box::new(builder().flat_map(|e| e.explode()));
            iter
        })
        .into()
    }

    /// Returns the earliest time of the edges.
    fn earliest_time(&self) -> OptionI64Iterable {
        let edges: Arc<
            dyn Fn() -> Box<dyn Iterator<Item = EdgeView<DynamicGraph>> + Send> + Send + Sync,
        > = self.builder.clone();
        (move || edges().earliest_time()).into()
    }

    /// Returns the latest time of the edges.
    fn latest_time(&self) -> OptionI64Iterable {
        let edges: Arc<
            dyn Fn() -> Box<dyn Iterator<Item = EdgeView<DynamicGraph>> + Send> + Send + Sync,
        > = self.builder.clone();
        (move || edges().latest_time()).into()
    }

    fn property(&self, name: String, include_static: Option<bool>) -> OptionPropIterable {
        let edges: Arc<
            dyn Fn() -> Box<dyn Iterator<Item = EdgeView<DynamicGraph>> + Send> + Send + Sync,
        > = self.builder.clone();
        (move || edges().property(name.clone(), include_static.unwrap_or(true))).into()
    }

    fn __repr__(&self) -> String {
        self.repr()
    }
}

impl Repr for PyEdges {
    fn repr(&self) -> String {
        format!("Edges({})", iterator_repr(self.__iter__().into_iter()))
    }
}

impl<F: Fn() -> BoxedIter<EdgeView<DynamicGraph>> + Send + Sync + 'static> From<F> for PyEdges {
    fn from(value: F) -> Self {
        Self {
            builder: Arc::new(value),
        }
    }
}

py_iterator!(
    PyNestedEdgeIter,
    BoxedIter<EdgeView<DynamicGraph>>,
    PyEdgeIter,
    "NestedEdgeIter"
);

#[pyclass(name = "NestedEdges")]
pub struct PyNestedEdges {
    builder: Arc<dyn Fn() -> BoxedIter<BoxedIter<EdgeView<DynamicGraph>>> + Send + Sync + 'static>,
}

impl PyNestedEdges {
    fn iter(&self) -> BoxedIter<BoxedIter<EdgeView<DynamicGraph>>> {
        (self.builder)()
    }
}

#[pymethods]
impl PyNestedEdges {
    fn __iter__(&self) -> PyNestedEdgeIter {
        self.iter().into()
    }

    fn collect(&self) -> Vec<Vec<PyEdge>> {
        self.iter()
            .map(|e| e.map(|ee| ee.into()).collect())
            .collect()
    }

    fn explode(&self) -> PyNestedEdges {
        let builder = self.builder.clone();
        (move || {
            let iter: BoxedIter<BoxedIter<EdgeView<DynamicGraph>>> = Box::new(builder().map(|e| {
                let inner_box: BoxedIter<EdgeView<DynamicGraph>> =
                    Box::new(e.flat_map(|e| e.explode()));
                inner_box
            }));
            iter
        })
        .into()
    }
}

impl<F: Fn() -> BoxedIter<BoxedIter<EdgeView<DynamicGraph>>> + Send + Sync + 'static> From<F>
    for PyNestedEdges
{
    fn from(value: F) -> Self {
        Self {
            builder: Arc::new(value),
        }
    }
}