hypergraphx 0.0.5

A hypergraph library for Rust, based on the Python library of the same name.
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
use fixedbitset::FixedBitSet;
use std::{hash::Hash, iter, usize};

use crate::prelude::*;

/// Just a graph.
/// I originally wanted to have this really neat system where no edges are actually stored,
/// but computed on the fly - but then I realised that I couldn't get an iterator over references to
/// edges - which bad.
///
/// Thusly, I must resort to making a complete graph a very inefficient wrapper over an ordinary graph.
/// On the bright side, that means it is mutable with WeightsMut. :'(
pub struct CompleteGraph<N: Clone + Hash + Eq, E: Clone + Hash + Eq> {
    inner: Graph<N, E>,
}

impl_graph_basics_wrapper!(
    CompleteGraph<N, E>,
    Graph<N, E>,
    false
);

impl_weights_wrapper!(
    CompleteGraph<N, E>
);

impl<'a, N: Clone + Eq + Hash + 'a, E: Clone + Eq + Hash + 'a> CompleteGraph<N, E> {
    pub fn add_node(&mut self, weight: N, edges: Vec<E>) -> Result<usize, HypergraphErrors> {
        if edges.len() != self.node_count() {
            return Err(HypergraphErrors::InvariantViolation {
                err: "Require edge to every existing node".to_string(),
            });
        }

        let node = self.inner.add_node(weight);
        self.inner
            .add_edges(edges.into_iter().enumerate().map(|x| (x.1, [node, x.0])))?;

        return Ok(node);
    }

    pub fn add_nodes(
        &mut self,
        weights: impl Iterator<Item = N>,
        edges_it: impl Iterator<Item = Vec<E>>,
    ) -> Result<(), HypergraphErrors> {
        for (weight, edges) in weights.zip(edges_it) {
            self.add_node(weight, edges)?;
        }
        return Ok(());
    }

    pub fn remove_node(
        &mut self,
        node_index: <CompleteGraph<N, E> as GraphBasics<'a>>::NodeIndex,
    ) -> Result<UndirectedNode<N>, HypergraphErrors> {
        self.inner.remove_node(node_index)
    }
}

impl<'a, N: Clone + Eq + Hash + 'a, E: Default + Clone + Eq + Hash + 'a> CompleteGraph<N, E> {
    pub fn add_node_default(&mut self, weight: N) -> HypergraphResult<usize> {
        let node = self.inner.add_node(weight);
        self.inner.add_edges(
            (0..self.node_count())
                .into_iter()
                .map(|x| (E::default(), [node, x])),
        )?;

        return Ok(node);
    }

    pub fn add_nodes_default(
        &mut self,
        weights: impl Iterator<Item = N>,
    ) -> Result<(), HypergraphErrors> {
        for weight in weights {
            self.add_node_default(weight)?;
        }
        return Ok(());
    }
}

pub struct DirectedCompleteGraph<N: Clone + Hash + Eq, E: Clone + Hash + Eq> {
    inner: DiGraph<N, E>,
}

impl_graph_basics_wrapper!(
    DirectedCompleteGraph<N, E>,
    DiGraph<N, E>,
    true
);

impl_weights_wrapper!(
    DirectedCompleteGraph<N, E>
);

impl<'a, N: Clone + Eq + Hash + 'a, E: Clone + Eq + Hash + 'a> DirectedCompleteGraph<N, E> {
    pub fn add_node(
        &mut self,
        weight: N,
        src_edges: Vec<E>,
        dst_edges: Vec<E>,
    ) -> Result<usize, HypergraphErrors> {
        if src_edges.len() != self.node_count() || dst_edges.len() != self.node_count() {
            return Err(HypergraphErrors::InvariantViolation {
                err: "Require edge to and from every existing node".to_string(),
            });
        }

        let node = self.inner.add_node(weight);
        self.inner.add_edges(
            src_edges
                .into_iter()
                .enumerate()
                .map(|x| (x.1, [node], [x.0])),
        )?;
        self.inner.add_edges(
            dst_edges
                .into_iter()
                .enumerate()
                .map(|x| (x.1, [x.0], [node])),
        )?;

        return Ok(node);
    }

    pub fn add_nodes(
        &mut self,
        weights: impl Iterator<Item = N>,
        edges_it: impl Iterator<Item = (Vec<E>, Vec<E>)>,
    ) -> Result<(), HypergraphErrors> {
        for (weight, edges) in weights.zip(edges_it) {
            self.add_node(weight, edges.0, edges.1)?;
        }
        return Ok(());
    }

    pub fn remove_node(
        &mut self,
        node_index: <CompleteGraph<N, E> as GraphBasics<'a>>::NodeIndex,
    ) -> Result<DirectedNode<N>, HypergraphErrors> {
        self.inner.remove_node(node_index)
    }
}

