spokes 0.4.0-rc.3

A network and network flow library.
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
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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
#![warn(clippy::pedantic)]
#![deny(missing_docs)]

//! Network and Network Flow Optimization Tools
//!
//! # Introduction
//!
//! The following example is based on the following graph
//! ![An example graph](https://upload.wikimedia.org/wikipedia/commons/5/57/Dijkstra_Animation.gif)
//! sourced from [Wikipedia][https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm].
//!
//! Here, the goal is to find the [shortest path tree](https://en.wikipedia.org/wiki/Shortest-path_tree) rooted at node 0.
//! In the example, it is verified the distance from node 0 to node 4 is 20.
//!
//! ```
//! use spokes::{Network, algorithms::{dijkstra_shortest_path, Distance}, ArcStorage};
//!
//! let mut network: Network<usize, (), u16> = Network::new();
//! network.add_nodes((0..6).map(|i| (i, ())));
//! network.add_arcs([
//!     (0, 1, 7), (1, 0, 7),
//!     (0, 5, 14), (5, 0, 14),
//!     (0, 2, 9), (2, 0, 9),
//!     (1, 2, 10), (2, 1, 10),
//!     (1, 3, 15), (3, 1, 15),
//!     (2, 5, 2), (5, 2, 2),
//!     (2, 3, 11), (3, 2, 11),
//!     (3, 4, 6), (4, 3, 6),
//!     (4, 5, 9), (5, 4, 9),
//! ]);
//!
//! let shortest_path_tree = dijkstra_shortest_path(&network, 0);
//!
//! assert_eq!(shortest_path_tree.node(&4), Some(&Distance::Finite(20)));
//!
//! let mut expected_network: Network<usize, Distance<u16>, ()> = Network::new();
//!
//! expected_network.add_nodes([
//!     (0, Distance::Finite(0)),
//!     (1, Distance::Finite(7)),
//!     (2, Distance::Finite(9)),
//!     (3, Distance::Finite(20)),
//!     (4, Distance::Finite(20)),
//!     (5, Distance::Finite(11)),
//! ]);
//!
//! expected_network.add_arcs([
//!     (1, 0),
//!     (2, 0),
//!     (3, 2),
//!     (5, 2),
//!     (4, 5),
//! ]);
//!
//! assert_eq!(shortest_path_tree, expected_network);
//! ```

pub mod algorithms;
pub mod arc_storage;
#[cfg(feature = "datasets")]
pub mod datasets;
pub mod node_storage;
pub mod search;

mod arc_info;
use std::{
    collections::{HashMap, HashSet},
    fmt::{Display, Write},
    hash::Hash,
    marker::PhantomData,
    ops::Index,
    write,
};

pub use arc_storage::{ArcStorage, HashMapStorage};
use search::{BfsIter, DfsIter, Direction};

use crate::{
    algorithms::{Cyclic, topological_sorting},
    node_storage::NodeStorage,
    search::PathIter,
};

pub use self::arc_info::ArcInfo;

#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))]
/// A representation of a network with node and arc attributes
pub struct Network<
    I,
    NodeAttr,
    ArcAttr,
    NodeStore = HashMap<I, NodeAttr>,
    ArcStore = HashMapStorage<I, ArcAttr>,
> where
    NodeStore: NodeStorage<I, NodeAttr>,
    ArcStore: ArcStorage<I, ArcAttr>,
{
    _phantom_aa: PhantomData<ArcAttr>,
    _phantom_na: PhantomData<NodeAttr>,
    _phantom_i: PhantomData<I>,
    nodes: NodeStore,
    arc_store: ArcStore,
}

impl<I, NodeAttr, ArcAttr, NodeStore, ArcStore> Clone
    for Network<I, NodeAttr, ArcAttr, NodeStore, ArcStore>
