bounded_graph 0.3.0

A thin newtype wrapper for `petgraph` to assist in the creation of graphs with restrictions on their edges
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
//! Bounded acyclic graph implementation.
//!
//! This module provides [`BoundedAcyclicGraph`], which combines both node capacity
//! constraints (from [`BoundedGraph`]) and cycle prevention (from petgraph's [`Acyclic`]).

use std::fmt::{self, Debug, Formatter};
use std::marker::PhantomData;

#[cfg(feature = "serde-1")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use petgraph::data::{Build, DataMap, DataMapMut};
use petgraph::visit::{
    Data, EdgeCount, EdgeRef, GraphBase, GraphProp, IntoEdges, IntoEdgesDirected, NodeCount,
};
use petgraph::{
    acyclic::Acyclic,
    graph::{DefaultIx, EdgeIndex, IndexType, NodeIndex},
    stable_graph::StableGraph,
    Directed, Direction, EdgeType, Graph,
};

use crate::{BoundedAcyclicGraphError, BoundedGraph, BoundedGraphError, BoundedNode};

/// A bounded graph that also enforces acyclicity (DAG property).
///
/// `BoundedAcyclicGraph` wraps a [`BoundedGraph`] that uses petgraph's [`Acyclic`]
/// wrapper, providing both node capacity constraints and cycle prevention. All edge
/// additions are checked to ensure they don't violate either constraint.
///
/// # Type Parameters
///
/// * `N` - The node weight type, which must implement [`BoundedNode`]
/// * `E` - The edge weight type
/// * `G` - The underlying graph type (defaults to `Graph<N, E, Directed, DefaultIx>`)
///
/// # Examples
///
/// ```
/// use bounded_graph::{BoundedAcyclicDiGraph, FixedEdgeCount};
///
/// let mut dag = BoundedAcyclicDiGraph::<FixedEdgeCount<5>, ()>::new();
/// let n1 = dag.add_node(FixedEdgeCount::empty());
/// let n2 = dag.add_node(FixedEdgeCount::empty());
/// let n3 = dag.add_node(FixedEdgeCount::empty());
///
/// // Create a path: n1 -> n2 -> n3
/// assert!(dag.add_edge(n1, n2, ()).is_ok());
/// assert!(dag.add_edge(n2, n3, ()).is_ok());
///
/// // This would create a cycle, so it fails
/// assert!(dag.add_edge(n3, n1, ()).is_err());
/// ```
#[derive(Clone)]
pub struct BoundedAcyclicGraph<
    N,
    E,
    G: petgraph::visit::Visitable + GraphBase = Graph<N, E, Directed, DefaultIx>,
> {
    pub(crate) inner: BoundedGraph<N, E, Acyclic<G>>,
    pub(crate) _phantom: PhantomData<(N, E)>,
}

impl<N, E, G> Debug for BoundedAcyclicGraph<N, E, G>
where
    G: petgraph::visit::Visitable + GraphBase + Debug,
    G::NodeId: Debug,
    BoundedGraph<N, E, Acyclic<G>>: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("BoundedAcyclicGraph")
            .field("inner", &self.inner)
            .finish()
    }
}

#[cfg(feature = "serde-1")]
impl<N, E, G> Serialize for BoundedAcyclicGraph<N, E, G>
where
    G: petgraph::visit::Visitable + GraphBase + Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        // Serialize the underlying graph (not the Acyclic wrapper)
        self.inner.graph.inner().serialize(serializer)
    }
}

#[cfg(feature = "serde-1")]
impl<'de, N, E, Ix> Deserialize<'de> for BoundedAcyclicGraph<N, E, Graph<N, E, Directed, Ix>>
where
    Ix: IndexType,
    N: BoundedNode<Ix> + Deserialize<'de>,
    E: Clone + Deserialize<'de>,
    Graph<N, E, Directed, Ix>: Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let graph = Graph::<N, E, Directed, Ix>::deserialize(deserializer)?;
        // Use TryFrom to create Acyclic - this validates it's acyclic
        let acyclic = Acyclic::try_from(graph)
            .map_err(|_| serde::de::Error::custom("graph contains a cycle"))?;
        Ok(BoundedAcyclicGraph {
            inner: BoundedGraph {
                graph: acyclic,
                _phantom: PhantomData,
            },
            _phantom: PhantomData,
        })
    }
}

