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
use crate::utils::*;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::{HashMap, HashSet};
use uuid::Uuid;

/// Metadata struct that contains common metadata for any instance.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Metadata {
    /// Unique instance ID.
    #[serde(rename = "id")]
    _id: Uuid,
    /// Instance name.
    pub name: String,
    /// Main category of this instance.
    pub kind: String,
    /// Instance labels.
    #[serde(
        default,
        serialize_with = "sort_alphabetically",
        skip_serializing_if = "is_empty_set"
    )]
    pub labels: HashSet<String>,
    /// Numeric instance weights.
    #[serde(
        default,
        serialize_with = "sort_alphabetically",
        skip_serializing_if = "is_empty_map"
    )]
    pub weights: HashMap<String, f64>,
    /// Miscellaneous data fields for this instance.
    #[serde(
        default,
        serialize_with = "sort_alphabetically",
        skip_serializing_if = "is_empty_map"
    )]
    pub annotations: HashMap<String, Value>,
}
impl Default for Metadata {
    fn default() -> Self {
        let _id = Uuid::new_v4();
        Self {
            _id,
            name: _id.to_string(),
            kind: "default".to_string(),
            labels: HashSet::<String>::default(),
            weights: HashMap::<String, f64>::default(),
            annotations: HashMap::<String, Value>::default(),
        }
    }
}
impl Metadata {
    /// Create a new Meta struct with arguments.
    pub fn new(
        id: Option<Uuid>,
        name: Option<String>,
        kind: Option<String>,
        labels: Option<HashSet<String>>,
        weights: Option<HashMap<String, f64>>,
        annotations: Option<HashMap<String, Value>>,
    ) -> Self {
        let _id = match id {
            None => Uuid::new_v4(),
            Some(x) => x,
        };
        Self {
            _id,
            name: name.unwrap_or_else(|| _id.to_string()),
            kind: kind.unwrap_or_else(|| "default".to_string()),
            labels: labels.unwrap_or_default(),
            weights: weights.unwrap_or_default(),
            annotations: annotations.unwrap_or_default(),
        }
    }
    /// The unique ID of this instance.
    pub fn id(&self) -> &Uuid {
        &self._id
    }
    /// Set the unique ID to a custom value (or generate a new one with None).
    /// Use with care! References in node and edge stores are NOT updated automatically.
    pub fn set_id(&mut self, value: Option<Uuid>) {
        self._id = value.unwrap_or_else(Uuid::new_v4);
    }
}

pub trait Meta {
    fn get_meta(&self) -> &Metadata;
    fn id(&self) -> &Uuid {
        &self.get_meta()._id
    }
    fn name(&self) -> &String {
        &self.get_meta().name
    }
    fn kind(&self) -> &String {
        &self.get_meta().kind
    }
    fn labels(&self) -> &HashSet<String> {
        &self.get_meta().labels
    }
    fn weights(&self) -> &HashMap<String, f64> {
        &self.get_meta().weights
    }
    fn annotations(&self) -> &HashMap<String, Value> {
        &self.get_meta().annotations
    }
}

#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub enum Aggregator {
    #[default]
    Binary,
    Kinds,
    Labels,
    Weights,
    Annotations,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct Aggregate {
    /// Over how many items the aggregate has been taken.
    pub items: isize,
    /// Kind occurrence.
    pub kinds: HashMap<String, isize>,
    /// Label occurrence.
    pub labels: HashMap<String, isize>,
    /// Weight sum value.
    pub weights: HashMap<String, f64>,
    /// Annotation key occurrence.
    pub annotations: HashMap<String, isize>,
}
impl Aggregate {
    pub fn new(data: Vec<&Metadata>) -> Self {
        let mut agg = Self::default();
        for d in data.into_iter() {
            agg.add(d)
        }
        agg
    }
    /// Add metadata to the aggregate.
    pub fn add(&mut self, item: &Metadata) {
        self.items += 1;
        *self.kinds.entry(item.kind.clone()).or_insert(0) += 1;
        for label in item.labels.iter() {
            *self.labels.entry(label.clone()).or_insert(0) += 1;
        }
        for (key, value) in item.weights.iter() {
            *self.weights.entry(key.clone()).or_insert(0.0) += value;
        }
        for key in item.annotations.keys() {
            *self.annotations.entry(key.clone()).or_insert(0) += 1;
        }
    }
    /// Subtract metadata from the aggregate.
    pub fn subtract(&mut self, item: &Metadata) {
        self.items -= 1;
        if let Some(&num) = self.kinds.get(&item.kind) {
            if num <= 1 {
                self.kinds.remove(&item.kind);
            } else {
                *self.kinds.entry(item.kind.clone()).or_insert(1) -= 1;
            }
        }
        for label in item.labels.iter() {
            if let Some(&num) = self.labels.get(label) {
                if num <= 1 {
                    self.labels.remove(label);
                } else {
                    *self.labels.entry(label.clone()).or_insert(1) -= 1;
                }
            }
        }
        for (key, value) in item.weights.iter() {
            *self.weights.entry(key.clone()).or_insert(0.0) -= value;
        }
        for key in item.annotations.keys() {
            if let Some(&num) = self.annotations.get(key) {
                if num <= 1 {
                    self.annotations.remove(key);
                } else {
                    *self.annotations.entry(key.clone()).or_insert(1) -= 1;
                }
            }
        }
    }
    /// Add another Aggregate's values to this.
    pub fn extend(&mut self, other: Self) -> &Self {
        self.items += other.items;
        for (key, value) in other.kinds {
            *self.kinds.entry(key).or_insert(0) += value;
        }
        for (key, value) in other.labels {
            *self.labels.entry(key).or_insert(0) += value;
        }
        for (key, value) in other.weights {
            *self.weights.entry(key).or_insert(0.0) += value;
        }
        for (key, value) in other.annotations {
            *self.annotations.entry(key).or_insert(0) += value;
        }
        self
    }

    pub fn sum(&self, aggregator: &Aggregator, fields: Option<&HashSet<String>>) -> f64 {
        match aggregator {
            Aggregator::Binary => {
                if self.items > 0 {
                    1.0
                } else {
                    0.0
                }
            }
            Aggregator::Kinds => match fields {
                None => self.kinds.values().sum::<isize>() as f64,
                Some(fields) => self
                    .kinds
                    .iter()
                    .map(|(key, &value)| if fields.contains(key) { value } else { 0isize })
                    .sum::<isize>() as f64,
            },
            Aggregator::Labels => match fields {
                None => self.labels.values().sum::<isize>() as f64,
                Some(fields) => self
                    .labels
                    .iter()
                    .map(|(key, &value)| if fields.contains(key) { value } else { 0isize })
                    .sum::<isize>() as f64,
            },
            Aggregator::Weights => match fields {
                None => self.weights.values().sum(),
                Some(fields) => self
                    .weights
                    .iter()
                    .map(
                        |(key, &value)| {
                            if fields.contains(key) {
                                value
                            } else {
                                0.0
                            }
                        },
                    )
                    .sum(),
            },
            Aggregator::Annotations => match fields {
                None => self.annotations.values().sum::<isize>() as f64,
                Some(fields) => self
                    .annotations
                    .iter()
                    .map(|(key, &value)| if fields.contains(key) { value } else { 0isize })
                    .sum::<isize>() as f64,
            },
        }
    }
}