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
use uuid::Uuid;

use crate::{EdgeStore, Error, Graph, Meta, Node, NodeStore};
use std::collections::{HashMap, HashSet};

/// Whether any node of any kind should be selected independently or they should at
/// least share one edge with the "lead" node kind.
#[derive(Clone, Debug, PartialEq)]
pub enum NodeSelectionMode {
    Independent,
    Dependent(String),
}

/// What to display for edges.
#[derive(Copy, Clone, Default, Debug, PartialEq)]
pub enum EdgeDisplayMode {
    #[default]
    Binary,
    Kinds,
    Labels,
    WeightLabels,
    WeightValues,
    WeightSum,
}

/// How to divide the piecharts per edge.
#[derive(Copy, Clone, Default, Debug, PartialEq)]
pub enum EdgeDivisionMode {
    Absolute,
    #[default]
    Equal,
    Relative,
}

/// Filtering options on metadata.
#[derive(Clone, Default, Debug, PartialEq)]
pub struct MetadataFilter {
    kinds: Option<Vec<String>>,
    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
            }
        }
    }
}

impl Graph {
    pub fn mdm_axis_nodes(
        &self,
        node_filter: MetadataFilter,
        edge_filter: MetadataFilter,
        root_ids: Option<&Vec<Uuid>>,
        node_depth: Option<usize>,
        node_selection_mode: NodeSelectionMode,
    ) -> Result<Vec<Uuid>, Error> {
        let root_ids = root_ids.cloned().unwrap_or_else(|| {
            self.root_ids()
                .into_iter()
                .map(|id| id.to_owned())
                .collect()
        });

        let node_kind_order = node_filter.kinds.clone().map(|kinds| {
            kinds
                .into_iter()
                .enumerate()
                .map(|(i, kind)| (kind, i))
                .collect::<HashMap<String, usize>>()
        });

        // Split independent roots from dependent roots.
        let (ind_roots, dep_roots) = self.split_dependent_roots(root_ids, &node_selection_mode)?;

        // Get all leaf IDs for the independent roots.
        let ind_leaf_vec: Vec<Vec<Uuid>> =
            self.independent_leafs(&ind_roots, &node_filter, node_depth);

        // Aggregate them in a set for filtering and sorting functions.
        let ind_leaf_set: HashSet<Uuid> = ind_leaf_vec
            .clone()
            .into_iter()
            .flatten()
            .map(|x| x.to_owned())
            .collect();

        // Determine independent root order on these results following display logic.
        let ind_root_order =
            self.display_sort(&ind_roots, node_kind_order.as_ref(), Some(&ind_leaf_set));

        // Flatten independent leafs.
        let mut result = ind_root_order
            .into_iter()
            .filter_map(|x| ind_leaf_vec.get(x))
            .flatten()
            .map(|x| x.to_owned())
            .collect();

        // Early return if there are only independent roots.
        if &node_selection_mode == &NodeSelectionMode::Independent {
            return Ok(result);
        }

        // Get dependent leafs by further filtering after the independent leafs logic.
        let dep_leaf_vec: Vec<Vec<Uuid>> =
            self.independent_leafs(&dep_roots, &node_filter, node_depth);
        let dep_leaf_set: HashSet<Uuid> = dep_leaf_vec
            .clone()
            .into_iter()
            .flatten()
            .map(|x| x.to_owned())
            .collect();
        let edges: HashSet<Uuid> =
            self.dependency_edges(&ind_leaf_set, &dep_leaf_set, &edge_filter);
        let dep_leaf_vec: Vec<Vec<Uuid>> = dep_leaf_vec
            .into_iter()
            .map(|leafs| {
                leafs
                    .into_iter()
                    .filter(|x| self.is_connected_to(x, &ind_leaf_set, Some(&edges)))
                    .collect()
            })
            .collect();

        // Determine dependent root order on these results following display logic.
        let dep_root_order =
            self.display_sort(&dep_roots, node_kind_order.as_ref(), Some(&dep_leaf_set));

        // Flatten dependent leafs.
        let dep_leaf_vec: Vec<Uuid> = dep_root_order
            .into_iter()
            .filter_map(|x| dep_leaf_vec.get(x))
            .flatten()
            .map(|x| x.to_owned())
            .collect();

        result.extend(dep_leaf_vec);

        Ok(result)
    }

    fn split_dependent_roots(
        &self,
        root_ids: Vec<Uuid>,
        mode: &NodeSelectionMode,
    ) -> Result<(Vec<Uuid>, Vec<Uuid>), Error> {
        Ok(match mode {
            NodeSelectionMode::Independent => (root_ids, vec![]),
            NodeSelectionMode::Dependent(lead_kind) => {
                let mut ind_roots = vec![];
                let mut dep_roots = vec![];
                for root_id in root_ids.into_iter() {
                    if self.get_node_err(&root_id)?.kind() == lead_kind {
                        ind_roots.push(root_id);
                    } else {
                        dep_roots.push(root_id);
                    }
                }
                (ind_roots, dep_roots)
            }
        })
    }

    fn independent_leafs(
        &self,
        root_ids: &Vec<Uuid>,
        node_filter: &MetadataFilter,
        node_depth: Option<usize>,
    ) -> Vec<Vec<Uuid>> {
        root_ids
            .iter()
            .map(|x| {
                let leaf_ids = self.descendant_ids(x, true, true, None, node_depth)?;
                let leaf_ids = if leaf_ids.is_empty() {
                    vec![x]
                } else {
                    leaf_ids
                };
                let mut filtered = vec![];
                for leaf in leaf_ids.into_iter() {
                    if node_filter.satisfies(self.get_node_err(leaf)?) {
                        filtered.push(leaf.to_owned())
                    }
                }
                Ok(filtered)
            })
            .filter_map(|x: Result<Vec<Uuid>, Error>| x.ok())
            .collect()
    }

    fn display_sort(
        &self,
        node_ids: &Vec<Uuid>,
        node_kind_order: Option<&HashMap<String, usize>>,
        leaf_ids: Option<&HashSet<Uuid>>,
    ) -> Vec<usize> {
        let mut nodes: Vec<(usize, &Node)> = node_ids
            .iter()
            .filter_map(|x| self.get_node(x))
            .enumerate()
            .collect();
        nodes.sort_unstable_by_key(|&(_, node)| {
            (
                node_kind_order.map(|x| x.get(node.kind())),
                self.node_width(node.id(), false, leaf_ids, None).unwrap(),
                node.name(),
                node.id(),
            )
        });
        nodes.into_iter().map(|x| x.0).collect()
    }

    fn dependency_edges(
        &self,
        independents: &HashSet<Uuid>,
        dependents: &HashSet<Uuid>,
        edge_filter: &MetadataFilter,
    ) -> HashSet<Uuid> {
        self.edge_ids_between_all(independents, dependents)
            .union(&self.edge_ids_between_all(independents, dependents))
            .cloned()
            .into_iter()
            .filter(|x| {
                if let Some(e) = self.get_edge(x) {
                    edge_filter.satisfies(e)
                } else {
                    false
                }
            })
            .collect()
    }
}