where
    NodeStore: NodeStorage<I, NodeAttr> + Clone,
    ArcStore: ArcStorage<I, ArcAttr> + Clone,
    ArcAttr: Clone,
    NodeAttr: Clone,
{
    fn clone(&self) -> Self {
        Self {
            _phantom_aa: self._phantom_aa,
            _phantom_na: self._phantom_na,
            _phantom_i: PhantomData,
            nodes: self.nodes.clone(),
            arc_store: self.arc_store.clone(),
        }
    }
}

impl<I, NodeAttr, ArcAttr, NodeStore, ArcStore> PartialEq
    for Network<I, NodeAttr, ArcAttr, NodeStore, ArcStore>
where
    NodeStore: NodeStorage<I, NodeAttr> + PartialEq,
    ArcStore: ArcStorage<I, ArcAttr> + PartialEq,
    ArcAttr: PartialEq,
    NodeAttr: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.nodes == other.nodes && self.arc_store == other.arc_store
    }
}

impl<I, NA, AA, NodeStore, ArcStore> Default for Network<I, NA, AA, NodeStore, ArcStore>
where
    NodeStore: NodeStorage<I, NA> + Default,
    ArcStore: ArcStorage<I, AA> + Default,
{
    fn default() -> Self {
        Self {
            _phantom_aa: PhantomData,
            _phantom_na: PhantomData,
            _phantom_i: PhantomData,
            nodes: Default::default(),
            arc_store: Default::default(),
        }
    }
}

impl<I, NA, AA, NodeStore, ArcStore> std::fmt::Debug for Network<I, NA, AA, NodeStore, ArcStore>
where
    NodeStore: NodeStorage<I, NA> + std::fmt::Debug,
    ArcStore: ArcStorage<I, AA> + std::fmt::Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Network")
            .field("nodes", &self.nodes)
            .field("arc_store", &self.arc_store)
            .finish()
    }
}

impl<I, NA, AA, NodeStore, ArcStore> Network<I, NA, AA, NodeStore, ArcStore>
where
    NodeStore: NodeStorage<I, NA> + Default,
    ArcStore: ArcStorage<I, AA> + Default,
{
    /// Create a new, empty network.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
}

impl<I, NodeAttr, ArcAttr, NodeStore, ArcStore> Network<I, NodeAttr, ArcAttr, NodeStore, ArcStore>
where
    NodeStore: NodeStorage<I, NodeAttr>,
    ArcStore: ArcStorage<I, ArcAttr>,
{
}

