SILICON
Loading...
Searching...
No Matches
ogdfCircuit.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 "ogdfCircuit.hpp"
19
20#include <algorithm>
21#include <cstddef>
22#include <cstdint>
23#include <limits>
24#include <tuple>
25#include <unordered_map>
26#include <utility>
27#include <vector>
28
29#include <QRectF>
30
31#include <boost/graph/graph_traits.hpp>
32#include <boost/range/iterator_range.hpp>
33
34#include <ogdf/basic/Graph.h>
35#include <ogdf/basic/GraphAttributes.h>
36#include <ogdf/energybased/FMMMLayout.h>
37#include <ogdf/layered/FastHierarchyLayout.h>
38#include <ogdf/layered/SugiyamaLayout.h>
39
40#include <core/circuit.hpp>
42
43namespace SILICON::ui {
44using namespace SILICON::core;
45
46namespace {
47
48 QPointF orientedLayerPoint(const double x, const double y,
49 const GraphLayoutDirection direction)
50 {
51 switch (direction) {
52 case GraphLayoutDirection::TopToBottom: return {x, y};
53 case GraphLayoutDirection::LeftToRight: return {y, x};
54 }
55 std::unreachable();
56 }
57
58} // namespace
59
62 std::span<GraphicalLogicComponent* const> components,
63 const GraphLayoutOptions& options)
64{
65 ogdf::Graph graph;
66
67 const auto& circuitGraph = circuit.getGraph();
68 const auto vertexCount = boost::num_vertices(circuitGraph);
69
70 std::vector<ogdf::node> vertexToNode(vertexCount, nullptr);
71 std::vector<GraphicalLogicComponent*> vertexToGraphics(vertexCount, nullptr);
72 std::unordered_map<const Component*, GraphicalLogicComponent*> componentToGraphics;
73 std::unordered_map<ogdf::node, GraphicalLogicComponent*> nodeToGraphics;
74
75 for (GraphicalLogicComponent* component : components) {
76 if (!component || !component->getComponent())
77 continue;
78
79 componentToGraphics.emplace(component->getComponent().get(), component);
80 }
81
82 std::vector<std::size_t> orderedVertices;
83 orderedVertices.reserve(vertexCount);
84 for (const auto vertex : boost::make_iterator_range(boost::vertices(circuitGraph))) {
85 const auto& component = circuitGraph[vertex].component;
86 if (!component)
87 continue;
88
89 auto graphicsIt = componentToGraphics.find(component.get());
90 if (graphicsIt == componentToGraphics.end())
91 continue;
92
93 const auto index = static_cast<std::size_t>(vertex);
94 vertexToGraphics[index] = graphicsIt->second;
95 orderedVertices.push_back(index);
96 }
97
98 std::ranges::sort(orderedVertices, [&](const std::size_t lhs, const std::size_t rhs) {
99 const auto* lhsGraphics = vertexToGraphics[lhs];
100 const auto* rhsGraphics = vertexToGraphics[rhs];
101 return std::pair{lhsGraphics->getUiId(), lhs}
102 < std::pair{rhsGraphics->getUiId(), rhs};
103 });
104 for (const std::size_t vertex : orderedVertices) {
105 ogdf::node node = graph.newNode();
106 vertexToNode[vertex] = node;
107 nodeToGraphics.emplace(node, vertexToGraphics[vertex]);
108 }
109
110 if (graph.numberOfNodes() == 0)
111 return {};
112
113 struct OrderedEdge {
114 std::size_t source;
115 std::size_t target;
116 std::vector<std::uint64_t> busKey;
117 };
118 std::vector<OrderedEdge> orderedEdges;
119 orderedEdges.reserve(boost::num_edges(circuitGraph));
120 for (const auto edge : boost::make_iterator_range(boost::edges(circuitGraph))) {
121 const auto sourceVertex = boost::source(edge, circuitGraph);
122 const auto targetVertex = boost::target(edge, circuitGraph);
123 if (sourceVertex == targetVertex)
124 continue;
125
126 const auto source = static_cast<std::size_t>(sourceVertex);
127 const auto target = static_cast<std::size_t>(targetVertex);
128 if (!vertexToNode[source] || !vertexToNode[target])
129 continue;
130
131 std::vector<std::uint64_t> busKey;
132 busKey.reserve(circuitGraph[edge].bus.size());
133 for (const auto& wire : circuitGraph[edge].bus)
134 busKey.push_back(wire ? wire->getId() : 0);
135 orderedEdges.push_back(
136 {.source = source, .target = target, .busKey = std::move(busKey)});
137 }
138
139 std::ranges::sort(orderedEdges, [&](const OrderedEdge& lhs, const OrderedEdge& rhs) {
140 return std::tuple{vertexToGraphics[lhs.source]->getUiId(),
141 vertexToGraphics[lhs.target]->getUiId(), lhs.busKey}
142 < std::tuple{vertexToGraphics[rhs.source]->getUiId(),
143 vertexToGraphics[rhs.target]->getUiId(), rhs.busKey};
144 });
145 for (const OrderedEdge& edge : orderedEdges)
146 graph.newEdge(vertexToNode[edge.source], vertexToNode[edge.target]);
147
148 ogdf::GraphAttributes attributes(graph, ogdf::GraphAttributes::nodeGraphics
149 | ogdf::GraphAttributes::edgeGraphics);
150
151 const bool horizontalLayers = options.algorithm == GraphLayoutAlgorithm::Layered
153 for (ogdf::node node : graph.nodes) {
154 const QRectF bounds = nodeToGraphics.at(node)->sceneBoundingRect();
155 attributes.width(node) =
156 std::max(static_cast<double>(horizontalLayers ? options.fallbackNodeHeight
157 : options.fallbackNodeWidth),
158 horizontalLayers ? bounds.height() : bounds.width());
159 attributes.height(node) =
160 std::max(static_cast<double>(horizontalLayers ? options.fallbackNodeWidth
161 : options.fallbackNodeHeight),
162 horizontalLayers ? bounds.width() : bounds.height());
163 }
164
166 ogdf::FMMMLayout layout;
167 layout.useHighLevelOptions(true);
168 layout.unitEdgeLength(options.layerDistance);
169 layout.minDistCC(options.connectedComponentDistance);
170 layout.qualityVersusSpeed(ogdf::FMMMOptions::QualityVsSpeed::GorgeousAndEfficient);
171 // FMMM documents newInitialPlacement=true as deliberately varying the coarsest
172 // placement between calls. Keep it disabled so randomSeed identifies a reproducible
173 // candidate and rerunning full autoplacement compares the same search space.
174 layout.newInitialPlacement(false);
175 layout.randSeed(options.randomSeed);
176 layout.call(attributes);
177 } else {
178 ogdf::SugiyamaLayout layout;
179 layout.arrangeCCs(true);
180 layout.minDistCC(options.connectedComponentDistance);
181 if (options.deterministic) {
182 layout.runs(1);
183 layout.permuteFirst(false);
184 }
185
186 auto* hierarchyLayout = new ogdf::FastHierarchyLayout();
187 hierarchyLayout->nodeDistance(options.nodeDistance);
188 hierarchyLayout->layerDistance(options.layerDistance);
189 hierarchyLayout->fixedLayerDistance(true);
190 layout.setLayout(hierarchyLayout);
191 layout.call(attributes);
192 }
193
194 double minSceneLeft = std::numeric_limits<double>::infinity();
195 double minSceneTop = std::numeric_limits<double>::infinity();
196
197 for (ogdf::node node : graph.nodes) {
198 const QPointF layoutPoint =
200 ? orientedLayerPoint(attributes.x(node), attributes.y(node),
201 options.direction)
202 : QPointF(attributes.x(node), attributes.y(node));
203 const double x = layoutPoint.x();
204 const double y = layoutPoint.y();
205 const double sceneWidth =
206 horizontalLayers ? attributes.height(node) : attributes.width(node);
207 const double sceneHeight =
208 horizontalLayers ? attributes.width(node) : attributes.height(node);
209 minSceneLeft = std::min(minSceneLeft, x - sceneWidth / 2.0);
210 minSceneTop = std::min(minSceneTop, y - sceneHeight / 2.0);
211 }
212
213 PlacementMap placements;
214 placements.reserve(static_cast<std::size_t>(graph.numberOfNodes()));
215
216 for (ogdf::node node : graph.nodes) {
217 GraphicalLogicComponent* component = nodeToGraphics.at(node);
218 const QRectF bounds = component->sceneBoundingRect();
219 const QPointF centerOffset =
220 bounds.isValid() ? bounds.center() - component->pos() : QPointF(0.0, 0.0);
221
222 const QPointF layoutPoint =
224 ? orientedLayerPoint(attributes.x(node), attributes.y(node),
225 options.direction)
226 : QPointF(attributes.x(node), attributes.y(node));
227 const double x = layoutPoint.x();
228 const double y = layoutPoint.y();
229 const QPointF arrangedCenter(options.origin.x() + x - minSceneLeft,
230 options.origin.y() + y - minSceneTop);
231
232 placements.emplace(component,
233 DiagramScene::snapToGrid(arrangedCenter - centerOffset));
234 }
235
236 return placements;
237}
238
239} // namespace SILICON::ui
Represents a digital circuit as a directed graph of components.
Definition circuit.hpp:125
const CircuitGraph & getGraph() const
Gets the underlying circuit graph.
Definition circuit.hpp:349
static QPoint snapToGrid(QPointF point)
Snaps a point to the grid.
static PlacementMap compute(const core::Circuit &circuit, std::span< GraphicalLogicComponent *const > components, const GraphLayoutOptions &options={})
Computes component placements for the subset represented by components.
std::unordered_map< GraphicalLogicComponent *, QPointF > PlacementMap
Map from graphical component to the computed scene position for that item.
Base class for logic-gate graphical components.
GraphLayoutDirection
Signal-flow direction used for a layered layout.
Configuration for OGDF-based component placement.
bool deterministic
True to use a single deterministic Sugiyama crossing-minimization run.
int nodeDistance
Minimum horizontal scene distance between nodes on the same OGDF layer.
int fallbackNodeHeight
Height used when a graphical item has no valid scene bounds.
int randomSeed
Deterministic seed used by force-directed candidates.
int layerDistance
Minimum vertical scene distance between neighboring OGDF layers.
int connectedComponentDistance
Minimum distance between disconnected graph components.
GraphLayoutAlgorithm algorithm
Placement family used to generate the candidate.
GraphLayoutDirection direction
Scene direction assigned to source-to-target ranks.
QPointF origin
Top-left scene position of the normalized arranged layout.
int fallbackNodeWidth
Width used when a graphical item has no valid scene bounds.