impl<'a, N: Clone + Eq + Hash + 'a, E: Default + Clone + Eq + Hash + 'a>
    DirectedCompleteGraph<N, E>
{
    pub fn add_node_default(&mut self, weight: N) -> HypergraphResult<usize> {
        let node = self.inner.add_node(weight);
        self.inner.add_edges(
            (0..self.node_count())
                .into_iter()
                .map(|x| (E::default(), [node], [x])),
        )?;
        self.inner.add_edges(
            (0..self.node_count())
                .into_iter()
                .map(|x| (E::default(), [x], [node])),
        )?;

        return Ok(node);
    }

    pub fn add_nodes_default(
        &mut self,
        weights: impl Iterator<Item = N>,
    ) -> Result<(), HypergraphErrors> {
        for weight in weights {
            self.add_node_default(weight)?;
        }
        return Ok(());
    }
}

/// Tournaments are unweighted.
pub struct Tournament<N: Clone + Eq + Hash> {
    inner: DiGraph<N, ()>,
    rounds: Vec<FixedBitSet>,
}

#[derive(Debug, Clone, PartialEq, Eq, Copy, Hash)]
pub struct NodePair(u32, u32);
impl Into<usize> for NodePair {
    fn into(self) -> usize {
        (self.0 << u32::BITS + self.1) as usize
    }
}
impl From<usize> for NodePair {
    fn from(value: usize) -> Self {
        NodePair(
            (value >> u32::BITS) as u32,
            (value % (1 << u32::BITS)) as u32,
        )
    }
}

impl<'a, N> GraphBasics<'a> for Tournament<N>
where
    N: Clone + Eq + Hash + 'a,
{
    type NodeRef = <DiGraph<N, ()> as GraphBasics<'a>>::NodeRef;

    type EdgeRef = (usize, usize);

    type NodeIndex = <DiGraph<N, ()> as GraphBasics<'a>>::NodeIndex;

    type EdgeIndex = NodePair;

    fn nodes(&'a self) -> impl Iterator<Item = Self::NodeRef> {
        self.inner.nodes()
    }

    fn node_count(&'a self) -> usize {
        self.inner.node_count()
    }

    fn edges(&'a self) -> impl Iterator<Item = Self::EdgeRef> {
        // let mut out = iter::empty();
        // self.fares.iter().enumerate().rev().for_each(|(i, x)| {
        //     out = out.chain(x.ones().map(|y| (NodePair(i as u32, y as u32), true)));
        // });

        // out

        self.rounds
            .iter()
            .enumerate()
            .map(|(i, x)| {
                x.ones()
                    .map(move |y| ((i, y)))
                    .chain(x.zeroes().map(move |y| ((y, i))))
            })
            .flatten()
    }

    fn edge_count(&'a self) -> usize {
        (self.node_count() * (self.node_count() + 1)) >> 1
    }

    fn is_directed(&self) -> bool {
        true
    }

    fn node(&'a self, node_index: Self::NodeIndex) -> Option<Self::NodeRef> {
        self.inner.node(node_index)
    }

    fn edge(&'a self, edge_index: Self::EdgeIndex) -> Option<Self::EdgeRef> {
        let a = edge_index.0.max(edge_index.1) as usize;
        let b = edge_index.0.min(edge_index.1) as usize;
        if self.rounds[b].contains(a) {
            Some((b, a))
        } else {
            Some((a, b))
        }
    }

    fn node_iter(
        &'a self,
        node_index: impl Iterator<Item = Self::NodeIndex>,
    ) -> impl Iterator<Item = Option<Self::NodeRef>> {
        self.inner.node_iter(node_index)
    }

    fn edge_iter(
        &'a self,
        edge_index: impl Iterator<Item = Self::EdgeIndex>,
    ) -> impl Iterator<Item = Option<Self::EdgeRef>> {
        edge_index.map(|e| self.edge(e))
    }
}