impl<I, NodeAttr, ArcAttr, NodeStore, ArcStore> Network<I, NodeAttr, ArcAttr, NodeStore, ArcStore>
where
    NodeStore: NodeStorage<I, NodeAttr>,
    ArcStore: ArcStorage<I, ArcAttr>,
{
    /// Get a reference to the network's arc store.
    #[must_use]
    pub const fn arc_store(&self) -> &ArcStore {
        &self.arc_store
    }

    /// Return the number of nodes in the network.
    pub fn n_nodes(&self) -> usize {
        self.nodes.n_nodes()
    }

    /// Add a node to the network.
    ///
    /// This will return the node attributes for a replaced node.
    pub fn add_node(&mut self, id: I, attributes: NodeAttr) -> Option<NodeAttr> {
        self.nodes.add_node(id, attributes)
    }

    /// Convert the network into it's constituent parts.
    pub fn into_parts(self) -> (NodeStore, ArcStore) {
        (self.nodes, self.arc_store)
    }

    /// Create a [`Network`] from node and arc storage.
    pub fn from_parts(
        nodes: NodeStore,
        arc_store: ArcStore,
    ) -> Result<Self, IncompatableArcAndNodeStores> {
        if arc_store
            .arc_iter()
            .all(|a| nodes.contains_node(&a.head) && nodes.contains_node(&a.tail))
        {
            Ok(Self {
                _phantom_na: PhantomData,
                _phantom_aa: PhantomData,
                _phantom_i: PhantomData,
                nodes,
                arc_store,
            })
        } else {
            Err(IncompatableArcAndNodeStores)
        }
    }

    /// Add nodes from an iterator.
    pub fn add_nodes<T: IntoIterator<Item = (I, NodeAttr)>>(&mut self, from: T) {
        from.into_iter().for_each(|(id, attr)| {
            self.add_node(id, attr);
        });
    }

    /// Remove a node.
    ///
    /// If the node is a part of an arc, the arc will be removed as well.
    pub fn remove_node(&mut self, id: &I) -> Option<NodeAttr> {
        self.arc_store.remove_arcs_with_node(id);
        self.nodes.remove_node(id)
    }

    /// Test if a given node id is within the network
    pub fn contains_node(&self, id: &I) -> bool {
        self.nodes.contains_node(id)
    }

    /// Access a particular node's attributes.
    pub fn node(&self, id: &I) -> Option<&NodeAttr> {
        self.nodes.node(id)
    }

    /// Access a particular node's attributes, mutibly.
    pub fn node_mut(&mut self, id: &I) -> Option<&mut NodeAttr> {
        self.nodes.node_mut(id)
    }

    /// Return an iterator through the nodes and their attributes
    pub fn iter_nodes(&self) -> impl Iterator<Item = (&I, &NodeAttr)> {
        self.nodes.iter_nodes()
    }

    /// Return an iterator that performs a breadth first search of the network starting from
    /// `start_id`.
    pub fn bfs<'a>(
        &'a self,
        start_id: &'a I,
        direction: Direction,
    ) -> BfsIter<'a, I, ArcAttr, ArcStore> {
        BfsIter::new(&self.arc_store, start_id, direction)
    }

    /// Return an iterator that performs a depth first search of the network starting from
    /// `start_id`.
    pub fn dfs<'a>(
        &'a self,
        start_id: &'a I,
        direction: Direction,
    ) -> DfsIter<'a, I, ArcAttr, ArcStore> {
        DfsIter::new(&self.arc_store, start_id, direction)
    }

    /// Return an interator over all paths starting at the `start_id`, in the given `direction`.
    pub fn paths<'a>(
        &'a self,
        start_id: &'a I,
        direction: Direction,
    ) -> PathIter<'a, I, ArcAttr, ArcStore>
    where
        I: Eq + Hash,
    {
        PathIter::new(self.arc_store(), start_id, direction)
    }

    /// Consume this network and transform it's nodes with a Fn.
    pub fn map_nodes<F, NewNodeAttr, NewNodeStore>(
        self,
        f: F,
    ) -> Result<
        Network<I, NewNodeAttr, ArcAttr, NewNodeStore, ArcStore>,
        IncompatableArcAndNodeStores,
    >
    where
        F: Fn((I, NodeAttr)) -> (I, NewNodeAttr),
        NewNodeStore: NodeStorage<I, NewNodeAttr> + std::iter::FromIterator<(I, NewNodeAttr)>,
        NodeStore: IntoIterator<Item = (I, NodeAttr)>,
    {
        Network::from_parts(self.nodes.into_iter().map(f).collect(), self.arc_store)
    }

    /// Consume this network and transform it's arcs with a Fn.
    pub fn map_arcs<F, NewArcAttr, NewArcStore>(
        self,
        f: F,
    ) -> Result<
        Network<I, NodeAttr, NewArcAttr, NodeStore, NewArcStore>,
        IncompatableArcAndNodeStores,
    >
    where
        F: Fn(ArcInfo<I, ArcAttr>) -> ArcInfo<I, NewArcAttr>,
        NewArcStore: ArcStorage<I, NewArcAttr> + FromIterator<ArcInfo<I, NewArcAttr>>,
        ArcStore: IntoIterator<Item = ArcInfo<I, ArcAttr>>,
    {
        Network::from_parts(self.nodes, self.arc_store.into_iter().map(f).collect())
    }

    /// Consume a network and transform it's nodes and arcs with Fns.
    pub fn map_nodes_and_arcs<FN, FA, NewNodeAttr, NewArcAttr, NewNodeStore, NewArcStore>(
        self,
        f_nodes: FN,
        f_arcs: FA,
    ) -> Result<
        Network<I, NewNodeAttr, NewArcAttr, NewNodeStore, NewArcStore>,
        IncompatableArcAndNodeStores,
    >
    where
        FN: Fn((I, NodeAttr)) -> (I, NewNodeAttr),
        FA: Fn(ArcInfo<I, ArcAttr>) -> ArcInfo<I, NewArcAttr>,
        NodeStore: IntoIterator<Item = (I, NodeAttr)>,
        ArcStore: IntoIterator<Item = ArcInfo<I, ArcAttr>>,
        NewNodeStore: NodeStorage<I, NewNodeAttr> + std::iter::FromIterator<(I, NewNodeAttr)>,
        NewArcStore: ArcStorage<I, NewArcAttr> + FromIterator<ArcInfo<I, NewArcAttr>>,
    {
        Network::from_parts(
            self.nodes.into_iter().map(f_nodes).collect(),
            self.arc_store.into_iter().map(f_arcs).collect(),
        )
    }

    /// Return a topological sorting of the indices for this network
    ///
    /// # Errors
    /// If the network has a cycle this will return `Err(Cyclic)`.
    pub fn topological_sorting(&self) -> Result<Vec<I>, Cyclic>
    where
        I: Eq + Hash + Clone,
    {
        topological_sorting(self)
    }

    /// Calculate the generations from this network
    ///
    /// # Example
    /// For the network:
    /// ```text
    ///           ┌───┐
    ///           │ 8 │
    ///           └───┘
    ///    ///    ///    /// ┌───┐     ┌───┐
    /// │ 9 │ ──▶ │ 0 │
    /// └───┘     └───┘
    ///    ///    ///    /// ┌───┐     ┌───┐     ┌───┐
    /// │ 5 │ ◀── │ 1 │ ──▶ │ 6 │
    /// └───┘     └───┘     └───┘
    ///   │         │         │
    ///   │         │         │
    ///   │         ▼         ▼
    ///   │       ┌───┐     ┌───┐
    ///   │       │ 2 │     │ 7 │
    ///   │       └───┘     └───┘
    ///   │         │         │
    ///   │         │         │
    ///   │         ▼         │
    ///   │       ┌───┐       │
    ///   └─────▶ │ 3 │       │
    ///           └───┘       │
    ///             │         │
    ///             │         │
    ///             ▼         │
    ///           ┌───┐       │
    ///           │ 4 │ ◀─────┘
    ///           └───┘
    /// ```
    /// ```
    /// use spokes::*;
    /// let mut net: Network<usize, (), ()> = Network::new();
    ///
    /// net.add_nodes((0..10).map(|i| (i, ())));
    /// net.add_arcs([
    ///     (9, 0),
    ///     (8, 0),
    ///     (0, 1),
    ///     (1, 5),
    ///     (1, 6),
    ///     (1, 2),
    ///     (6, 7),
    ///     (2, 3),
    ///     (5, 3),
    ///     (3, 4),
    ///     (7, 4),
    /// ]);
    ///
    /// let layers = net.generations()
    ///     .unwrap()
    ///     .into_iter()
    ///     .map(|x| {
    ///             let mut xs = x.into_iter().copied().collect::<Vec<usize>>();
    ///             xs.sort();
    ///             xs
    ///     })
    ///     .collect::<Vec<Vec<usize>>>();
    /// assert_eq!(
    ///     layers,
    ///     [
    ///         vec![8, 9],
    ///         vec![0],
    ///         vec![1],
    ///         vec![2, 5, 6],
    ///         vec![3, 7],
    ///         vec![4],
    ///     ]
    /// );
    /// ```
    ///
    /// # Errors
    /// If there is a cycle in the given network, this will return `Err(Cyclic)`.
    ///
    /// # Panics
    /// This will panic if the `ArcStore` is broken.
    pub fn generations(&self) -> Result<Vec<HashSet<&I>>, Cyclic>
    where
        I: Eq + Hash,
    {
        let mut generations: Vec<HashSet<&I>> = vec![];

        let mut indegrees = HashMap::new();
        let mut zero_indegrees = HashSet::new();

        self.nodes.iter_nodes().for_each(|(i, _attributes)| {
            let indegree = self.reverse_arcs(i).count();
            if indegree > 0 {
                indegrees.insert(i, indegree);
            } else {
                zero_indegrees.insert(i);
            }
        });

        while !zero_indegrees.is_empty() {
            let this_generation = std::mem::take(&mut zero_indegrees);
            for node in &this_generation {
                self.forward_arcs(node).for_each(|arc| {
                    let child_indegrees = indegrees
                        .get_mut(arc.head())
                        .expect("Child should be in the indegrees map");
                    *child_indegrees -= 1;

                    if *child_indegrees == 0 {
                        zero_indegrees.insert(arc.head());
                        indegrees.remove(arc.head());
                    }
                });
            }
            generations.push(this_generation);
        }

        if indegrees.is_empty() {
            Ok(generations)
        } else {
            Err(Cyclic)
        }
    }

    /// Return the number of arcs in this network
    pub fn m_arcs(&self) -> usize {
        self.arc_store.m_arcs()
    }

    /// Add an arc to the network.
    ///
    /// # Errors
    /// If the given arc refers to a missing node, an `Err(NoSuchNode)` is returned.
    pub fn add_arc<T: Into<ArcInfo<I, ArcAttr>>>(&mut self, arc: T) -> Result<(), NoSuchNode<I>> {
        let arc = arc.into();

        if !self.contains_node(&arc.tail) {
            Err(NoSuchNode(arc.tail))
        } else if !self.contains_node(&arc.head) {
            Err(NoSuchNode(arc.head))
        } else {
            self.arc_store.add_arc(arc);
            Ok(())
        }
    }

    /// Add multiple arcs to this network
    ///
    /// # Errors
    /// If an arc is encountered which refers to a non-existant node, this will return an
    /// `Err(NoSuchNode)`.
    pub fn add_arcs<T: Into<ArcInfo<I, ArcAttr>>, It: IntoIterator<Item = T>>(
        &mut self,
        iter: It,
    ) -> Result<(), NoSuchNode<I>> {
        for arc in iter {
            self.add_arc(arc)?;
        }
        Ok(())
    }

    /// Remove an arc from the network
    pub fn remove_arc(&mut self, tail: &I, head: &I) -> Option<ArcAttr> {
        self.arc_store.remove_arc(tail, head)
    }

    /// Remove multiple arcs from the network
    pub fn remove_arcs<'a, It>(&'a mut self, iter: It)
    where
        It: IntoIterator<Item = (&'a I, &'a I)>,
    {
        for (tail, head) in iter {
            self.arc_store.remove_arc(tail, head);
        }
    }

    /// Return an iterator of  references to arcs within this network
    pub fn arc_iter<'a>(&'a self) -> impl Iterator<Item = &'a ArcInfo<I, ArcAttr>> + 'a
    where
        ArcAttr: 'a,
        I: 'a,
    {
        self.arc_store.arc_iter()
    }

    /// Return an iterator of mutable references to arcs within this network
    pub fn arc_iter_mut<'a>(&'a mut self) -> impl Iterator<Item = &'a mut ArcInfo<I, ArcAttr>> + 'a
    where
        ArcAttr: 'a,
        I: 'a,
    {
        self.arc_store.arc_iter_mut()
    }

    /// Iterate over arcs originating from the given node.
    pub fn forward_arcs<'a>(
        &'a self,
        node: &'a I,
    ) -> impl Iterator<Item = &'a ArcInfo<I, ArcAttr>> + 'a
    where
        ArcAttr: 'a,
        I: 'a,
    {
        self.arc_store.forward_arcs(node)
    }

    /// Iterate over arcs terminating at the given node.
    pub fn reverse_arcs<'a>(
        &'a self,
        node: &'a I,
    ) -> impl Iterator<Item = &'a ArcInfo<I, ArcAttr>> + 'a
    where
        ArcAttr: 'a,
        I: 'a,
    {
        self.arc_store.reverse_arcs(node)
    }

    /// get a reference to an arc.
    pub fn arc(&self, tail: &I, head: &I) -> Option<&ArcAttr> {
        self.arc_store.arc(tail, head)
    }

    /// Get a mutable refernce to an arc
    pub fn arc_mut(&mut self, tail: &I, head: &I) -> Option<&mut ArcAttr> {
        self.arc_store.arc_mut(tail, head)
    }

    /// Check if an arc exists
    pub fn contains_arc(&self, tail: &I, head: &I) -> bool {
        self.arc_store.contains_arc(tail, head)
    }

    /// Check if there are arcs originating from this node.
    pub fn has_forward_arcs(&self, node: &I) -> bool {
        self.arc_store.has_forward_arcs(node)
    }

    /// Check if there are arcs terminating at this node.
    pub fn has_reverse_arcs(&self, node: &I) -> bool {
        self.arc_store.has_reverse_arcs(node)
    }

    /// Create a `DotWriter` for this network.
    pub fn dot<'a>(&'a self) -> DotWriter<'a, I, NodeAttr, ArcAttr, NodeStore, ArcStore>
    where
        I: Display,
    {
        DotWriter::new(self)
    }
}

