25#include <unordered_set>
36#include <boost/dynamic_bitset.hpp>
37#include <boost/graph/strong_components.hpp>
38#include <boost/graph/topological_sort.hpp>
40#include <nlohmann/json.hpp>
46 std::vector<uint64_t> readPortIds(
const nlohmann::json& component,
47 std::string_view field)
49 const auto it = component.find(field);
50 if (it == component.end())
53 throw std::runtime_error(
"Port identities must be an array");
54 std::vector<uint64_t> ids;
55 for (
const auto& value : *it)
60 const SILICON::logging::Logger circuitLog(
"circuit");
62 using CircuitVertexSet = boost::dynamic_bitset<>;
64 [[nodiscard]]
bool markVisited(CircuitVertexSet& visited,
const VertexDescriptor vertex)
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))
77 [[nodiscard]] std::string interfacePortName(
const PortRole role,
78 const std::size_t index)
80 return std::format(
"{}_{}", role ==
PortRole::Input ?
"input" :
"output", index);
83 [[nodiscard]] std::vector<CircuitPort> boundaryPorts(
const CircuitGraph& graph,
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)
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));
102 {.name = component->getPropertyValue<std::string>(
"name").value_or(
103 interfacePortName(role, ports.size())),
105 .boundaryVertex = vertex,
115 if (vertexId >= boost::num_vertices(
graph))
117 return graph[vertexId].component;
141 const auto cPtr =
graph[v].component;
145 const auto& outputs = cPtr->outputBuses();
148 for (
auto target_v : boost::make_iterator_range(boost::vertices(
graph))) {
152 const auto neighbor =
graph[target_v].component;
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);
163 auto out_edges = boost::make_iterator_range(boost::out_edges(v,
graph));
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;
179 std::vector<Bus> inputs = {};
180 std::vector<Bus> outputs = {};
182 for (
auto v : boost::make_iterator_range(boost::vertices(
graph))) {
183 auto cPtr =
graph[v].component;
187 for (
const Bus& bus : cPtr->inputBuses())
188 inputs.push_back(bus);
190 for (
const Bus& bus : cPtr->outputBuses())
191 outputs.push_back(bus);
194 std::ranges::sort(inputs);
195 inputs.erase(std::ranges::unique(inputs).begin(), inputs.end());
197 std::ranges::sort(outputs);
198 outputs.erase(std::ranges::unique(outputs).begin(), outputs.end());
200 return {std::move(inputs), std::move(outputs)};
209 for (
auto v : boost::make_iterator_range(boost::vertices(
graph))) {
210 const auto comp =
graph[v].component;
215 comp->inputBuses() | std::views::join
216 | std::views::filter([](
const auto& wire) {
return static_cast<bool>(wire); });
218 for (
const auto& wire : valid_wires) {
230 std::vector<Component_weakPtr> result;
231 result.reserve(it->second.size());
233 for (
const auto& ptr : it->second) {
234 result.push_back(ptr);
250 for (
const auto& c : components)
253 for (
auto v : boost::make_iterator_range(boost::vertices(
graph)))
258 for (
const auto& c : components)
279 std::vector<VertexDescriptor>& newlyAdded)
286 newlyAdded.push_back(v);
289 for (
const Bus& bus : component->allBuses())
296 std::vector<VertexDescriptor> newlyAdded;
318 boost::clear_vertex(v,
graph);
319 boost::remove_vertex(v,
graph);
323 for (
auto vd : boost::make_iterator_range(vertices(
graph))) {
345 | std::ranges::to<std::vector>();
355 auto ports = boundaryPorts(
graph, role);
361 std::ranges::sort(inputBuses);
362 std::ranges::sort(outputBuses);
364 std::vector<Bus> result;
367 std::ranges::set_difference(inputBuses, outputBuses, std::back_inserter(result));
369 std::ranges::set_difference(outputBuses, inputBuses, std::back_inserter(result));
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]});
382 | std::ranges::to<std::vector>();
395 for (
const auto& wire : b) {
400 if (
auto comp = weakComp.lock()) {
401 connectedComponents.insert(comp);
407 for (
auto v : boost::make_iterator_range(boost::vertices(
graph))) {
408 const auto cPtr =
graph[v].component;
412 const bool matches = std::ranges::any_of(
413 cPtr->outputBuses(), [&](
const Bus& outBus) { return b.sharesWireWith(outBus); });
416 connectedComponents.insert(cPtr);
420 return connectedComponents;
425 std::vector<CircuitConnection> connections;
426 connections.reserve(boost::num_edges(
graph));
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)
437 const auto& outputs = sourceComponent->outputBuses();
438 for (std::size_t sourceBusIndex = 0; sourceBusIndex < outputs.size();
440 if (outputs[sourceBusIndex] != bus)
443 const auto& inputs = targetComponent->inputBuses();
444 for (std::size_t targetBusIndex = 0; targetBusIndex < inputs.size();
449 connections.push_back(
451 .target = targetComponent,
452 .sourceBusIndex =
static_cast<unsigned int>(sourceBusIndex),
453 .targetBusIndex =
static_cast<unsigned int>(targetBusIndex),
467 std::vector<VertexDescriptor> stack;
468 CircuitVertexSet visited(boost::num_vertices(
graph));
470 auto valid_target_wires = targetOutput | std::views::filter([](
const auto& w) {
471 return static_cast<bool>(w);
475 for (
auto v : boost::make_iterator_range(boost::vertices(
graph))) {
476 const auto cPtr =
graph[v].component;
481 auto out_wires = cPtr->outputBuses() | std::views::join;
484 const bool drivesWire =
485 std::ranges::any_of(valid_target_wires, [&](
const auto& wire) {
486 return std::ranges::contains(out_wires, wire);
489 if (drivesWire && markVisited(visited, v)) {
495 while (!stack.empty()) {
499 if (
const auto comp =
graph[v].component) {
500 coiComponents.insert(comp);
503 for (
auto edge : boost::make_iterator_range(boost::in_edges(v,
graph))) {
505 if (markVisited(visited, sourceVertex)) {
506 stack.push_back(sourceVertex);
511 return Circuit(coiComponents,
false);
517 std::vector<VertexDescriptor> stack;
518 CircuitVertexSet visited(boost::num_vertices(
graph));
520 auto valid_source_wires = sourceInput | std::views::filter([](
const auto& w) {
521 return static_cast<bool>(w);
524 for (
const auto& wire : valid_source_wires) {
526 if (
auto cPtr = weakComp.lock()) {
530 stack.push_back(it->second);
536 while (!stack.empty()) {
540 if (
const auto comp =
graph[v].component) {
541 focComponents.insert(comp);
544 for (
auto edge : boost::make_iterator_range(boost::out_edges(v,
graph))) {
546 if (markVisited(visited, targetVertex)) {
547 stack.push_back(targetVertex);
552 return Circuit(focComponents,
false);
559 circuitLog.debug(
"Splitting the circuit in cyclic and acyclic blocks...");
560 const auto n = boost::num_vertices(
graph);
570 std::vector<int> componentMap(n);
571 const auto vertexIndexMap = boost::get(boost::vertex_index,
graph);
573 const int numSccs = boost::strong_components(
574 graph, boost::make_iterator_property_map(componentMap.begin(), vertexIndexMap));
577 std::vector<std::vector<VertexDescriptor>> sccVertices(numSccs);
578 auto [v_begin, v_end] = boost::vertices(
graph);
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);
589 std::vector<SimulationBlock> blocks;
590 std::vector<Component_weakPtr> currentDagComps;
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));
605 for (
int i = numSccs - 1; i >= 0; --i) {
606 const auto& verts = sccVertices[i];
607 bool isCyclic = verts.size() > 1;
609 if (verts.size() == 1) {
610 auto [e_begin, e_end] = boost::out_edges(verts.front(),
graph);
612 std::ranges::any_of(std::ranges::subrange(e_begin, e_end), [&](
const auto& e) {
613 return boost::target(e,
graph) == verts.front();
618 verts | std::views::transform([
this](
auto v) {
return graph[v].component; })
619 | std::views::filter([](
const auto& comp) {
return comp !=
nullptr; });
626 auto cyclicComps = validComps | std::ranges::to<Component_set>();
628 if (!cyclicComps.empty()) {
629 blocks.emplace_back(
true,
Circuit(cyclicComps,
false),
630 std::vector<Component_weakPtr>{});
633 for (
const auto& comp : validComps)
634 currentDagComps.push_back(comp);
640 circuitLog.debug(std::format(
"Found {} blocks!", blocks.size()));
646 std::vector<VertexDescriptor> order;
647 order.reserve(boost::num_vertices(
graph));
649 circuitLog.debug(
"Topologically sorting the circuit...");
650 boost::topological_sort(
graph, std::back_inserter(order));
653 std::ranges::reverse(order);
664 std::vector<unsigned int> vertexLevels(boost::num_vertices(
graph), 0);
667 unsigned int maxLevel = 0;
670 for (
const auto& edge : boost::make_iterator_range(boost::in_edges(v,
graph))) {
674 const auto predLevel = vertexLevels[pred];
675 maxLevel = std::max(maxLevel, predLevel + 1);
679 vertexLevels[v] = maxLevel;
684 if (compWeak.lock()) {
685 levelMap[compWeak] = maxLevel;
696 nlohmann::ordered_json j = {{
"version", SILICON_VERSION},
697 {
"components", nlohmann::ordered_json::array()}};
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));
707 busArray.push_back(std::move(wireArray));
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()) {
718 [&](
const auto& arg) {
719 using Value = std::remove_cvref_t<
decltype(arg)>;
720 if constexpr (std::same_as<Value, BusValue>)
723 propsJson[key] = arg;
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();
752 const auto j = nlohmann::json::parse(jsonStr);
754 std::unordered_map<uint64_t, Wire_ptr> wireMap;
756 const auto deserializeBusList = [&wireMap](
const nlohmann::json& busListJson) {
757 std::vector<Bus> buses;
758 buses.reserve(busListJson.size());
760 for (
const auto& busJson : busListJson) {
761 std::vector<Wire_ptr> wires;
762 wires.reserve(busJson.size());
764 for (
const auto& wireJson : busJson) {
765 if (wireJson.is_null()) {
766 wires.push_back(
nullptr);
770 const auto id = wireJson.get<uint64_t>();
771 auto& wire = wireMap[id];
776 wires.push_back(wire);
779 buses.emplace_back(std::move(wires));
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)
792 if (!value.is_string())
793 throw std::runtime_error(
794 std::format(
"BusValue property '{}' must be a string", key));
796 component->setProperty(key,
busValueFromBits(value.get_ref<
const std::string&>()));
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>());
808 std::vector<std::pair<int, Component_ptr>> parsedComponents;
810 if (
const auto it = j.find(
"components"); it != j.end() && it->is_array()) {
811 parsedComponents.reserve(it->size());
813 for (
const auto& compJson : *it) {
814 const auto typeIt = compJson.find(
"type");
815 if (typeIt == compJson.end())
818 const auto type = typeIt->get<std::string>();
819 auto component = reg.
create(type);
821 if (
auto subcircuit = std::dynamic_pointer_cast<SubcircuitComponent>(component))
822 subcircuit->setCircuitResolver(resolver);
825 throw std::runtime_error(
826 std::format(
"Failed to create unknown component type: {}", type));
829 if (
const auto boundary =
830 std::dynamic_pointer_cast<BoundaryIoComponent>(component)) {
836 if (
const auto propsIt = compJson.find(
"properties");
837 propsIt != compJson.end() && propsIt->is_object()) {
839 for (
const auto& [key, value] : propsIt->items())
840 applyProperty(component, key, value,
false);
842 for (
const auto& [key, value] : propsIt->items())
843 applyProperty(component, key, value,
true);
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())
852 return deserializeBusList(*it);
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"));
863 component->setInputs(savedInputs);
864 component->setOutputs(savedOutputs);
878 const auto id = compJson.at(
"id").get<
int>();
879 parsedComponents.emplace_back(
id, std::move(component));
883 std::ranges::sort(parsedComponents, [](
const auto& lhs,
const auto& rhs) {
884 return lhs.first < rhs.first;
888 result.ownedComponents.reserve(parsedComponents.size());
891 for (
auto& [
id, component] : parsedComponents) {
892 result.getOrAddVertex(component);
893 result.ownedComponents.push_back(std::move(component));
897 for (
const auto vertex : boost::make_iterator_range(boost::vertices(result.graph))) {
898 result.rebuildEdges(vertex);
901 result.ownedWires = wireMap | std::views::values | std::ranges::to<std::vector>();
903 result.buildTopologyMap();
bool sharesWireWith(const Bus &other) const
VertexDescriptor getOrAddVertex(const Component_ptr &component)
Gets or adds a vertex for a component.
static Circuit deserialize(const std::string &jsonStr, const ComponentRegistry ®, const CircuitResolver *resolver=nullptr)
Deserializes the core circuit model from a JSON string.
std::optional< VertexDescriptor > getVertexId(const Component *component) const
Gets the vertex ID for a component.
std::pair< std::vector< Bus >, std::vector< Bus > > getComponentIOs() const
Collects all unique input and output buses from every component in the circuit.
Circuit getBackwardsSubgraph(const Bus &targetOutput) const
Extracts the cone of influence (COI) for a target output bus.
std::vector< Component_weakPtr > getListenersForWire(uint64_t wireId) const
Gets all components listening to changes on a specific wire.
Component_ptr getComponentByVertexId(VertexDescriptor vertexId) const
Gets a component by its vertex ID.
std::vector< VertexDescriptor > topologicalOrder() const
Computes a valid execution order for all vertices in the circuit.
std::map< Component_weakPtr, unsigned int, std::owner_less< Component_weakPtr > > LevelMap
std::vector< CircuitPort > getOutputPorts() const
Gets named output ports using boundary names or deterministic fallbacks.
void buildTopologyMap()
Builds a reverse mapping from wires to components that use them.
Circuit getForwardSubgraph(const Bus &sourceInput) const
Extracts the forward cone of influence for a source input bus.
std::vector< SimulationBlock > splitCyclic() const
Splits the circuit into simulation blocks separating cyclic from acyclic parts.
std::string serialize() const
Serializes the core circuit model to a JSON string.
std::vector< CircuitPort > interfacePorts(PortRole role) const
Circuit::LevelMap getLevelMap() const
Get a levelized map between the components and their level number.
std::vector< Bus > getOutputs() const
Gets all output buses of the circuit.
void addComponent(const Component_ptr &component)
Adds a component to the circuit recursively.
void addComponentRecursive(const Component_ptr &component, std::vector< VertexDescriptor > &newlyAdded)
Recursively adds a component and all connected components.
void rebuildEdges(VertexDescriptor v)
Rebuilds directed edges in the graph based on wire connections.
std::vector< CircuitPort > getInputPorts() const
Gets named input ports using boundary names or deterministic fallbacks.
std::unordered_map< uint64_t, std::vector< Component_ptr > > wireListeners
Maps wire IDs to components that listen to changes on that wire.
CircuitGraph graph
The Boost graph representing the circuit topology.
Component_set getComponentsForBus(Bus b) const
Finds all components that are connected to a given bus.
std::vector< CircuitConnection > getConnections() const
Gets concrete output-to-input logical connections for routing.
void removeComponent(const Component_ptr &component)
Removes a component from the circuit.
std::unordered_map< const Component *, VertexDescriptor > componentToVertex
Maps components to their vertex descriptors in the graph.
std::vector< Bus > getInputs() const
Gets all input buses of the circuit.
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.
uint64_t deserializeBoundaryPortId(const nlohmann::json &component)
boost::graph_traits< CircuitGraph >::vertex_descriptor VertexDescriptor
Descriptor type for vertices in the circuit graph.
std::set< Component_ptr, std::owner_less< Component_ptr > > Component_set
std::weak_ptr< Component > Component_weakPtr
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.
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.
Property stored in each edge of the circuit graph.
Property stored in each vertex of the circuit graph.