|
| 1 | +use std::collections::BTreeSet; |
| 2 | + |
| 3 | +use hugr_core::{ |
| 4 | + IncomingPort, OutgoingPort, |
| 5 | + hugr::views::{ |
| 6 | + SiblingSubgraph, |
| 7 | + sibling_subgraph::{IncomingPorts, InvalidSubgraph, OutgoingPorts}, |
| 8 | + }, |
| 9 | +}; |
| 10 | +use itertools::Itertools; |
| 11 | +use thiserror::Error; |
| 12 | + |
| 13 | +use crate::{CommitId, PatchNode, PersistentHugr, PersistentWire, Resolver, Walker}; |
| 14 | + |
| 15 | +/// A set of pinned nodes and wires between them, along with a fixed input |
| 16 | +/// and output boundary, simmilar to [`SiblingSubgraph`]. |
| 17 | +/// |
| 18 | +/// Unlike [`SiblingSubgraph`], subgraph validity (in particular convexity) is |
| 19 | +/// not checked (and cannot be checked), as the same [`PinnedSubgraph`] may |
| 20 | +/// represent [`SiblingSubgraph`]s in different HUGRs. |
| 21 | +/// |
| 22 | +/// Obtain a valid [`SiblingSubgraph`] for a specific [`PersistentHugr`] by |
| 23 | +/// calling [`PinnedSubgraph::to_sibling_subgraph`]. |
| 24 | +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 25 | +pub struct PinnedSubgraph { |
| 26 | + /// The nodes of the induced subgraph. |
| 27 | + nodes: BTreeSet<PatchNode>, |
| 28 | + /// The input ports of the subgraph. |
| 29 | + /// |
| 30 | + /// Grouped by input parameter. Each port must be unique and belong to a |
| 31 | + /// node in `nodes`. |
| 32 | + inputs: Vec<Vec<(PatchNode, IncomingPort)>>, |
| 33 | + /// The output ports of the subgraph. |
| 34 | + /// |
| 35 | + /// Repeated ports are allowed and correspond to copying the output. Every |
| 36 | + /// port must belong to a node in `nodes`. |
| 37 | + outputs: Vec<(PatchNode, OutgoingPort)>, |
| 38 | + /// The commits that must be selected in the host for the subgraph to be |
| 39 | + /// valid. |
| 40 | + selected_commits: BTreeSet<CommitId>, |
| 41 | +} |
| 42 | + |
| 43 | +impl From<SiblingSubgraph<PatchNode>> for PinnedSubgraph { |
| 44 | + fn from(subgraph: SiblingSubgraph<PatchNode>) -> Self { |
| 45 | + Self { |
| 46 | + inputs: subgraph.incoming_ports().clone(), |
| 47 | + outputs: subgraph.outgoing_ports().clone(), |
| 48 | + nodes: BTreeSet::from_iter(subgraph.nodes().iter().copied()), |
| 49 | + selected_commits: BTreeSet::new(), |
| 50 | + } |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +impl PinnedSubgraph { |
| 55 | + /// Create a new subgraph from a set of pinned nodes and wires. |
| 56 | + /// |
| 57 | + /// All nodes must be pinned and all wires must be complete in the given |
| 58 | + /// `walker`. |
| 59 | + /// |
| 60 | + /// Nodes that are not isolated, i.e. are attached to at least one wire in |
| 61 | + /// `wires` will be added implicitly to the graph and do not need to be |
| 62 | + /// explicitly listed in `nodes`. |
| 63 | + pub fn try_from_pinned<R: Resolver>( |
| 64 | + nodes: impl IntoIterator<Item = PatchNode>, |
| 65 | + wires: impl IntoIterator<Item = PersistentWire>, |
| 66 | + walker: &Walker<R>, |
| 67 | + ) -> Result<Self, InvalidPinnedSubgraph> { |
| 68 | + let mut selected_commits = BTreeSet::new(); |
| 69 | + let host = walker.as_hugr_view(); |
| 70 | + let wires = wires.into_iter().collect_vec(); |
| 71 | + let nodes = nodes.into_iter().collect_vec(); |
| 72 | + |
| 73 | + for w in wires.iter() { |
| 74 | + if !walker.is_complete(w, None) { |
| 75 | + return Err(InvalidPinnedSubgraph::IncompleteWire(w.clone())); |
| 76 | + } |
| 77 | + for id in w.owners() { |
| 78 | + if host.contains_id(id) { |
| 79 | + selected_commits.insert(id); |
| 80 | + } else { |
| 81 | + return Err(InvalidPinnedSubgraph::InvalidCommit(id)); |
| 82 | + } |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + if let Some(&unpinned) = nodes.iter().find(|&&n| !walker.is_pinned(n)) { |
| 87 | + return Err(InvalidPinnedSubgraph::UnpinnedNode(unpinned)); |
| 88 | + } |
| 89 | + |
| 90 | + let (inputs, outputs, all_nodes) = Self::compute_io_ports(nodes, wires, host); |
| 91 | + |
| 92 | + Ok(Self { |
| 93 | + selected_commits, |
| 94 | + nodes: all_nodes, |
| 95 | + inputs, |
| 96 | + outputs, |
| 97 | + }) |
| 98 | + } |
| 99 | + |
| 100 | + /// Create a new subgraph from a set of complete wires in `walker`. |
| 101 | + pub fn try_from_wires<R: Resolver>( |
| 102 | + wires: impl IntoIterator<Item = PersistentWire>, |
| 103 | + walker: &Walker<R>, |
| 104 | + ) -> Result<Self, InvalidPinnedSubgraph> { |
| 105 | + Self::try_from_pinned(std::iter::empty(), wires, walker) |
| 106 | + } |
| 107 | + |
| 108 | + /// Compute the input and output ports for the given pinned nodes and wires. |
| 109 | + /// |
| 110 | + /// Return the input boundary ports, output boundary ports as well as the |
| 111 | + /// set of all nodes in the subgraph. |
| 112 | + pub fn compute_io_ports<R: Resolver>( |
| 113 | + nodes: impl IntoIterator<Item = PatchNode>, |
| 114 | + wires: impl IntoIterator<Item = PersistentWire>, |
| 115 | + host: &PersistentHugr<R>, |
| 116 | + ) -> ( |
| 117 | + IncomingPorts<PatchNode>, |
| 118 | + OutgoingPorts<PatchNode>, |
| 119 | + BTreeSet<PatchNode>, |
| 120 | + ) { |
| 121 | + let mut wire_ports_incoming = BTreeSet::new(); |
| 122 | + let mut wire_ports_outgoing = BTreeSet::new(); |
| 123 | + |
| 124 | + for w in wires { |
| 125 | + wire_ports_incoming.extend(w.all_incoming_ports(host)); |
| 126 | + wire_ports_outgoing.extend(w.single_outgoing_port(host)); |
| 127 | + } |
| 128 | + |
| 129 | + let mut all_nodes = BTreeSet::from_iter(nodes); |
| 130 | + all_nodes.extend(wire_ports_incoming.iter().map(|&(n, _)| n)); |
| 131 | + all_nodes.extend(wire_ports_outgoing.iter().map(|&(n, _)| n)); |
| 132 | + |
| 133 | + // (in/out) boundary: all in/out ports on the nodes of the wire, minus ports |
| 134 | + // that are part of the wires |
| 135 | + let inputs = all_nodes |
| 136 | + .iter() |
| 137 | + .flat_map(|&n| host.input_value_ports(n)) |
| 138 | + .filter(|node_port| !wire_ports_incoming.contains(node_port)) |
| 139 | + .map(|np| vec![np]) |
| 140 | + .collect_vec(); |
| 141 | + let outputs = all_nodes |
| 142 | + .iter() |
| 143 | + .flat_map(|&n| host.output_value_ports(n)) |
| 144 | + .filter(|node_port| !wire_ports_outgoing.contains(node_port)) |
| 145 | + .collect_vec(); |
| 146 | + |
| 147 | + (inputs, outputs, all_nodes) |
| 148 | + } |
| 149 | + |
| 150 | + /// Convert the pinned subgraph to a [`SiblingSubgraph`] for the given |
| 151 | + /// `host`. |
| 152 | + /// |
| 153 | + /// This will fail if any of the required selected commits are not in the |
| 154 | + /// host, if any of the nodes are invalid in the host (e.g. deleted by |
| 155 | + /// another commit in host), or if the subgraph is not convex. |
| 156 | + pub fn to_sibling_subgraph<R>( |
| 157 | + &self, |
| 158 | + host: &PersistentHugr<R>, |
| 159 | + ) -> Result<SiblingSubgraph<PatchNode>, InvalidPinnedSubgraph> { |
| 160 | + if let Some(&unselected) = self |
| 161 | + .selected_commits |
| 162 | + .iter() |
| 163 | + .find(|&&id| !host.contains_id(id)) |
| 164 | + { |
| 165 | + return Err(InvalidPinnedSubgraph::InvalidCommit(unselected)); |
| 166 | + } |
| 167 | + |
| 168 | + if let Some(invalid) = self.nodes.iter().find(|&&n| !host.contains_node(n)) { |
| 169 | + return Err(InvalidPinnedSubgraph::InvalidNode(*invalid)); |
| 170 | + } |
| 171 | + |
| 172 | + Ok(SiblingSubgraph::try_new( |
| 173 | + self.inputs.clone(), |
| 174 | + self.outputs.clone(), |
| 175 | + host, |
| 176 | + )?) |
| 177 | + } |
| 178 | + |
| 179 | + /// Iterate over all the commits required by this pinned subgraph. |
| 180 | + pub fn selected_commits(&self) -> impl Iterator<Item = CommitId> + '_ { |
| 181 | + self.selected_commits.iter().copied() |
| 182 | + } |
| 183 | + |
| 184 | + /// Iterate over all the nodes in this pinned subgraph. |
| 185 | + pub fn nodes(&self) -> impl Iterator<Item = PatchNode> + '_ { |
| 186 | + self.nodes.iter().copied() |
| 187 | + } |
| 188 | + |
| 189 | + /// Returns the computed [`IncomingPorts`] of the subgraph. |
| 190 | + #[must_use] |
| 191 | + pub fn incoming_ports(&self) -> &IncomingPorts<PatchNode> { |
| 192 | + &self.inputs |
| 193 | + } |
| 194 | + |
| 195 | + /// Returns the computed [`OutgoingPorts`] of the subgraph. |
| 196 | + #[must_use] |
| 197 | + pub fn outgoing_ports(&self) -> &OutgoingPorts<PatchNode> { |
| 198 | + &self.outputs |
| 199 | + } |
| 200 | +} |
| 201 | + |
| 202 | +#[derive(Debug, Clone, Error)] |
| 203 | +#[non_exhaustive] |
| 204 | +pub enum InvalidPinnedSubgraph { |
| 205 | + #[error("Invalid subgraph: {0}")] |
| 206 | + InvalidSubgraph(#[from] InvalidSubgraph<PatchNode>), |
| 207 | + #[error("Invalid commit in host: {0}")] |
| 208 | + InvalidCommit(CommitId), |
| 209 | + #[error("Wire is not complete: {0:?}")] |
| 210 | + IncompleteWire(PersistentWire), |
| 211 | + #[error("Node is not pinned: {0}")] |
| 212 | + UnpinnedNode(PatchNode), |
| 213 | + #[error("Invalid node in host: {0}")] |
| 214 | + InvalidNode(PatchNode), |
| 215 | +} |
0 commit comments