/// Dot output writer in a builder-ish pattern.
pub struct DotWriter<'a, I, NodeAttr, ArcAttr, NodeStore, ArcStore>
where
    NodeStore: NodeStorage<I, NodeAttr>,
    ArcStore: ArcStorage<I, ArcAttr>,
    I: Display,
{
    network: &'a Network<I, NodeAttr, ArcAttr, NodeStore, ArcStore>,
    node_attr_label: Box<dyn Fn(&NodeAttr) -> Option<String> + 'a>,
    arc_attr_label: Box<dyn Fn(&ArcAttr) -> Option<String> + 'a>,
}

impl<'a, I, NodeAttr, ArcAttr, NodeStore, ArcStore>
    DotWriter<'a, I, NodeAttr, ArcAttr, NodeStore, ArcStore>
where
    NodeStore: NodeStorage<I, NodeAttr>,
    ArcStore: ArcStorage<I, ArcAttr>,
    I: Display,
{
    /// Create a new `DotWriter`
    fn new(network: &'a Network<I, NodeAttr, ArcAttr, NodeStore, ArcStore>) -> Self {
        Self {
            network,
            node_attr_label: Box::new(|_| None),
            arc_attr_label: Box::new(|_| None),
        }
    }

    /// Replace the current node attribute label function
    pub fn with_node_attr_display<F: Fn(&NodeAttr) -> Option<String> + 'a>(
        self,
        node_attr_label: F,
    ) -> Self {
        Self {
            node_attr_label: Box::new(node_attr_label),
            ..self
        }
    }

    /// Replace the current arc attribute label function
    pub fn with_arc_attr_display<F: Fn(&ArcAttr) -> Option<String> + 'a>(
        self,
        arc_attr_label: F,
    ) -> Self {
        Self {
            arc_attr_label: Box::new(arc_attr_label),
            ..self
        }
    }

    /// Return a String in Graphviz dot format representing the network.
    pub fn to_string(self) -> Result<String, std::fmt::Error> {
        let mut out = String::new();

        writeln!(&mut out, "digraph G {{")?;

        writeln!(&mut out, "    // Nodes")?;
        for (node_id, node_attr) in self.network.iter_nodes() {
            write!(&mut out, "    {node_id}")?;
            if let Some(label) = (self.node_attr_label)(node_attr) {
                writeln!(&mut out, " [label=\"{node_id}\\n({label})\"];")?;
            } else {
                writeln!(&mut out, ";")?;
            }
        }

        out.push_str("\n    // Arcs\n");
        for arc in self.network.arc_iter() {
            write!(&mut out, "    {} -> {}", arc.tail, arc.head,)?;

            if let Some(label) = (self.arc_attr_label)(&arc.attributes) {
                writeln!(&mut out, "[label=\"{label}\"];")?;
            } else {
                writeln!(&mut out, ";")?;
            }
        }

        writeln!(&mut out, "}}")?;
        Ok(out)
    }
}

