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
#[cfg(feature = "serde")]
use crate::serde_utils::*;
use std::collections::{HashMap, HashSet};
use uuid::Uuid;

/// Metadata struct that contains common metadata for any instance.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Metadata {
    /// Unique instance ID.
    #[cfg_attr(feature = "serde", serde(rename = "id"))]
    _id: Uuid,
    /// Instance name.
    pub name: String,
    /// Main category of this instance.
    pub kind: String,
    /// Instance labels.
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            serialize_with = "sort_alphabetically",
            skip_serializing_if = "is_empty_set"
        )
    )]
    pub labels: HashSet<String>,
    /// Numeric instance weights.
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            serialize_with = "sort_alphabetically",
            skip_serializing_if = "is_empty_map"
        )
    )]
    pub weights: HashMap<String, f64>,
    /// Miscellaneous data fields for this instance.
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            serialize_with = "sort_alphabetically",
            skip_serializing_if = "is_empty_map"
        )
    )]
    pub annotations: HashMap<String, serde_json::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, serde_json::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, serde_json::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, serde_json::Value> {
        &self.get_meta().annotations
    }
}

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

#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
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: &[&Metadata]) -> Self {
        let mut agg = Self::default();
        for &d in data.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
    }
    /// Get the sum for all given fields' values for a given aggregator.
    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,
            },
        }
    }
    /// Get the value that a field represents for a certain aggregator.
    pub fn value(&self, aggregator: &Aggregator, field: &String) -> f64 {
        match aggregator {
            Aggregator::Binary => 1.0,
            Aggregator::Kinds => self.kinds.get(field).map(|&x| x as f64).unwrap_or(0.0),
            Aggregator::Labels => self.labels.get(field).map(|&x| x as f64).unwrap_or(0.0),
            Aggregator::Weights => self.weights.get(field).copied().unwrap_or(0.0),
            Aggregator::Annotations => self
                .annotations
                .get(field)
                .map(|&x| x as f64)
                .unwrap_or(0.0),
        }
    }
    /// Get a fraction that a field represents for a certain aggregator.
    pub fn fraction(
        &self,
        aggregator: &Aggregator,
        field: &String,
        fields: Option<&HashSet<String>>,
    ) -> f64 {
        let sum = self.sum(aggregator, fields);
        let value = self.value(aggregator, field);
        if sum == 0.0 {
            0.0
        } else {
            value / sum
        }
    }
    /// Get all fractions for the given fields with respect to each other.
    pub fn fractions(
        &self,
        aggregator: &Aggregator,
        fields: &Vec<String>,
        factor: f64,
    ) -> Vec<f64> {
        let all: HashSet<String> = fields.clone().into_iter().collect();
        let sum = self.sum(aggregator, Some(&all));
        let factor = {
            if sum == 0.0 {
                1.0
            } else {
                factor / sum
            }
        };
        fields
            .iter()
            .map(|field| factor * self.value(aggregator, field))
            .collect()
    }
}

/// Track lower and upper bounds for float hashmaps.
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Domains {
    pub bounds: HashMap<String, (f64, f64)>,
}
impl Domains {
    /// Update the lower and upper bounds according to
    pub fn update(&mut self, values: &HashMap<String, f64>) {
        for (key, &value) in values.iter() {
            if let Some(entry) = self.bounds.get_mut(key) {
                entry.0 = entry.0.min(value);
                entry.1 = entry.1.max(value);
            } else {
                self.bounds.insert(key.to_owned(), (value, value));
            }
        }
    }
    /// Get the domains for a specified key.
    pub fn get(&self, key: &String) -> Option<&(f64, f64)> {
        self.bounds.get(key)
    }
    /// Interpolate a value for a specified key's domain. Returns 1.0 when the domain has no size
    /// (lower and upper bound are equal).
    pub fn interpolate(&self, key: &String, value: f64) -> Option<f64> {
        self.get(key).map(|&(lower, upper)| {
            if lower == upper {
                1.0
            } else {
                (value - lower) / (upper - lower)
            }
        })
    }
}

/// Filtering options on metadata.
#[derive(Clone, Default, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MetadataFilter {
    pub kinds: Option<Vec<String>>,
    pub labels: Option<HashSet<String>>,
}
impl MetadataFilter {
    /// Whether some metadata holding object satisfies this filter.
    pub fn satisfies<T: Meta>(&self, instance: &T) -> bool {
        self.satisfies_kinds(instance) && self.satisfies_labels(instance)
    }

    /// Whether some metadata holding object satisfies the set kinds.
    pub fn satisfies_kinds<T: Meta>(&self, instance: &T) -> bool {
        if let Some(kinds) = &self.kinds {
            kinds.contains(instance.kind())
        } else {
            true
        }
    }
    /// Whether some metadata holding object satisfies the set labels.
    pub fn satisfies_labels<T: Meta>(&self, instance: &T) -> bool {
        {
            if let Some(labels) = &self.labels {
                !labels.is_disjoint(instance.labels())
            } else {
                true
            }
        }
    }
}