perf(math): route ordinary products through MKL and preserve arithmetic

This commit is contained in:
KOKO\Mimi
2026-10-14 15:09:53 +09:00
parent b4fc1bb54b
commit 59c8e93b07
18 changed files with 793 additions and 169 deletions
+21 -19
View File
@@ -10,6 +10,7 @@
#include <vector>
#include "fesa/fem/dof_manager.h"
#include "math/dense_blas_internal.h"
namespace fesa::eigen_internal {
namespace {
@@ -117,7 +118,8 @@ Result<NodalLift> MakeLift(const Matrix& mass,
if (positive == 0U) return Result<NodalLift>::Success(std::move(result));
const Matrix scaled = ScaledMass(mass, length);
Matrix mp(positive, positive);
Matrix mp = dense_blas_internal::MultiplyTransposeLeft(basis, scaled)
.Multiply(basis);
double scale = 0.0;
double basis_error = 0.0;
for (std::size_t i = 0; i < positive; ++i) {
@@ -125,9 +127,6 @@ Result<NodalLift> MakeLift(const Matrix& mass,
double gram = 0.0;
for (std::size_t a = 0; a < 6U; ++a) {
gram += basis(a, i) * basis(a, j);
for (std::size_t b = 0; b < 6U; ++b) {
mp(i, j) += basis(a, i) * scaled(a, b) * basis(b, j);
}
}
basis_error = std::hypot(basis_error, gram - (i == j ? 1.0 : 0.0));
scale = (std::max)(scale, std::abs(mp(i, j)));
@@ -343,17 +342,18 @@ Result<EigenReduction> BuildEigenReduction(
kz_error = std::hypot(kz_error, item.second);
}
const auto& left = lifts[node];
std::map<std::size_t, Matrix> projected_blocks;
for (const auto& entry : blocks) {
projected_blocks.emplace(
entry.first, dense_blas_internal::MultiplyTransposeLeft(
left.scaled_lift, entry.second)
.Multiply(lifts[entry.first].scaled_lift));
}
for (std::size_t i = 0; i < left.scaled_lift.Columns(); ++i) {
for (const auto& entry : blocks) {
for (const auto& entry : projected_blocks) {
const auto& right = lifts[entry.first];
for (std::size_t j = 0; j < right.scaled_lift.Columns(); ++j) {
double value = 0.0;
for (std::size_t a = 0; a < 6U; ++a) {
for (std::size_t b = 0; b < 6U; ++b) {
value += left.scaled_lift(a, i) * entry.second(a, b) *
right.scaled_lift(b, j);
}
}
const double value = entry.second(i, j);
pattern.column_indices.push_back(right.offset + j);
contributions.push_back({left.offset + i, right.offset + j, value,
node, pattern.column_indices.size() - 1U});
@@ -385,11 +385,12 @@ Vector RestoreScaledMode(const EigenReduction& reduction, const Matrix& vectors,
Vector result(reduction.nodes.size() * 6U);
for (std::size_t node = 0; node < reduction.nodes.size(); ++node) {
const auto& lift = reduction.nodes[node];
Vector reduced{lift.scaled_lift.Columns()};
for (std::size_t j = 0; j < reduced.Size(); ++j)
reduced[j] = vectors(lift.offset + j, column);
const auto restored = lift.scaled_lift.Multiply(reduced);
for (std::size_t a = 0; a < 6U; ++a) {
for (std::size_t j = 0; j < lift.scaled_lift.Columns(); ++j) {
result[6U * node + a] +=
lift.scaled_lift(a, j) * vectors(lift.offset + j, column);
}
result[6U * node + a] = restored[a];
}
}
return result;
@@ -399,10 +400,11 @@ Vector MultiplyNodalMass(const std::vector<Matrix>& mass,
const Vector& vector) {
Vector result(vector.Size());
for (std::size_t node = 0; node < mass.size(); ++node) {
Vector local{6U};
for (std::size_t b = 0; b < 6U; ++b) local[b] = vector[6U * node + b];
const auto product = mass[node].Multiply(local);
for (std::size_t a = 0; a < 6U; ++a) {
for (std::size_t b = 0; b < 6U; ++b) {
result[6U * node + a] += mass[node](a, b) * vector[6U * node + b];
}
result[6U * node + a] = product[a];
}
}
return result;
@@ -32,11 +32,7 @@ Status Failure(const std::string& code, const std::string& identity,
}
double Dot(const Vector& left, const Vector& right) {
double result = 0.0;
for (std::size_t index = 0U; index < left.Size(); ++index) {
result += left[index] * right[index];
}
return result;
return left.Dot(right);
}
double Norm(const Vector& vector) {
@@ -318,8 +314,13 @@ Result<EigenAnalysisState> ExecuteCandidate(const Domain& domain) {
(pencil_scale * y_norm) * y_norm);
const double rayleigh = energy / modal_mass;
Vector x(a.Rows());
for (std::size_t row = 0; row < x.Size(); ++row)
for (std::size_t row = 0; row < x.Size(); ++row) {
x[row] = state.backend.eigenvectors(row, column) * normalization;
if (!std::isfinite(x[row]))
return Result<EigenAnalysisState>::Failure(
Failure("invalid-eigenvalue-result", std::to_string(column),
"Recovered mode is nonfinite or violates constraints."));
}
Vector ax = a.Multiply(x);
Vector whitened_residual = ax;
whitened_residual.Axpy(-lambda, x);
@@ -421,6 +422,10 @@ Result<EigenAnalysisState> LinearFrequencyProcedureExecutor::Execute(
return Result<EigenAnalysisState>::Failure(
Failure("eigen-index-overflow", "modal-workspace",
"Requested workspace exceeds container capacity."));
} catch (const std::runtime_error&) {
return Result<EigenAnalysisState>::Failure(
Failure("eigen-multiplication-failed", "modal-workspace",
"Modal sparse multiplication failed."));
}
}
@@ -248,8 +248,13 @@ Result<SolidFrequencyState> ExecuteCandidate(const Domain& domain) {
mass_phi.reserve(count);
for (std::size_t c = 0; c < count; ++c) {
Vector vector(k.Rows());
for (std::size_t row = 0; row < k.Rows(); ++row)
for (std::size_t row = 0; row < k.Rows(); ++row) {
vector[row] = state.backend.eigenvectors(row, c);
if (!std::isfinite(vector[row]))
return Result<SolidFrequencyState>::Failure(
Failure("solid-eigenpair-validation-failed",
"Modal mass is not finite positive."));
}
Vector mv = m.Multiply(vector);
const double raw_mass = vector.Dot(mv);
if (!(raw_mass > 0.0) || !std::isfinite(raw_mass))
@@ -257,6 +262,12 @@ Result<SolidFrequencyState> ExecuteCandidate(const Domain& domain) {
Failure("solid-eigenpair-validation-failed",
"Modal mass is not finite positive."));
vector.Scale(1.0 / std::sqrt(raw_mass));
for (std::size_t row = 0; row < vector.Size(); ++row) {
if (!std::isfinite(vector[row]))
return Result<SolidFrequencyState>::Failure(
Failure("solid-eigenpair-validation-failed",
"Normalized modal vector is not finite."));
}
mv = m.Multiply(vector);
const Vector kv = k.Multiply(vector);
const double lambda = state.backend.eigenvalues[c];
@@ -362,6 +373,10 @@ Result<SolidFrequencyState> SolidFrequencyProcedureExecutor::Execute(
return Result<SolidFrequencyState>::Failure(
Failure("eigen-allocation-failed",
"Solid modal workspace exceeds addressable storage."));
} catch (const std::runtime_error&) {
return Result<SolidFrequencyState>::Failure(
Failure("eigen-multiplication-failed",
"Solid modal sparse multiplication failed."));
}
}
} // namespace fesa
+52 -14
View File
@@ -3,6 +3,7 @@
#include <algorithm>
#include <cmath>
#include <limits>
#include <stdexcept>
#include <string>
#include <utility>
@@ -116,6 +117,14 @@ Result<Equations> Build(const ThermalSystem& s, const ThermalPartition& p,
constrained[p.constrained[i]] = i;
SparsePattern pattern{{0}, {}};
std::vector<CooContribution> coo;
SparsePattern rhs_pattern{{0U}, {}};
std::vector<CooContribution> capacity_rhs, conductivity_rhs;
Vector capacity_input = old;
Vector prescribed_full{m};
std::vector<bool> capacity_column_used(m, false);
for (std::size_t i = 0; i < p.constrained.size(); ++i) {
prescribed_full[p.constrained[i]] = p.prescribed[i];
}
Vector b{n};
std::vector<I> exact_a, exact_b(n);
for (std::size_t f = 0; f < n; ++f) {
@@ -126,22 +135,43 @@ Result<Equations> Build(const ThermalSystem& s, const ThermalPartition& p,
const auto col = s.c.ColumnIndices()[j];
const double c = s.c.Values()[j], k = s.k.Values()[j];
const I cd = Div(I{c}, I{delta});
rhs_pattern.column_indices.push_back(col);
capacity_column_used[col] = true;
capacity_rhs.push_back({f, col, c / delta, 0U, j});
conductivity_rhs.push_back({f, col, k, 0U, j});
if (free[col] != n) {
coo.push_back({f, free[col], c / delta + k, 0, coo.size()});
pattern.column_indices.push_back(free[col]);
exact_a.push_back(Add(cd, I{k}));
b[f] += (c / delta) * old[col];
exact_b[f] = Add(exact_b[f], Mul(cd, I{old[col]}));
} else {
const double g = p.prescribed[constrained[col]];
// Preserve raw old constrained capacity; never project frame zero.
b[f] += (c / delta) * (old[col] - g) - k * g;
exact_b[f] = Add(exact_b[f],
Sub(Mul(cd, Sub(I{old[col]}, I{g})), Mul(I{k}, I{g})));
}
}
pattern.row_offsets.push_back(coo.size());
rhs_pattern.row_offsets.push_back(capacity_rhs.size());
}
// Do not create overflow in an absent constrained column: the original
// free-row RHS never evaluated that subtraction. Referenced structural
// zeros still evaluate it and reject nonfinite intermediate values.
for (std::size_t i = 0; i < p.constrained.size(); ++i) {
const auto column = p.constrained[i];
if (capacity_column_used[column]) capacity_input[column] -= p.prescribed[i];
}
if (!Finite(capacity_input))
return Result<Equations>::Failure(Failure("Nonfinite backward Euler RHS."));
auto c_rhs = SparseMatrix::FromCoo(n, m, std::move(capacity_rhs), rhs_pattern);
auto k_rhs = SparseMatrix::FromCoo(n, m, std::move(conductivity_rhs),
rhs_pattern);
if (!c_rhs.HasValue() || !k_rhs.HasValue())
return Result<Equations>::Failure(Failure("Nonfinite backward Euler RHS."));
const auto capacity_action = c_rhs.Value().Multiply(capacity_input);
const auto conductivity_action = k_rhs.Value().Multiply(prescribed_full);
for (std::size_t f = 0; f < n; ++f)
b[f] += capacity_action[f] - conductivity_action[f];
auto a = SparseMatrix::FromCoo(n, n, std::move(coo), pattern);
if (!a.HasValue()) return Result<Equations>::Failure(a.GetStatus());
if (!Finite(b))
@@ -178,13 +208,15 @@ Status Check(const ThermalSystem& s, const ThermalPartition& p,
I a_norm, t_norm, b_norm = Norm(eq.b);
Vector red{n}, red_error{n};
std::vector<I> construction(n);
Vector free_temperature{n};
for (std::size_t f = 0; f < n; ++f)
free_temperature[f] = candidate.temperature[p.free[f]];
const auto reduced_action = eq.a.Multiply(free_temperature);
for (std::size_t f = 0; f < n; ++f) {
I row_norm, scale, ea, identity;
double dot = 0;
for (auto j = eq.a.RowOffsets()[f]; j < eq.a.RowOffsets()[f + 1]; ++j) {
const double a = eq.a.Values()[j],
t = candidate.temperature[p.free[eq.a.ColumnIndices()[j]]];
dot += a * t;
row_norm = Add(row_norm, Magnitude(a));
scale = Add(scale, Mul(Magnitude(a), Magnitude(t)));
const I error{Error(eq.exact_a[j], a)};
@@ -193,7 +225,7 @@ Status Check(const ThermalSystem& s, const ThermalPartition& p,
}
a_norm = Max(a_norm, row_norm);
t_norm = Max(t_norm, Magnitude(candidate.temperature[p.free[f]]));
red[f] = dot - eq.b[f];
red[f] = reduced_action[f] - eq.b[f];
scale = Add(scale, Magnitude(eq.b[f]));
const double nu =
static_cast<double>(eq.a.RowOffsets()[f + 1] - eq.a.RowOffsets()[f]);
@@ -216,18 +248,19 @@ Status Check(const ThermalSystem& s, const ThermalPartition& p,
for (std::size_t i = 0; i < m; ++i)
change[i] = candidate.temperature[i] - old[i];
if (!Finite(change)) return Failure("Nonfinite temperature change.");
const auto capacity_change = s.c.Multiply(change);
const auto conductivity_new = s.k.Multiply(candidate.temperature);
I c_change, k_new, q_abs, c_temperatures, underflow_sum;
std::vector<I> k_columns(m);
double energy = 0;
for (std::size_t i = 0; i < m; ++i) {
double cd = 0, kt = 0, ksum = 0;
const double cd = capacity_change[i], kt = conductivity_new[i];
double ksum = 0;
I cs, ks, ts, cabs, nullscale, nullerror, coefficient;
for (auto j = s.c.RowOffsets()[i]; j < s.c.RowOffsets()[i + 1]; ++j) {
const auto col = s.c.ColumnIndices()[j];
const double c = s.c.Values()[j], k = s.k.Values()[j],
t = candidate.temperature[col];
cd += c * change[col];
kt += k * t;
ksum += k;
cs = Add(cs, Mul(Magnitude(c), Magnitude(change[col])));
ks = Add(ks, Mul(Magnitude(k), Magnitude(t)));
@@ -334,10 +367,13 @@ Status Check(const ThermalSystem& s, const ThermalPartition& p,
if (p.constrained.empty() && Zero(q_abs)) {
ev.dissipation_checked = true;
double cn = 0, co = 0, cd = 0, kn = 0;
const auto capacity_new = s.c.Multiply(candidate.temperature);
const auto capacity_old = s.c.Multiply(old);
I sc, subscale, t_one, d_square, o_square, skew_square, quadratic_underflow;
for (std::size_t i = 0; i < m; ++i) {
const double t = candidate.temperature[i];
double row_cn = 0, row_co = 0, row_cd = 0, row_kn = 0;
const double row_cn = capacity_new[i], row_co = capacity_old[i],
row_cd = capacity_change[i], row_kn = conductivity_new[i];
I scale_cn, scale_co, scale_cd, scale_kn;
t_one = Add(t_one, Magnitude(t));
d_square = Add(d_square, Mul(Magnitude(change[i]), Magnitude(change[i])));
@@ -345,10 +381,6 @@ Status Check(const ThermalSystem& s, const ThermalPartition& p,
for (auto j = s.c.RowOffsets()[i]; j < s.c.RowOffsets()[i + 1]; ++j) {
const auto col = s.c.ColumnIndices()[j];
const double c = s.c.Values()[j], k = s.k.Values()[j];
row_cn += c * candidate.temperature[col];
row_co += c * old[col];
row_cd += c * change[col];
row_kn += k * candidate.temperature[col];
scale_cn = Add(
scale_cn, Mul(Magnitude(c), Magnitude(candidate.temperature[col])));
scale_co = Add(scale_co, Mul(Magnitude(c), Magnitude(old[col])));
@@ -421,7 +453,7 @@ Status Check(const ThermalSystem& s, const ThermalPartition& p,
Result<ThermalStepCandidate> SolveThermalIncrement(
const ThermalSystem& s, const ThermalPartition& p, const Vector& old,
double delta, LinearSolver& solver, ThermalFactorization& cache) {
double delta, LinearSolver& solver, ThermalFactorization& cache) try {
auto status = Validate(s, p, old, delta);
if (!status.IsOk()) return Result<ThermalStepCandidate>::Failure(status);
auto equations = Build(s, p, old, delta);
@@ -461,6 +493,12 @@ Result<ThermalStepCandidate> SolveThermalIncrement(
status = Check(s, p, old, delta, equations.Value(), candidate);
if (!status.IsOk()) return Result<ThermalStepCandidate>::Failure(status);
return Result<ThermalStepCandidate>::Success(std::move(candidate));
} catch (const std::length_error&) {
return Result<ThermalStepCandidate>::Failure(
Failure("Thermal sparse action exceeds the backend integer range."));
} catch (const std::runtime_error&) {
return Result<ThermalStepCandidate>::Failure(
Failure("Thermal sparse action failed."));
}
Status RunThermalHistory(const ThermalAssembly& assembly,
+18 -23
View File
@@ -12,6 +12,7 @@
#include "fesa/math/vector3.h"
#include "fesa/model/model_types.h"
#include "math/dense_blas_internal.h"
namespace fesa {
@@ -228,10 +229,9 @@ double NormalizedMatrixError(const Matrix& lhs, const Matrix& rhs) {
std::array<double, kGeneralizedComponentCount> GeneralizedStrain(
const Matrix& b, const Vector& local_displacement) {
std::array<double, kGeneralizedComponentCount> strain{};
const auto product = b.Multiply(local_displacement);
for (std::size_t component = 0; component < strain.size(); ++component) {
for (std::size_t dof = 0; dof < local_displacement.Size(); ++dof) {
strain[component] += b(component, dof) * local_displacement[dof];
}
strain[component] = product[component];
}
return strain;
}
@@ -395,13 +395,15 @@ Matrix EulerBeam3D::LocalStiffness() const {
// Both Gauss points are required: a one-point bending rule loses two ranks.
for (const double xi : gauss_points) {
const Matrix b = StrainDisplacement(xi, length_);
Matrix weighted_b = b;
for (std::size_t component = 0; component < diagonal.size(); ++component)
for (std::size_t column = 0; column < kElementDofCount; ++column)
weighted_b(component, column) *= diagonal[component];
const auto contribution =
dense_blas_internal::MultiplyTransposeLeft(b, weighted_b);
for (std::size_t row = 0; row < kElementDofCount; ++row) {
for (std::size_t column = 0; column < kElementDofCount; ++column) {
for (std::size_t component = 0; component < diagonal.size();
++component) {
stiffness(row, column) += b(component, row) * diagonal[component] *
b(component, column) * jacobian;
}
stiffness(row, column) += contribution(row, column) * jacobian;
}
}
}
@@ -418,22 +420,17 @@ Matrix EulerBeam3D::GlobalStiffness() const {
const Matrix local = LocalStiffness();
const Matrix transform = Transformation(rotation_);
const Matrix local_times_transform = local.Multiply(transform);
Matrix global{kElementDofCount, kElementDofCount};
// Kg=T^T*Kl*T while dl=T*dg.
for (std::size_t row = 0; row < kElementDofCount; ++row) {
for (std::size_t column = 0; column < kElementDofCount; ++column) {
for (std::size_t inner = 0; inner < kElementDofCount; ++inner) {
global(row, column) +=
transform(inner, row) * local_times_transform(inner, column);
}
}
}
return global;
return dense_blas_internal::MultiplyTransposeLeft(transform,
local_times_transform);
}
Vector EulerBeam3D::LocalEquivalentLoad(
const ConstantLocalLineLoad& load) const {
const std::array<double, 4> components = {load.px, load.py, load.pz, load.mx};
Matrix component_column{components.size(), 1U};
for (std::size_t component = 0; component < components.size(); ++component)
component_column(component, 0U) = components[component];
Vector equivalent{kElementDofCount};
const double inverse_sqrt_three = 1.0 / std::sqrt(3.0);
const std::array<double, 2> gauss_points = {-inverse_sqrt_three,
@@ -441,12 +438,10 @@ Vector EulerBeam3D::LocalEquivalentLoad(
const double jacobian = 0.5 * length_;
for (const double xi : gauss_points) {
const Matrix interpolation = KinematicInterpolation(xi, length_);
const auto contribution = dense_blas_internal::MultiplyTransposeLeft(
interpolation, component_column);
for (std::size_t dof = 0; dof < equivalent.Size(); ++dof) {
for (std::size_t component = 0; component < components.size();
++component) {
equivalent[dof] +=
interpolation(component, dof) * components[component] * jacobian;
}
equivalent[dof] += contribution(dof, 0U) * jacobian;
}
}
return equivalent;
+11
View File
@@ -5,6 +5,17 @@
namespace fesa::dense_blas_internal {
Matrix MultiplyTransposeLeft(const Matrix& left, const Matrix& right) {
if (left.Rows() != right.Rows()) {
throw std::invalid_argument{"Transpose product dimensions differ."};
}
Matrix transposed{left.Columns(), left.Rows()};
for (std::size_t row = 0; row < left.Rows(); ++row)
for (std::size_t column = 0; column < left.Columns(); ++column)
transposed(column, row) = left(row, column);
return transposed.Multiply(right);
}
Result<MKL_INT> ToMklSize(const std::size_t size) {
if (size > static_cast<std::size_t>((std::numeric_limits<MKL_INT>::max)())) {
return Result<MKL_INT>::Failure(Status::Failure(
+5
View File
@@ -6,6 +6,7 @@
#include <cstddef>
#include "fesa/core/status.h"
#include "fesa/math/matrix.h"
namespace fesa::dense_blas_internal {
@@ -13,6 +14,10 @@ namespace fesa::dense_blas_internal {
/// @return The converted length or an uncategorized overflow failure.
Result<MKL_INT> ToMklSize(std::size_t size);
/// @brief Computes left-transpose times right through ordinary dense MKL.
/// @throws std::invalid_argument if the row counts differ.
Matrix MultiplyTransposeLeft(const Matrix& left, const Matrix& right);
/// @brief Copies contiguous double values through the private BLAS backend.
/// @param source Readable storage for size values when size is nonzero.
/// @param size Number of contiguous values to copy.
+24 -10
View File
@@ -4,6 +4,8 @@
#include <cmath>
#include <cfenv>
#include <cstdint>
#include <cstring>
#include <initializer_list>
#include <limits>
#if defined(_M_X64) || defined(__SSE2__)
#include <xmmintrin.h>
@@ -56,9 +58,9 @@ inline bool IsNormalized(HighLow value) {
if (!IsFinite(value)) return false;
if (value.high == 0 && value.low == 0)
return !std::signbit(value.high) && !std::signbit(value.low);
const auto normalized = TwoSum(value.high, value.low);
return IsFinite(normalized) && normalized.high == value.high &&
normalized.low == value.low;
// If RN(high + low) == high, TwoSum's bridge is zero and its error is
// exactly low. The finite and canonical exact-zero guards remain above.
return value.high + value.low == value.high;
}
/// @brief Rounds the full physical value to one finite output value.
inline double Rounded(HighLow value) {
@@ -92,15 +94,27 @@ inline HighLow Subtract(HighLow left, HighLow right) {
/// @brief Returns the exponent of the least nonzero binary64 significand bit.
/// @pre value is finite and nonzero; gradual underflow is enabled.
inline int LowestBitExponent(double value) {
int exponent = 0;
const double fraction = std::frexp(std::abs(value), &exponent);
auto significand = static_cast<std::uint64_t>(std::ldexp(fraction, 53));
static_assert(sizeof(double) == sizeof(std::uint64_t) &&
std::numeric_limits<double>::is_iec559 &&
std::numeric_limits<double>::digits == 53);
std::uint64_t bits = 0;
std::memcpy(&bits, &value, sizeof(bits));
const auto encoded_exponent = (bits >> 52U) & 0x7ffU;
auto significand = bits & 0xfffffffffffffULL;
const int exponent = encoded_exponent == 0U
? -1074
: static_cast<int>(encoded_exponent) - 1075;
if (encoded_exponent != 0U) significand |= 1ULL << 52U;
int trailing = 0;
while ((significand & 1U) == 0U) {
significand >>= 1U;
++trailing;
// Strip large zero groups first without vendor/compiler intrinsics.
for (const int shift : {32, 16, 8, 4, 2, 1}) {
const auto mask = (1ULL << shift) - 1U;
if ((significand & mask) == 0U) {
significand >>= shift;
trailing += shift;
}
}
return exponent - 53 + trailing;
return exponent + trailing;
}
/// @brief Gives a product and its FMA residual when the dyadic tail fits.
/// @note Rejects underflow-risk exact tails, even if the rounded high is finite.
+74 -9
View File
@@ -8,11 +8,49 @@
#include <tuple>
#include <utility>
#include <mkl.h>
#include "fesa/fem/dof_manager.h"
#include "math/dense_blas_internal.h"
namespace fesa {
namespace {
/// @brief Checks the actual private backend integer width before conversion.
MKL_INT SparseSize(const std::size_t size) {
const auto converted = dense_blas_internal::ToMklSize(size);
if (!converted.HasValue()) {
throw std::length_error{"Sparse size exceeds the MKL integer range."};
}
return converted.Value();
}
/// @brief Releases a call-local sparse handle before its borrowed arrays die.
class SparseHandle {
public:
SparseHandle() = default;
SparseHandle(const SparseHandle&) = delete;
SparseHandle& operator=(const SparseHandle&) = delete;
~SparseHandle() {
if (handle != nullptr) static_cast<void>(mkl_sparse_destroy(handle));
}
/// @brief Reports normal release failure before publishing the candidate.
sparse_status_t Destroy() {
const auto owned = handle;
handle = nullptr;
return mkl_sparse_destroy(owned);
}
sparse_matrix_t handle{nullptr};
};
/// @brief Fails explicitly instead of substituting a scalar backend.
void CheckSparseStatus(const sparse_status_t status, const char* operation) {
if (status != SPARSE_STATUS_SUCCESS) {
throw std::runtime_error{std::string{"Sparse backend "} + operation +
" failed."};
}
}
/// @brief Builds a structured sparse-matrix model failure.
Status SparseFailure(const std::string& code, const std::string& identity,
const std::string& message) {
@@ -170,16 +208,43 @@ Vector SparseMatrix::Multiply(const Vector& rhs) const {
throw std::invalid_argument{
"Sparse matrix-vector multiplication has incompatible dimensions."};
}
Vector result{rows_};
for (std::size_t row = 0U; row < rows_; ++row) {
double value = 0.0;
for (std::size_t position = row_offsets_[row];
position < row_offsets_[row + 1U]; ++position) {
value += values_[position] * rhs[column_indices_[position]];
}
result[row] = value;
if (!Validate().IsOk()) {
throw std::invalid_argument{"Sparse multiplication requires valid CSR."};
}
const MKL_INT rows = SparseSize(rows_);
const MKL_INT columns = SparseSize(columns_);
static_cast<void>(SparseSize(values_.size()));
Vector result{rows_};
if (rows == 0 || columns == 0 || values_.empty()) return result;
// Each const call owns its converted arrays and handle. Neither copy/move
// nor concurrent calls retain pointers into another call's storage.
std::vector<MKL_INT> row_offsets;
std::vector<MKL_INT> column_indices;
row_offsets.reserve(row_offsets_.size());
column_indices.reserve(column_indices_.size());
for (const auto offset : row_offsets_) {
row_offsets.push_back(SparseSize(offset));
}
for (const auto column : column_indices_) {
column_indices.push_back(SparseSize(column));
}
auto values = values_;
SparseHandle sparse;
CheckSparseStatus(
mkl_sparse_d_create_csr(&sparse.handle, SPARSE_INDEX_BASE_ZERO, rows,
columns, row_offsets.data(),
row_offsets.data() + 1, column_indices.data(),
values.data()),
"create CSR");
const matrix_descr descriptor{SPARSE_MATRIX_TYPE_GENERAL,
SPARSE_FILL_MODE_FULL,
SPARSE_DIAG_NON_UNIT};
CheckSparseStatus(
mkl_sparse_d_mv(SPARSE_OPERATION_NON_TRANSPOSE, 1.0, sparse.handle,
descriptor, rhs.Data(), 0.0, result.Data()),
"multiply");
CheckSparseStatus(sparse.Destroy(), "destroy CSR");
return result;
}
@@ -5,6 +5,7 @@
#include <cmath>
#include <cstddef>
#include <limits>
#include <stdexcept>
#include <string>
#include <vector>
@@ -26,33 +27,25 @@ double IndexedNorm(const Vector& values,
return result;
}
/// @brief Computes separate Kff*df and Kfc*dc norms in stable CSR order.
/// @brief Computes separate Kff*df and Kfc*dc norms through sparse MKL.
std::array<double, 2> FreeEquationInternalTermNorms(
const SparseMatrix& stiffness, const Vector& displacement,
const DofManager& dofs) {
std::vector<unsigned char> free_column(dofs.FullDofCount(), 0U);
Vector free_displacement{displacement.Size()};
Vector constrained_displacement = displacement;
for (const std::size_t full_dof : dofs.FreeDofs()) {
free_column[full_dof] = 1U;
free_displacement[full_dof] = displacement[full_dof];
constrained_displacement[full_dof] = 0.0;
}
const auto free_term = stiffness.Multiply(free_displacement);
const auto constrained_term = stiffness.Multiply(constrained_displacement);
double free_term_norm = 0.0;
double constrained_term_norm = 0.0;
for (const std::size_t row : dofs.FreeDofs()) {
double free_term = 0.0;
double constrained_term = 0.0;
for (std::size_t position = stiffness.RowOffsets()[row];
position < stiffness.RowOffsets()[row + 1U]; ++position) {
const std::size_t column = stiffness.ColumnIndices()[position];
const double contribution =
stiffness.Values()[position] * displacement[column];
if (free_column[column] != 0U) {
free_term += contribution;
} else {
constrained_term += contribution;
}
}
free_term_norm = std::hypot(free_term_norm, free_term);
constrained_term_norm = std::hypot(constrained_term_norm, constrained_term);
// Only the original free-row terms enter these acceptance scales.
free_term_norm = std::hypot(free_term_norm, free_term[row]);
constrained_term_norm =
std::hypot(constrained_term_norm, constrained_term[row]);
}
return {free_term_norm, constrained_term_norm};
}
@@ -96,7 +89,7 @@ double NormalizedBalance(const std::array<double, 3>& balance,
Result<GlobalEquilibriumResult> GlobalEquilibriumRecovery(
const Domain& domain, const DofManager& dofs,
const SparseMatrix& full_stiffness, const Vector& full_displacement,
const Vector& full_external_force) {
const Vector& full_external_force) try {
const std::size_t full_count = dofs.FullDofCount();
if (full_stiffness.Rows() != full_count ||
full_stiffness.Columns() != full_count ||
@@ -171,6 +164,15 @@ Result<GlobalEquilibriumResult> GlobalEquilibriumRecovery(
// shell global equilibrium below separately filters constrained reactions.
result.reaction = result.residual;
return Result<GlobalEquilibriumResult>::Success(std::move(result));
} catch (const std::length_error&) {
return RecoveryResultFailure<GlobalEquilibriumResult>(
"recovery-index-overflow", {domain.SourcePath(), 0U},
domain.SourceContentIdentity(),
"Recovery multiplication exceeds the backend integer range.");
} catch (const std::runtime_error&) {
return RecoveryResultFailure<GlobalEquilibriumResult>(
"recovery-multiplication-failed", {domain.SourcePath(), 0U},
domain.SourceContentIdentity(), "Recovery sparse multiplication failed.");
}
Status RecoverShellGlobalEvidence(const Domain& domain, const DofManager& dofs,
@@ -12,11 +12,13 @@
#include <new>
#include <numeric>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include "fesa/math/sparse_matrix.h"
#include "fesa/fem/dof_manager.h"
#include "fesa/math/vector.h"
#include "fesa/solvers/linear/mkl_pardiso_solver.h"
#include "solvers/eigen/mkl_feast_eigen_solver_test_seam.h"
@@ -186,6 +188,37 @@ Result<Csr> CopyUpperOneBased(const SparseMatrix& matrix, const double scale) {
return Result<Csr>::Success(std::move(copy));
}
/// @brief Keeps the independently scaled full or upper-mirrored operator.
Result<SparseMatrix> ScaledActionMatrix(const SparseMatrix& matrix,
const double scale,
const bool mirror_upper = false) {
std::vector<CooContribution> contributions;
std::vector<std::vector<std::size_t>> columns(matrix.Rows());
for (std::size_t row = 0; row < matrix.Rows(); ++row) {
for (auto position = matrix.RowOffsets()[row];
position < matrix.RowOffsets()[row + 1U]; ++position) {
const auto column = matrix.ColumnIndices()[position];
if (mirror_upper && column < row) continue;
const auto value = matrix.Values()[position] / scale;
columns[row].push_back(column);
contributions.push_back({row, column, value, row, position});
if (mirror_upper && column != row) {
columns[column].push_back(row);
contributions.push_back({column, row, value, row, position});
}
}
}
SparsePattern pattern{{0U}, {}};
for (auto& row : columns) {
std::sort(row.begin(), row.end());
pattern.column_indices.insert(pattern.column_indices.end(), row.begin(),
row.end());
pattern.row_offsets.push_back(pattern.column_indices.size());
}
return SparseMatrix::FromCoo(matrix.Rows(), matrix.Columns(),
std::move(contributions), pattern);
}
Result<Csr> IdentityOneBased(const std::size_t size) {
if (!FitsMkl(size) || !FitsMkl(size + 1U)) {
return Result<Csr>::Failure(
@@ -321,13 +354,11 @@ bool FillInitialBasis(std::vector<double>& vectors, const std::size_t n,
}
for (double& value : reflector) value /= reflector_norm;
for (std::size_t target = column; target < columns; ++target) {
double dot = 0.0;
for (std::size_t row = column; row < n; ++row) {
dot += reflector[row - column] * vectors[row + target * n];
}
for (std::size_t row = column; row < n; ++row) {
vectors[row + target * n] -= 2.0 * reflector[row - column] * dot;
}
const auto length = static_cast<MKL_INT>(n - column);
auto* target_column = vectors.data() + column + target * n;
const double dot = cblas_ddot(length, reflector.data(), 1,
target_column, 1);
cblas_daxpy(length, -2.0 * dot, reflector.data(), 1, target_column, 1);
}
reflectors.push_back(std::move(reflector));
}
@@ -338,13 +369,11 @@ bool FillInitialBasis(std::vector<double>& vectors, const std::size_t n,
const std::size_t column = index - 1U;
const auto& reflector = reflectors[column];
for (std::size_t target = 0U; target < columns; ++target) {
double dot = 0.0;
for (std::size_t row = column; row < n; ++row) {
dot += reflector[row - column] * vectors[row + target * n];
}
for (std::size_t row = column; row < n; ++row) {
vectors[row + target * n] -= 2.0 * reflector[row - column] * dot;
}
const auto length = static_cast<MKL_INT>(n - column);
auto* target_column = vectors.data() + column + target * n;
const double dot = cblas_ddot(length, reflector.data(), 1,
target_column, 1);
cblas_daxpy(length, -2.0 * dot, reflector.data(), 1, target_column, 1);
}
}
for (std::size_t column = 0U; column < columns; ++column)
@@ -353,10 +382,9 @@ bool FillInitialBasis(std::vector<double>& vectors, const std::size_t n,
double gram_error = 0.0;
for (std::size_t left = 0U; left < columns; ++left) {
for (std::size_t right = 0U; right < columns; ++right) {
double dot = 0.0;
for (std::size_t row = 0U; row < n; ++row) {
dot += vectors[row + left * n] * vectors[row + right * n];
}
const double dot = cblas_ddot(static_cast<MKL_INT>(n),
vectors.data() + left * n, 1,
vectors.data() + right * n, 1);
gram_error = std::hypot(gram_error, dot - (left == right ? 1.0 : 0.0));
}
}
@@ -390,7 +418,7 @@ Result<FeastEigenResult> MklFeastEigenSolver::Solve(
Result<FeastEigenResult> MklFeastEigenSolver::SolveImpl(
const SparseMatrix& whitened_operator, const SparseMatrix* mass,
const std::size_t requested_modes, const double zero_operator_scale,
const double mass_lower_bound) const {
const double mass_lower_bound) const try {
static_assert(sizeof(MKL_INT) == 8U,
"FEAST requires the installed ILP64 ABI.");
const Status csr_status = whitened_operator.Validate();
@@ -472,6 +500,9 @@ Result<FeastEigenResult> MklFeastEigenSolver::SolveImpl(
auto b =
mass != nullptr ? CopyUpperOneBased(*mass, 1.0) : IdentityOneBased(n);
if (!b.HasValue()) return Result<FeastEigenResult>::Failure(b.GetStatus());
auto action_matrix = ScaledActionMatrix(whitened_operator, operator_scale);
if (!action_matrix.HasValue())
return Result<FeastEigenResult>::Failure(action_matrix.GetStatus());
double lower = -1.0;
double upper = 1.0;
@@ -1045,13 +1076,11 @@ Result<FeastEigenResult> MklFeastEigenSolver::SolveImpl(
"eigen-endpoint-separation", std::to_string(input),
"A returned FEAST eigenvalue is too close to a solve endpoint."));
}
double norm = 0.0;
Vector raw(n);
for (std::size_t row = 0U; row < n; ++row)
norm += vectors[row + input * n] * vectors[row + input * n];
raw[row] = vectors[row + input * n];
double norm = raw.Dot(raw);
if (mass != nullptr) {
Vector raw(n);
for (std::size_t row = 0U; row < n; ++row)
raw[row] = vectors[row + input * n];
norm = raw.Dot(mass->Multiply(raw));
}
norm = std::sqrt(norm);
@@ -1060,21 +1089,10 @@ Result<FeastEigenResult> MklFeastEigenSolver::SolveImpl(
TraceFailure("eigenpair-validation-failed", std::to_string(input),
"FEAST returned a non-normalizable eigenvector."));
double residual_norm = 0.0;
const auto action = action_matrix.Value().Multiply(raw);
const auto mass_action = mass != nullptr ? mass->Multiply(raw) : raw;
for (std::size_t row = 0U; row < n; ++row) {
double ax = 0.0;
for (std::size_t p = offsets[row]; p < offsets[row + 1U]; ++p) {
ax += values[p] / operator_scale *
vectors[whitened_operator.ColumnIndices()[p] + input * n];
}
double mx = vectors[row + input * n];
if (mass != nullptr) {
mx = 0.0;
for (std::size_t p = mass->RowOffsets()[row];
p < mass->RowOffsets()[row + 1U]; ++p)
mx +=
mass->Values()[p] * vectors[mass->ColumnIndices()[p] + input * n];
}
const double difference = ax - mu * mx;
const double difference = action[row] - mu * mass_action[row];
residual_norm += difference * difference;
ordered_vectors(row, output) = vectors[row + input * n] / norm;
}
@@ -1109,20 +1127,11 @@ Result<FeastEigenResult> MklFeastEigenSolver::SolveImpl(
FormatDouble(rho_b) + ", mu=" + FormatDouble(mu) +
"; calls=" + CallHistory(calls)));
const FeastBackendCall& last_call = calls.back();
std::vector<double> mirrored_action(n, 0.0);
std::vector<double> full_action(n, 0.0);
for (std::size_t row = 0U; row < n; ++row) {
for (std::size_t p = offsets[row]; p < offsets[row + 1U]; ++p) {
const std::size_t column = whitened_operator.ColumnIndices()[p];
const double entry = values[p] / operator_scale;
full_action[row] += entry * vectors[column + input * n];
if (column < row) continue;
mirrored_action[row] += entry * vectors[column + input * n];
if (column != row) {
mirrored_action[column] += entry * vectors[row + input * n];
}
}
}
auto mirrored_matrix =
ScaledActionMatrix(whitened_operator, operator_scale, true);
if (!mirrored_matrix.HasValue())
return Result<FeastEigenResult>::Failure(mirrored_matrix.GetStatus());
const auto mirrored_action = mirrored_matrix.Value().Multiply(raw);
double mirrored_residual_squared = 0.0;
double action_difference_squared = 0.0;
for (std::size_t row = 0U; row < n; ++row) {
@@ -1130,7 +1139,7 @@ Result<FeastEigenResult> MklFeastEigenSolver::SolveImpl(
mirrored_action[row] - mu * vectors[row + input * n];
mirrored_residual_squared += mirrored_residual * mirrored_residual;
const double action_difference =
full_action[row] - mirrored_action[row];
action[row] - mirrored_action[row];
action_difference_squared += action_difference * action_difference;
}
const double rho_b_upper = std::sqrt(mirrored_residual_squared) / norm;
@@ -1174,22 +1183,20 @@ Result<FeastEigenResult> MklFeastEigenSolver::SolveImpl(
}
double gram_error = 0.0;
double gram_squared = 0.0;
std::vector<Vector> mass_modes;
mass_modes.reserve(count);
for (std::size_t right = 0; right < count; ++right) {
Vector mode(n);
for (std::size_t row = 0; row < n; ++row)
mode[row] = ordered_vectors(row, right);
mass_modes.push_back(mass != nullptr ? mass->Multiply(mode)
: std::move(mode));
}
for (std::size_t left = 0U; left < count; ++left) {
for (std::size_t right = 0U; right < count; ++right) {
double dot = 0.0;
for (std::size_t row = 0U; row < n; ++row)
dot += ordered_vectors(row, left) * ordered_vectors(row, right);
if (mass != nullptr) {
dot = 0.0;
for (std::size_t row = 0U; row < n; ++row) {
double action = 0.0;
for (std::size_t p = mass->RowOffsets()[row];
p < mass->RowOffsets()[row + 1U]; ++p)
action += mass->Values()[p] *
ordered_vectors(mass->ColumnIndices()[p], right);
dot += ordered_vectors(row, left) * action;
}
}
dot += ordered_vectors(row, left) * mass_modes[right][row];
const double expected = left == right ? 1.0 : 0.0;
const double difference = std::abs(dot - expected);
gram_squared += difference * difference;
@@ -1233,6 +1240,14 @@ Result<FeastEigenResult> MklFeastEigenSolver::SolveImpl(
solve_upper,
upper_search_termination};
return Result<FeastEigenResult>::Success(std::move(result));
} catch (const std::length_error&) {
return Result<FeastEigenResult>::Failure(
Failure("feast-integer-overflow", "independent-action",
"Independent sparse action exceeds the backend range."));
} catch (const std::runtime_error&) {
return Result<FeastEigenResult>::Failure(
Failure("eigen-multiplication-failed", "independent-action",
"Independent sparse action failed."));
}
} // namespace fesa