/// Error value when attempting to reference a node that does not exist in the network.
#[derive(Debug)]
pub struct NoSuchNode<I>(I);

impl<I> Display for NoSuchNode<I>
where
    I: Display,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "No node corresponds to id '{0}'", self.0)
    }
}

impl<I: Display + std::fmt::Debug> std::error::Error for NoSuchNode<I> {}

/// An error for `Network::from_parts`, where the given node and arc stores may have incompatable
/// node ids.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord)]
pub struct IncompatableArcAndNodeStores;

impl Display for IncompatableArcAndNodeStores {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "The provided ArcStore constains nodes not in provided NodeStore"
        )
    }
}

impl std::error::Error for IncompatableArcAndNodeStores {}

/// Temporary structure used to access a network's nodes
pub struct NodeAccessor<'a, I, NodeAttr, ArcAttr, NodeStore, ArcStore>
where
    ArcStore: ArcStorage<I, ArcAttr>,
    NodeStore: NodeStorage<I, NodeAttr>,
{
    network: &'a Network<I, NodeAttr, ArcAttr, NodeStore, ArcStore>,
}

impl<I, NodeAttr, ArcAttr, NodeStore, ArcStore> Index<&I>
    for NodeAccessor<'_, I, NodeAttr, ArcAttr, NodeStore, ArcStore>
