MimIR
MimIR is my Intermediate Representation
Loading...
Searching...
No Matches
graph.h
Go to the documentation of this file.
1#pragma once
2
3#include <cassert>
4#include <concepts>
5#include <cstddef>
6#include <cstdint>
7
8#include <algorithm>
9#include <initializer_list>
10#include <iosfwd>
11#include <limits>
12#include <ranges>
13#include <type_traits>
14#include <utility>
15
16#include <ankerl/unordered_dense.h>
17#include <fe/span.h>
18#include <fe/vector.h>
19
20namespace pbqp {
21
22/// @name Ids
23/// Node and edge ids are dense and stable: nothing is ever removed from a Graph.
24///@{
25using NodeId = size_t; ///< Identifier of a node in a Graph.
26using EdgeId = size_t; ///< Identifier of an edge in a Graph.
27using OptionId = size_t; ///< Index of an option within a node's cost vector.
28///@}
29
30/// A saturating cost; Cost::inf forbids an option or option pair.
31class Cost {
32public:
33 using Rep = int32_t;
34
35 constexpr Cost() = default;
36 constexpr Cost(Rep value)
37 : value_(value) {}
38
39 [[nodiscard]] static constexpr Cost inf() { return std::numeric_limits<Rep>::max(); }
40 [[nodiscard]] static constexpr Cost min() { return std::numeric_limits<Rep>::min(); }
41
42 [[nodiscard]] constexpr Rep value() const { return value_; }
43 [[nodiscard]] constexpr bool is_inf() const { return value_ == std::numeric_limits<Rep>::max(); }
44 constexpr explicit operator Rep() const { return value_; }
45
46 friend constexpr auto operator<=>(Cost, Cost) = default;
47
48 /// Any sign; saturates and Cost::inf absorbs.
49 friend constexpr Cost operator+(Cost lhs, Cost rhs) {
50 if (lhs.is_inf() || rhs.is_inf()) return inf();
51 const auto sum = int64_t{lhs.value_} + rhs.value_;
52 return static_cast<Rep>(std::clamp<int64_t>(sum, min().value_, inf().value_));
53 }
54
55 constexpr Cost& operator+=(Cost rhs) { return *this = *this + rhs; }
56
57 friend std::ostream& operator<<(std::ostream&, Cost); ///< Prints Cost::inf as `inf`.
58
59private:
60 Rep value_ = 0;
61};
62
63/// @name PBQP Vectors & Matrices
64/// PBQP vectors and matrices are small, so they live inline; a Matrix views such storage row-major.
65///@{
66using Costs = fe::Vector<Cost, 4>;
67using Edges = fe::Vector<EdgeId, 4>;
68using Choices = fe::Vector<OptionId, 8>; ///< One option per node, indexed by node id.
69///@}
70
71/// A view of a cost matrix over row-major storage owned elsewhere; transposed() views the same storage column-major.
72template<class T>
73requires std::same_as<std::remove_cv_t<T>, Cost> class BasicMatrix {
74public:
75 constexpr BasicMatrix() = default;
76 constexpr BasicMatrix(T* data, size_t rows, size_t cols)
77 : BasicMatrix(data, rows, cols, true) {}
78
79 template<class U>
80 requires(std::same_as<T, const Cost> && std::same_as<U, Cost>) constexpr BasicMatrix(const BasicMatrix<U>& other)
81 : BasicMatrix(other.data(), other.rows(), other.cols(), other.row_major()) {}
82
83 [[nodiscard]] constexpr T& operator[](size_t row, size_t col) const {
84 assert(row < rows_ && col < cols_);
85 return data_[row * row_stride_ + col * col_stride_];
86 }
87
88 [[nodiscard]] constexpr size_t rows() const { return rows_; }
89 [[nodiscard]] constexpr size_t cols() const { return cols_; }
90 [[nodiscard]] constexpr size_t size() const { return rows_ * cols_; }
91
92 /// Whether rows are contiguous, which also holds for a transposed single row or column.
93 [[nodiscard]] constexpr bool row_major() const { return col_stride_ == 1; }
94 [[nodiscard]] constexpr BasicMatrix transposed() const { return {data_, cols_, rows_, !row_major()}; }
95
96 /// @name Storage
97 /// Iteration covers the storage in memory order, which is row-major only if row_major().
98 ///@{
99 [[nodiscard]] constexpr T* data() const { return data_; }
100 [[nodiscard]] constexpr T* begin() const { return data_; }
101 [[nodiscard]] constexpr T* end() const { return data_ + size(); }
102 [[nodiscard]] constexpr T* row(size_t row) const {
103 assert(row < rows_ && row_major());
104 return data_ + row * row_stride_;
105 }
106 ///@}
107
108 constexpr const BasicMatrix& operator+=(BasicMatrix<const Cost> rhs) const requires(!std::is_const_v<T>) {
109 assert(rows_ == rhs.rows() && cols_ == rhs.cols());
110 assert((size() <= 1 || data_ != rhs.data() || row_major() == rhs.row_major()) && "+=: rhs aliases this");
111 for (size_t r = 0; r < rows_; ++r)
112 for (size_t c = 0; c < cols_; ++c)
113 (*this)[r, c] += rhs[r, c];
114 return *this;
115 }
116
117 constexpr void copy_from(BasicMatrix<const Cost> src) const requires(!std::is_const_v<T>) {
118 assert(rows_ == src.rows() && cols_ == src.cols());
119 assert((size() <= 1 || data_ != src.data() || row_major() == src.row_major()) && "copy_from: src aliases this");
120 for (size_t r = 0; r < rows_; ++r)
121 for (size_t c = 0; c < cols_; ++c)
122 (*this)[r, c] = src[r, c];
123 }
124
125 /// Erases the rows in `rows`, which must be sorted and distinct.
126 /// The `&` ensures erasing an rvalue cannot compact the storage yet drop the shrunken dimensions.
127 constexpr void erase_rows(fe::View<size_t> rows) & requires(!std::is_const_v<T>) {
128 if (rows.empty()) return;
129 assert(std::ranges::is_sorted(rows) && "erase_rows: rows not sorted");
130 assert(std::ranges::adjacent_find(rows) == rows.end() && "erase_rows: duplicate row");
131 assert(rows.back() < rows_ && "erase_rows: row out of range");
132 if (row_major()) {
133 size_t dst = 0;
134 size_t src = 0;
135 for (const size_t row : rows) {
136 if (dst != src) std::copy_n(data_ + src * cols_, (row - src) * cols_, data_ + dst * cols_);
137 dst += row - src;
138 src = row + 1;
139 }
140 if (dst != src) std::copy_n(data_ + src * cols_, (rows_ - src) * cols_, data_ + dst * cols_);
141 dst += rows_ - src;
142 *this = BasicMatrix(data_, dst, cols_, true);
143 } else {
144 erase_storage_cols(rows);
145 *this = BasicMatrix(data_, rows_ - rows.size(), cols_, false);
146 }
147 }
148
149 /// Erases the columns in `cols`, which must be sorted and distinct.
150 constexpr void erase_cols(fe::View<size_t> cols) & requires(!std::is_const_v<T>) {
151 *this = transposed();
153 *this = transposed();
154 }
155
156private:
157 constexpr BasicMatrix(T* data, size_t rows, size_t cols, bool row_major)
158 : data_(data)
159 , rows_(rows)
160 , cols_(cols)
161 , row_stride_(row_major || rows <= 1 || cols <= 1 ? cols : 1)
162 , col_stride_(row_major || rows <= 1 || cols <= 1 ? 1 : rows) {}
163
164 /// Erases the storage columns in `cols`, which are positions within each of the `cols_` rows of `rows_` entries.
165 constexpr void erase_storage_cols(fe::View<size_t> cols) {
166 T* out = data_;
167 for (size_t r = 0; r < cols_; ++r) {
168 const T* const base = data_ + r * rows_;
169 const T* in = base;
170 for (const auto col : cols) {
171 out = std::copy(in, base + col, out);
172 in = base + col + 1;
173 }
174 out = std::copy(in, base + rows_, out);
175 }
176 }
177
178 T* data_ = nullptr;
179 size_t rows_ = 0;
180 size_t cols_ = 0;
181 size_t row_stride_ = 0;
182 size_t col_stride_ = 1;
183};
184
187
188/// An owning row-major cost matrix; it views its own storage, so writes go through span().
189class Matrix : public MatrixView {
190public:
191 Matrix() = default;
192 Matrix(size_t rows, size_t cols, Cost fill = 0)
193 : Matrix(Costs(rows * cols, fill), rows, cols) {}
194 Matrix(size_t rows, size_t cols, std::initializer_list<Cost> costs)
195 : Matrix(Costs(costs), rows, cols) {}
196 /// Entry `(r, c)` is `f(r, c)`, generated in row-major order.
197 template<class F>
198 requires std::is_invocable_r_v<Cost, F&, size_t, size_t> Matrix(size_t rows, size_t cols, F f)
199 : Matrix(Costs(rows * cols, [&f, cols](size_t i) -> Cost { return f(i / cols, i % cols); }), rows, cols) {}
200 explicit Matrix(MatrixView view)
201 : Matrix(view.rows(), view.cols(), [view](size_t r, size_t c) { return view[r, c]; }) {}
202
203 Matrix(const Matrix& other)
204 : Matrix(Costs(other.costs_), other.rows(), other.cols()) {}
205 Matrix(Matrix&& other) noexcept
206 : Matrix(std::move(other.costs_), other.rows(), other.cols()) {
207 other.view() = {};
208 }
209 Matrix& operator=(Matrix other) noexcept {
210 costs_ = std::move(other.costs_);
211 view() = {costs_.data(), other.rows(), other.cols()};
212 other.view() = {};
213 return *this;
214 }
215
216 [[nodiscard]] MatrixSpan span() { return {costs_.data(), rows(), cols()}; }
217
219 span() += rhs;
220 return *this;
221 }
222
223 friend bool operator==(const Matrix& a, const Matrix& b) {
224 return a.rows() == b.rows() && a.cols() == b.cols() && a.costs_ == b.costs_;
225 }
226
227private:
228 Matrix(Costs&& costs, size_t rows, size_t cols)
229 : costs_(std::move(costs)) {
230 assert(costs_.size() == rows * cols && "Matrix: wrong number of costs");
231 view() = {costs_.data(), rows, cols};
232 }
233
234 MatrixView& view() { return *this; }
235
236 Costs costs_;
237};
238
239/// A PBQP problem graph.
240///
241/// Every node carries a cost vector with one entry per option. Every edge
242/// carries a cost matrix indexed by the options of its endpoints:
243///
244/// matrix[src_option, dst_option]
245///
246/// The total cost of an assignment `x` is
247///
248/// sum_n c_n(x_n) + sum_{mn} M_mn(x_m, x_n)
249///
250/// A node holds at most one edge to any other node, so parallel edges have to be merged by summing their matrices
251/// first. A Graph only grows; ids are handed out consecutively from 0.
252class Graph {
253public:
254 struct Ends {
257 };
258
259 static constexpr EdgeId npos = static_cast<EdgeId>(-1);
260
261 /// @name Construction
262 ///@{
263 /// @name Add Nodes, Edges, and Costs
264 ///@{
265
266 /// Add a node with the given cost vector.
267 /// The vector must not be empty.
268 NodeId add(fe::View<Cost> costs);
269
270 /// Link `m` and `n` with a num_options(m) × num_options(n) matrix.
271 /// Requires distinct nodes that are not linked yet.
272 EdgeId link(NodeId m, NodeId n, MatrixView costs);
273
274 /// Like link, but sums `costs` onto an existing edge between `m` and `n`, whichever way it points.
275 /// Sums saturate and Cost::inf absorbs.
277
278 void set_node_costs(NodeId n, fe::View<Cost> costs); ///< Replace a cost vector; the option count must not change.
279 void set_edge_costs(EdgeId e, MatrixView costs); ///< Replace a cost matrix, src options as rows.
280 ///@}
281
282 /// @name Getters
283 ///@{
284 [[nodiscard]] fe::View<Cost> node_costs(NodeId n) const { return checked_node(n).costs; }
285
286 /// Row-major with the src option as the row.
287 [[nodiscard]] MatrixView edge_matrix(EdgeId e) const {
288 const Edge& edge = checked_edge(e);
289 const Costs& costs = matrix(edge.matrix);
290 return {costs.data(), num_options(edge.src), num_options(edge.dst)};
291 }
292
293 /// The options of `from`, an end of `e`, are the rows.
294 [[nodiscard]] MatrixView edge_matrix(EdgeId e, NodeId from) const {
295 const auto [src, dst] = edge(e);
296 assert((from == src || from == dst) && "edge_matrix: not an end of the edge");
297 return from == src ? edge_matrix(e) : edge_matrix(e).transposed();
298 }
299
300 [[nodiscard]] size_t num_options(NodeId n) const { return node_costs(n).size(); }
301
302 [[nodiscard]] fe::View<EdgeId> incident_edges(NodeId n) const { return checked_node(n).edges; }
303 [[nodiscard]] Ends edge(EdgeId e) const {
304 const Edge& edge = checked_edge(e);
305 return {.src = edge.src, .dst = edge.dst};
306 }
307 [[nodiscard]] EdgeId edge(NodeId m, NodeId n) const; ///< The edge between `m` and `n`, or npos.
308
309 [[nodiscard]] auto nodes() const { return std::views::iota(NodeId{0}, num_nodes()); } ///< All node ids.
310 [[nodiscard]] auto edges() const { return std::views::iota(EdgeId{0}, num_edges()); } ///< All edge ids.
311
312 [[nodiscard]] size_t num_nodes() const { return nodes_.size(); }
313 [[nodiscard]] size_t num_edges() const { return edges_.size(); }
314 /// Number of distinct edge matrices ever linked or set; edges with equal matrices share one copy.
315 [[nodiscard]] size_t num_matrices() const { return matrices_.size(); }
316 ///@}
317
318private:
319 using MatrixId = size_t;
320
321 /// Costs that are not interned yet, together with their hash.
322 struct Probe {
323 fe::View<Cost> costs;
324 size_t hash;
325 };
326
327 struct PooledMatrix {
328 explicit PooledMatrix(const Probe& probe)
329 : costs(probe.costs.begin(), probe.costs.end())
330 , hash(probe.hash) {}
331
332 Costs costs;
333 size_t hash;
334 };
335
336 struct PooledMatrixHash {
337 using is_transparent = void;
338 using is_avalanching = void;
339 size_t operator()(const PooledMatrix& matrix) const noexcept { return matrix.hash; }
340 size_t operator()(const Probe& probe) const noexcept { return probe.hash; }
341 };
342
343 struct PooledMatrixEq {
344 using is_transparent = void;
345 bool operator()(const PooledMatrix& a, const PooledMatrix& b) const noexcept { return a.costs == b.costs; }
346 bool operator()(const Probe& probe, const PooledMatrix& matrix) const noexcept {
347 return std::ranges::equal(matrix.costs, probe.costs);
348 }
349 bool operator()(const PooledMatrix& matrix, const Probe& probe) const noexcept {
350 return (*this)(probe, matrix);
351 }
352 };
353
354 struct Node {
355 Costs costs;
356 Edges edges; // incident edges, no duplicates
357 };
358
359 struct Edge {
360 NodeId src = 0;
361 NodeId dst = 0;
362 MatrixId matrix = npos;
363 };
364
365 [[nodiscard]] const Node& checked_node(NodeId n) const {
366 assert((n < num_nodes()) && "node: unknown node");
367 return nodes_[n];
368 }
369
370 [[nodiscard]] const Edge& checked_edge(EdgeId e) const {
371 assert((e < num_edges()) && "edge: unknown edge");
372 return edges_[e];
373 }
374
375 [[nodiscard]] MatrixId intern(MatrixView matrix);
376 [[nodiscard]] const Costs& matrix(MatrixId id) const { return matrices_.values()[id].costs; }
377
378 fe::Vector<Node> nodes_;
379 fe::Vector<Edge> edges_;
380 // Never erased, so positions are ids.
381 ankerl::unordered_dense::set<PooledMatrix, PooledMatrixHash, PooledMatrixEq> matrices_;
382};
383
384} // namespace pbqp
A view of a cost matrix over row-major storage owned elsewhere; transposed() views the same storage c...
Definition graph.h:73
constexpr size_t size() const
Definition graph.h:90
constexpr T * begin() const
Definition graph.h:100
constexpr T * end() const
Definition graph.h:101
constexpr T & operator[](size_t row, size_t col) const
Definition graph.h:83
constexpr Cost * row(size_t row) const
Definition graph.h:102
constexpr BasicMatrix(T *data, size_t rows, size_t cols)
Definition graph.h:76
constexpr const BasicMatrix & operator+=(BasicMatrix< const Cost > rhs) const
Definition graph.h:108
constexpr BasicMatrix transposed() const
Definition graph.h:94
constexpr size_t rows() const
Definition graph.h:88
constexpr bool row_major() const
Definition graph.h:93
constexpr void erase_cols(fe::View< size_t > cols) &
Erases the columns in cols, which must be sorted and distinct.
Definition graph.h:150
constexpr BasicMatrix()=default
constexpr void erase_rows(fe::View< size_t > rows) &
Erases the rows in rows, which must be sorted and distinct.
Definition graph.h:127
constexpr void copy_from(BasicMatrix< const Cost > src) const
Definition graph.h:117
constexpr size_t cols() const
Definition graph.h:89
constexpr BasicMatrix(const BasicMatrix< U > &other)
Definition graph.h:80
constexpr Cost * data() const
Definition graph.h:99
A saturating cost; Cost::inf forbids an option or option pair.
Definition graph.h:31
friend constexpr Cost operator+(Cost lhs, Cost rhs)
Any sign; saturates and Cost::inf absorbs.
Definition graph.h:49
static constexpr Cost inf()
Definition graph.h:39
static constexpr Cost min()
Definition graph.h:40
friend constexpr auto operator<=>(Cost, Cost)=default
constexpr Cost()=default
constexpr Cost(Rep value)
Definition graph.h:36
constexpr Rep value() const
Definition graph.h:42
constexpr Cost & operator+=(Cost rhs)
Definition graph.h:55
constexpr bool is_inf() const
Definition graph.h:43
int32_t Rep
Definition graph.h:33
A PBQP problem graph.
Definition graph.h:252
MatrixView edge_matrix(EdgeId e, NodeId from) const
The options of from, an end of e, are the rows.
Definition graph.h:294
Ends edge(EdgeId e) const
Definition graph.h:303
void set_node_costs(NodeId n, fe::View< Cost > costs)
Replace a cost vector; the option count must not change.
Definition graph.cpp:43
static constexpr EdgeId npos
Definition graph.h:259
size_t num_options(NodeId n) const
Definition graph.h:300
fe::View< EdgeId > incident_edges(NodeId n) const
Definition graph.h:302
size_t num_matrices() const
Number of distinct edge matrices ever linked or set; edges with equal matrices share one copy.
Definition graph.h:315
size_t num_nodes() const
Definition graph.h:312
MatrixView edge_matrix(EdgeId e) const
Row-major with the src option as the row.
Definition graph.h:287
size_t num_edges() const
Definition graph.h:313
fe::View< Cost > node_costs(NodeId n) const
Definition graph.h:284
auto nodes() const
All node ids.
Definition graph.h:309
NodeId add(fe::View< Cost > costs)
Add a node with the given cost vector.
Definition graph.cpp:12
auto edges() const
All edge ids.
Definition graph.h:310
void set_edge_costs(EdgeId e, MatrixView costs)
Replace a cost matrix, src options as rows.
Definition graph.cpp:48
EdgeId add_edge_costs(NodeId m, NodeId n, MatrixView costs)
Like link, but sums costs onto an existing edge between m and n, whichever way it points.
Definition graph.cpp:32
EdgeId link(NodeId m, NodeId n, MatrixView costs)
Link m and n with a num_options(m) × num_options(n) matrix.
Definition graph.cpp:18
Matrix(const Matrix &other)
Definition graph.h:203
Matrix(size_t rows, size_t cols, std::initializer_list< Cost > costs)
Definition graph.h:194
Matrix(size_t rows, size_t cols, Cost fill=0)
Definition graph.h:192
Matrix & operator+=(MatrixView rhs)
Definition graph.h:218
Matrix & operator=(Matrix other) noexcept
Definition graph.h:209
Matrix(size_t rows, size_t cols, F f)
Entry (r, c) is f(r, c), generated in row-major order.
Definition graph.h:198
Matrix(MatrixView view)
Definition graph.h:200
Matrix(Matrix &&other) noexcept
Definition graph.h:205
Matrix()=default
friend bool operator==(const Matrix &a, const Matrix &b)
Definition graph.h:223
MatrixSpan span()
Definition graph.h:216
Node
Definition def.h:121
Definition dot.h:9
size_t OptionId
Index of an option within a node's cost vector.
Definition graph.h:27
BasicMatrix< const Cost > MatrixView
Definition graph.h:186
fe::Vector< OptionId, 8 > Choices
One option per node, indexed by node id.
Definition graph.h:68
std::ostream & operator<<(std::ostream &out, Cost cost)
Definition graph.cpp:10
fe::Vector< EdgeId, 4 > Edges
Definition graph.h:67
fe::Vector< Cost, 4 > Costs
Definition graph.h:66
size_t EdgeId
Identifier of an edge in a Graph.
Definition graph.h:26
size_t NodeId
Identifier of a node in a Graph.
Definition graph.h:25
BasicMatrix< Cost > MatrixSpan
Definition graph.h:185