Debian Codegraph @

packages/muelu/research/caglusa/Tpetra_HierarchicalOperator_def.hpp

raw
1 // @HEADER
2 // *****************************************************************************
3 // MueLu: A package for multigrid based preconditioning
4 //
5 // Copyright 2012 NTESS and the MueLu contributors.
6 // SPDX-License-Identifier: BSD-3-Clause
7 // *****************************************************************************
8 // @HEADER
9
10 #ifndef TPETRA_HIERARCHICALOPERATOR_DEF_HPP
11 #define TPETRA_HIERARCHICALOPERATOR_DEF_HPP
12
13 #include <TpetraExt_MatrixMatrix.hpp>
14 #include <Tpetra_RowMatrixTransposer.hpp>
15 #include <Tpetra_HierarchicalOperator_decl.hpp>
16
17 namespace Tpetra {
18
19 template <class Scalar,
20 class LocalOrdinal,
21 class GlobalOrdinal,
22 class Node>
23 Teuchos::RCP<Tpetra::CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> >
24 removeSmallEntries(Teuchos::RCP<Tpetra::CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> >& A,
25 typename Teuchos::ScalarTraits<Scalar>::magnitudeType tol) {
26 using crs_matrix = Tpetra::CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node>;
27 using row_ptr_type = typename crs_matrix::local_graph_device_type::row_map_type::non_const_type;
28 using col_idx_type = typename crs_matrix::local_graph_device_type::entries_type::non_const_type;
29 using vals_type = typename crs_matrix::local_matrix_device_type::values_type;
30
31 using ATS = Kokkos::ArithTraits<Scalar>;
32 using impl_SC = typename ATS::val_type;
33 using impl_ATS = Kokkos::ArithTraits<impl_SC>;
34
35 auto lclA = A->getLocalMatrixDevice();
36
37 auto rowptr = row_ptr_type("rowptr", lclA.numRows() + 1);
38
39 LocalOrdinal nnz;
40 Kokkos::parallel_scan(
41 "removeSmallEntries::rowptr",
42 Kokkos::RangePolicy<LocalOrdinal>(0, lclA.numRows()),
43 KOKKOS_LAMBDA(const LocalOrdinal rlid, LocalOrdinal& partial_nnz, bool is_final) {
44 auto row = lclA.row(rlid);
45 for (LocalOrdinal k = 0; k < row.length; ++k) {
46 if (impl_ATS::magnitude(row.value(k)) > tol) {
47 partial_nnz += 1;
48 }
49 }
50 if (is_final)
51 rowptr(rlid + 1) = partial_nnz;
52 },
53 nnz);
54
55 auto idx = col_idx_type("idx", nnz);
56 auto vals = vals_type("vals", nnz);
57
58 Kokkos::parallel_for(
59 "removeSmallEntries::indicesValues",
60 Kokkos::RangePolicy<LocalOrdinal>(0, lclA.numRows()),
61 KOKKOS_LAMBDA(const LocalOrdinal rlid) {
62 auto row = lclA.row(rlid);
63 auto I = rowptr(rlid);
64 for (LocalOrdinal k = 0; k < row.length; ++k) {
65 if (impl_ATS::magnitude(row.value(k)) > tol) {
66 idx(I) = row.colidx(k);
67 vals(I) = row.value(k);
68 I += 1;
69 }
70 }
71 });
72
73 Kokkos::fence();
74
75 auto newA = Teuchos::rcp(new crs_matrix(A->getRowMap(), A->getColMap(), rowptr, idx, vals));
76 newA->fillComplete(A->getDomainMap(),
77 A->getRangeMap());
78 return newA;
79 }
80
81 template <class Scalar,
82 class LocalOrdinal,
83 class GlobalOrdinal,
84 class Node>
85 Teuchos::RCP<Tpetra::CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> >
86 constructSubMatrix(const Teuchos::RCP<Tpetra::CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> >& A,
87 std::pair<LocalOrdinal, LocalOrdinal> lid_range) {
88 using crs_matrix = Tpetra::CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node>;
89 using local_graph_type = typename crs_matrix::local_graph_device_type;
90 using local_matrix_type = typename crs_matrix::local_matrix_device_type;
91 using row_ptr_type = typename local_graph_type::row_map_type::non_const_type;
92 using col_idx_type = typename local_graph_type::entries_type::non_const_type;
93 using vals_type = typename local_matrix_type::values_type;
94
95 auto lclA = A->getLocalMatrixDevice();
96
97 auto old_rowptr = lclA.graph.row_map;
98 auto rowptr = row_ptr_type("rowptr", lclA.numRows() + 1);
99
100 LocalOrdinal nnz;
101 Kokkos::parallel_scan(
102 "constructSubMatrix::rowptr",
103 Kokkos::RangePolicy<LocalOrdinal>(0, lclA.numRows()),
104 KOKKOS_LAMBDA(const LocalOrdinal rlid, LocalOrdinal& partial_nnz, bool is_final) {
105 if ((lid_range.first <= rlid) && (rlid < lid_range.second)) {
106 partial_nnz += old_rowptr(rlid + 1) - old_rowptr(rlid);
107 }
108 if (is_final)
109 rowptr(rlid + 1) = partial_nnz;
110 },
111 nnz);
112
113 typename local_graph_type::size_type start;
114 typename local_graph_type::size_type end;
115 Kokkos::deep_copy(start, Kokkos::subview(old_rowptr, lid_range.first));
116 Kokkos::deep_copy(end, Kokkos::subview(old_rowptr, lid_range.second));
117 auto vals_range = Kokkos::make_pair(start, end);
118
119 TEUCHOS_ASSERT_EQUALITY(nnz, static_cast<LocalOrdinal>(end - start));
120
121 auto idx = Kokkos::subview(lclA.graph.entries, vals_range);
122 auto vals = Kokkos::subview(lclA.values, vals_range);
123
124 auto newA = Teuchos::rcp(new crs_matrix(A->getRowMap(), A->getColMap(), rowptr, idx, vals));
125 newA->fillComplete(A->getDomainMap(),
126 A->getRangeMap());
127 return newA;
128 }
129
130 template <class Scalar,
131 class LocalOrdinal,
132 class GlobalOrdinal,
133 class Node>
134 Teuchos::RCP<Tpetra::BlockedMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> >
135 transpose(Teuchos::RCP<Tpetra::BlockedMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> >& A) {
136 TEUCHOS_ASSERT(A->ghosted_blockMap_.is_null());
137
138 Teuchos::RCP<Teuchos::ParameterList> transposeParams = rcp(new Teuchos::ParameterList);
139
140 Tpetra::RowMatrixTransposer<Scalar, LocalOrdinal, GlobalOrdinal, Node> transposerPoint(A->pointA_);
141 auto pointAT = transposerPoint.createTranspose(transposeParams);
142
143 Tpetra::RowMatrixTransposer<Scalar, LocalOrdinal, GlobalOrdinal, Node> transposerBlock(A->blockA_);
144 auto blockAT = transposerBlock.createTranspose(transposeParams);
145
146 auto AT = Teuchos::rcp(new Tpetra::BlockedMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node>(pointAT, blockAT, A->blockMap_));
147
148 return AT;
149 }
150
151 template <class Scalar,
152 class LocalOrdinal,
153 class GlobalOrdinal,
154 class Node>
155 Teuchos::RCP<Tpetra::CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> >
156 buildIdentityMatrix(Teuchos::RCP<const Tpetra::Map<LocalOrdinal, GlobalOrdinal, Node> >& map) {
157 using matrix_type = Tpetra::CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node>;
158 Teuchos::RCP<matrix_type> identity = Teuchos::rcp(new matrix_type(map, 1));
159 Teuchos::ArrayView<const GlobalOrdinal> gblRows = map->getLocalElementList();
160 for (auto it = gblRows.begin(); it != gblRows.end(); ++it) {
161 Teuchos::Array<GlobalOrdinal> col(1, *it);
162 Teuchos::Array<Scalar> val(1, Teuchos::ScalarTraits<Scalar>::one());
163 identity->insertGlobalValues(*it, col(), val());
164 }
165 identity->fillComplete();
166 return identity;
167 }
168
169 template <class Scalar,
170 class LocalOrdinal,
171 class GlobalOrdinal,
172 class Node>
173 HierarchicalOperator<Scalar, LocalOrdinal, GlobalOrdinal, Node>::
174 HierarchicalOperator(const Teuchos::RCP<matrix_type>& nearField,
175 const Teuchos::RCP<blocked_matrix_type>& kernelApproximations,
176 const Teuchos::RCP<matrix_type>& basisMatrix,
177 std::vector<Teuchos::RCP<blocked_matrix_type> >& transferMatrices,
178 const Teuchos::RCP<Teuchos::ParameterList>& params)
179 : nearField_(nearField)
180 , kernelApproximations_(kernelApproximations)
181 , basisMatrix_(basisMatrix)
182 , transferMatrices_(transferMatrices)
183 , params_(params) {
184 auto map = nearField_->getDomainMap();
185 clusterCoeffMap_ = basisMatrix_->getDomainMap();
186
187 bool setupTransposes;
188 bool doDebugChecks;
189 std::string sendTypeNearField;
190 std::string sendTypeBasisMatrix;
191 std::string sendTypeKernelApproximations;
192
193 Teuchos::ParameterList defaultParams("Default params");
194 defaultParams.set("setupTransposes", true);
195 defaultParams.set("doDebugChecks", true);
196 defaultParams.set("Send type nearField", "Isend");
197 defaultParams.set("Send type basisMatrix", "Isend");
198 defaultParams.set("Send type kernelApproximations", "Alltoall");
199 defaultParams.set("Coarsening criterion", "transferLevels");
200 defaultParams.set("debugOutput", false);
201 defaultParams.set("keepTransfers", -1);
202 defaultParams.set("treeCoarseningFactor", 2.0);
203 defaultParams.set("leftOverFactor", 1.0);
204 defaultParams.set("batchSize", 50);
205 defaultParams.set("numBatches", 36);
206 if (params_.is_null())
207 params_ = Teuchos::rcp(new Teuchos::ParameterList(""));
208 params_->validateParametersAndSetDefaults(defaultParams);
209
210 setupTransposes = params_->get<bool>("setupTransposes");
211 doDebugChecks = params_->get<bool>("doDebugChecks");
212 sendTypeNearField = params_->get<std::string>("Send type nearField");
213 sendTypeBasisMatrix = params_->get<std::string>("Send type basisMatrix");
214 sendTypeKernelApproximations = params_->get<std::string>("Send type kernelApproximations");
215 coarseningCriterion_ = params_->get<std::string>("Coarsening criterion");
216 TEUCHOS_ASSERT((coarseningCriterion_ == "numClusters") || (coarseningCriterion_ == "equivalentDense") || (coarseningCriterion_ == "transferLevels"));
217 setDebugOutput(params_->get<bool>("debugOutput"));
218
219 auto comm = getComm();
220 if (debugOutput_ && (comm->getRank() == 0))
221 std::cout << *params_ << std::endl;
222
223 if (doDebugChecks) {
224 // near field matrix lives on map and is nonlocal
225 TEUCHOS_ASSERT(map->isSameAs(*nearField_->getRangeMap()));
226 TEUCHOS_ASSERT(map->isSameAs(*nearField_->getRowMap()));
227
228 // basis matrix is entirely local and maps from clusterCoeffMap_ to map.
229 TEUCHOS_ASSERT(map->isSameAs(*basisMatrix->getRangeMap()));
230 TEUCHOS_ASSERT(map->isSameAs(*basisMatrix->getRowMap()));
231 // TEUCHOS_ASSERT(clusterCoeffMap_->isSameAs(*basisMatrix->getDomainMap()));
232
233 // kernel approximations live on clusterCoeffMap and are nonlocal
234 TEUCHOS_ASSERT(clusterCoeffMap_->isSameAs(*kernelApproximations_->pointA_->getDomainMap()));
235 TEUCHOS_ASSERT(clusterCoeffMap_->isSameAs(*kernelApproximations_->pointA_->getRangeMap()));
236 TEUCHOS_ASSERT(clusterCoeffMap_->isSameAs(*kernelApproximations_->pointA_->getRowMap()));
237
238 for (size_t i = 0; i < transferMatrices_.size(); i++) {
239 // transfer matrices are entirely local, block diagonal on clusterCoeffMap
240 TEUCHOS_ASSERT(clusterCoeffMap_->isSameAs(*transferMatrices_[i]->pointA_->getDomainMap()));
241 TEUCHOS_ASSERT(clusterCoeffMap_->isSameAs(*transferMatrices_[i]->pointA_->getColMap()));
242 TEUCHOS_ASSERT(clusterCoeffMap_->isSameAs(*transferMatrices_[i]->pointA_->getRowMap()));
243 TEUCHOS_ASSERT(clusterCoeffMap_->isSameAs(*transferMatrices_[i]->pointA_->getRangeMap()));
244 }
245 }
246
247 // Set the send types
248 Teuchos::RCP<Teuchos::ParameterList> distParams = rcp(new Teuchos::ParameterList());
249 {
250 distParams->set("Send type", sendTypeNearField);
251 Teuchos::RCP<const Tpetra::Import<LocalOrdinal, GlobalOrdinal, Node> > nearFieldImporter = nearField_->getGraph()->getImporter();
252 nearFieldImporter->getDistributor().setParameterList(distParams);
253 auto revDistor = nearFieldImporter->getDistributor().getReverse(false);
254 if (!revDistor.is_null())
255 revDistor->setParameterList(distParams);
256 }
257
258 {
259 distParams->set("Send type", sendTypeBasisMatrix);
260 Teuchos::RCP<const Tpetra::Import<LocalOrdinal, GlobalOrdinal, Node> > basisMatrixImporter = basisMatrix_->getGraph()->getImporter();
261 if (!basisMatrixImporter.is_null()) {
262 basisMatrixImporter->getDistributor().setParameterList(distParams);
263 auto revDistor = basisMatrixImporter->getDistributor().getReverse(false);
264 if (!revDistor.is_null())
265 revDistor->setParameterList(distParams);
266 }
267 }
268
269 {
270 distParams->set("Send type", sendTypeKernelApproximations);
271 Teuchos::RCP<const Tpetra::Import<LocalOrdinal, GlobalOrdinal, Node> > kernelApproximationsImporter = kernelApproximations_->pointA_->getGraph()->getImporter();
272 kernelApproximationsImporter->getDistributor().setParameterList(distParams);
273 auto revDistor = kernelApproximationsImporter->getDistributor().getReverse(false);
274 if (!revDistor.is_null())
275 revDistor->setParameterList(distParams);
276 }
277
278 if (setupTransposes) {
279 Teuchos::RCP<Teuchos::ParameterList> transposeParams = rcp(new Teuchos::ParameterList);
280
281 Tpetra::RowMatrixTransposer<Scalar, LocalOrdinal, GlobalOrdinal, Node> transposerBasisMatrix(basisMatrix_);
282 basisMatrixT_ = transposerBasisMatrix.createTranspose(transposeParams);
283
284 for (size_t i = 0; i < transferMatrices_.size(); i++) {
285 transferMatricesT_.push_back(transpose(transferMatrices_[i]));
286 }
287
288 canApplyWithoutTransposes_ = true;
289 } else
290 canApplyWithoutTransposes_ = false;
291
292 // Allocate memory for apply with vectors
293 allocateMemory(1);
294 }
295
296 template <class Scalar,
297 class LocalOrdinal,
298 class GlobalOrdinal,
299 class Node>
300 void HierarchicalOperator<Scalar, LocalOrdinal, GlobalOrdinal, Node>::
301 apply(const Tpetra::MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node>& X,
302 Tpetra::MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node>& Y,
303 Teuchos::ETransp mode,
304 Scalar alpha,
305 Scalar beta) const {
306 if (canApplyWithoutTransposes_)
307 applyWithoutTransposes(X, Y, mode, alpha, beta);
308 else
309 applyWithTransposes(X, Y, mode, alpha, beta);
310 }
311
312 template <class Scalar,
313 class LocalOrdinal,
314 class GlobalOrdinal,
315 class Node>
316 void HierarchicalOperator<Scalar, LocalOrdinal, GlobalOrdinal, Node>::
317 applyWithTransposes(const Tpetra::MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node>& X,
318 Tpetra::MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node>& Y,
319 Teuchos::ETransp mode,
320 Scalar alpha,
321 Scalar beta) const {
322 using Teuchos::RCP;
323 const Scalar one = Teuchos::ScalarTraits<Scalar>::one();
324 const Scalar zero = Teuchos::ScalarTraits<Scalar>::zero();
325 bool flip = true;
326
327 allocateMemory(X.getNumVectors());
328
329 // upward pass
330 {
331 Teuchos::TimeMonitor tM(*Teuchos::TimeMonitor::getNewTimer(std::string("upward pass")));
332
333 basisMatrix_->apply(X, *coefficients_, Teuchos::TRANS);
334
335 for (int i = Teuchos::as<int>(transferMatrices_.size()) - 1; i >= 0; i--)
336 if (flip) {
337 coefficients2_->assign(*coefficients_);
338 transferMatrices_[i]->localApply(*coefficients_, *coefficients2_, Teuchos::NO_TRANS, one, one);
339 flip = false;
340 } else {
341 coefficients_->assign(*coefficients2_);
342 transferMatrices_[i]->localApply(*coefficients2_, *coefficients_, Teuchos::NO_TRANS, one, one);
343 flip = true;
344 }
345 }
346
347 // far field interactions - part 1
348 {
349 Teuchos::TimeMonitor tM(*Teuchos::TimeMonitor::getNewTimer(std::string("far field 1")));
350
351 RCP<const Tpetra::Import<LocalOrdinal, GlobalOrdinal, Node> > kernelApproximationsImporter = kernelApproximations_->pointA_->getGraph()->getImporter();
352 if (flip) {
353 if (mode == Teuchos::NO_TRANS) {
354 coefficients_colmap_->beginImport(*coefficients_, *kernelApproximationsImporter, INSERT);
355 } else if (mode == Teuchos::TRANS) {
356 kernelApproximations_->localApply(*coefficients_, *coefficients_colmap_, mode, alpha);
357 coefficients2_->putScalar(zero);
358 coefficients2_->beginExport(*coefficients_colmap_, *kernelApproximationsImporter, ADD_ASSIGN);
359 }
360 } else {
361 if (mode == Teuchos::NO_TRANS) {
362 coefficients_colmap_->beginImport(*coefficients2_, *kernelApproximationsImporter, INSERT);
363 } else if (mode == Teuchos::TRANS) {
364 kernelApproximations_->localApply(*coefficients2_, *coefficients_colmap_, mode, alpha);
365 coefficients_->putScalar(zero);
366 coefficients_->beginExport(*coefficients_colmap_, *kernelApproximationsImporter, ADD_ASSIGN);
367 }
368 }
369 }
370
371 // near field - part 1
372 RCP<const Tpetra::Import<LocalOrdinal, GlobalOrdinal, Node> > nearFieldImporter = nearField_->getGraph()->getImporter();
373 {
374 Teuchos::TimeMonitor tM(*Teuchos::TimeMonitor::getNewTimer(std::string("near field 1")));
375 if (mode == Teuchos::NO_TRANS) {
376 X_colmap_->beginImport(X, *nearFieldImporter, INSERT);
377 } else if (mode == Teuchos::TRANS) {
378 nearField_->localApply(X, *X_colmap_, mode, alpha, zero);
379 Y.scale(beta);
380 Y.beginExport(*X_colmap_, *nearFieldImporter, ADD_ASSIGN);
381 }
382 }
383
384 // far field interactions - part 2
385 {
386 Teuchos::TimeMonitor tM(*Teuchos::TimeMonitor::getNewTimer(std::string("far field 2")));
387
388 RCP<const Tpetra::Import<LocalOrdinal, GlobalOrdinal, Node> > kernelApproximationsImporter = kernelApproximations_->pointA_->getGraph()->getImporter();
389 if (flip) {
390 if (mode == Teuchos::NO_TRANS) {
391 coefficients_colmap_->endImport(*coefficients_, *kernelApproximationsImporter, INSERT);
392 kernelApproximations_->localApply(*coefficients_colmap_, *coefficients2_, mode, alpha);
393 } else if (mode == Teuchos::TRANS) {
394 coefficients2_->endExport(*coefficients_colmap_, *kernelApproximationsImporter, ADD_ASSIGN);
395 }
396 } else {
397 if (mode == Teuchos::NO_TRANS) {
398 coefficients_colmap_->endImport(*coefficients2_, *kernelApproximationsImporter, INSERT);
399 kernelApproximations_->localApply(*coefficients_colmap_, *coefficients_, mode, alpha);
400 } else if (mode == Teuchos::TRANS) {
401 coefficients_->endExport(*coefficients_colmap_, *kernelApproximationsImporter, ADD_ASSIGN);
402 }
403 }
404 }
405
406 // near field - part 2
407 {
408 Teuchos::TimeMonitor tM(*Teuchos::TimeMonitor::getNewTimer(std::string("near field 2")));
409
410 if (mode == Teuchos::NO_TRANS) {
411 X_colmap_->endImport(X, *nearFieldImporter, INSERT);
412 nearField_->localApply(*X_colmap_, Y, mode, alpha, beta);
413 } else if (mode == Teuchos::TRANS) {
414 Y.endExport(*X_colmap_, *nearFieldImporter, ADD_ASSIGN);
415 }
416 }
417
418 // downward pass
419 {
420 Teuchos::TimeMonitor tM(*Teuchos::TimeMonitor::getNewTimer(std::string("downward pass")));
421
422 for (size_t i = 0; i < transferMatrices_.size(); i++)
423 if (flip) {
424 coefficients_->assign(*coefficients2_);
425 transferMatrices_[i]->localApply(*coefficients2_, *coefficients_, Teuchos::TRANS, one, one);
426 flip = false;
427 } else {
428 coefficients2_->assign(*coefficients_);
429 transferMatrices_[i]->localApply(*coefficients_, *coefficients2_, Teuchos::TRANS, one, one);
430 flip = true;
431 }
432 if (flip)
433 basisMatrix_->apply(*coefficients2_, Y, Teuchos::NO_TRANS, one, one);
434 else
435 basisMatrix_->apply(*coefficients_, Y, Teuchos::NO_TRANS, one, one);
436 }
437 }
438
439 template <class Scalar,
440 class LocalOrdinal,
441 class GlobalOrdinal,
442 class Node>
443 void HierarchicalOperator<Scalar, LocalOrdinal, GlobalOrdinal, Node>::
444 applyWithoutTransposes(const Tpetra::MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node>& X,
445 Tpetra::MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node>& Y,
446 Teuchos::ETransp mode,
447 Scalar alpha,
448 Scalar beta) const {
449 using Teuchos::RCP;
450 const Scalar one = Teuchos::ScalarTraits<Scalar>::one();
451 const Scalar zero = Teuchos::ScalarTraits<Scalar>::zero();
452 bool flip = true;
453
454 allocateMemory(X.getNumVectors());
455
456 // upward pass
457 {
458 Teuchos::TimeMonitor tM(*Teuchos::TimeMonitor::getNewTimer(std::string("upward pass")));
459
460 basisMatrixT_->apply(X, *coefficients_, Teuchos::NO_TRANS);
461
462 for (int i = Teuchos::as<int>(transferMatrices_.size()) - 1; i >= 0; i--)
463 if (flip) {
464 coefficients2_->assign(*coefficients_);
465 transferMatrices_[i]->localApply(*coefficients_, *coefficients2_, Teuchos::NO_TRANS, one, one);
466 flip = false;
467 } else {
468 coefficients_->assign(*coefficients2_);
469 transferMatrices_[i]->localApply(*coefficients2_, *coefficients_, Teuchos::NO_TRANS, one, one);
470 flip = true;
471 }
472 }
473
474 // far field interactions - part 1
475 {
476 Teuchos::TimeMonitor tM(*Teuchos::TimeMonitor::getNewTimer(std::string("far field 1")));
477
478 RCP<const Tpetra::Import<LocalOrdinal, GlobalOrdinal, Node> > kernelApproximationsImporter = kernelApproximations_->pointA_->getGraph()->getImporter();
479 if (flip) {
480 if (mode == Teuchos::NO_TRANS) {
481 coefficients_colmap_->beginImport(*coefficients_, *kernelApproximationsImporter, INSERT);
482 } else if (mode == Teuchos::TRANS) {
483 kernelApproximations_->localApply(*coefficients_, *coefficients_colmap_, mode, alpha);
484 coefficients2_->putScalar(zero);
485 coefficients2_->beginExport(*coefficients_colmap_, *kernelApproximationsImporter, ADD_ASSIGN);
486 }
487 } else {
488 if (mode == Teuchos::NO_TRANS) {
489 coefficients_colmap_->beginImport(*coefficients2_, *kernelApproximationsImporter, INSERT);
490 } else if (mode == Teuchos::TRANS) {
491 kernelApproximations_->localApply(*coefficients2_, *coefficients_colmap_, mode, alpha);
492 coefficients_->putScalar(zero);
493 coefficients_->beginExport(*coefficients_colmap_, *kernelApproximationsImporter, ADD_ASSIGN);
494 }
495 }
496 }
497
498 // near field - part 1
499 RCP<const Tpetra::Import<LocalOrdinal, GlobalOrdinal, Node> > nearFieldImporter = nearField_->getGraph()->getImporter();
500 {
501 Teuchos::TimeMonitor tM(*Teuchos::TimeMonitor::getNewTimer(std::string("near field 1")));
502 if (mode == Teuchos::NO_TRANS) {
503 X_colmap_->beginImport(X, *nearFieldImporter, INSERT);
504 } else if (mode == Teuchos::TRANS) {
505 nearField_->localApply(X, *X_colmap_, mode, alpha, zero);
506 Y.scale(beta);
507 Y.beginExport(*X_colmap_, *nearFieldImporter, ADD_ASSIGN);
508 }
509 }
510
511 // far field interactions - part 2
512 {
513 Teuchos::TimeMonitor tM(*Teuchos::TimeMonitor::getNewTimer(std::string("far field 2")));
514
515 RCP<const Tpetra::Import<LocalOrdinal, GlobalOrdinal, Node> > kernelApproximationsImporter = kernelApproximations_->pointA_->getGraph()->getImporter();
516 if (flip) {
517 if (mode == Teuchos::NO_TRANS) {
518 coefficients_colmap_->endImport(*coefficients_, *kernelApproximationsImporter, INSERT);
519 kernelApproximations_->localApply(*coefficients_colmap_, *coefficients2_, mode, alpha);
520 } else if (mode == Teuchos::TRANS) {
521 coefficients2_->endExport(*coefficients_colmap_, *kernelApproximationsImporter, ADD_ASSIGN);
522 }
523 } else {
524 if (mode == Teuchos::NO_TRANS) {
525 coefficients_colmap_->endImport(*coefficients2_, *kernelApproximationsImporter, INSERT);
526 kernelApproximations_->localApply(*coefficients_colmap_, *coefficients_, mode, alpha);
527 } else if (mode == Teuchos::TRANS) {
528 coefficients_->endExport(*coefficients_colmap_, *kernelApproximationsImporter, ADD_ASSIGN);
529 }
530 }
531 }
532
533 // near field - part 2
534 {
535 Teuchos::TimeMonitor tM(*Teuchos::TimeMonitor::getNewTimer(std::string("near field 2")));
536
537 if (mode == Teuchos::NO_TRANS) {
538 X_colmap_->endImport(X, *nearFieldImporter, INSERT);
539 nearField_->localApply(*X_colmap_, Y, mode, alpha, beta);
540 } else if (mode == Teuchos::TRANS) {
541 Y.endExport(*X_colmap_, *nearFieldImporter, ADD_ASSIGN);
542 }
543 }
544
545 // downward pass
546 {
547 Teuchos::TimeMonitor tM(*Teuchos::TimeMonitor::getNewTimer(std::string("downward pass")));
548
549 for (size_t i = 0; i < transferMatrices_.size(); i++)
550 if (flip) {
551 coefficients_->assign(*coefficients2_);
552 transferMatricesT_[i]->localApply(*coefficients2_, *coefficients_, Teuchos::NO_TRANS, one, one);
553 flip = false;
554 } else {
555 coefficients2_->assign(*coefficients_);
556 transferMatricesT_[i]->localApply(*coefficients_, *coefficients2_, Teuchos::NO_TRANS, one, one);
557 flip = true;
558 }
559 if (flip)
560 basisMatrix_->apply(*coefficients2_, Y, Teuchos::NO_TRANS, one, one);
561 else
562 basisMatrix_->apply(*coefficients_, Y, Teuchos::NO_TRANS, one, one);
563 }
564 }
565
566 template <class Scalar,
567 class LocalOrdinal,
568 class GlobalOrdinal,
569 class Node>
570 Teuchos::RCP<HierarchicalOperator<Scalar, LocalOrdinal, GlobalOrdinal, Node> >
571 HierarchicalOperator<Scalar, LocalOrdinal, GlobalOrdinal, Node>::
572 restrict(const Teuchos::RCP<matrix_type>& P) {
573 Teuchos::TimeMonitor tM(*Teuchos::TimeMonitor::getNewTimer(std::string("Galerkin product")));
574
575 // H_c = P^T * H * P
576 using lo_vec_type = typename blocked_map_type::lo_vec_type;
577 using vec_type = typename Tpetra::Vector<Scalar, LocalOrdinal, GlobalOrdinal, Node>;
578 using MagnitudeType = typename Teuchos::ScalarTraits<Scalar>::magnitudeType;
579 using Teuchos::RCP;
580 using Teuchos::rcp;
581 const Scalar ONE = Teuchos::ScalarTraits<Scalar>::one();
582 const Scalar ZERO = Teuchos::ScalarTraits<Scalar>::zero();
583 const Scalar HALF = ONE / (ONE + ONE);
584
585 RCP<Teuchos::ParameterList> coarseParams = rcp(new Teuchos::ParameterList(*params_));
586
587 // newBasisMatrix = P^T * basisMatrix
588 RCP<matrix_type> newBasisMatrix = rcp(new matrix_type(P->getDomainMap(), clusterCoeffMap_, 0));
589 MatrixMatrix::Multiply(*P, true, *basisMatrix_, false, *newBasisMatrix);
590
591 //
592 auto clusterSizes = kernelApproximations_->blockMap_->blockSizes_;
593 auto ghosted_clusterMap = kernelApproximations_->blockA_->getColMap();
594 auto ghosted_clusterSizes = kernelApproximations_->ghosted_blockMap_->blockSizes_;
595
596 // Get number of unknowns associated with each cluster via new basisMatrix.
597 // numUnknownsPerCluster = \prod transfer_k * graph(newBasisMatrix)^T * ones
598 RCP<vec_type> numUnknownsPerCluster;
599 RCP<vec_type> ghosted_numUnknownsPerCluster;
600 if ((coarseningCriterion_ == "equivalentDense") ||
601 (coarseningCriterion_ == "numClusters")) {
602 {
603 numUnknownsPerCluster = rcp(new vec_type(kernelApproximations_->blockA_->getRowMap(), false));
604 auto lcl_clusterSizes = clusterSizes->getLocalViewHost(Tpetra::Access::ReadOnly);
605 auto lcl_numUnknownsPerCluster = numUnknownsPerCluster->getLocalViewHost(Tpetra::Access::OverwriteAll);
606 // Compute the transpose of the newBasisMatrix.
607 RCP<Tpetra::CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> > newBasisMatrixT;
608 Tpetra::RowMatrixTransposer<Scalar, LocalOrdinal, GlobalOrdinal, Node> transposer(newBasisMatrix);
609 RCP<Teuchos::ParameterList> transposeParams = rcp(new Teuchos::ParameterList);
610 newBasisMatrixT = transposer.createTranspose(transposeParams);
611
612 // TODO: parallel_for
613 auto rowptr = newBasisMatrixT->getLocalRowPtrsHost();
614 LocalOrdinal clusterStart = 0;
615 LocalOrdinal clusterEnd = 0;
616 for (LocalOrdinal cluster = 0; cluster < lcl_clusterSizes.extent_int(0); ++cluster) {
617 clusterStart = clusterEnd;
618 clusterEnd += lcl_clusterSizes(cluster, 0);
619 LocalOrdinal maxEntries = 0;
620 for (LocalOrdinal row = clusterStart; row < clusterEnd; ++row) {
621 LocalOrdinal numEntriesPerRow = rowptr(row + 1) - rowptr(row);
622 maxEntries = std::max(maxEntries, numEntriesPerRow);
623 }
624 lcl_numUnknownsPerCluster(cluster, 0) = maxEntries;
625 }
626 TEUCHOS_ASSERT_EQUALITY(clusterEnd + 1, rowptr.extent_int(0));
627 }
628
629 // sum from child nodes to parents via transfer operators
630 for (int i = Teuchos::as<int>(transferMatrices_.size()) - 1; i >= 0; i--)
631 transferMatrices_[i]->blockA_->apply(*numUnknownsPerCluster, *numUnknownsPerCluster, Teuchos::NO_TRANS, ONE, ONE);
632
633 // get ghosted numUnknownsPerCluster
634 ghosted_numUnknownsPerCluster = rcp(new vec_type(ghosted_clusterMap, false));
635 auto import = kernelApproximations_->blockA_->getCrsGraph()->getImporter();
636 ghosted_numUnknownsPerCluster->doImport(*numUnknownsPerCluster, *import, Tpetra::INSERT);
637 }
638
639 // coarse cluster pair graph
640 RCP<matrix_type> newKernelBlockGraph;
641 // point entries of cluster pairs that should be moved to the near field
642 RCP<matrix_type> diffKernelApprox;
643 // coarse point matrix of cluster pairs
644 Teuchos::RCP<matrix_type> newKernelApprox;
645
646 // Determine which cluster pairs should be moved to the near field.
647 // We are constructing the coarse block matrix newKernelBlockGraph
648 // and the point matrix diffKernelApprox.
649 {
650 typename vec_type::dual_view_type::t_host::const_type lcl_numUnknownsPerCluster;
651 typename vec_type::dual_view_type::t_host::const_type lcl_ghosted_numUnknownsPerCluster;
652 auto lcl_offsets = Kokkos::create_mirror_view(kernelApproximations_->blockMap_->offsets_);
653 auto lcl_ghosted_offsets = Kokkos::create_mirror_view(kernelApproximations_->ghosted_blockMap_->offsets_);
654 Kokkos::deep_copy(lcl_offsets, kernelApproximations_->blockMap_->offsets_);
655 Kokkos::deep_copy(lcl_ghosted_offsets, kernelApproximations_->ghosted_blockMap_->offsets_);
656 auto lcl_clusterSizes = clusterSizes->getLocalViewHost(Tpetra::Access::ReadOnly);
657 auto lcl_ghosted_clusterSizes = ghosted_clusterSizes->getLocalViewHost(Tpetra::Access::ReadOnly);
658
659 if ((coarseningCriterion_ == "equivalentDense") ||
660 (coarseningCriterion_ == "numClusters")) {
661 lcl_numUnknownsPerCluster = numUnknownsPerCluster->getLocalViewHost(Tpetra::Access::ReadOnly);
662 lcl_ghosted_numUnknownsPerCluster = ghosted_numUnknownsPerCluster->getLocalViewHost(Tpetra::Access::ReadOnly);
663 }
664
665 // Criterion: "numClusters"
666 // Compute all cluster pair sizes, sort them, and pick cut-off
667 // so that the number of cluster pairs decreases propotionally
668 // to the number of unknowns.
669 size_t tgt_clusterPairSize = 0;
670 if (coarseningCriterion_ == "numClusters") {
671 auto lcl_BlockGraph = kernelApproximations_->blockA_->getLocalMatrixHost();
672 std::vector<size_t> clusterPairSizes;
673 for (LocalOrdinal brlid = 0; brlid < lcl_BlockGraph.numRows(); ++brlid) {
674 auto brow = lcl_BlockGraph.row(brlid);
675 for (LocalOrdinal k = 0; k < brow.length; ++k) {
676 // Entries of the block matrix for kernelApproximations
677 // decide whether the cluster pair is present and only take
678 // values 1 or 0.
679 if (brow.value(k) > HALF) {
680 LocalOrdinal bclid = brow.colidx(k);
681 clusterPairSizes.push_back(lcl_numUnknownsPerCluster(brlid, 0) * lcl_ghosted_numUnknownsPerCluster(bclid, 0));
682 }
683 }
684 }
685 std::sort(clusterPairSizes.begin(), clusterPairSizes.end());
686 double coarseningRate = Teuchos::as<double>(P->getGlobalNumCols()) / Teuchos::as<double>(P->getGlobalNumRows());
687 tgt_clusterPairSize = clusterPairSizes[Teuchos::as<size_t>(static_cast<double>(clusterPairSizes.size()) * (1 - coarseningRate))];
688 // std::cout << "HERE " << clusterPairSizes[0] << " " << tgt_clusterPairSize << " " << clusterPairSizes[clusterPairSizes.size()-1] << std::endl;
689 }
690
691 // Criterion: "transferLevels"
692 // Drop cluster pairs by level in the tree.
693 auto comm = getComm();
694 std::set<LocalOrdinal> blidsToDrop;
695 LocalOrdinal minDrop = kernelApproximations_->blockMap_->blockMap_->getLocalNumElements() + 1;
696 LocalOrdinal maxDrop = -1;
697 if (coarseningCriterion_ == "transferLevels") {
698 double coarseningRate = Teuchos::as<double>(P->getGlobalNumCols()) / Teuchos::as<double>(P->getGlobalNumRows());
699 size_t droppedClusterPairs = 0;
700 size_t totalNumClusterPairs = kernelApproximations_->blockA_->getGlobalNumEntries();
701 RCP<vec_type> tempV = Teuchos::rcp(new vec_type(kernelApproximations_->blockMap_->blockMap_, false));
702 RCP<vec_type> tempV2 = Teuchos::rcp(new vec_type(kernelApproximations_->blockMap_->blockMap_, false));
703 // keepTransfers == transferMatrices_.size(): keep all transfers
704 // keepTransfers == 0: keep no transfers
705 int keepTransfers = params_->get<int>("keepTransfers", -1);
706 const double treeCoarseningFactor = params_->get<double>("treeCoarseningFactor");
707 if (keepTransfers == -1) {
708 double leftOverFactor = params_->get<double>("leftOverFactor");
709 keepTransfers = transferMatrices_.size();
710 double temp = (1.0 / coarseningRate) * leftOverFactor;
711 while (temp >= 1.0) {
712 --keepTransfers;
713 temp /= treeCoarseningFactor;
714 }
715 keepTransfers = std::max(keepTransfers, 0);
716 coarseParams->set("leftOverFactor", temp);
717 }
718 coarseParams->set("keepTransfers", -1);
719 TEUCHOS_ASSERT((0 <= keepTransfers) && (keepTransfers <= Teuchos::as<int>(transferMatrices_.size())));
720
721 size_t droppedTransfers = 0;
722 for (int k = Teuchos::as<int>(transferMatrices_.size()) - 1; k >= 0; --k) {
723 size_t numTreeEdgesBetweenLevels = transferMatrices_[k]->blockA_->getGlobalNumEntries();
724 size_t numClusters_k1 = numTreeEdgesBetweenLevels;
725 auto numClusters_k = Teuchos::as<size_t>(static_cast<double>(numTreeEdgesBetweenLevels) / treeCoarseningFactor);
726
727 if (debugOutput_ && (comm->getRank() == 0))
728 std::cout << "transfer " << k << " between levels " << k + 1 << " and " << k << " maps " << numClusters_k1 << " to " << numClusters_k << " clusters" << std::endl;
729
730 tempV->putScalar(ONE);
731 transferMatrices_[k]->blockA_->apply(*tempV, *tempV2, Teuchos::TRANS);
732 tempV->putScalar(ZERO);
733 kernelApproximations_->blockA_->apply(*tempV2, *tempV);
734 Scalar numClusterPairs = tempV->dot(*tempV2);
735 if (debugOutput_ && (comm->getRank() == 0))
736 std::cout << "cluster pairs on level " << k + 1 << ": " << numClusterPairs << std::endl;
737
738 bool doDrop;
739 if (keepTransfers >= 0) {
740 doDrop = (keepTransfers <= k);
741 } else {
742 doDrop = (droppedClusterPairs + numClusterPairs < (1.0 - coarseningRate) * static_cast<double>(totalNumClusterPairs));
743 }
744 if (doDrop) {
745 auto lcl_transfer = transferMatrices_[k]->blockA_->getLocalMatrixHost();
746 auto lcl_transfer_graph = lcl_transfer.graph;
747 for (LocalOrdinal j = 0; j < lcl_transfer_graph.entries.extent_int(0); j++) {
748 blidsToDrop.insert(lcl_transfer_graph.entries(j));
749 minDrop = std::min(minDrop, lcl_transfer_graph.entries(j));
750 maxDrop = std::max(maxDrop, lcl_transfer_graph.entries(j));
751 }
752
753 droppedTransfers += 1;
754 droppedClusterPairs += numClusterPairs;
755 }
756 }
757 if (debugOutput_ && (comm->getRank() == 0))
758 std::cout << "Dropped " << droppedTransfers << " transfers of " << transferMatrices_.size() << ", dropped cluster pairs: " << droppedClusterPairs << std::endl;
759 }
760
761 bool dropContiguousRange = (static_cast<size_t>(maxDrop + 1 - minDrop) == blidsToDrop.size());
762
763 // number of cluster pairs dropped
764 int dropped = 0;
765 // number of cluster pairs we kept
766 int kept = 0;
767 // number of cluster pairs that were no longer present
768 int ignored = 0;
769
770 if (dropContiguousRange) {
771 newKernelBlockGraph = constructSubMatrix(kernelApproximations_->blockA_, {0, minDrop});
772 dropped = maxDrop + 1 - minDrop;
773 kept = minDrop;
774 LocalOrdinal minLid = lcl_offsets(minDrop);
775 LocalOrdinal maxLid = lcl_offsets(maxDrop + 1);
776 diffKernelApprox = constructSubMatrix(kernelApproximations_->pointA_, {minLid, maxLid});
777 newKernelApprox = constructSubMatrix(kernelApproximations_->pointA_, {0, minLid});
778
779 } else {
780 newKernelBlockGraph = rcp(new matrix_type(kernelApproximations_->blockA_->getCrsGraph()));
781 newKernelBlockGraph->resumeFill();
782 diffKernelApprox = rcp(new matrix_type(kernelApproximations_->pointA_->getCrsGraph()));
783
784 // loop over cluster pairs
785 // TODO: parallel_for
786 auto lcl_BlockGraph = kernelApproximations_->blockA_->getLocalMatrixHost();
787 auto lcl_newBlockGraph = newKernelBlockGraph->getLocalMatrixHost();
788 auto lcl_KernelApprox = kernelApproximations_->pointA_->getLocalMatrixHost();
789 auto lcl_diffKernelApprox = diffKernelApprox->getLocalMatrixHost();
790 for (LocalOrdinal brlid = 0; brlid < lcl_BlockGraph.numRows(); ++brlid) {
791 size_t brsize = lcl_clusterSizes(brlid, 0);
792 auto brow = lcl_BlockGraph.row(brlid);
793 auto new_brow = lcl_newBlockGraph.row(brlid);
794 for (LocalOrdinal k = 0; k < brow.length; ++k) {
795 // Entries of the block matrix for kernelApproximations
796 // decide whether the cluster pair is present and only take
797 // values 1 or 0.
798 if (brow.value(k) > HALF) {
799 LocalOrdinal bclid = brow.colidx(k);
800 size_t bcsize = lcl_ghosted_clusterSizes(bclid, 0);
801
802 // criterium for removing a cluster pair from the far field
803 bool removeCluster = false;
804 if (coarseningCriterion_ == "equivalentDense") {
805 // Size of the sparse cluster approximation >= size of dense equivalent
806 removeCluster = (brsize * bcsize >= lcl_numUnknownsPerCluster(brlid, 0) * lcl_ghosted_numUnknownsPerCluster(bclid, 0));
807 } else if (coarseningCriterion_ == "numClusters") {
808 removeCluster = (lcl_numUnknownsPerCluster(brlid, 0) * lcl_ghosted_numUnknownsPerCluster(bclid, 0) < tgt_clusterPairSize);
809 } else if (coarseningCriterion_ == "transferLevels") {
810 removeCluster = ((blidsToDrop.find(brlid) != blidsToDrop.end()) ||
811 (blidsToDrop.find(bclid) != blidsToDrop.end()));
812 }
813 if (removeCluster) {
814 // we are dropping the cluster pair from the far field
815 ++dropped;
816 new_brow.value(k) = ZERO;
817
818 // loop over the point matrix and add the entries to diffKernelApprox
819 const LocalOrdinal row_start = lcl_offsets(brlid);
820 const LocalOrdinal row_end = lcl_offsets(brlid + 1);
821 const LocalOrdinal col_start = lcl_ghosted_offsets(bclid);
822 const LocalOrdinal col_end = lcl_ghosted_offsets(bclid + 1);
823 TEUCHOS_ASSERT_EQUALITY(Teuchos::as<size_t>(row_end - row_start), brsize);
824 TEUCHOS_ASSERT_EQUALITY(Teuchos::as<size_t>(col_end - col_start), bcsize);
825 for (LocalOrdinal rlid = row_start; rlid < row_end; ++rlid) {
826 auto diff_row = lcl_diffKernelApprox.row(rlid);
827 auto row = lcl_KernelApprox.row(rlid);
828 size_t removed = 0;
829 for (LocalOrdinal n = 0; n < row.length; ++n) {
830 if ((col_start <= row.colidx(n)) && (col_end > row.colidx(n))) {
831 diff_row.value(n) = row.value(n);
832 ++removed;
833 }
834 }
835 if (removed != bcsize) {
836 std::ostringstream oss;
837 oss << "brlid " << brlid << " row " << rlid << std::endl;
838 oss << "col_start " << col_start << " col_end " << col_end << std::endl;
839 for (LocalOrdinal n = 0; n < row.length; ++n) {
840 oss << row.colidx(n) << " " << row.value(n) << std::endl;
841 }
842 std::cout << oss.str();
843 }
844 TEUCHOS_ASSERT_EQUALITY(removed, bcsize);
845 }
846 } else {
847 // We are keeping the cluster pair.
848 ++kept;
849 new_brow.value(k) = brow.value(k);
850 }
851 } else {
852 // The cluster pair has already been dropped on the fine level.
853 ++ignored;
854 new_brow.value(k) = brow.value(k);
855 }
856 }
857 }
858
859 newKernelBlockGraph->fillComplete(kernelApproximations_->blockA_->getDomainMap(),
860 kernelApproximations_->blockA_->getRangeMap());
861 newKernelBlockGraph = removeSmallEntries(newKernelBlockGraph, Teuchos::ScalarTraits<MagnitudeType>::eps());
862 diffKernelApprox->fillComplete(clusterCoeffMap_,
863 clusterCoeffMap_);
864
865 {
866 Teuchos::RCP<matrix_type> temp = MatrixMatrix::add(ONE, false, *kernelApproximations_->pointA_, -ONE, false, *diffKernelApprox);
867 newKernelApprox = removeSmallEntries(temp, Teuchos::ScalarTraits<MagnitudeType>::eps());
868 }
869 }
870 if (debugOutput_) {
871 // number of cluster pairs dropped
872 int gbl_dropped = 0;
873 // number of cluster pairs we kept
874 int gbl_kept = 0;
875 // number of cluster pairs that were no longer present
876 int gbl_ignored = 0;
877 Teuchos::reduceAll(*comm, Teuchos::REDUCE_SUM, 1, &dropped, &gbl_dropped);
878 Teuchos::reduceAll(*comm, Teuchos::REDUCE_SUM, 1, &kept, &gbl_kept);
879 Teuchos::reduceAll(*comm, Teuchos::REDUCE_SUM, 1, &ignored, &gbl_ignored);
880 if (comm->getRank() == 0)
881 std::cout << "dropped " << gbl_dropped << " cluster pairs, kept " << gbl_kept << " cluster pairs, ignored " << gbl_ignored << " cluster pairs" << std::endl;
882 }
883 }
884
885 // construct identity on clusterCoeffMap_
886 Teuchos::RCP<matrix_type> identity = buildIdentityMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node>(clusterCoeffMap_);
887
888 Teuchos::RCP<blocked_matrix_type> newBlockedKernelApproximation = rcp(new blocked_matrix_type(newKernelApprox, newKernelBlockGraph, kernelApproximations_->blockMap_, kernelApproximations_->ghosted_blockMap_));
889
890 // select subset of transfer matrices for coarse operator
891 std::vector<Teuchos::RCP<blocked_matrix_type> > newTransferMatrices;
892 {
893 Teuchos::TimeMonitor tM_basis_transfer(*Teuchos::TimeMonitor::getNewTimer(std::string("Coarse basis and transfers")));
894
895 auto comm = getComm();
896
897 RCP<vec_type> v_temp = rcp(new vec_type(newKernelBlockGraph->getDomainMap()));
898 RCP<vec_type> clusterUseCount = rcp(new vec_type(newKernelBlockGraph->getDomainMap()));
899 v_temp->putScalar(ONE);
900 clusterUseCount->putScalar(ZERO);
901 newKernelBlockGraph->apply(*v_temp, *clusterUseCount, Teuchos::NO_TRANS);
902 newKernelBlockGraph->apply(*v_temp, *clusterUseCount, Teuchos::TRANS, ONE, ONE);
903
904 for (int i = Teuchos::as<int>(transferMatrices_.size()) - 1; i >= 0; i--) {
905 // We drop a transfer operator T_i when
906 // sum(T_i * clusterUseCount) == 0
907 // Since we need to use Scalar, we instead check for < 0.5
908 transferMatrices_[i]->blockA_->localApply(*clusterUseCount, *v_temp, Teuchos::NO_TRANS);
909 Scalar gbl_use_count = v_temp->norm1();
910 // if (comm->getRank() == 0)
911 // std::cout << "Transfer " << i << " count " << gbl_use_count << std::endl;
912
913 if (gbl_use_count < HALF) {
914 // We do not keep the i-th transfer for the coarse operator.
915 // newBasisMatrix := newBasisMatrix * (I+transferMatrices_[i])^T
916 Teuchos::RCP<matrix_type> temp2 = MatrixMatrix::add(ONE, false, *identity, ONE, false, *transferMatrices_[i]->pointA_);
917 RCP<matrix_type> temp = rcp(new matrix_type(newBasisMatrix->getRowMap(), clusterCoeffMap_, 0));
918 MatrixMatrix::Multiply(*newBasisMatrix, false, *temp2, true, *temp);
919 newBasisMatrix = temp;
920 } else {
921 // We keep the i-th transfer for the coarse operator.
922 newTransferMatrices.insert(newTransferMatrices.begin(), transferMatrices_[i]);
923 }
924 }
925 }
926
927 // Coarse near field
928 RCP<matrix_type> newNearField;
929 {
930 Teuchos::TimeMonitor tM_near(*Teuchos::TimeMonitor::getNewTimer(std::string("Coarse near field")));
931
932 // diffKernelApprox := (identity + newTransferMatrices[K-1])^T * ... * (identity + newTransferMatrices[0])^T
933 // * diffKernelApprox
934 // * (identity + newTransferMatrices[0]) * ... * (identity + newTransferMatrices[K-1])
935 {
936 Teuchos::TimeMonitor tM_near_1(*Teuchos::TimeMonitor::getNewTimer(std::string("Coarse near field 1")));
937 for (int i = 0; i < Teuchos::as<int>(newTransferMatrices.size()); ++i) {
938 // diffKernelApprox := (I + newTransferMatrices[i])^T * diffKernelApprox * (I + newTransferMatrices[i])
939 Teuchos::RCP<matrix_type> temp = MatrixMatrix::add(ONE, false, *identity, ONE, false, *newTransferMatrices[i]->pointA_);
940 Teuchos::RCP<matrix_type> temp2 = rcp(new matrix_type(clusterCoeffMap_, 0));
941 MatrixMatrix::Multiply(*temp, true, *diffKernelApprox, false, *temp2);
942 MatrixMatrix::Multiply(*temp2, false, *temp, false, *diffKernelApprox);
943 }
944 }
945
946 // diffKernelApprox := (newBasisMatrix * diffKernelApprox) * newBasisMatrix^T
947 {
948 Teuchos::TimeMonitor tM_near2(*Teuchos::TimeMonitor::getNewTimer(std::string("Coarse near field 2")));
949
950 Teuchos::RCP<matrix_type> temp = rcp(new matrix_type(newBasisMatrix->getRowMap(), 0));
951 {
952 Teuchos::TimeMonitor tM_near2a(*Teuchos::TimeMonitor::getNewTimer(std::string("Coarse near field 2a")));
953 MatrixMatrix::Multiply(*newBasisMatrix, false, *diffKernelApprox, false, *temp);
954 }
955
956 {
957 Teuchos::TimeMonitor tM_near2a(*Teuchos::TimeMonitor::getNewTimer(std::string("Coarse near field 2b")));
958 diffKernelApprox = rcp(new matrix_type(newBasisMatrix->getRowMap(), 0));
959 MatrixMatrix::Multiply(*temp, false, *newBasisMatrix, true, *diffKernelApprox);
960 }
961 }
962
963 // newNearField = (P^T * nearField * P) + diffKernelApprox
964 {
965 Teuchos::TimeMonitor tM_near3(*Teuchos::TimeMonitor::getNewTimer(std::string("Coarse near field 3")));
966 RCP<matrix_type> temp = rcp(new matrix_type(nearField_->getRowMap(), 0));
967 MatrixMatrix::Multiply(*nearField_, false, *P, false, *temp);
968 RCP<matrix_type> temp2 = rcp(new matrix_type(P->getDomainMap(), 0));
969 MatrixMatrix::Multiply(*P, true, *temp, false, *temp2);
970 newNearField = MatrixMatrix::add(ONE, false, *temp2, ONE, false, *diffKernelApprox);
971 diffKernelApprox = Teuchos::null;
972 // newNearField = removeSmallEntries(newNearField, Teuchos::ScalarTraits<MagnitudeType>::eps());
973 }
974 }
975
976 return Teuchos::rcp(new HierarchicalOperator<Scalar, LocalOrdinal, GlobalOrdinal, Node>(newNearField,
977 newBlockedKernelApproximation,
978 newBasisMatrix,
979 newTransferMatrices,
980 coarseParams));
981 }
982
983 template <class Scalar,
984 class LocalOrdinal,
985 class GlobalOrdinal,
986 class Node>
987 Teuchos::RCP<Tpetra::CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> >
988 HierarchicalOperator<Scalar, LocalOrdinal, GlobalOrdinal, Node>::
989 toMatrix() {
990 Teuchos::TimeMonitor tM(*Teuchos::TimeMonitor::getNewTimer(std::string("Conversion from H-matrix to CSR")));
991
992 using Teuchos::RCP;
993 using Teuchos::rcp;
994
995 const Scalar ONE = Teuchos::ScalarTraits<Scalar>::one();
996
997 if (hasFarField()) {
998 RCP<matrix_type> kernelApproximations;
999
1000 if (hasTransferMatrices()) {
1001 kernelApproximations = rcp(new matrix_type(*kernelApproximations_->pointA_));
1002
1003 // construct identity on clusterCoeffMap_
1004 Teuchos::RCP<matrix_type> identity = buildIdentityMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node>(clusterCoeffMap_);
1005
1006 Teuchos::TimeMonitor tM_near_1(*Teuchos::TimeMonitor::getNewTimer(std::string("Densify far field 1")));
1007 for (int i = 0; i < Teuchos::as<int>(transferMatrices_.size()); ++i) {
1008 // kernelApproximations := (I + newTransferMatrices[i])^T * kernelApproximations * (I + newTransferMatrices[i])
1009 Teuchos::RCP<matrix_type> temp = MatrixMatrix::add(ONE, false, *identity, ONE, false, *transferMatrices_[i]->pointA_);
1010 Teuchos::RCP<matrix_type> temp2 = rcp(new matrix_type(clusterCoeffMap_, 0));
1011 MatrixMatrix::Multiply(*temp, true, *kernelApproximations, false, *temp2);
1012 Teuchos::RCP<matrix_type> temp3 = rcp(new matrix_type(clusterCoeffMap_, 0));
1013 MatrixMatrix::Multiply(*temp2, false, *temp, false, *temp3);
1014 kernelApproximations = temp3;
1015 }
1016 } else {
1017 kernelApproximations = kernelApproximations_->pointA_;
1018 }
1019
1020 // farField = (basisMatrix_ * kernelApproximations) * basisMatrix_^T
1021 RCP<matrix_type> farField;
1022 {
1023 Teuchos::TimeMonitor tM_near_2(*Teuchos::TimeMonitor::getNewTimer(std::string("Densify far field 2")));
1024 int rank = getComm()->getRank();
1025 int size = getComm()->getSize();
1026 int numBatches = params_->get<int>("numBatches");
1027 if (numBatches < 0) {
1028 int batchSize = params_->get<int>("batchSize");
1029 numBatches = size / batchSize;
1030 }
1031 numBatches = std::max(numBatches, 1);
1032 for (int batchNo = 0; batchNo < numBatches; ++batchNo) {
1033 RCP<matrix_type> kernelApproximationsSlice;
1034 {
1035 Teuchos::TimeMonitor tM_near_2a(*Teuchos::TimeMonitor::getNewTimer(std::string("Densify far field 2 0")));
1036
1037 using local_matrix_type = typename matrix_type::local_matrix_device_type;
1038 local_matrix_type lclKernelApproximationsSlice;
1039
1040 if (rank % numBatches == batchNo) {
1041 lclKernelApproximationsSlice = kernelApproximations->getLocalMatrixDevice();
1042
1043 } else {
1044 using local_graph_type = typename matrix_type::local_graph_device_type;
1045 using row_ptr_type = typename local_graph_type::row_map_type::non_const_type;
1046 using col_idx_type = typename local_graph_type::entries_type::non_const_type;
1047 using vals_type = typename local_matrix_type::values_type;
1048
1049 auto lclKernelApproximations = kernelApproximations->getLocalMatrixDevice();
1050 auto rowptr = row_ptr_type("rowptr", lclKernelApproximations.numRows() + 1);
1051 auto idx = col_idx_type("colidx", 0);
1052 auto vals = vals_type("vals", 0);
1053
1054 auto lclKernelApproximationsSliceGraph = local_graph_type(idx, rowptr);
1055 lclKernelApproximationsSlice = local_matrix_type("slice", lclKernelApproximations.numCols(), vals, lclKernelApproximationsSliceGraph);
1056 }
1057 kernelApproximationsSlice = rcp(new matrix_type(lclKernelApproximationsSlice,
1058 kernelApproximations->getRowMap(),
1059 kernelApproximations->getColMap(),
1060 kernelApproximations->getDomainMap(),
1061 kernelApproximations->getRangeMap()));
1062 }
1063 {
1064 RCP<matrix_type> temp;
1065 {
1066 Teuchos::TimeMonitor tM_near_2a(*Teuchos::TimeMonitor::getNewTimer(std::string("Densify far field 2a")));
1067 temp = rcp(new matrix_type(basisMatrix_->getRowMap(), 0));
1068 MatrixMatrix::Multiply(*basisMatrix_, false, *kernelApproximationsSlice, false, *temp);
1069 }
1070
1071 {
1072 Teuchos::TimeMonitor tM_near_2b(*Teuchos::TimeMonitor::getNewTimer(std::string("Densify far field 2b")));
1073 auto temp2 = rcp(new matrix_type(basisMatrix_->getRowMap(), 0));
1074 MatrixMatrix::Multiply(*temp, false, *basisMatrix_, true, *temp2);
1075 temp = Teuchos::null;
1076 if (batchNo == 0)
1077 farField = temp2;
1078 else
1079 farField = MatrixMatrix::add(ONE, false, *farField, ONE, false, *temp2);
1080 }
1081 }
1082 }
1083 }
1084
1085 // nearField_ + farField
1086 RCP<matrix_type> dense;
1087 {
1088 Teuchos::TimeMonitor tM_near_3(*Teuchos::TimeMonitor::getNewTimer(std::string("Densify far field 3")));
1089 dense = MatrixMatrix::add(ONE, false, *nearField_, ONE, false, *farField);
1090 }
1091 return dense;
1092
1093 } else
1094
1095 return nearField_;
1096 }
1097
1098 template <class Scalar,
1099 class LocalOrdinal,
1100 class GlobalOrdinal,
1101 class Node>
1102 void HierarchicalOperator<Scalar, LocalOrdinal, GlobalOrdinal, Node>::
1103 allocateMemory(size_t numVectors) const {
1104 if (coefficients_.is_null() || coefficients_->getNumVectors() != numVectors) {
1105 coefficients_ = Teuchos::rcp(new mv_type(clusterCoeffMap_, numVectors));
1106 coefficients2_ = Teuchos::rcp(new mv_type(clusterCoeffMap_, numVectors));
1107 X_colmap_ = Teuchos::rcp(new mv_type(nearField_->getColMap(), numVectors));
1108 coefficients_colmap_ = Teuchos::rcp(new mv_type(kernelApproximations_->pointA_->getColMap(), numVectors));
1109 }
1110 }
1111 } // namespace Tpetra
1112
1113 #endif // TPETRA_HIERARCHICALOPERATOR_DEF_HPP