#[cfg(feature = "serde-1")]
impl<'de, N, E, Ix> Deserialize<'de> for BoundedAcyclicGraph<N, E, StableGraph<N, E, Directed, Ix>>
where
    Ix: IndexType,
    N: BoundedNode<Ix> + Deserialize<'de>,
    E: Clone + Deserialize<'de>,
    StableGraph<N, E, Directed, Ix>: Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let graph = StableGraph::<N, E, Directed, Ix>::deserialize(deserializer)?;
        // Use TryFrom to create Acyclic - this validates it's acyclic
        let acyclic = Acyclic::try_from(graph)
            .map_err(|_| serde::de::Error::custom("graph contains a cycle"))?;
        Ok(BoundedAcyclicGraph {
            inner: BoundedGraph {
                graph: acyclic,
                _phantom: PhantomData,
            },
            _phantom: PhantomData,
        })
    }
}

/// A directed bounded acyclic graph using [`Graph`] with default index type.
pub type BoundedAcyclicDiGraph<N, E> = BoundedAcyclicGraph<N, E, Graph<N, E, Directed, DefaultIx>>;

/// A directed bounded acyclic graph using [`StableGraph`] with default index type.
pub type BoundedAcyclicStableDiGraph<N, E> =
    BoundedAcyclicGraph<N, E, StableGraph<N, E, Directed, DefaultIx>>;

