Eigen  5.0.1
 
Loading...
Searching...
No Matches
SparseDenseProduct.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2008-2015 Gael Guennebaud <gael.guennebaud@inria.fr>
5//
6// This Source Code Form is subject to the terms of the Mozilla
7// Public License v. 2.0. If a copy of the MPL was not distributed
8// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9// SPDX-License-Identifier: MPL-2.0
10
11#ifndef EIGEN_SPARSEDENSEPRODUCT_H
12#define EIGEN_SPARSEDENSEPRODUCT_H
13
14// IWYU pragma: private
15#include "./InternalHeaderCheck.h"
16
17namespace Eigen {
18
19namespace internal {
20
21template <>
22struct product_promote_storage_type<Sparse, Dense, OuterProduct> {
23 using ret = Sparse;
24};
25template <>
26struct product_promote_storage_type<Dense, Sparse, OuterProduct> {
27 using ret = Sparse;
28};
29
30// Type trait to detect if a sparse type supports direct compressed storage access
31// (i.e., has valuePtr(), innerIndexPtr(), outerIndexPtr(), isCompressed()).
32// All types deriving from SparseCompressedBase provide these methods.
33template <typename T>
34struct has_compressed_storage : std::is_base_of<SparseCompressedBase<T>, T> {};
35
36template <typename SparseLhsType, typename DenseRhsType, typename DenseResType, typename AlphaType,
37 int LhsStorageOrder = ((SparseLhsType::Flags & RowMajorBit) == RowMajorBit) ? RowMajor : ColMajor,
38 bool ColPerCol = ((DenseRhsType::Flags & RowMajorBit) == 0) || DenseRhsType::ColsAtCompileTime == 1>
39struct sparse_time_dense_product_impl;
40
41// RowMajor, single column (ColPerCol=true): CSR SpMV
42template <typename SparseLhsType, typename DenseRhsType, typename DenseResType>
43struct sparse_time_dense_product_impl<SparseLhsType, DenseRhsType, DenseResType, typename DenseResType::Scalar,
44 RowMajor, true> {
45 using Lhs = internal::remove_all_t<SparseLhsType>;
46 using Res = internal::remove_all_t<DenseResType>;
47 using LhsInnerIterator = typename evaluator<Lhs>::InnerIterator;
48 using LhsEval = evaluator<Lhs>;
49 using ResScalar = typename Res::Scalar;
50
51 static void run(const SparseLhsType& lhs, const DenseRhsType& rhs, DenseResType& res,
52 const typename Res::Scalar& alpha) {
53 LhsEval lhsEval(lhs);
54 Index n = lhs.outerSize();
55
56 for (Index c = 0; c < rhs.cols(); ++c) {
57 runCol(lhsEval, lhs, rhs, res, alpha, n, c, bool_constant<has_compressed_storage<Lhs>::value>());
58 }
59 }
60
61 // Direct pointer path: works for both compressed and non-compressed storage.
62 static void runCol(const LhsEval& /*lhsEval*/, const SparseLhsType& lhs, const DenseRhsType& rhs, DenseResType& res,
63 const ResScalar& alpha, Index n, Index c, std::true_type /* has_compressed_storage */) {
64 runColImpl(lhs, rhs, res, alpha, n, c, bool_constant<bool(DenseRhsType::Flags & DirectAccessBit)>());
65 }
66
67 template <typename RhsT>
68 static void runColImpl(const SparseLhsType& lhs, const RhsT& rhs, DenseResType& res, const ResScalar& alpha, Index n,
69 Index c, std::true_type) {
70 const Lhs& mat = lhs;
71 const auto* vals = mat.valuePtr();
72 const auto* inds = mat.innerIndexPtr();
73 // Sparse vectors don't store outer indices.
74 const auto* outer = mat.outerIndexPtr();
75 const auto* innerNnz = mat.innerNonZeroPtr();
76 // The fast rhs pointer path requires unit inner stride (common case: VectorXd, contiguous matrix column).
77 if (rhs.innerStride() == 1) {
78 const auto* x = rhs.data() + c * rhs.outerStride();
79#ifdef EIGEN_HAS_OPENMP
80 Index threads = Eigen::nbThreads();
81 if (threads > 1 && mat.nonZeros() > 20000) {
82#pragma omp parallel for schedule(dynamic, (n + threads * 4 - 1) / (threads * 4)) num_threads(threads)
83 for (Index i = 0; i < n; ++i) {
84 Index k = outer ? outer[i] : 0;
85 const Index end = innerNnz ? (outer ? outer[i] : 0) + innerNnz[i] : (outer ? outer[i + 1] : mat.nonZeros());
86 ResScalar sum0(0), sum1(0);
87 for (; k < end; ++k) {
88 sum0 += vals[k] * x[inds[k]];
89 ++k;
90 if (k < end) {
91 sum1 += vals[k] * x[inds[k]];
92 }
93 }
94 res.coeffRef(i, c) += alpha * (sum0 + sum1);
95 }
96 } else
97#endif
98 {
99 for (Index i = 0; i < n; ++i) {
100 Index k = outer ? outer[i] : 0;
101 const Index end = innerNnz ? (outer ? outer[i] : 0) + innerNnz[i] : (outer ? outer[i + 1] : mat.nonZeros());
102 // Two independent accumulators to break the dependency chain
103 ResScalar sum0(0), sum1(0);
104 for (; k < end; ++k) {
105 sum0 += vals[k] * x[inds[k]];
106 ++k;
107 if (k < end) {
108 sum1 += vals[k] * x[inds[k]];
109 }
110 }
111 res.coeffRef(i, c) += alpha * (sum0 + sum1);
112 }
113 }
114 } else {
115 runColImpl(lhs, rhs, res, alpha, n, c, std::false_type());
116 }
117 }
118
119 // Use fall-back path without direct access to rhs.
120 template <typename RhsT>
121 static void runColImpl(const SparseLhsType& lhs, const RhsT& rhs, DenseResType& res, const ResScalar& alpha, Index n,
122 Index c, std::false_type) {
123 const Lhs& mat = lhs;
124 const auto* vals = mat.valuePtr();
125 const auto* inds = mat.innerIndexPtr();
126 const auto* outer = mat.outerIndexPtr();
127 const auto* innerNnz = mat.innerNonZeroPtr();
128 // Non-unit rhs stride (or no direct access): use direct pointers for sparse side, coeff() for rhs
129 for (Index i = 0; i < n; ++i) {
130 Index k = outer ? outer[i] : 0;
131 const Index end = innerNnz ? (outer ? outer[i] : 0) + innerNnz[i] : (outer ? outer[i + 1] : mat.nonZeros());
132 ResScalar sum0(0), sum1(0);
133 for (; k < end; ++k) {
134 sum0 += vals[k] * rhs.coeff(inds[k], c);
135 ++k;
136 if (k < end) {
137 sum1 += vals[k] * rhs.coeff(inds[k], c);
138 }
139 }
140 res.coeffRef(i, c) += alpha * (sum0 + sum1);
141 }
142 }
143
144 // Iterator fallback path
145 static void runCol(const LhsEval& lhsEval, const SparseLhsType& /*lhs*/, const DenseRhsType& rhs, DenseResType& res,
146 const ResScalar& alpha, Index n, Index c, std::false_type /* has_compressed_storage */) {
147#ifdef EIGEN_HAS_OPENMP
148 Index threads = Eigen::nbThreads();
149 if (threads > 1 && lhsEval.nonZerosEstimate() > 20000) {
150#pragma omp parallel for schedule(dynamic, (n + threads * 4 - 1) / (threads * 4)) num_threads(threads)
151 for (Index i = 0; i < n; ++i) processRow(lhsEval, rhs, res, alpha, i, c);
152 } else
153#endif
154 {
155 for (Index i = 0; i < n; ++i) processRow(lhsEval, rhs, res, alpha, i, c);
156 }
157 }
158
159 static void processRow(const LhsEval& lhsEval, const DenseRhsType& rhs, DenseResType& res, const ResScalar& alpha,
160 Index i, Index col) {
161 ResScalar tmp_a(0);
162 ResScalar tmp_b(0);
163 for (LhsInnerIterator it(lhsEval, i); it; ++it) {
164 tmp_a += it.value() * rhs.coeff(it.index(), col);
165 ++it;
166 if (it) {
167 tmp_b += it.value() * rhs.coeff(it.index(), col);
168 }
169 }
170 res.coeffRef(i, col) += alpha * (tmp_a + tmp_b);
171 }
172};
173
174// ColMajor, single column (ColPerCol=true): CSC SpMV
175template <typename SparseLhsType, typename DenseRhsType, typename DenseResType, typename AlphaType>
176struct sparse_time_dense_product_impl<SparseLhsType, DenseRhsType, DenseResType, AlphaType, ColMajor, true> {
177 using Lhs = internal::remove_all_t<SparseLhsType>;
178 using Rhs = internal::remove_all_t<DenseRhsType>;
179 using Res = internal::remove_all_t<DenseResType>;
180 using LhsEval = evaluator<Lhs>;
181 using LhsInnerIterator = typename LhsEval::InnerIterator;
182
183 static void run(const SparseLhsType& lhs, const DenseRhsType& rhs, DenseResType& res, const AlphaType& alpha) {
184 runImpl(lhs, rhs, res, alpha, bool_constant<has_compressed_storage<Lhs>::value>());
185 }
186
187 // Direct pointer path: works for both compressed and non-compressed storage.
188 static void runImpl(const SparseLhsType& lhs, const DenseRhsType& rhs, DenseResType& res, const AlphaType& alpha,
189 std::true_type /* has_compressed_storage */) {
190 using LhsScalar = typename Lhs::Scalar;
191 using StorageIndex = typename Lhs::StorageIndex;
192 const Lhs& mat = lhs;
193 const LhsScalar* vals = mat.valuePtr();
194 const StorageIndex* inds = mat.innerIndexPtr();
195 // Sparse vectors don't store outer indices.
196 const auto* outer = mat.outerIndexPtr();
197 const auto* innerNnz = mat.innerNonZeroPtr();
198 // The fast result pointer path requires contiguous ColMajor result layout.
199 // Transpose<ColMajor> reports innerStride()==1 but is actually RowMajor, so check both.
200 EIGEN_IF_CONSTEXPR (!(Res::Flags & RowMajorBit)) {
201 if (res.innerStride() == 1) {
202 const Index n = lhs.outerSize();
203 // The threaded scatter+reduce path relies on a thread_local scratch buffer for
204 // host-thread safety (see below), so it is only available where thread_local is
205 // usable; under EIGEN_AVOID_THREAD_LOCAL fall through to the serial scatter.
206#if defined(EIGEN_HAS_OPENMP) && !defined(EIGEN_AVOID_THREAD_LOCAL)
207 using ResScalar = typename Res::Scalar;
208 const Index m = res.rows();
209 const Index threads = Eigen::nbThreads();
210 // Per-thread scratch + reduction: the natural per-column partition would
211 // race on the output (writes to y[inds[k]] are scattered across rows),
212 // so each thread accumulates into its own m-sized output buffer and the
213 // results are summed at the end. Activated above the same 20000-nnz
214 // threshold as the RowMajor kernel, plus a second gate on per-thread
215 // scratch size: `threads * m` scalars are touched by the reduction,
216 // and on tall / very-sparse matrices that can dwarf the SpMV cost --
217 // require avg nnz per row >= threads so the reduction can't dominate.
218 // `outer` is null for SparseVector lhs; the nnz-balanced partition needs
219 // the outer-index array, so fall back to the serial scatter below.
220 if (outer && threads > 1 && mat.nonZeros() > 20000 && mat.nonZeros() >= Index(threads) * m) {
221 // Per-calling-thread persistent scratch (per template instantiation).
222 // Grows monotonically; reused across calls. The buffer is left at
223 // all-zeros after each call by folding the zero-out into the reduction
224 // step, which avoids a separate init pass on every SpMV. `thread_local`
225 // is required: two unrelated host threads concurrently calling
226 // y = A*x would otherwise race on this static buffer (and a reallocating
227 // grow on one would dangle the other's scratch_ptr).
228 thread_local static std::vector<ResScalar> scratch_buf;
229 const std::size_t need = static_cast<std::size_t>(threads) * static_cast<std::size_t>(m);
230 if (scratch_buf.size() < need) scratch_buf.assign(need, ResScalar(0));
231 ResScalar* scratch_ptr = scratch_buf.data();
232 // nnz-balanced column partition: each thread t owns the contiguous
233 // column range [part[t], part[t+1]). Deterministic mapping of j to
234 // thread (required for bit-reproducible reduction below) AND
235 // nnz-balanced load (dynamic scheduling would balance but break
236 // determinism; static round-robin would be deterministic but
237 // imbalanced on skewed matrices).
238 std::vector<Index> part(static_cast<std::size_t>(threads) + 1);
239 part[threads] = n;
240 part[0] = 0;
241 // Targets are monotonically increasing in t, so each lower_bound starts
242 // from the previous result; total work is O(T + log n) rather than
243 // T * log n.
244 const StorageIndex* const part_last = outer + n + 1;
245 const StorageIndex* part_lo = outer;
246 for (Index t = 1; t < threads; ++t) {
247 const Index target = (t * mat.nonZeros()) / threads;
248 part_lo = std::lower_bound(part_lo, part_last, StorageIndex(target));
249 part[t] = part_lo - outer;
250 }
251 for (Index c = 0; c < rhs.cols(); ++c) {
252 typename Res::Scalar* y = res.data() + c * res.outerStride();
253#pragma omp parallel for schedule(static, 1) num_threads(threads)
254 for (Index t = 0; t < threads; ++t) {
255 ResScalar* yt = scratch_ptr + t * m;
256 const Index j_lo = part[t], j_hi = part[t + 1];
257 for (Index j = j_lo; j < j_hi; ++j) {
258 typename ScalarBinaryOpTraits<AlphaType, typename Rhs::Scalar>::ReturnType rhs_j(alpha *
259 rhs.coeff(j, c));
260 const Index start = outer ? outer[j] : 0;
261 const Index end = innerNnz ? start + innerNnz[j] : (outer ? outer[j + 1] : mat.nonZeros());
262 Index k = start;
263 for (; k + 3 < end; k += 4) {
264 yt[inds[k]] += vals[k] * rhs_j;
265 yt[inds[k + 1]] += vals[k + 1] * rhs_j;
266 yt[inds[k + 2]] += vals[k + 2] * rhs_j;
267 yt[inds[k + 3]] += vals[k + 3] * rhs_j;
268 }
269 for (; k < end; ++k) yt[inds[k]] += vals[k] * rhs_j;
270 }
271 }
272 // Reduce per-thread buffers into y AND zero them, so the next call
273 // doesn't have to re-init. Process rows in cache-resident blocks: the
274 // natural [t*m+i] scratch layout makes the cross-thread read for a
275 // single row a stride-m gather (one cache line per thread, ~threads*m
276 // bytes apart, unvectorizable). Blocking lets each thread's stripe be
277 // swept as a unit-stride, vectorizable stream into a small per-block
278 // accumulator. Each thread owns a contiguous range of row blocks
279 // (static schedule) so the zero stores stay independent, and the
280 // accumulator is summed in the exact t = 0..threads-1 order, keeping
281 // the result bit-identical to the scalar reduction it replaces.
282 constexpr Index kReduceBlock = 512;
283#pragma omp parallel for schedule(static) num_threads(threads)
284 for (Index i0 = 0; i0 < m; i0 += kReduceBlock) {
285 const Index i1 = numext::mini(i0 + kReduceBlock, m);
286 const Index len = i1 - i0;
287 EIGEN_ALIGN_MAX ResScalar acc[kReduceBlock];
288 for (Index ii = 0; ii < len; ++ii) acc[ii] = ResScalar(0);
289 for (Index t = 0; t < threads; ++t) {
290 ResScalar* row = scratch_ptr + t * m + i0;
291 for (Index ii = 0; ii < len; ++ii) {
292 acc[ii] += row[ii];
293 row[ii] = ResScalar(0);
294 }
295 }
296 for (Index ii = 0; ii < len; ++ii) y[i0 + ii] += acc[ii];
297 }
298 }
299 } else
300#endif
301 {
302 for (Index c = 0; c < rhs.cols(); ++c) {
303 typename Res::Scalar* y = res.data() + c * res.outerStride();
304 for (Index j = 0; j < n; ++j) {
305 typename ScalarBinaryOpTraits<AlphaType, typename Rhs::Scalar>::ReturnType rhs_j(alpha * rhs.coeff(j, c));
306 const Index start = outer ? outer[j] : 0;
307 const Index end = innerNnz ? start + innerNnz[j] : (outer ? outer[j + 1] : mat.nonZeros());
308 Index k = start;
309 // 4-way unrolled scatter-add (no SIMD: writes are scattered)
310 for (; k + 3 < end; k += 4) {
311 y[inds[k]] += vals[k] * rhs_j;
312 y[inds[k + 1]] += vals[k + 1] * rhs_j;
313 y[inds[k + 2]] += vals[k + 2] * rhs_j;
314 y[inds[k + 3]] += vals[k + 3] * rhs_j;
315 }
316 for (; k < end; ++k) y[inds[k]] += vals[k] * rhs_j;
317 }
318 }
319 }
320 return;
321 }
322 }
323 // Non-unit result stride: use coeffRef() for result access
324 for (Index c = 0; c < rhs.cols(); ++c) {
325 for (Index j = 0; j < lhs.outerSize(); ++j) {
326 typename ScalarBinaryOpTraits<AlphaType, typename Rhs::Scalar>::ReturnType rhs_j(alpha * rhs.coeff(j, c));
327 const Index start = outer ? outer[j] : 0;
328 const Index end = innerNnz ? start + innerNnz[j] : (outer ? outer[j + 1] : mat.nonZeros());
329 for (Index k = start; k < end; ++k) res.coeffRef(inds[k], c) += vals[k] * rhs_j;
330 }
331 }
332 }
333
334 // Iterator-based fallback
335 static void runImpl(const SparseLhsType& lhs, const DenseRhsType& rhs, DenseResType& res, const AlphaType& alpha,
336 std::false_type /* has_compressed_storage */) {
337 LhsEval lhsEval(lhs);
338 for (Index c = 0; c < rhs.cols(); ++c) {
339 for (Index j = 0; j < lhs.outerSize(); ++j) {
340 typename ScalarBinaryOpTraits<AlphaType, typename Rhs::Scalar>::ReturnType rhs_j(alpha * rhs.coeff(j, c));
341 for (LhsInnerIterator it(lhsEval, j); it; ++it) res.coeffRef(it.index(), c) += it.value() * rhs_j;
342 }
343 }
344 }
345};
346
347// RowMajor, multiple columns (ColPerCol=false): sparse * dense_matrix
348template <typename SparseLhsType, typename DenseRhsType, typename DenseResType>
349struct sparse_time_dense_product_impl<SparseLhsType, DenseRhsType, DenseResType, typename DenseResType::Scalar,
350 RowMajor, false> {
351 using Lhs = internal::remove_all_t<SparseLhsType>;
352 using Res = internal::remove_all_t<DenseResType>;
353 using LhsEval = evaluator<Lhs>;
354 using LhsInnerIterator = typename LhsEval::InnerIterator;
355
356 static constexpr bool IsCompressedLhs = has_compressed_storage<Lhs>::value;
357
358 static void run(const SparseLhsType& lhs, const DenseRhsType& rhs, DenseResType& res,
359 const typename Res::Scalar& alpha) {
360 Index n = lhs.rows();
361 LhsEval lhsEval(lhs);
362
363#ifdef EIGEN_HAS_OPENMP
364 Index threads = Eigen::nbThreads();
365 // This 20000 threshold has been found experimentally on 2D and 3D Poisson problems.
366 // It basically represents the minimal amount of work to be done to be worth it.
367 if (threads > 1 && lhsEval.nonZerosEstimate() * rhs.cols() > 20000) {
368#pragma omp parallel for schedule(dynamic, (n + threads * 4 - 1) / (threads * 4)) num_threads(threads)
369 for (Index i = 0; i < n; ++i) processRow(lhsEval, lhs, rhs, res, alpha, i, bool_constant<IsCompressedLhs>());
370 } else
371#endif
372 {
373 for (Index i = 0; i < n; ++i) processRow(lhsEval, lhs, rhs, res, alpha, i, bool_constant<IsCompressedLhs>());
374 }
375 }
376
377 // Direct pointer path: works for both compressed and non-compressed storage.
378 static void processRow(const LhsEval& /*lhsEval*/, const SparseLhsType& lhs, const DenseRhsType& rhs, Res& res,
379 const typename Res::Scalar& alpha, Index i, std::true_type /* has_compressed_storage */) {
380 using LhsScalar = typename Lhs::Scalar;
381 using StorageIndex = typename Lhs::StorageIndex;
382 const Lhs& mat = lhs;
383 const LhsScalar* vals = mat.valuePtr();
384 const StorageIndex* inds = mat.innerIndexPtr();
385 // Sparse vectors don't store outer indices.
386 const Index start = mat.outerIndexPtr() ? mat.outerIndexPtr()[i] : 0;
387 const auto* innerNnz = mat.innerNonZeroPtr();
388 const Index end =
389 innerNnz ? start + innerNnz[i] : (mat.outerIndexPtr() ? mat.outerIndexPtr()[i + 1] : mat.nonZeros());
390 typename Res::RowXpr res_i(res.row(i));
391 for (Index k = start; k < end; ++k) res_i += (alpha * vals[k]) * rhs.row(inds[k]);
392 }
393
394 static void processRow(const LhsEval& lhsEval, const SparseLhsType& /*lhs*/, const DenseRhsType& rhs, Res& res,
395 const typename Res::Scalar& alpha, Index i, std::false_type /* has_compressed_storage */) {
396 typename Res::RowXpr res_i(res.row(i));
397 for (LhsInnerIterator it(lhsEval, i); it; ++it) res_i += (alpha * it.value()) * rhs.row(it.index());
398 }
399};
400
401// ColMajor, multiple columns (ColPerCol=false): sparse * dense_matrix
402template <typename SparseLhsType, typename DenseRhsType, typename DenseResType>
403struct sparse_time_dense_product_impl<SparseLhsType, DenseRhsType, DenseResType, typename DenseResType::Scalar,
404 ColMajor, false> {
405 using Lhs = internal::remove_all_t<SparseLhsType>;
406 using Rhs = internal::remove_all_t<DenseRhsType>;
407 using Res = internal::remove_all_t<DenseResType>;
408 using LhsInnerIterator = typename evaluator<Lhs>::InnerIterator;
409
410 static void run(const SparseLhsType& lhs, const DenseRhsType& rhs, DenseResType& res,
411 const typename Res::Scalar& alpha) {
412 runImpl(lhs, rhs, res, alpha, bool_constant<has_compressed_storage<Lhs>::value>());
413 }
414
415 // Direct pointer path: works for both compressed and non-compressed storage.
416 static void runImpl(const SparseLhsType& lhs, const DenseRhsType& rhs, DenseResType& res,
417 const typename Res::Scalar& alpha, std::true_type /* has_compressed_storage */) {
418 using LhsScalar = typename Lhs::Scalar;
419 using StorageIndex = typename Lhs::StorageIndex;
420 const Lhs& mat = lhs;
421 const LhsScalar* vals = mat.valuePtr();
422 const StorageIndex* inds = mat.innerIndexPtr();
423 // Sparse vectors don't store outer indices.
424 const auto* outer = mat.outerIndexPtr();
425 const auto* innerNnz = mat.innerNonZeroPtr();
426 for (Index j = 0; j < lhs.outerSize(); ++j) {
427 typename Rhs::ConstRowXpr rhs_j(rhs.row(j));
428 const Index start = outer ? outer[j] : 0;
429 const Index end = innerNnz ? start + innerNnz[j] : (outer ? outer[j + 1] : mat.nonZeros());
430 for (Index k = start; k < end; ++k) res.row(inds[k]) += (alpha * vals[k]) * rhs_j;
431 }
432 }
433
434 static void runImpl(const SparseLhsType& lhs, const DenseRhsType& rhs, DenseResType& res,
435 const typename Res::Scalar& alpha, std::false_type /* has_compressed_storage */) {
436 evaluator<Lhs> lhsEval(lhs);
437 for (Index j = 0; j < lhs.outerSize(); ++j) {
438 typename Rhs::ConstRowXpr rhs_j(rhs.row(j));
439 for (LhsInnerIterator it(lhsEval, j); it; ++it) res.row(it.index()) += (alpha * it.value()) * rhs_j;
440 }
441 }
442};
443
444template <typename SparseLhsType, typename DenseRhsType, typename DenseResType, typename AlphaType>
445inline void sparse_time_dense_product(const SparseLhsType& lhs, const DenseRhsType& rhs, DenseResType& res,
446 const AlphaType& alpha) {
447 sparse_time_dense_product_impl<SparseLhsType, DenseRhsType, DenseResType, AlphaType>::run(lhs, rhs, res, alpha);
448}
449
450} // end namespace internal
451
452namespace internal {
453
454template <typename Lhs, typename Rhs, int ProductType>
455struct generic_product_impl<Lhs, Rhs, SparseShape, DenseShape, ProductType>
456 : generic_product_impl_base<Lhs, Rhs, generic_product_impl<Lhs, Rhs, SparseShape, DenseShape, ProductType> > {
457 using Scalar = typename Product<Lhs, Rhs>::Scalar;
458
459 template <typename Dest>
460 static void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) {
461 using LhsNested = typename nested_eval<Lhs, ((Rhs::Flags & RowMajorBit) == 0) ? 1 : Rhs::ColsAtCompileTime>::type;
462 using RhsNested = typename nested_eval<Rhs, ((Lhs::Flags & RowMajorBit) == 0) ? 1 : Dynamic>::type;
463 LhsNested lhsNested(lhs);
464 RhsNested rhsNested(rhs);
465 internal::sparse_time_dense_product(lhsNested, rhsNested, dst, alpha);
466 }
467};
468
469template <typename Lhs, typename Rhs, int ProductType>
470struct generic_product_impl<Lhs, Rhs, SparseTriangularShape, DenseShape, ProductType>
471 : generic_product_impl<Lhs, Rhs, SparseShape, DenseShape, ProductType> {};
472
473template <typename Lhs, typename Rhs, int ProductType>
474struct generic_product_impl<Lhs, Rhs, DenseShape, SparseShape, ProductType>
475 : generic_product_impl_base<Lhs, Rhs, generic_product_impl<Lhs, Rhs, DenseShape, SparseShape, ProductType> > {
476 using Scalar = typename Product<Lhs, Rhs>::Scalar;
477
478 template <typename Dst>
479 static void scaleAndAddTo(Dst& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) {
480 using LhsNested = typename nested_eval<Lhs, ((Rhs::Flags & RowMajorBit) == 0) ? Dynamic : 1>::type;
481 using RhsNested =
482 typename nested_eval<Rhs, ((Lhs::Flags & RowMajorBit) == RowMajorBit) ? 1 : Lhs::RowsAtCompileTime>::type;
483 LhsNested lhsNested(lhs);
484 RhsNested rhsNested(rhs);
485
486 // transpose everything
487 Transpose<Dst> dstT(dst);
488 internal::sparse_time_dense_product(rhsNested.transpose(), lhsNested.transpose(), dstT, alpha);
489 }
490};
491
492template <typename Lhs, typename Rhs, int ProductType>
493struct generic_product_impl<Lhs, Rhs, DenseShape, SparseTriangularShape, ProductType>
494 : generic_product_impl<Lhs, Rhs, DenseShape, SparseShape, ProductType> {};
495
496template <typename LhsT, typename RhsT, bool NeedToTranspose>
497struct sparse_dense_outer_product_evaluator {
498 protected:
499 using Lhs1 = std::conditional_t<NeedToTranspose, RhsT, LhsT>;
500 using ActualRhs = std::conditional_t<NeedToTranspose, LhsT, RhsT>;
501 using ProdXprType = Product<LhsT, RhsT, DefaultProduct>;
502
503 // if the actual left-hand side is a dense vector,
504 // then build a sparse-view so that we can seamlessly iterate over it.
505 using ActualLhs = std::conditional_t<std::is_same<typename internal::traits<Lhs1>::StorageKind, Sparse>::value, Lhs1,
506 SparseView<Lhs1>>;
507 using LhsArg = std::conditional_t<std::is_same<typename internal::traits<Lhs1>::StorageKind, Sparse>::value,
508 const Lhs1&, SparseView<Lhs1>>;
509
510 using LhsEval = evaluator<ActualLhs>;
511 using RhsEval = evaluator<ActualRhs>;
512 using LhsIterator = typename evaluator<ActualLhs>::InnerIterator;
513 using Scalar = typename ProdXprType::Scalar;
514
515 public:
516 enum { Flags = NeedToTranspose ? RowMajorBit : 0, CoeffReadCost = HugeCost };
517
518 class InnerIterator : public LhsIterator {
519 public:
520 InnerIterator(const sparse_dense_outer_product_evaluator& xprEval, Index outer)
521 : LhsIterator(xprEval.m_lhsXprImpl, 0),
522 m_outer(outer),
523 m_empty(false),
524 m_factor(get(xprEval.m_rhsXprImpl, outer, typename internal::traits<ActualRhs>::StorageKind())) {}
525
526 EIGEN_STRONG_INLINE Index outer() const { return m_outer; }
527 EIGEN_STRONG_INLINE Index row() const { return NeedToTranspose ? m_outer : LhsIterator::index(); }
528 EIGEN_STRONG_INLINE Index col() const { return NeedToTranspose ? LhsIterator::index() : m_outer; }
529
530 EIGEN_STRONG_INLINE Scalar value() const { return LhsIterator::value() * m_factor; }
531 EIGEN_STRONG_INLINE operator bool() const { return LhsIterator::operator bool() && (!m_empty); }
532
533 protected:
534 Scalar get(const RhsEval& rhs, Index outer, Dense = Dense()) const { return rhs.coeff(outer); }
535
536 Scalar get(const RhsEval& rhs, Index outer, Sparse = Sparse()) {
537 typename RhsEval::InnerIterator it(rhs, outer);
538 if (it && it.index() == 0 && it.value() != Scalar(0)) return it.value();
539 m_empty = true;
540 return Scalar(0);
541 }
542
543 Index m_outer;
544 bool m_empty;
545 Scalar m_factor;
546 };
547
548 sparse_dense_outer_product_evaluator(const Lhs1& lhs, const ActualRhs& rhs)
549 : m_lhs(lhs), m_lhsXprImpl(m_lhs), m_rhsXprImpl(rhs) {
550 EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost);
551 }
552
553 // transpose case
554 sparse_dense_outer_product_evaluator(const ActualRhs& rhs, const Lhs1& lhs)
555 : m_lhs(lhs), m_lhsXprImpl(m_lhs), m_rhsXprImpl(rhs) {
556 EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost);
557 }
558
559 protected:
560 const LhsArg m_lhs;
561 evaluator<ActualLhs> m_lhsXprImpl;
562 evaluator<ActualRhs> m_rhsXprImpl;
563};
564
565// sparse * dense outer product
566template <typename Lhs, typename Rhs>
567struct product_evaluator<Product<Lhs, Rhs, DefaultProduct>, OuterProduct, SparseShape, DenseShape>
568 : sparse_dense_outer_product_evaluator<Lhs, Rhs, Lhs::IsRowMajor> {
569 using Base = sparse_dense_outer_product_evaluator<Lhs, Rhs, Lhs::IsRowMajor>;
570
571 using XprType = Product<Lhs, Rhs>;
572 using PlainObject = typename XprType::PlainObject;
573
574 explicit product_evaluator(const XprType& xpr) : Base(xpr.lhs(), xpr.rhs()) {}
575};
576
577template <typename Lhs, typename Rhs>
578struct product_evaluator<Product<Lhs, Rhs, DefaultProduct>, OuterProduct, DenseShape, SparseShape>
579 : sparse_dense_outer_product_evaluator<Lhs, Rhs, Rhs::IsRowMajor> {
580 using Base = sparse_dense_outer_product_evaluator<Lhs, Rhs, Rhs::IsRowMajor>;
581
582 using XprType = Product<Lhs, Rhs>;
583 using PlainObject = typename XprType::PlainObject;
584
585 explicit product_evaluator(const XprType& xpr) : Base(xpr.lhs(), xpr.rhs()) {}
586};
587
588} // end namespace internal
589
590} // end namespace Eigen
591
592#endif // EIGEN_SPARSEDENSEPRODUCT_H
@ ColMajor
Definition Constants.h:319
@ RowMajor
Definition Constants.h:321
constexpr unsigned int DirectAccessBit
Definition Constants.h:160
constexpr unsigned int RowMajorBit
Definition Constants.h:71