Aleph-w 3.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
Matrix_Chain.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
76#ifndef MATRIX_CHAIN_H
77#define MATRIX_CHAIN_H
78
79#include <limits>
80#include <string>
81#include <cstddef>
82
83#include <ah-errors.H>
84#include <tpl_array.H>
85
86namespace Aleph {
94
95namespace matrix_chain_detail {
96inline size_t checked_add(const size_t a, const size_t b, const char *ctx)
97{
98 ah_runtime_error_if(a > std::numeric_limits<size_t>::max() - b)
99 << "matrix_chain_order: overflow while computing " << ctx;
100 return a + b;
101}
102
103inline size_t checked_mul(const size_t a, const size_t b, const char *ctx)
104{
105 if (a == 0 or b == 0)
106 return 0;
107
108 ah_runtime_error_if(a > std::numeric_limits<size_t>::max() / b)
109 << "matrix_chain_order: overflow while computing " << ctx;
110 return a * b;
111}
112
113inline size_t scalar_cost(const size_t di, const size_t dk, const size_t dj)
114{
115 const size_t lhs = checked_mul(di, dk, "dims[i] * dims[k+1]");
116 return checked_mul(lhs, dj, "dims[i] * dims[k+1] * dims[j+1]");
117}
118
119inline void build_parens(const Array<Array<size_t>> &s, size_t i, size_t j, std::string &out)
120{
121 if (i == j)
122 {
123 out += "A";
124 out += std::to_string(i + 1);
125 return;
126 }
127 out += "(";
128 build_parens(s, i, s[i][j], out);
129 out += " ";
130 build_parens(s, s[i][j] + 1, j, out);
131 out += ")";
132}
133} // namespace matrix_chain_detail
134
154{
155 ah_domain_error_if(dims.size() < 2) << "matrix_chain_order: dims must have at least 2 entries";
156 for (const size_t dim : dims)
157 ah_domain_error_if(dim == 0) << "matrix_chain_order: matrix dimensions must be positive";
158
159 const size_t n = dims.size() - 1; // number of matrices
160 if (n == 1)
161 return Matrix_Chain_Result{0, "A1", Array<Array<size_t>>()};
162
163 // dp[i][j] = min cost of multiplying matrices i..j (0-based)
165 dp.reserve(n);
166 for (size_t i = 0; i < n; ++i)
167 {
169 for (size_t j = 0; j < n; ++j)
170 row(j) = 0;
171 dp.append(std::move(row));
172 }
173
175 split.reserve(n);
176 for (size_t i = 0; i < n; ++i)
177 {
179 for (size_t j = 0; j < n; ++j)
180 row(j) = 0;
181 split.append(std::move(row));
182 }
183
184 // chain length l = 2..n
185 for (size_t l = 2; l <= n; ++l)
186 for (size_t i = 0; i <= n - l; ++i)
187 {
188 const size_t j = i + l - 1;
189 dp[i][j] = std::numeric_limits<size_t>::max();
190 for (size_t k = i; k < j; ++k)
191 {
192 const size_t mul_cost
193 = matrix_chain_detail::scalar_cost(dims[i], dims[k + 1], dims[j + 1]);
194 const size_t subtotal
195 = matrix_chain_detail::checked_add(dp[i][k], dp[k + 1][j], "dp[i][k] + dp[k+1][j]");
196 const size_t cost
197 = matrix_chain_detail::checked_add(subtotal, mul_cost, "dp + scalar multiplications");
198 if (cost < dp[i][j])
199 {
200 dp[i][j] = cost;
201 split[i][j] = k;
202 }
203 }
204 }
205
206 std::string parens;
208
209 return Matrix_Chain_Result{dp[0][n - 1], std::move(parens), std::move(split)};
210}
211
229} // namespace Aleph
230
231#endif // MATRIX_CHAIN_H
Exception handling system with formatted messages for Aleph-w.
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:527
#define ah_runtime_error_if(C)
Throws std::runtime_error if condition holds.
Definition ah-errors.H:271
size_t size_t int32_t * out
Definition ca-c-api.h:120
size_t row
Definition ca-c-api.h:115
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:138
static Array create(size_t n)
Create an array with n logical elements.
Definition tpl_array.H:196
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:250
void reserve(size_t cap)
Reserves cap cells into the array.
Definition tpl_array.H:320
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_dim_function > > dim(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4063
size_t blossom_maximum_cardinality_matching(const GT &g, DynDlist< typename GT::Arc * > &matching, SA sa=SA())
Alias of compute_maximum_cardinality_general_matching().
Definition Blossom.H:466
size_t checked_add(const size_t a, const size_t b, const char *ctx)
size_t scalar_cost(const size_t di, const size_t dk, const size_t dj)
size_t checked_mul(const size_t a, const size_t b, const char *ctx)
void build_parens(const Array< Array< size_t > > &s, size_t i, size_t j, std::string &out)
Main namespace for Aleph-w library functions.
Definition ah-arena.H:89
Matrix_Chain_Result matrix_chain_order(const Array< size_t > &dims)
Compute the optimal matrix-chain multiplication order.
size_t matrix_chain_min_cost(const Array< size_t > &dims)
Compute only the minimum multiplication cost (value only).
std::vector< std::string > & split(const std::string &s, const char delim, std::vector< std::string > &elems)
Split a std::string by a single delimiter character.
Result of matrix-chain multiplication optimization.
Array< Array< size_t > > split
Internal split table used for reconstruction.
size_t min_multiplications
Minimum scalar multiplications required.
std::string parenthesization
Optimal parenthesization string (e.g., "(A1 (A2 A3))").
static int * k
Dynamic array container with automatic resizing.
DynList< int > l