impl<N, E, Ty, Ix, G> BoundedAcyclicGraph<N, E, G>
where
    Ty: EdgeType,
    Ix: IndexType,
    N: BoundedNode<Ix>,
    E: Clone,
    G: GraphBase<NodeId = NodeIndex<Ix>, EdgeId = EdgeIndex<Ix>>
        + Data<NodeWeight = N, EdgeWeight = E>
        + GraphProp<EdgeType = Ty>
        + DataMap
        + DataMapMut
        + Build
        + NodeCount
        + EdgeCount
        + petgraph::visit::Visitable
        + petgraph::visit::NodeIndexable,
    for<'a> &'a G: petgraph::visit::IntoNeighborsDirected
        + petgraph::visit::IntoNodeIdentifiers
        + petgraph::visit::IntoEdgesDirected
        + petgraph::visit::IntoEdges
        + GraphBase<NodeId = NodeIndex<Ix>>,
{
    /// Creates a new empty bounded acyclic graph.
    pub fn new() -> Self
    where
        G: Default,
    {
        Self {
            inner: BoundedGraph {
                graph: Acyclic::new(),
                _phantom: PhantomData,
            },
            _phantom: PhantomData,
        }
    }

    /// Checks if an edge can be added between two nodes.
    ///
    /// This checks both:
    /// - Node capacity constraints (via [`BoundedNode::can_add_edge`])
    /// - Acyclicity constraint (would the edge create a cycle?)
    ///
    /// # Arguments
    ///
    /// * `source` - The source node index
    /// * `target` - The target node index
    ///
    /// # Returns
    ///
    /// `true` if both constraints are satisfied, `false` otherwise.
    #[must_use = "checking edge validity is only useful if the result is used"]
    pub fn can_add_edge(&self, source: NodeIndex<Ix>, target: NodeIndex<Ix>) -> bool {
        // Check bounded constraints first
        let (source_weight, target_weight) = match (
            self.inner.graph.node_weight(source),
            self.inner.graph.node_weight(target),
        ) {
            (Some(s), Some(t)) => (s, t),
            _ => return false,
        };

        // Count edges in each direction using inner() to access the underlying graph
        let outgoing_count = self
            .inner
            .graph
            .inner()
            .edges_directed(source, Direction::Outgoing)
            .count();
        let incoming_count = self
            .inner
            .graph
            .inner()
            .edges_directed(target, Direction::Incoming)
            .count();

        let bounded_ok =
            source_weight.can_add_edge(Direction::Outgoing, outgoing_count, target_weight)
                && target_weight.can_add_edge(Direction::Incoming, incoming_count, source_weight);

        // Check acyclic constraint
        let acyclic_ok = self.inner.graph.is_valid_edge(source, target);

        bounded_ok && acyclic_ok
    }

    /// Adds a new node with the given weight to the graph.
    ///
    /// # Returns
    ///
    /// The index of the newly added node.
    #[must_use = "the node index is needed to reference the added node"]
    pub fn add_node(&mut self, node: N) -> NodeIndex<Ix> {
        self.inner.graph.add_node(node)
    }

    /// Adds a new edge from source to target with the given weight.
    ///
    /// This method checks both node capacity constraints and the acyclicity constraint
    /// before adding the edge.
    ///
    /// # Arguments
    ///
    /// * `source` - The source node index
    /// * `target` - The target node index
    /// * `edge` - The edge weight
    ///
    /// # Returns
    ///
    /// * `Ok(EdgeIndex)` - The index of the newly added edge
    /// * `Err(BoundedAcyclicGraphError)` - If the edge cannot be added
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Either node is at capacity ([`BoundedGraphError::EdgeRejected`])
    /// - Either node doesn't exist ([`BoundedGraphError::NodeNotFound`])
    /// - The edge would create a cycle ([`BoundedAcyclicGraphError::Acyclic`])
    #[must_use = "edge addition may fail due to capacity or acyclicity constraints"]
    pub fn add_edge(
        &mut self,
        source: NodeIndex<Ix>,
        target: NodeIndex<Ix>,
        edge: E,
    ) -> Result<EdgeIndex<Ix>, BoundedAcyclicGraphError<Ix>> {
        // First check bounded constraints (capacity)
        // Get node weights - return NodeNotFound if either doesn't exist
        let (source_weight, target_weight) = match (
            self.inner.graph.node_weight(source),
            self.inner.graph.node_weight(target),
        ) {
            (Some(s), Some(t)) => (s, t),
            (None, None) => return Err(BoundedGraphError::not_found(None, None).into()),
            (None, Some(_)) => return Err(BoundedGraphError::not_found(None, Some(target)).into()),
            (Some(_), None) => return Err(BoundedGraphError::not_found(Some(source), None).into()),
        };

        // Count edges in each direction using inner() to access the underlying graph
        let outgoing_count = self
            .inner
            .graph
            .inner()
            .edges_directed(source, Direction::Outgoing)
            .count();
        let incoming_count = self
            .inner
            .graph
            .inner()
            .edges_directed(target, Direction::Incoming)
            .count();

        // Check capacity for both nodes
        let source_has_space =
            source_weight.can_add_edge(Direction::Outgoing, outgoing_count, target_weight);
        let target_has_space =
            target_weight.can_add_edge(Direction::Incoming, incoming_count, source_weight);

        // Check bounded constraints first (early return if capacity issue)
        match (source_has_space, target_has_space) {
            (false, true) => return Err(BoundedGraphError::source_rejected(source, target).into()),
            (true, false) => return Err(BoundedGraphError::target_rejected(source, target).into()),
            (false, false) => return Err(BoundedGraphError::both_rejected(source, target).into()),
            (true, true) => {} // Continue to acyclic check
        }

        // Now check acyclic constraint using try_add_edge
        self.inner
            .graph
            .try_add_edge(source, target, edge)
            .map_err(Into::into)
    }

    /// Updates the edge from source to target with the given weight, or adds it if it doesn't exist.
    ///
    /// If an edge already exists, its weight is updated. Otherwise, this method attempts
    /// to add a new edge, respecting both bounded and acyclic constraints.
    ///
    /// # Returns
    ///
    /// * `Ok(EdgeIndex)` - The index of the updated or newly added edge
    /// * `Err(BoundedAcyclicGraphError)` - If adding a new edge would violate constraints
    #[must_use = "edge update may fail due to capacity or acyclicity constraints"]
    pub fn update_edge(
        &mut self,
        source: NodeIndex<Ix>,
        target: NodeIndex<Ix>,
        weight: E,
    ) -> Result<EdgeIndex<Ix>, BoundedAcyclicGraphError<Ix>> {
        // Check if edge already exists using inner() to access the underlying graph
        let edge_exists = self
            .inner
            .graph
            .inner()
            .edges(source)
            .any(|e| e.target() == target);

        if edge_exists {
            // Edge exists - try_update_edge on Acyclic won't create cycles
            self.inner
                .graph
                .try_update_edge(source, target, weight)
                .map_err(Into::into)
        } else {
            // Edge doesn't exist, use add_edge which checks all constraints
            self.add_edge(source, target, weight)
        }
    }

    /// Returns a reference to the inner [`BoundedGraph`].
    #[must_use]
    pub fn inner(&self) -> &BoundedGraph<N, E, Acyclic<G>> {
        &self.inner
    }

    /// Returns a reference to the underlying petgraph [`Acyclic`] wrapper.
    #[must_use]
    pub fn as_acyclic(&self) -> &Acyclic<G> {
        &self.inner.graph
    }

    /// Get an iterator over the nodes in topological order.
    ///
    /// This iterator yields nodes in an order such that for every edge from node A to node B,
    /// A appears before B in the iteration.
    #[must_use = "iterators are lazy and do nothing unless consumed"]
    pub fn topological_iter(&self) -> impl Iterator<Item = NodeIndex<Ix>> + '_ {
        self.inner.graph.nodes_iter()
    }

    /// Get the topological position of a node.
    ///
    /// The topological position represents the node's position in the topological ordering
    /// maintained by the acyclic graph.
    #[must_use]
    pub fn get_position(
        &self,
        node: NodeIndex<Ix>,
    ) -> Option<petgraph::acyclic::TopologicalPosition> {
        Some(self.inner.graph.get_position(node))
    }

    /// Get the node at a specific topological position.
    #[must_use]
    pub fn at_position(
        &self,
        pos: petgraph::acyclic::TopologicalPosition,
    ) -> Option<NodeIndex<Ix>> {
        self.inner.graph.at_position(pos)
    }

    /// Returns the number of nodes in the graph.
    pub fn node_count(&self) -> usize {
        self.inner.node_count()
    }

    /// Returns the number of edges in the graph.
    pub fn edge_count(&self) -> usize {
        self.inner.edge_count()
    }
}

