Sort the nodes vec so it is in a topological order. This ensures that no node takes an input from a node that is found later in the list.
(&mut self)
| 503 | |
| 504 | /// Sort the nodes vec so it is in a topological order. This ensures that no node takes an input from a node that is found later in the list. |
| 505 | fn reorder_ids(&mut self) -> Result<(), String> { |
| 506 | let (order, _id_map) = self.topological_sort()?; |
| 507 | |
| 508 | // // Map of node ids to their current index in the nodes vector |
| 509 | // let current_positions: FxHashMap<_, _> = self.nodes.iter().enumerate().map(|(pos, (id, _))| (*id, pos)).collect(); |
| 510 | |
| 511 | // // Map of node ids to their new index based on topological order |
| 512 | let new_positions: FxHashMap<_, _> = order.iter().enumerate().map(|(pos, id)| (self.nodes[id.0 as usize].0, pos)).collect(); |
| 513 | // assert_eq!(id_map, current_positions); |
| 514 | |
| 515 | // Create a new nodes vector based on the topological order |
| 516 | |
| 517 | let mut new_nodes = Vec::with_capacity(order.len()); |
| 518 | for (index, &id) in order.iter().enumerate() { |
| 519 | let mut node = std::mem::take(&mut self.nodes[id.0 as usize].1); |
| 520 | // Update node references to reflect the new order |
| 521 | node.map_ids(|id| NodeId(*new_positions.get(&id).expect("node not found in lookup table") as u64)); |
| 522 | new_nodes.push((NodeId(index as u64), node)); |
| 523 | } |
| 524 | |
| 525 | // Update node references to reflect the new order |
| 526 | // new_nodes.iter_mut().for_each(|(_, node)| { |
| 527 | // node.map_ids(|id| *new_positions.get(&id).expect("node not found in lookup table"), false); |
| 528 | // }); |
| 529 | |
| 530 | // Update the nodes vector and other references |
| 531 | self.nodes = new_nodes; |
| 532 | self.inputs = self.inputs.iter().filter_map(|id| new_positions.get(id).map(|x| NodeId(*x as u64))).collect(); |
| 533 | self.output = NodeId(*new_positions.get(&self.output).unwrap() as u64); |
| 534 | |
| 535 | assert_eq!(order.len(), self.nodes.len()); |
| 536 | Ok(()) |
| 537 | } |
| 538 | } |
| 539 | #[derive(Clone, PartialEq, serde::Serialize, serde::Deserialize)] |
| 540 | pub enum GraphErrorType { |