impl<'a, N: 'a> GraphWrapper<'a> for Tournament<N>
where
    DiGraph<N, ()>: GraphBasics<'a>,
    N: 'a + Clone + Eq + Hash,
{
    type Inner = DiGraph<N, ()>;

    fn into_inner(&'a self) -> &'a Self::Inner {
        &self.inner
    }
}

impl<'a, N> Weights<'a, N, ()> for Tournament<N>
where
    N: 'a + Clone + Hash + Eq,
{
    fn node_weights(&'a self) -> impl Iterator<Item = &'a N> + 'a {
        self.inner.node_weights()
    }

    fn edge_weights(&'a self) -> impl Iterator<Item = &'a ()> + 'a {
        iter::empty()
    }

    fn node_weights_mut(&'a mut self) -> impl Iterator<Item = &'a mut N> + 'a {
        self.inner.node_weights_mut()
    }

    fn edge_weights_mut(&'a mut self) -> impl Iterator<Item = &'a mut ()> + 'a {
        iter::empty()
    }

    fn node_weight_mut(
        &'a mut self,
        node_index: <Self as GraphBasics<'a>>::NodeIndex,
    ) -> Option<&'a mut N> {
        self.inner.node_weight_mut(node_index)
    }

    fn edge_weight_mut(
        &'a mut self,
        _: <Self as GraphBasics<'a>>::EdgeIndex,
    ) -> Option<&'a mut ()> {
        None
    }

    fn node_weight(&'a self, node_index: <Self as GraphBasics<'a>>::NodeIndex) -> Option<&'a N> {
        self.inner.node_weight(node_index)
    }

    fn edge_weight(&'a self, _: <Self as GraphBasics<'a>>::EdgeIndex) -> Option<&'a ()> {
        None
    }

    unsafe fn node_weight_unchecked(
        &'a self,
        node_index: <Self as GraphBasics<'a>>::NodeIndex,
    ) -> &'a N {
        unsafe { self.inner.node_weight_unchecked(node_index) }
    }

    unsafe fn edge_weight_unchecked(&'a self, _: <Self as GraphBasics<'a>>::EdgeIndex) -> &'a () {
        &()
    }

    unsafe fn node_weight_unchecked_mut(
        &'a mut self,
        node_index: <Self as GraphBasics<'a>>::NodeIndex,
    ) -> &'a mut N {
        unsafe { self.inner.node_weight_unchecked_mut(node_index) }
    }

    unsafe fn edge_weight_unchecked_mut(
        &'a mut self,
        _: <Self as GraphBasics<'a>>::EdgeIndex,
    ) -> &'a mut () {
        Box::leak(Box::new(()))
    }

    fn edge_weight_copied(&'a self, edge_index: <Self as GraphBasics<'a>>::EdgeIndex) -> Option<()>
    where
        (): Copy,
    {
        None
    }

    fn node_weight_copied(&'a self, node_index: <Self as GraphBasics<'a>>::NodeIndex) -> Option<N>
    where
        N: Copy,
    {
        self.inner.node_weight_copied(node_index)
    }

    unsafe fn edge_weight_copied_unchecked(
        &'a self,
        edge_index: <Self as GraphBasics<'a>>::EdgeIndex,
    ) -> ()
    where
        (): Copy,
    {
        ()
    }

    unsafe fn node_weight_copied_unchecked(
        &'a self,
        node_index: <Self as GraphBasics<'a>>::NodeIndex,
    ) -> N
    where
        N: Copy,
    {
        unsafe { self.inner.node_weight_copied_unchecked(node_index) }
    }
}

impl<N> Tournament<N>
where
    N: Clone + Eq + Hash,
{
    pub fn add_node(&mut self, weight: N, round: FixedBitSet) -> usize {
        self.rounds.push(round);
        self.inner.add_node(weight)
    }

    pub fn add_nodes(&mut self, weights_and_rounds: impl Iterator<Item = (N, FixedBitSet)>) {
        weights_and_rounds.for_each(|(weight, round)| {
            self.add_node(weight, round);
        });
    }
}