// Separate impl block for inner_mut() that requires ImmutableEdgeBounds
impl<N, E, Ty, Ix, G> BoundedAcyclicGraph<N, E, G>
where
    Ty: EdgeType,
    Ix: IndexType,
    N: BoundedNode<Ix> + crate::ImmutableEdgeBounds,
    E: Clone,
    G: GraphBase<NodeId = NodeIndex<Ix>, EdgeId = EdgeIndex<Ix>>
        + Data<NodeWeight = N, EdgeWeight = E>
        + GraphProp<EdgeType = Ty>
        + DataMap
        + DataMapMut
        + Build
        + NodeCount
        + EdgeCount
        + petgraph::visit::Visitable
        + petgraph::visit::NodeIndexable,
    for<'a> &'a G: petgraph::visit::IntoNeighborsDirected
        + petgraph::visit::IntoNodeIdentifiers
        + petgraph::visit::IntoEdgesDirected
        + petgraph::visit::IntoEdges
        + GraphBase<NodeId = NodeIndex<Ix>>,
{
    /// Returns a mutable reference to the inner [`BoundedGraph`].
    ///
    /// This method is only available for node types with [`ImmutableEdgeBounds`](crate::ImmutableEdgeBounds)
    /// to prevent mutations that could violate edge bound constraints.
    ///
    /// # Safety
    ///
    /// Direct manipulation of the inner graph can violate the acyclic invariant.
    /// Use with caution.
    pub fn inner_mut(&mut self) -> &mut BoundedGraph<N, E, Acyclic<G>> {
        &mut self.inner
    }
}

// Concrete implementations for remove operations for Graph
impl<N, E, Ix> BoundedAcyclicGraph<N, E, Graph<N, E, Directed, Ix>>
where
    N: BoundedNode,
    Ix: IndexType,
{
    /// Removes an edge from the graph.
    ///
    /// Returns the edge weight if the edge existed, or `None` if it didn't.
    ///
    /// This operation updates the internal topological ordering in O(v) time.
    pub fn remove_edge(&mut self, edge: EdgeIndex<Ix>) -> Option<E> {
        self.inner.graph.remove_edge(edge)
    }

    /// Removes a node from the graph.
    ///
    /// Returns the node weight if the node existed, or `None` if it didn't.
    /// All edges connected to the node are also removed.
    ///
    /// This operation updates the internal topological ordering in O(v) time.
    pub fn remove_node(&mut self, node: NodeIndex<Ix>) -> Option<N> {
        self.inner.graph.remove_node(node)
    }
}

