SILICON
Loading...
Searching...
No Matches
circuit.cpp
Go to the documentation of this file.
1/*
2 Copyright (c) 2026. Giulio Cocconi
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#include "circuit.hpp"
19
20#include <algorithm>
21#include <cstdint>
22#include <format>
23#include <ranges>
24#include <stdexcept>
25#include <unordered_set>
26
28#include <core/component.hpp>
29#include <core/io.hpp>
31#include <core/subcircuit.hpp>
33
34#include <logging/logger.hpp>
35
36#include <boost/dynamic_bitset.hpp>
37#include <boost/graph/strong_components.hpp>
38#include <boost/graph/topological_sort.hpp>
39
40#include <nlohmann/json.hpp>
41
42namespace SILICON::core {
43
44namespace {
45
46 std::vector<uint64_t> readPortIds(const nlohmann::json& component,
47 std::string_view field)
48 {
49 const auto it = component.find(field);
50 if (it == component.end())
51 return {};
52 if (!it->is_array())
53 throw std::runtime_error("Port identities must be an array");
54 std::vector<uint64_t> ids;
55 for (const auto& value : *it)
56 ids.push_back(deserializePortId(value));
57 return ids;
58 }
59
60 const SILICON::logging::Logger circuitLog("circuit");
61
62 using CircuitVertexSet = boost::dynamic_bitset<>;
63
64 [[nodiscard]] bool markVisited(CircuitVertexSet& visited, const VertexDescriptor vertex)
65 {
66 const auto index = static_cast<std::size_t>(vertex);
67 if (index >= visited.size())
68 throw std::logic_error(
69 "Circuit vertex index exceeds the reachability set size");
70 if (visited.test(index))
71 return false;
72
73 visited.set(index);
74 return true;
75 }
76
77 [[nodiscard]] std::string interfacePortName(const PortRole role,
78 const std::size_t index)
79 {
80 return std::format("{}_{}", role == PortRole::Input ? "input" : "output", index);
81 }
82
83 [[nodiscard]] std::vector<CircuitPort> boundaryPorts(const CircuitGraph& graph,
84 const PortRole role)
85 {
86 std::vector<CircuitPort> ports;
87 std::unordered_set<uint64_t> identities;
88 for (const auto vertex : boost::make_iterator_range(boost::vertices(graph))) {
89 const auto& component = graph[vertex].component;
90 if (!component || component->metadata().portRole != role)
91 continue;
92
93 const auto& buses =
94 role == PortRole::Input ? component->outputBuses() : component->inputBuses();
95 const auto boundary = std::dynamic_pointer_cast<BoundaryIoComponent>(component);
96 const auto identity = boundary ? boundary->portId() : 0;
97 for (const auto& bus : buses) {
98 if (identity != 0 && !identities.insert(identity).second)
99 throw std::runtime_error(
100 std::format("Duplicate boundary port identity: {}", identity));
101 ports.push_back(
102 {.name = component->getPropertyValue<std::string>("name").value_or(
103 interfacePortName(role, ports.size())),
104 .bus = bus,
105 .boundaryVertex = vertex,
106 .id = identity});
107 }
108 }
109 return ports;
110 }
111} // namespace
112
114{
115 if (vertexId >= boost::num_vertices(graph))
116 return nullptr;
117 return graph[vertexId].component;
118}
119
120// --- Internal Helpers ------------------------------------------------------------------
121
123{
124 if (!component)
125 return {};
126
127 const Component* key = component.get();
128
129 if (auto it = componentToVertex.find(key); it != componentToVertex.end()) {
130 return it->second;
131 }
132
133 const VertexDescriptor v = boost::add_vertex(VertexProperty{component}, graph);
134 componentToVertex.emplace(key, v);
135
136 return v;
137}
138
140{
141 const auto cPtr = graph[v].component;
142 if (!cPtr)
143 return;
144
145 const auto& outputs = cPtr->outputBuses();
146
147 // 1. subrange allows us to use range-based for loops with Boost.Graph
148 for (auto target_v : boost::make_iterator_range(boost::vertices(graph))) {
149 if (target_v == v)
150 continue;
151
152 const auto neighbor = graph[target_v].component;
153 if (!neighbor)
154 continue;
155
156 for (const Bus& outBus : outputs) {
157 const bool sharesWire =
158 std::ranges::any_of(neighbor->inputBuses(), [&](const Bus& inBus) {
159 return outBus.sharesWireWith(inBus);
160 });
161
162 if (sharesWire) {
163 auto out_edges = boost::make_iterator_range(boost::out_edges(v, graph));
164
165 const bool isDuplicate = std::ranges::any_of(out_edges, [&](const auto& edge) {
166 return boost::target(edge, graph) == target_v && graph[edge].bus == outBus;
167 });
168
169 if (!isDuplicate) {
170 boost::add_edge(v, target_v, EdgeProperty{outBus}, graph);
171 }
172 }
173 }
174 }
175}
176
177std::pair<std::vector<Bus>, std::vector<Bus>> Circuit::getComponentIOs() const
178{
179 std::vector<Bus> inputs = {};
180 std::vector<Bus> outputs = {};
181
182 for (auto v : boost::make_iterator_range(boost::vertices(graph))) {
183 auto cPtr = graph[v].component;
184 if (!cPtr)
185 continue;
186
187 for (const Bus& bus : cPtr->inputBuses())
188 inputs.push_back(bus);
189
190 for (const Bus& bus : cPtr->outputBuses())
191 outputs.push_back(bus);
192 }
193
194 std::ranges::sort(inputs);
195 inputs.erase(std::ranges::unique(inputs).begin(), inputs.end());
196
197 std::ranges::sort(outputs);
198 outputs.erase(std::ranges::unique(outputs).begin(), outputs.end());
199
200 return {std::move(inputs), std::move(outputs)};
201}
202
203// --- Topology Map ----------------------------------------------------------------------
204
206{
207 wireListeners.clear();
208
209 for (auto v : boost::make_iterator_range(boost::vertices(graph))) {
210 const auto comp = graph[v].component;
211 if (!comp)
212 continue;
213
214 auto valid_wires =
215 comp->inputBuses() | std::views::join
216 | std::views::filter([](const auto& wire) { return static_cast<bool>(wire); });
217
218 for (const auto& wire : valid_wires) {
219 wireListeners[wire->getId()].push_back(comp);
220 }
221 }
222}
223std::vector<Component_weakPtr> Circuit::getListenersForWire(uint64_t wireId) const
224{
225 auto it = wireListeners.find(wireId);
226
227 if (it == wireListeners.end())
228 return {};
229
230 std::vector<Component_weakPtr> result;
231 result.reserve(it->second.size());
232
233 for (const auto& ptr : it->second) {
234 result.push_back(ptr);
235 }
236
237 return result;
238}
239
240// --- Constructors ----------------------------------------------------------------------
241
242Circuit::Circuit(const Component_set& components, bool explore)
243 : Circuit(std::vector<Component_ptr>(components.begin(), components.end()), explore)
244{
245}
246
247Circuit::Circuit(const std::vector<Component_ptr>& components, bool explore)
248{
249 if (!explore) {
250 for (const auto& c : components)
252
253 for (auto v : boost::make_iterator_range(boost::vertices(graph)))
254 rebuildEdges(v);
255 }
256
257 else {
258 for (const auto& c : components)
259 addComponent(c);
260 }
261
263}
264
265Circuit::Circuit(const Component_ptr& component, const bool explore)
266{
267 if (!explore) {
268 getOrAddVertex(component);
269 } else {
270 addComponent(component);
271 }
272
274}
275
276// --- Public methods --------------------------------------------------------------------
277
279 std::vector<VertexDescriptor>& newlyAdded)
280{
281 // Already present or null = early return
282 if (!component.get() || componentToVertex.contains(component.get()))
283 return;
284
285 const VertexDescriptor v = getOrAddVertex(component);
286 newlyAdded.push_back(v);
287
288 // Recursively explore neighbors through shared buses
289 for (const Bus& bus : component->allBuses())
290 for (const auto& c : getComponentsForBus(bus))
291 addComponentRecursive(c, newlyAdded);
292}
293
295{
296 std::vector<VertexDescriptor> newlyAdded;
297 addComponentRecursive(component, newlyAdded);
298
299 // Rebuild edges for every vertex (including newly added ones).
300 // This is safe because addComponent guards against re-entry via the map check.
301 for (VertexDescriptor v : newlyAdded)
302 rebuildEdges(v);
303
305}
306
308{
309 if (!component)
310 return;
311
312 auto it = componentToVertex.find(component.get());
313 if (it == componentToVertex.end())
314 return;
315
316 VertexDescriptor v = it->second;
317
318 boost::clear_vertex(v, graph);
319 boost::remove_vertex(v, graph);
320
321 componentToVertex.clear();
322
323 for (auto vd : boost::make_iterator_range(vertices(graph))) {
324 componentToVertex[graph[vd].component.get()] = vd;
325 }
326
328}
329
330std::optional<VertexDescriptor> Circuit::getVertexId(const Component* component) const
331{
332 if (!component)
333 return std::nullopt;
334
335 if (auto it = componentToVertex.find(component); it != componentToVertex.end())
336 return it->second;
337
338 return std::nullopt;
339}
340
341std::vector<Bus> Circuit::getInputs() const
342{
343 auto ports = getInputPorts();
344 return ports | std::views::transform(&CircuitPort::bus)
345 | std::ranges::to<std::vector>();
346}
347
348std::vector<CircuitPort> Circuit::getInputPorts() const
349{
351}
352
353std::vector<CircuitPort> Circuit::interfacePorts(const PortRole role) const
354{
355 auto ports = boundaryPorts(graph, role);
356 if (!ports.empty())
357 return ports;
358
359 auto [inputBuses, outputBuses] = getComponentIOs();
360
361 std::ranges::sort(inputBuses);
362 std::ranges::sort(outputBuses);
363
364 std::vector<Bus> result;
365
366 if (role == PortRole::Input)
367 std::ranges::set_difference(inputBuses, outputBuses, std::back_inserter(result));
368 else
369 std::ranges::set_difference(outputBuses, inputBuses, std::back_inserter(result));
370
371 std::vector<CircuitPort> fallback;
372 fallback.reserve(result.size());
373 for (std::size_t index = 0; index < result.size(); ++index)
374 fallback.push_back({.name = interfacePortName(role, index), .bus = result[index]});
375 return fallback;
376}
377
378std::vector<Bus> Circuit::getOutputs() const
379{
380 auto ports = getOutputPorts();
381 return ports | std::views::transform(&CircuitPort::bus)
382 | std::ranges::to<std::vector>();
383}
384
385std::vector<CircuitPort> Circuit::getOutputPorts() const
386{
388}
389
391{
392 Component_set connectedComponents;
393
394 // Gather components that are listening to these wires
395 for (const auto& wire : b) {
396 if (!wire)
397 continue;
398
399 for (const auto& weakComp : getListenersForWire(wire->getId())) {
400 if (auto comp = weakComp.lock()) {
401 connectedComponents.insert(comp);
402 }
403 }
404 }
405
406 // Gather components that output to these wires
407 for (auto v : boost::make_iterator_range(boost::vertices(graph))) {
408 const auto cPtr = graph[v].component;
409 if (!cPtr)
410 continue;
411
412 const bool matches = std::ranges::any_of(
413 cPtr->outputBuses(), [&](const Bus& outBus) { return b.sharesWireWith(outBus); });
414
415 if (matches) {
416 connectedComponents.insert(cPtr); // Re-use cPtr, no double lookup!
417 }
418 }
419
420 return connectedComponents;
421}
422
423std::vector<CircuitConnection> Circuit::getConnections() const
424{
425 std::vector<CircuitConnection> connections;
426 connections.reserve(boost::num_edges(graph));
427
428 for (const auto edge : boost::make_iterator_range(boost::edges(graph))) {
429 const auto sourceVertex = boost::source(edge, graph);
430 const auto targetVertex = boost::target(edge, graph);
431 const auto sourceComponent = graph[sourceVertex].component;
432 const auto targetComponent = graph[targetVertex].component;
433 if (!sourceComponent || !targetComponent)
434 continue;
435
436 const Bus& bus = graph[edge].bus;
437 const auto& outputs = sourceComponent->outputBuses();
438 for (std::size_t sourceBusIndex = 0; sourceBusIndex < outputs.size();
439 ++sourceBusIndex) {
440 if (outputs[sourceBusIndex] != bus)
441 continue;
442
443 const auto& inputs = targetComponent->inputBuses();
444 for (std::size_t targetBusIndex = 0; targetBusIndex < inputs.size();
445 ++targetBusIndex) {
446 if (!bus.sharesWireWith(inputs[targetBusIndex]))
447 continue;
448
449 connections.push_back(
450 CircuitConnection{.source = sourceComponent,
451 .target = targetComponent,
452 .sourceBusIndex = static_cast<unsigned int>(sourceBusIndex),
453 .targetBusIndex = static_cast<unsigned int>(targetBusIndex),
454 .bus = bus});
455 }
456 }
457 }
458
459 return connections;
460}
461
462// --- Wire Reactivity & Cone Subgraphs --------------------------------------------------
463
464Circuit Circuit::getBackwardsSubgraph(const Bus& targetOutput) const
465{
466 Component_set coiComponents;
467 std::vector<VertexDescriptor> stack;
468 CircuitVertexSet visited(boost::num_vertices(graph));
469
470 auto valid_target_wires = targetOutput | std::views::filter([](const auto& w) {
471 return static_cast<bool>(w);
472 });
473
474 // Find starting vertices
475 for (auto v : boost::make_iterator_range(boost::vertices(graph))) {
476 const auto cPtr = graph[v].component;
477 if (!cPtr)
478 continue;
479
480 // Flatten all output buses into a single stream of wires
481 auto out_wires = cPtr->outputBuses() | std::views::join;
482
483 // Check if this component drives ANY of our valid target wires
484 const bool drivesWire =
485 std::ranges::any_of(valid_target_wires, [&](const auto& wire) {
486 return std::ranges::contains(out_wires, wire); // C++23
487 });
488
489 if (drivesWire && markVisited(visited, v)) {
490 stack.push_back(v);
491 }
492 }
493
494 // DFS backwards traversal
495 while (!stack.empty()) {
496 const VertexDescriptor v = stack.back();
497 stack.pop_back();
498
499 if (const auto comp = graph[v].component) {
500 coiComponents.insert(comp);
501 }
502
503 for (auto edge : boost::make_iterator_range(boost::in_edges(v, graph))) {
504 VertexDescriptor sourceVertex = boost::source(edge, graph);
505 if (markVisited(visited, sourceVertex)) {
506 stack.push_back(sourceVertex);
507 }
508 }
509 }
510
511 return Circuit(coiComponents, false);
512}
513
514Circuit Circuit::getForwardSubgraph(const Bus& sourceInput) const
515{
516 Component_set focComponents;
517 std::vector<VertexDescriptor> stack;
518 CircuitVertexSet visited(boost::num_vertices(graph));
519
520 auto valid_source_wires = sourceInput | std::views::filter([](const auto& w) {
521 return static_cast<bool>(w);
522 });
523
524 for (const auto& wire : valid_source_wires) {
525 for (const auto& weakComp : getListenersForWire(wire->getId())) {
526 if (auto cPtr = weakComp.lock()) {
527 auto it = componentToVertex.find(cPtr.get());
528
529 if (it != componentToVertex.end() && markVisited(visited, it->second)) {
530 stack.push_back(it->second);
531 }
532 }
533 }
534 }
535
536 while (!stack.empty()) {
537 const VertexDescriptor v = stack.back();
538 stack.pop_back();
539
540 if (const auto comp = graph[v].component) {
541 focComponents.insert(comp);
542 }
543
544 for (auto edge : boost::make_iterator_range(boost::out_edges(v, graph))) {
545 VertexDescriptor targetVertex = boost::target(edge, graph);
546 if (markVisited(visited, targetVertex)) {
547 stack.push_back(targetVertex);
548 }
549 }
550 }
551
552 return Circuit(focComponents, false);
553}
554
555// --- Execution Blocks -----------------------------------------------------------------
556
557std::vector<Circuit::SimulationBlock> Circuit::splitCyclic() const
558{
559 circuitLog.debug("Splitting the circuit in cyclic and acyclic blocks...");
560 const auto n = boost::num_vertices(graph);
561
562 // Early exit: Avoids allocating maps and vectors if there's nothing to process.
563 if (n == 0)
564 return {};
565
566 // --- STEP 1: Identify Strongly Connected Components (SCCs) --------------------------
567 // An SCC is a subgraph where every vertex can reach every other vertex. An SCC of size
568 // > 1 represents a feedback loop (cycle). BGL guarantees topological order.
569
570 std::vector<int> componentMap(n);
571 const auto vertexIndexMap = boost::get(boost::vertex_index, graph);
572
573 const int numSccs = boost::strong_components(
574 graph, boost::make_iterator_property_map(componentMap.begin(), vertexIndexMap));
575
576 // --- STEP 2: Group vertices by their SCC ID ------------------------------------------
577 std::vector<std::vector<VertexDescriptor>> sccVertices(numSccs);
578 auto [v_begin, v_end] = boost::vertices(graph);
579
580 for (const auto v : std::ranges::subrange(v_begin, v_end)) {
581 const auto scc_id = componentMap[boost::get(vertexIndexMap, v)];
582 sccVertices[scc_id].push_back(v);
583 }
584
585 // This vector acts as an accumulator for adjacent acyclic (DAG) components.
586 // We want to combine adjacent DAG segments into a single SimulationBlock to minimize
587 // execution overhead.
588
589 std::vector<SimulationBlock> blocks;
590 std::vector<Component_weakPtr> currentDagComps;
591
592 // Helper: finalize and store the accumulated DAG
593 auto flushDag = [&]() {
594 if (!currentDagComps.empty()) {
595 Component_set comps(currentDagComps.begin(), currentDagComps.end());
596 auto execOrder = std::move(currentDagComps);
597 blocks.emplace_back(false, Circuit(comps, false), std::move(execOrder));
598 }
599 };
600
601 // --- STEP 3: Topologically traverse and build SimulationBlocks -----------------------
602 // We iterate backwards (numSccs - 1 down to 0) because BGL's component IDs represent a
603 // reversed topological sort. High IDs are "upstream" dependencies.
604
605 for (int i = numSccs - 1; i >= 0; --i) {
606 const auto& verts = sccVertices[i];
607 bool isCyclic = verts.size() > 1;
608
609 if (verts.size() == 1) {
610 auto [e_begin, e_end] = boost::out_edges(verts.front(), graph);
611 isCyclic =
612 std::ranges::any_of(std::ranges::subrange(e_begin, e_end), [&](const auto& e) {
613 return boost::target(e, graph) == verts.front();
614 });
615 }
616
617 auto validComps =
618 verts | std::views::transform([this](auto v) { return graph[v].component; })
619 | std::views::filter([](const auto& comp) { return comp != nullptr; });
620
621 if (isCyclic) {
622 // A cycle interrupts standard execution flow. We must flush any pending
623 // DAG components so they execute *before* this cycle block.
624
625 flushDag();
626 auto cyclicComps = validComps | std::ranges::to<Component_set>();
627
628 if (!cyclicComps.empty()) {
629 blocks.emplace_back(true, Circuit(cyclicComps, false),
630 std::vector<Component_weakPtr>{});
631 }
632 } else {
633 for (const auto& comp : validComps)
634 currentDagComps.push_back(comp);
635 }
636 }
637
638 // Finalize the final DAG tail (that's present if the circuit ends with a DAG block)
639 flushDag();
640 circuitLog.debug(std::format("Found {} blocks!", blocks.size()));
641 return blocks;
642}
643
644std::vector<VertexDescriptor> Circuit::topologicalOrder() const
645{
646 std::vector<VertexDescriptor> order;
647 order.reserve(boost::num_vertices(graph));
648
649 circuitLog.debug("Topologically sorting the circuit...");
650 boost::topological_sort(graph, std::back_inserter(order));
651
652 // Boost's topological_sort produces reverse order, so we need to reverse it.
653 std::ranges::reverse(order);
654
655 return order;
656}
657
659{
660 LevelMap levelMap;
661
662 // Because vertex descriptors are integers 0 to N-1, a flat vector is the fastest way to
663 // cache levels.
664 std::vector<unsigned int> vertexLevels(boost::num_vertices(graph), 0);
665
666 for (const VertexDescriptor v : topologicalOrder()) {
667 unsigned int maxLevel = 0;
668
669 // 1. Calculate the level based on predecessors
670 for (const auto& edge : boost::make_iterator_range(boost::in_edges(v, graph))) {
671 const VertexDescriptor pred = boost::source(edge, graph);
672
673 // the topological sort guarantees that the pred level has already been processed
674 const auto predLevel = vertexLevels[pred];
675 maxLevel = std::max(maxLevel, predLevel + 1);
676 }
677
678 // Cache this vertex's level
679 vertexLevels[v] = maxLevel;
680
681 // 2. Map the calculated level back to the actual Component
682 const Component_weakPtr compWeak = graph[v].component;
683
684 if (compWeak.lock()) {
685 levelMap[compWeak] = maxLevel;
686 }
687 }
688
689 return levelMap;
690}
691
692// --- Serialization ---------------------------------------------------------------------
693
694std::string Circuit::serialize() const
695{
696 nlohmann::ordered_json j = {{"version", SILICON_VERSION},
697 {"components", nlohmann::ordered_json::array()}};
698
699 auto serializeBusList = [](const std::vector<Bus>& buses) -> nlohmann::ordered_json {
700 nlohmann::ordered_json busArray = nlohmann::ordered_json::array();
701 for (const Bus& bus : buses) {
702 nlohmann::ordered_json wireArray = nlohmann::ordered_json::array();
703 for (const auto& wire : bus) {
704 wireArray.push_back(wire ? nlohmann::ordered_json(wire->getId())
705 : nlohmann::ordered_json(nullptr));
706 }
707 busArray.push_back(std::move(wireArray));
708 }
709 return busArray;
710 };
711
712 for (auto [vi, vi_end] = boost::vertices(graph);
713 auto v : std::ranges::subrange(vi, vi_end)) {
714 if (auto cPtr = graph[v].component) {
715 nlohmann::ordered_json propsJson = nlohmann::ordered_json::object();
716 for (const auto& [key, val] : cPtr->getProperties()) {
717 std::visit(
718 [&](const auto& arg) {
719 using Value = std::remove_cvref_t<decltype(arg)>;
720 if constexpr (std::same_as<Value, BusValue>)
721 propsJson[key] = formatValue(arg, BusValueFormat::Raw);
722 else
723 propsJson[key] = arg;
724 },
725 val);
726 }
727
728 j["components"].push_back(
729 nlohmann::ordered_json{{"id", v},
730 {"type", cPtr->typeName()},
731 {"properties", propsJson},
732 {"inputs", serializeBusList(cPtr->getInputs())},
733 {"outputs", serializeBusList(cPtr->getOutputs())}});
734 auto& serialized = j["components"].back();
735 if (const auto boundary = std::dynamic_pointer_cast<BoundaryIoComponent>(cPtr))
736 serialized["portId"] = boundary->portId();
737 if (const auto instance = std::dynamic_pointer_cast<SubcircuitComponent>(cPtr)) {
738 if (!instance->inputPortIds().empty())
739 serialized["inputPortIds"] = instance->inputPortIds();
740 if (!instance->outputPortIds().empty())
741 serialized["outputPortIds"] = instance->outputPortIds();
742 }
743 }
744 }
745
746 return j.dump(2);
747}
748
749Circuit Circuit::deserialize(const std::string& jsonStr, const ComponentRegistry& reg,
750 const CircuitResolver* resolver)
751{
752 const auto j = nlohmann::json::parse(jsonStr);
753
754 std::unordered_map<uint64_t, Wire_ptr> wireMap;
755
756 const auto deserializeBusList = [&wireMap](const nlohmann::json& busListJson) {
757 std::vector<Bus> buses;
758 buses.reserve(busListJson.size());
759
760 for (const auto& busJson : busListJson) {
761 std::vector<Wire_ptr> wires;
762 wires.reserve(busJson.size());
763
764 for (const auto& wireJson : busJson) {
765 if (wireJson.is_null()) {
766 wires.push_back(nullptr);
767 continue;
768 }
769
770 const auto id = wireJson.get<uint64_t>();
771 auto& wire = wireMap[id];
772
773 if (!wire)
774 wire = std::make_shared<Wire>(id, State::UNKNOWN);
775
776 wires.push_back(wire);
777 }
778
779 buses.emplace_back(std::move(wires));
780 }
781
782 return buses;
783 };
784
785 const auto applyProperty = [](const Component_ptr& component, const std::string& key,
786 const nlohmann::json& value, bool busValue) {
787 const auto current = component->getProperty(key);
788 if (!current || std::holds_alternative<BusValue>(*current) != busValue)
789 return;
790
791 if (busValue) {
792 if (!value.is_string())
793 throw std::runtime_error(
794 std::format("BusValue property '{}' must be a string", key));
795
796 component->setProperty(key, busValueFromBits(value.get_ref<const std::string&>()));
797 return;
798 }
799
800 if (value.is_string())
801 component->setProperty(key, value.get<std::string>());
802 else if (value.is_boolean())
803 component->setProperty(key, value.get<bool>());
804 else if (value.is_number_integer())
805 component->setProperty(key, value.get<int>());
806 };
807
808 std::vector<std::pair<int, Component_ptr>> parsedComponents;
809
810 if (const auto it = j.find("components"); it != j.end() && it->is_array()) {
811 parsedComponents.reserve(it->size());
812
813 for (const auto& compJson : *it) {
814 const auto typeIt = compJson.find("type");
815 if (typeIt == compJson.end())
816 continue;
817
818 const auto type = typeIt->get<std::string>();
819 auto component = reg.create(type);
820
821 if (auto subcircuit = std::dynamic_pointer_cast<SubcircuitComponent>(component))
822 subcircuit->setCircuitResolver(resolver);
823
824 if (!component) {
825 throw std::runtime_error(
826 std::format("Failed to create unknown component type: {}", type));
827 }
828
829 if (const auto boundary =
830 std::dynamic_pointer_cast<BoundaryIoComponent>(component)) {
831 // Old documents resolve repeatedly before their first save. Give them a
832 // deterministic identity, then persist it independently of vertex renumbering.
833 boundary->setPortId(deserializeBoundaryPortId(compJson));
834 }
835
836 if (const auto propsIt = compJson.find("properties");
837 propsIt != compJson.end() && propsIt->is_object()) {
838 // Width and other scalar properties must settle before value normalization.
839 for (const auto& [key, value] : propsIt->items())
840 applyProperty(component, key, value, false);
841
842 for (const auto& [key, value] : propsIt->items())
843 applyProperty(component, key, value, true);
844 }
845
846 const auto deserializeInterface = [&](std::string_view name,
847 const std::vector<Bus>& current) {
848 const auto it = compJson.find(name);
849 if (it == compJson.end() || !it->is_array())
850 return current;
851
852 return deserializeBusList(*it);
853 };
854
855 auto savedInputs = deserializeInterface("inputs", component->getInputs());
856 auto savedOutputs = deserializeInterface("outputs", component->getOutputs());
857 if (const auto instance =
858 std::dynamic_pointer_cast<SubcircuitComponent>(component)) {
859 instance->restoreConnections(savedInputs, savedOutputs,
860 readPortIds(compJson, "inputPortIds"),
861 readPortIds(compJson, "outputPortIds"));
862 } else {
863 component->setInputs(savedInputs);
864 component->setOutputs(savedOutputs);
865 }
866
867 /* --- CRITICAL ORDERING STEP ------------------------------------------------------
868 * Boost.Graph (using boost::vecS) assigns VertexDescriptors strictly as sequential
869 * integers (0, 1, 2...) based on the order vertices are added.
870 * Visual components in the JSON rely on these exact VertexDescriptors ('vertexId')
871 * to link back to the correct underlying logic component.
872 * We must sort the components by their serialized 'id' before inserting them into
873 * the graph so that Boost reassigns them the exact same IDs they had when saved.
874 */
875
876 // Extract the serialized ID so we know what VertexDescriptor this component
877 // originally had
878 const auto id = compJson.at("id").get<int>();
879 parsedComponents.emplace_back(id, std::move(component));
880 }
881 }
882
883 std::ranges::sort(parsedComponents, [](const auto& lhs, const auto& rhs) {
884 return lhs.first < rhs.first;
885 });
886
887 Circuit result;
888 result.ownedComponents.reserve(parsedComponents.size());
889
890 // Insert components in strict serialized order
891 for (auto& [id, component] : parsedComponents) {
892 result.getOrAddVertex(component); // Boost assigns ID: 0, then 1, then 2...
893 result.ownedComponents.push_back(std::move(component));
894 }
895
896 // Rebuild the edges for the correctly-aligned vertices
897 for (const auto vertex : boost::make_iterator_range(boost::vertices(result.graph))) {
898 result.rebuildEdges(vertex);
899 }
900
901 result.ownedWires = wireMap | std::views::values | std::ranges::to<std::vector>();
902
903 result.buildTopologyMap();
904 return result;
905}
906
907} // namespace SILICON::core
bool sharesWireWith(const Bus &other) const
Definition wire.cpp:552
VertexDescriptor getOrAddVertex(const Component_ptr &component)
Gets or adds a vertex for a component.
Definition circuit.cpp:122
static Circuit deserialize(const std::string &jsonStr, const ComponentRegistry &reg, const CircuitResolver *resolver=nullptr)
Deserializes the core circuit model from a JSON string.
Definition circuit.cpp:749
std::optional< VertexDescriptor > getVertexId(const Component *component) const
Gets the vertex ID for a component.
Definition circuit.cpp:330
std::pair< std::vector< Bus >, std::vector< Bus > > getComponentIOs() const
Collects all unique input and output buses from every component in the circuit.
Definition circuit.cpp:177
Circuit getBackwardsSubgraph(const Bus &targetOutput) const
Extracts the cone of influence (COI) for a target output bus.
Definition circuit.cpp:464
std::vector< Component_weakPtr > getListenersForWire(uint64_t wireId) const
Gets all components listening to changes on a specific wire.
Definition circuit.cpp:223
Component_ptr getComponentByVertexId(VertexDescriptor vertexId) const
Gets a component by its vertex ID.
Definition circuit.cpp:113
std::vector< VertexDescriptor > topologicalOrder() const
Computes a valid execution order for all vertices in the circuit.
Definition circuit.cpp:644
std::map< Component_weakPtr, unsigned int, std::owner_less< Component_weakPtr > > LevelMap
Definition circuit.hpp:362
std::vector< CircuitPort > getOutputPorts() const
Gets named output ports using boundary names or deterministic fallbacks.
Definition circuit.cpp:385
void buildTopologyMap()
Builds a reverse mapping from wires to components that use them.
Definition circuit.cpp:205
Circuit getForwardSubgraph(const Bus &sourceInput) const
Extracts the forward cone of influence for a source input bus.
Definition circuit.cpp:514
std::vector< SimulationBlock > splitCyclic() const
Splits the circuit into simulation blocks separating cyclic from acyclic parts.
Definition circuit.cpp:557
std::string serialize() const
Serializes the core circuit model to a JSON string.
Definition circuit.cpp:694
std::vector< CircuitPort > interfacePorts(PortRole role) const
Definition circuit.cpp:353
Circuit::LevelMap getLevelMap() const
Get a levelized map between the components and their level number.
Definition circuit.cpp:658
std::vector< Bus > getOutputs() const
Gets all output buses of the circuit.
Definition circuit.cpp:378
void addComponent(const Component_ptr &component)
Adds a component to the circuit recursively.
Definition circuit.cpp:294
void addComponentRecursive(const Component_ptr &component, std::vector< VertexDescriptor > &newlyAdded)
Recursively adds a component and all connected components.
Definition circuit.cpp:278
void rebuildEdges(VertexDescriptor v)
Rebuilds directed edges in the graph based on wire connections.
Definition circuit.cpp:139
std::vector< CircuitPort > getInputPorts() const
Gets named input ports using boundary names or deterministic fallbacks.
Definition circuit.cpp:348
std::unordered_map< uint64_t, std::vector< Component_ptr > > wireListeners
Maps wire IDs to components that listen to changes on that wire.
Definition circuit.hpp:134
CircuitGraph graph
The Boost graph representing the circuit topology.
Definition circuit.hpp:128
Component_set getComponentsForBus(Bus b) const
Finds all components that are connected to a given bus.
Definition circuit.cpp:390
std::vector< CircuitConnection > getConnections() const
Gets concrete output-to-input logical connections for routing.
Definition circuit.cpp:423
void removeComponent(const Component_ptr &component)
Removes a component from the circuit.
Definition circuit.cpp:307
std::unordered_map< const Component *, VertexDescriptor > componentToVertex
Maps components to their vertex descriptors in the graph.
Definition circuit.hpp:131
std::vector< Bus > getInputs() const
Gets all input buses of the circuit.
Definition circuit.cpp:341
Component_ptr create(std::string_view type) const
Base class for all digital circuit components.
std::shared_ptr< Component > Component_ptr
uint64_t deserializePortId(const nlohmann::json &value)
boost::adjacency_list< boost::vecS, boost::vecS, boost::bidirectionalS, VertexProperty, EdgeProperty > CircuitGraph
Boost graph type representing the circuit topology.
Definition circuit.hpp:89
uint64_t deserializeBoundaryPortId(const nlohmann::json &component)
boost::graph_traits< CircuitGraph >::vertex_descriptor VertexDescriptor
Descriptor type for vertices in the circuit graph.
Definition circuit.hpp:94
std::set< Component_ptr, std::owner_less< Component_ptr > > Component_set
Definition wire.hpp:54
std::weak_ptr< Component > Component_weakPtr
Definition wire.hpp:52
BusValue busValueFromBits(const std::string_view bits)
Strictly decodes an MSB-first raw string containing 0, 1, X, or E.
PortRole
Declares whether a component represents a public circuit boundary port.
Definition component.hpp:66
std::string formatValue(const BusValue &value, const BusValueFormat format, const std::size_t fixedWidth)
Format an LSB-first BusValue for display.
Directed logical connection between one component output bus and one input bus.
Definition circuit.hpp:64
Property stored in each edge of the circuit graph.
Definition circuit.hpp:52
Property stored in each vertex of the circuit graph.
Definition circuit.hpp:46