where
    ArcStore: ArcStorage<I, ArcAttr>,
    NodeStore: NodeStorage<I, NodeAttr>,
{
    type Output = NodeAttr;

    fn index(&self, index: &I) -> &Self::Output {
        if let Some(value) = self.network.nodes.node(index) {
            return value;
        }
        panic!("Index does not correspond to a node.");
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use crate::{HashMapStorage, Network};

    #[test]
    fn into_and_from_parts() {
        let mut net: Network<usize, char, &str, HashMap<usize, char>, HashMapStorage<usize, &str>> =
            Network::new();
        net.add_nodes([(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f')]);
        net.add_arcs([
            (0, 1, "ab"),
            (1, 2, "bc"),
            (2, 3, "cd"),
            (3, 4, "de"),
            (4, 5, "ef"),
        ])
        .unwrap();

        let expected_network = net.clone();

        let (nodes, arcs): (HashMap<usize, char>, _) = net.into_parts();

        let mut expected_nodes = HashMap::new();
        expected_nodes.insert(0, 'a');
        expected_nodes.insert(1, 'b');
        expected_nodes.insert(2, 'c');
        expected_nodes.insert(3, 'd');
        expected_nodes.insert(4, 'e');
        expected_nodes.insert(5, 'f');

        assert_eq!(nodes, expected_nodes);

        let arcs: HashMap<(usize, usize), &str> = arcs.into();

        let expected_arcs = HashMap::from([
            ((0, 1), "ab"),
            ((1, 2), "bc"),
            ((2, 3), "cd"),
            ((3, 4), "de"),
            ((4, 5), "ef"),
        ]);

        assert_eq!(arcs, expected_arcs);

        // Check from_parts works
        let reconstructed_net = Network::from_parts(nodes, arcs.into()).unwrap();
        assert_eq!(reconstructed_net, expected_network);
    }
}