// Concrete implementations for remove operations for StableGraph
impl<N, E, Ix> BoundedAcyclicGraph<N, E, StableGraph<N, E, Directed, Ix>>
where
    N: BoundedNode,
    Ix: IndexType,
{
    /// Removes an edge from the graph.
    ///
    /// Returns the edge weight if the edge existed, or `None` if it didn't.
    ///
    /// This operation updates the internal topological ordering in O(v) time.
    pub fn remove_edge(&mut self, edge: EdgeIndex<Ix>) -> Option<E> {
        self.inner.graph.remove_edge(edge)
    }

    /// Removes a node from the graph.
    ///
    /// Returns the node weight if the node existed, or `None` if it didn't.
    /// All edges connected to the node are also removed.
    ///
    /// This operation updates the internal topological ordering in O(v) time.
    pub fn remove_node(&mut self, node: NodeIndex<Ix>) -> Option<N> {
        self.inner.graph.remove_node(node)
    }
}

impl<N, E, Ty, Ix, G> Default for BoundedAcyclicGraph<N, E, G>
where
    Ty: EdgeType,
    Ix: IndexType,
    N: BoundedNode<Ix>,
    E: Clone,
    G: GraphBase<NodeId = NodeIndex<Ix>, EdgeId = EdgeIndex<Ix>>
        + Data<NodeWeight = N, EdgeWeight = E>
        + GraphProp<EdgeType = Ty>
        + DataMap
        + DataMapMut
        + Build
        + NodeCount
        + EdgeCount
        + petgraph::visit::Visitable
        + petgraph::visit::NodeIndexable
        + Default,
    for<'a> &'a G: petgraph::visit::IntoNeighborsDirected
        + petgraph::visit::IntoNodeIdentifiers
        + petgraph::visit::IntoEdgesDirected
        + petgraph::visit::IntoEdges
        + GraphBase<NodeId = NodeIndex<Ix>>,
{
    fn default() -> Self {
        Self::new()
    }
}

// TryFrom implementation for Graph
impl<N, E, Ix> TryFrom<Graph<N, E, Directed, Ix>>
    for BoundedAcyclicGraph<N, E, Graph<N, E, Directed, Ix>>
where
    Ix: IndexType,
    N: BoundedNode<Ix>,
    E: Clone,
{
    type Error = BoundedAcyclicGraphError<Ix>;

    /// Attempts to create a bounded acyclic graph from an existing petgraph Graph.
    ///
    /// This validates that:
    /// 1. The graph is acyclic (contains no cycles)
    /// 2. All existing edges respect the node capacity constraints
    ///
    /// # Examples
    ///
    /// ```
    /// use petgraph::Graph;
    /// use bounded_graph::{BoundedAcyclicGraph, FixedEdgeCount};
    /// use std::convert::TryFrom;
    ///
    /// let mut pg = Graph::new();
    /// let n1 = pg.add_node(FixedEdgeCount::<3, 3>::empty());
    /// let n2 = pg.add_node(FixedEdgeCount::<3, 3>::empty());
    /// let n3 = pg.add_node(FixedEdgeCount::<3, 3>::empty());
    ///
    /// // Create a DAG: n1 -> n2 -> n3
    /// pg.add_edge(n1, n2, ());
    /// pg.add_edge(n2, n3, ());
    ///
    /// // This succeeds - graph is acyclic and respects bounds
    /// let bounded_dag = BoundedAcyclicGraph::try_from(pg).unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The graph contains a cycle ([`BoundedAcyclicGraphError::Acyclic`])
    /// - Any edge violates node capacity constraints ([`BoundedAcyclicGraphError::Bounded`])
    fn try_from(graph: Graph<N, E, Directed, Ix>) -> Result<Self, Self::Error> {
        // First validate bounded constraints
        for node in graph.node_indices() {
            let node_weight = graph
                .node_weight(node)
                .ok_or_else(|| BoundedGraphError::not_found(Some(node), None))?;

            // Count outgoing edges
            let outgoing_count = graph.edges_directed(node, Direction::Outgoing).count();

            // Count incoming edges
            let incoming_count = graph.edges_directed(node, Direction::Incoming).count();

            // Check outgoing capacity
            for edge in graph.edges_directed(node, Direction::Outgoing) {
                let target = edge.target();
                let target_weight = graph
                    .node_weight(target)
                    .ok_or_else(|| BoundedGraphError::not_found(None, Some(target)))?;

                if !node_weight.can_add_edge(Direction::Outgoing, outgoing_count - 1, target_weight)
                {
                    return Err(BoundedGraphError::source_rejected(node, target).into());
                }
            }

            // Check incoming capacity
            for edge in graph.edges_directed(node, Direction::Incoming) {
                let source = edge.source();
                let source_weight = graph
                    .node_weight(source)
                    .ok_or_else(|| BoundedGraphError::not_found(Some(source), None))?;

                if !node_weight.can_add_edge(Direction::Incoming, incoming_count - 1, source_weight)
                {
                    return Err(BoundedGraphError::target_rejected(source, node).into());
                }
            }
        }

        // Now validate acyclicity - try to convert to Acyclic
        let acyclic = Acyclic::try_from(graph).map_err(|_| {
            // The error from try_from for Acyclic is the graph itself if it has cycles
            // We need to return an appropriate error
            use petgraph::acyclic::AcyclicEdgeError;
            BoundedAcyclicGraphError::Acyclic(AcyclicEdgeError::InvalidEdge)
        })?;

        Ok(BoundedAcyclicGraph {
            inner: crate::BoundedGraph {
                graph: acyclic,
                _phantom: PhantomData,
            },
            _phantom: PhantomData,
        })
    }
}

