Sleipnir C++ API
Loading...
Searching...
No Matches
ruiz_equilibration.hpp
1// Copyright (c) Sleipnir contributors
2
3#pragma once
4
5#include <algorithm>
6#include <cmath>
7
8#include <Eigen/Core>
9#include <Eigen/SparseCore>
10
11namespace slp {
12
20template <typename Scalar>
22 public:
24 using DenseVector = Eigen::VectorX<Scalar>;
26 using SparseMatrix = Eigen::SparseMatrix<Scalar>;
27
31 void compute(const SparseMatrix& lower) {
32 using std::abs;
33
34 // Each sweep moves every row's largest entry closer to 1. A few are enough
35 // because the pivot tests only need rough scaling.
36 constexpr int num_sweeps = 3;
37
38 const int size = lower.rows();
39 const Scalar* values = lower.valuePtr();
40 const auto* outer = lower.outerIndexPtr();
41 const auto* inner = lower.innerIndexPtr();
42
43 m_scale.setOnes(size);
44 m_row_max.resize(size);
45 for (int sweep = 0; sweep < num_sweeps; ++sweep) {
46 m_row_max.setZero();
47 for (int col = 0; col < size; ++col) {
48 const Scalar col_scale = m_scale[col];
49 Scalar col_max{0};
50 for (auto k = outer[col]; k < outer[col + 1]; ++k) {
51 const int row = inner[k];
52 const Scalar value = abs(values[k]) * m_scale[row] * col_scale;
53 m_row_max[row] = std::max(m_row_max[row], value);
54 col_max = std::max(col_max, value);
55 }
56 m_row_max[col] = std::max(m_row_max[col], col_max);
57 }
58
59 // Empty rows keep their scale
60 m_row_max = (m_row_max.array() > Scalar(0)).select(m_row_max, Scalar(1));
61 m_scale.array() /= m_row_max.array().sqrt();
62 }
63 }
64
71 const Scalar* values = lower.valuePtr();
72 const auto* outer = lower.outerIndexPtr();
73 const auto* inner = lower.innerIndexPtr();
74 Scalar* scaled_values = scaled.valuePtr();
75
76 for (int col = 0; col < lower.cols(); ++col) {
77 const Scalar col_scale = m_scale[col];
78 for (auto k = outer[col]; k < outer[col + 1]; ++k) {
79 scaled_values[k] = values[k] * (m_scale[inner[k]] * col_scale);
80 }
81 }
82 }
83
87 const DenseVector& scale() const { return m_scale; }
88
89 private:
91 DenseVector m_scale;
92
94 DenseVector m_row_max;
95};
96
97} // namespace slp
Definition intrusive_shared_ptr.hpp:27
Definition ruiz_equilibration.hpp:21
Eigen::SparseMatrix< Scalar > SparseMatrix
Type alias for sparse matrix.
Definition ruiz_equilibration.hpp:26
Eigen::VectorX< Scalar > DenseVector
Type alias for dense vector.
Definition ruiz_equilibration.hpp:24
void compute(const SparseMatrix &lower)
Definition ruiz_equilibration.hpp:31
void apply(const SparseMatrix &lower, SparseMatrix &scaled) const
Definition ruiz_equilibration.hpp:70
const DenseVector & scale() const
Definition ruiz_equilibration.hpp:87