// TryFrom implementation for StableGraph
impl<N, E, Ix> TryFrom<StableGraph<N, E, Directed, Ix>>
    for BoundedAcyclicGraph<N, E, StableGraph<N, E, Directed, Ix>>
where
    Ix: IndexType,
    N: BoundedNode<Ix>,
    E: Clone,
{
    type Error = BoundedAcyclicGraphError<Ix>;

    /// Attempts to create a bounded acyclic graph from an existing petgraph StableGraph.
    ///
    /// This validates that:
    /// 1. The graph is acyclic (contains no cycles)
    /// 2. All existing edges respect the node capacity constraints
    ///
    /// # Examples
    ///
    /// ```
    /// use petgraph::stable_graph::StableGraph;
    /// use bounded_graph::{BoundedAcyclicGraph, FixedEdgeCount};
    /// use std::convert::TryFrom;
    ///
    /// let mut pg = StableGraph::new();
    /// let n1 = pg.add_node(FixedEdgeCount::<3, 3>::empty());
    /// let n2 = pg.add_node(FixedEdgeCount::<3, 3>::empty());
    ///
    /// // Create a DAG: n1 -> n2
    /// pg.add_edge(n1, n2, ());
    ///
    /// // This succeeds - graph is acyclic and respects bounds
    /// let bounded_dag = BoundedAcyclicGraph::try_from(pg).unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The graph contains a cycle ([`BoundedAcyclicGraphError::Acyclic`])
    /// - Any edge violates node capacity constraints ([`BoundedAcyclicGraphError::Bounded`])
    fn try_from(graph: StableGraph<N, E, Directed, Ix>) -> Result<Self, Self::Error> {
        // First validate bounded constraints
        for node in graph.node_indices() {
            let node_weight = graph
                .node_weight(node)
                .ok_or_else(|| BoundedGraphError::not_found(Some(node), None))?;

            // Count outgoing edges
            let outgoing_count = graph.edges_directed(node, Direction::Outgoing).count();

            // Count incoming edges
            let incoming_count = graph.edges_directed(node, Direction::Incoming).count();

            // Check outgoing capacity
            for edge in graph.edges_directed(node, Direction::Outgoing) {
                let target = edge.target();
                let target_weight = graph
                    .node_weight(target)
                    .ok_or_else(|| BoundedGraphError::not_found(None, Some(target)))?;

                if !node_weight.can_add_edge(Direction::Outgoing, outgoing_count - 1, target_weight)
                {
                    return Err(BoundedGraphError::source_rejected(node, target).into());
                }
            }

            // Check incoming capacity
            for edge in graph.edges_directed(node, Direction::Incoming) {
                let source = edge.source();
                let source_weight = graph
                    .node_weight(source)
                    .ok_or_else(|| BoundedGraphError::not_found(Some(source), None))?;

                if !node_weight.can_add_edge(Direction::Incoming, incoming_count - 1, source_weight)
                {
                    return Err(BoundedGraphError::target_rejected(source, node).into());
                }
            }
        }

        // Now validate acyclicity - try to convert to Acyclic
        let acyclic = Acyclic::try_from(graph).map_err(|_| {
            use petgraph::acyclic::AcyclicEdgeError;
            BoundedAcyclicGraphError::Acyclic(AcyclicEdgeError::InvalidEdge)
        })?;

        Ok(BoundedAcyclicGraph {
            inner: crate::BoundedGraph {
                graph: acyclic,
                _phantom: PhantomData,
            },
            _phantom: PhantomData,
        })
    }
}