244 const Matrix& A,
const int numDimensions,
245 const Teuchos::Array<LocalOrdinal>& lFineNodesPerDim)
const {
246 const std::string prefix =
"StructuredRAPFactory::DetectFineStencil: ";
249 prefix <<
"the number of dimensions must be between one and three.");
251 prefix <<
"insufficient fine-grid dimensions were supplied.");
253 const auto rowMap = A.getRowMap();
254 const auto colMap = A.getColMap();
255 const auto comm = rowMap->getComm();
256 const auto graph = A.getCrsGraph();
258 prefix <<
"A does not expose a CRS graph.");
260 const LO dofsPerNode = Teuchos::as<LO>(A.GetFixedBlockSize());
262 prefix <<
"A must have a positive fixed block size.");
264 Kokkos::Array<LO, 3> fineNodes{{LO(1), LO(1), LO(1)}};
265 Kokkos::Array<LO, 3> interior{{LO(0), LO(0), LO(0)}};
266 size_t numFineNodes = 1;
267 bool hasLocalInterior =
true;
269 for (
int dim = 0; dim < numDimensions; ++dim) {
270 fineNodes[dim] = lFineNodesPerDim[dim];
271 hasLocalInterior = hasLocalInterior && fineNodes[dim] >= LO(3);
272 if (fineNodes[dim] > LO(0)) {
273 interior[dim] = fineNodes[dim] / LO(2);
274 numFineNodes *= Teuchos::as<size_t>(fineNodes[dim]);
280 const bool localDimensionsMatch =
281 rowMap->getLocalNumElements() ==
282 numFineNodes * Teuchos::as<size_t>(dofsPerNode);
283 int invalidLocalDimensions = localDimensionsMatch ? 0 : 1;
284 int invalidDimensions = 0;
285 Teuchos::reduceAll(*comm, Teuchos::REDUCE_MAX, 1,
286 &invalidLocalDimensions, &invalidDimensions);
287 TEUCHOS_TEST_FOR_EXCEPTION(
289 prefix <<
"the structured local dimensions and fixed block size do not match A on every rank.");
291 const LO interiorNode = interior[2] * fineNodes[0] * fineNodes[1] +
292 interior[1] * fineNodes[0] + interior[0];
294 const auto localA = A.getLocalMatrixDevice();
295 const LO invalidLocalOrdinal = Teuchos::OrdinalTraits<LO>::invalid();
296 std::vector<std::vector<LO>> ownedColumns(
297 Teuchos::as<size_t>(dofsPerNode));
298 bool hasCompleteLocalStencil = hasLocalInterior;
299 if (hasLocalInterior) {
300 const size_t firstRow = Teuchos::as<size_t>(interiorNode * dofsPerNode);
301 const auto detectedRowMap = Kokkos::subview(
302 localA.graph.row_map,
303 std::make_pair(firstRow,
304 firstRow + Teuchos::as<size_t>(dofsPerNode) + 1));
305 const auto detectedRowMapHost = Kokkos::create_mirror_view_and_copy(
306 Kokkos::HostSpace(), detectedRowMap);
307 const size_t firstEntry = detectedRowMapHost(0);
308 const size_t lastEntry =
309 detectedRowMapHost(Teuchos::as<size_t>(dofsPerNode));
310 const auto detectedEntries = Kokkos::subview(
311 localA.graph.entries, std::make_pair(firstEntry, lastEntry));
312 using device_type =
typename Node::device_type;
313 using execution_space =
typename device_type::execution_space;
314 Kokkos::View<LO*, device_type> detectedOwnedColumns(
315 Kokkos::ViewAllocateWithoutInitializing(
316 "StructuredRAP: detected owned columns"),
317 lastEntry - firstEntry);
318 const auto rowLocalMap = rowMap->getLocalMap();
319 const auto colLocalMap = colMap->getLocalMap();
320 Kokkos::parallel_for(
321 "StructuredRAP: map detected stencil columns",
322 Kokkos::RangePolicy<execution_space>(0, lastEntry - firstEntry),
323 KOKKOS_LAMBDA(
const size_t entry) {
324 const GO globalColumn =
325 colLocalMap.getGlobalElement(detectedEntries(entry));
326 detectedOwnedColumns(entry) =
327 rowLocalMap.getLocalElement(globalColumn);
329 const auto detectedOwnedColumnsHost =
330 Kokkos::create_mirror_view_and_copy(
331 Kokkos::HostSpace(), detectedOwnedColumns);
333 for (LO rowDof = 0; rowDof < dofsPerNode; ++rowDof) {
334 const size_t rowBegin = detectedRowMapHost(Teuchos::as<size_t>(rowDof));
335 const size_t rowEnd =
336 detectedRowMapHost(Teuchos::as<size_t>(rowDof) + 1);
337 if (rowBegin == rowEnd)
338 hasCompleteLocalStencil =
false;
339 auto& rowColumns = ownedColumns[Teuchos::as<size_t>(rowDof)];
340 rowColumns.reserve(rowEnd - rowBegin);
341 for (
size_t entry = rowBegin; entry < rowEnd; ++entry) {
342 const LO ownedColumn =
343 detectedOwnedColumnsHost(entry - firstEntry);
344 rowColumns.push_back(ownedColumn);
345 if (ownedColumn == invalidLocalOrdinal)
346 hasCompleteLocalStencil =
false;
351 const int myRank = comm->getRank();
352 const int numRanks = comm->getSize();
353 const int candidateRank = hasCompleteLocalStencil ? myRank : numRanks;
354 int detectorRank = numRanks;
355 Teuchos::reduceAll(*comm, Teuchos::REDUCE_MIN, 1, &candidateRank, &detectorRank);
356 TEUCHOS_TEST_FOR_EXCEPTION(
358 prefix <<
"no MPI rank owns a local interior node whose complete stencil is locally owned; "
359 <<
"increase the local structured subdomain size.");
366 if (myRank == detectorRank) {
367 for (LO rowDof = 0; rowDof < dofsPerNode; ++rowDof) {
368 const auto& rowColumns = ownedColumns[Teuchos::as<size_t>(rowDof)];
369 const size_t rowLength = rowColumns.size();
370 for (
size_t entry = 0; entry < rowLength; ++entry) {
371 const LO ownedColumn = rowColumns[entry];
372 const LO columnNode = ownedColumn / dofsPerNode;
373 const LO columnDof = ownedColumn % dofsPerNode;
374 LO columnX, columnY, columnZ;
376 columnNode, fineNodes, columnX, columnY, columnZ);
378 Teuchos::as<int>(columnX - interior[0]),
379 Teuchos::as<int>(columnY - interior[1]),
380 Teuchos::as<int>(columnZ - interior[2])};
382 bool knownOffset =
false;
384 if (known.
x == offset.
x && known.
y == offset.
y && known.
z == offset.
z) {
393 offset, rowDof, columnDof});
399 Teuchos::as<int>(stencil.
entries.size())};
400 Teuchos::broadcast<int, int>(*comm, detectorRank, 2, counts);
402 Teuchos::Array<int> offsetData(3 * counts[0]);
403 Teuchos::Array<int> entryOffsetData(3 * counts[1]);
404 Teuchos::Array<LO> entryData(2 * counts[1]);
405 if (myRank == detectorRank) {
406 for (
int offset = 0; offset < counts[0]; ++offset) {
411 for (
int entry = 0; entry < counts[1]; ++entry) {
412 entryOffsetData[3 * entry] = stencil.
entries[entry].offset.x;
413 entryOffsetData[3 * entry + 1] = stencil.
entries[entry].offset.y;
414 entryOffsetData[3 * entry + 2] = stencil.
entries[entry].offset.z;
415 entryData[2 * entry] = stencil.
entries[entry].rowDof;
416 entryData[2 * entry + 1] = stencil.
entries[entry].columnDof;
421 Teuchos::broadcast<int, int>(*comm, detectorRank, 3 * counts[0],
422 offsetData.getRawPtr());
424 Teuchos::broadcast<int, int>(*comm, detectorRank, 3 * counts[1],
425 entryOffsetData.getRawPtr());
426 Teuchos::broadcast<int, LO>(*comm, detectorRank, 2 * counts[1],
427 entryData.getRawPtr());
430 if (myRank != detectorRank) {
432 for (
int offset = 0; offset < counts[0]; ++offset)
434 offsetData[3 * offset], offsetData[3 * offset + 1],
435 offsetData[3 * offset + 2]});
437 stencil.
entries.reserve(counts[1]);
438 for (
int entry = 0; entry < counts[1]; ++entry)
440 StencilOffset{entryOffsetData[3 * entry],
441 entryOffsetData[3 * entry + 1],
442 entryOffsetData[3 * entry + 2]},
443 entryData[2 * entry], entryData[2 * entry + 1]});
447 prefix <<
"the representative interior rows are empty.");
532 RCP<Matrix>& Ac,
const RCP<Matrix>& P,
533 const Teuchos::Array<LocalOrdinal>& lCoarseNodesPerDim,
535 using local_graph_type =
typename CrsGraph::local_graph_type;
536 using row_map_type =
typename local_graph_type::row_map_type::non_const_type;
537 using entries_type =
typename local_graph_type::entries_type::non_const_type;
538 using device_type =
typename Node::device_type;
539 using execution_space =
typename device_type::execution_space;
540 using range_policy = Kokkos::RangePolicy<execution_space, Kokkos::IndexType<size_t>>;
543 "StructuredRAPFactory::GetStructuredGraph(" << graphSpec.
description
544 <<
"): number of dimensions must be between one and three.");
546 "StructuredRAPFactory::GetStructuredGraph(" << graphSpec.
description
547 <<
"): insufficient local coarse-grid dimensions.");
549 "StructuredRAPFactory::GetStructuredGraph(" << graphSpec.
description
550 <<
"): dofsPerNode must be positive.");
552 "StructuredRAPFactory::GetStructuredGraph(" << graphSpec.
description
553 <<
"): coarse-grid stencil is empty; it must define at least one relative node position (dx, dy, dz).");
554 constexpr size_t maxSupportedStencilSize = 27;
555 constexpr size_t maxSupportedDofsPerNode = 3;
557 "StructuredRAPFactory::GetStructuredGraph(" << graphSpec.
description
558 <<
"): a radius-one stencil may contain at most 27 entries.");
560 "StructuredRAPFactory::GetStructuredGraph(" << graphSpec.
description
561 <<
"): at most three DOFs per node are supported.");
563 Kokkos::Array<GO, 3> localNodes{{GO(1), GO(1), GO(1)}};
565 localNodes[dim] = Teuchos::as<GO>(lCoarseNodesPerDim[dim]);
567 "StructuredRAPFactory::GetStructuredGraph(" << graphSpec.
description
568 <<
"): local coarse dimensions must be positive.");
571 Kokkos::Array<StencilOffset, maxSupportedStencilSize> stencilOffsets{};
572 Kokkos::Array<GO, maxSupportedStencilSize> localStencilNodeOffsets{};
573 for (
size_t stencil = 0; stencil < graphSpec.
stencilOffsets.size(); ++stencil) {
575 TEUCHOS_TEST_FOR_EXCEPTION(offset.
x < -1 || offset.
x > 1 ||
576 offset.
y < -1 || offset.
y > 1 ||
577 offset.
z < -1 || offset.
z > 1,
579 "StructuredRAPFactory::GetStructuredGraph(" << graphSpec.
description
580 <<
"): only radius-one stencil offsets are currently supported.");
581 TEUCHOS_TEST_FOR_EXCEPTION((graphSpec.
numDimensions < 2 && offset.
y != 0) ||
584 "StructuredRAPFactory::GetStructuredGraph(" << graphSpec.
description
585 <<
"): stencil contains an offset in an inactive dimension.");
586 stencilOffsets[stencil] = offset;
587 localStencilNodeOffsets[stencil] =
588 static_cast<GO
>(offset.
x) +
static_cast<GO
>(offset.
y) * localNodes[0] +
589 static_cast<GO
>(offset.
z) * localNodes[0] * localNodes[1];
592 RCP<ParameterList> paramList = rcp(
new ParameterList);
593 paramList->set(
"No Nonlocal Changes",
true);
594 paramList->set(
"Optimize Storage",
true);
595 paramList->set(
"compute global constants",
true);
598 auto rowMap = P->getDomainMap();
599 const size_t localNumRows = rowMap->getLocalNumElements();
601 const GO dofsPerNodeGO = Teuchos::as<GO>(dofsPerNode);
602 const size_t rowsPerNode = Teuchos::as<size_t>(dofsPerNode);
603 const GO localNumNodesGO = localNodes[0] * localNodes[1] * localNodes[2];
604 const size_t localNumNodes = Teuchos::as<size_t>(localNumNodesGO);
605 const GO expectedLocalRows = localNumNodesGO * dofsPerNodeGO;
607 "StructuredRAPFactory::GetStructuredGraph(" << graphSpec.
description
608 <<
"): local coarse dimensions with " << graphSpec.
dofsPerNode
609 <<
" dofs per node do not match local coarse row count "
610 << localNumRows <<
".");
612 "StructuredRAPFactory::GetStructuredGraph requires the Tpetra backend.");
614 const GO numGlobalRows = Teuchos::as<GO>(rowMap->getGlobalNumElements());
616 "StructuredRAPFactory::GetStructuredGraph(" << graphSpec.
description
617 <<
"): global coarse row count is not divisible by dofsPerNode.");
618 const GO numGlobalNodes = numGlobalRows / dofsPerNodeGO;
619 const GO globalMinGid = rowMap->getMinAllGlobalIndex();
620 const GO globalMaxGid = rowMap->getMaxAllGlobalIndex();
622 "StructuredRAPFactory::GetStructuredGraph(" << graphSpec.
description
623 <<
"): coarse row-map GIDs must form a contiguous range.");
625 RCP<const Teuchos::Comm<int>> comm = rowMap->getComm();
626 const int myRank = comm->getRank();
627 const int numRanks = comm->getSize();
628 const GO localMinGid = rowMap->getMinGlobalIndex();
630 "StructuredRAPFactory::GetStructuredGraph(" << graphSpec.
description
631 <<
"): local row range does not begin at a nodal boundary.");
632 const GO firstLocalNode = (localMinGid - globalMinGid) / dofsPerNodeGO;
634 Teuchos::Array<GO> localRankData(4);
635 localRankData[0] = firstLocalNode;
636 localRankData[1] = localNodes[0];
637 localRankData[2] = localNodes[1];
638 localRankData[3] = localNodes[2];
639 Teuchos::Array<GO> rankData(4 * numRanks);
640 Teuchos::gatherAll(*comm, 4, localRankData.getRawPtr(),
641 4 * numRanks, rankData.getRawPtr());
644 Kokkos::Array<int, 3> procGrid{{1, 1, 1}};
646 procGrid[0] = numRanks;
648 while ((procGrid[0] + 1) * (procGrid[0] + 1) <= numRanks)
650 procGrid[1] = numRanks / procGrid[0];
651 while (procGrid[0] * procGrid[1] != numRanks)
652 procGrid[1] = numRanks / (--procGrid[0]);
654 int cubeRootNumRanks = 1;
655 while ((cubeRootNumRanks + 1) * (cubeRootNumRanks + 1) * (cubeRootNumRanks + 1) <= numRanks)
657 procGrid[0] = cubeRootNumRanks;
658 procGrid[1] = cubeRootNumRanks;
659 procGrid[2] = cubeRootNumRanks;
661 if (procGrid[0] * procGrid[1] * procGrid[2] != numRanks) {
666 int procTemp = numRanks;
668 const int galeriFactorSearchLimit = 50;
669 int factors[galeriFactorSearchLimit] = {};
670 for (
int factor = 2; factor < galeriFactorSearchLimit; ++factor) {
671 while (procTemp % factor == 0) {
676 procGrid[0] = procTemp;
677 for (
int factor = galeriFactorSearchLimit - 1; factor > 0; --factor) {
678 while (factors[factor] != 0) {
679 if (procGrid[0] <= procGrid[1] && procGrid[0] <= procGrid[2])
680 procGrid[0] *= factor;
681 else if (procGrid[1] <= procGrid[0] && procGrid[1] <= procGrid[2])
682 procGrid[1] *= factor;
684 procGrid[2] *= factor;
691 const int procXY = procGrid[0] * procGrid[1];
692 TEUCHOS_TEST_FOR_EXCEPTION(procGrid[0] <= 0 || procGrid[1] <= 0 || procGrid[2] <= 0 ||
693 procXY * procGrid[2] != numRanks,
695 "StructuredRAPFactory::GetStructuredGraph(" << graphSpec.
description
696 <<
"): invalid inferred processor grid "
697 << procGrid[0] <<
"x" << procGrid[1] <<
"x" << procGrid[2]
698 <<
" for " << numRanks <<
" ranks.");
700 const int myProcX = myRank % procGrid[0];
701 const int myProcY = (myRank % procXY) / procGrid[0];
702 const int myProcZ = myRank / procXY;
704 Kokkos::Array<GO, 3> globalNodes{{GO(0), GO(0), GO(0)}};
705 for (
int px = 0; px < procGrid[0]; ++px)
706 globalNodes[0] += rankData[4 * px + 1];
707 for (
int py = 0; py < procGrid[1]; ++py)
708 globalNodes[1] += rankData[4 * (py * procGrid[0]) + 2];
709 for (
int pz = 0; pz < procGrid[2]; ++pz)
710 globalNodes[2] += rankData[4 * (pz * procXY) + 3];
711 TEUCHOS_TEST_FOR_EXCEPTION(globalNodes[0] * globalNodes[1] * globalNodes[2] != numGlobalNodes,
713 "StructuredRAPFactory::GetStructuredGraph(" << graphSpec.
description
714 <<
"): processor-grid coarse dimensions do not match coarse node count.");
716 execution_space executionSpace;
717 Kokkos::View<GO*, device_type> rankDataDevice(
718 Kokkos::ViewAllocateWithoutInitializing(
"StructuredRAP: rank metadata"), rankData.size());
719 auto rankDataHost = Kokkos::create_mirror_view(rankDataDevice);
720 for (
int entry = 0; entry < rankData.size(); ++entry)
721 rankDataHost(entry) = rankData[entry];
722 Kokkos::deep_copy(executionSpace, rankDataDevice, rankDataHost);
729 const auto rowLocalMap = rowMap->getLocalMap();
730 size_t invalidLocalRows = 0;
731 Kokkos::parallel_reduce(
732 "StructuredRAP: validate local rows", range_policy(executionSpace, 0, localNumRows),
733 KOKKOS_LAMBDA(
const size_t rowLid,
size_t& invalid) {
734 const GO rowGid = rowLocalMap.getGlobalElement(
static_cast<LO
>(rowLid));
735 const GO expectedRowGid = localMinGid +
static_cast<GO
>(rowLid);
736 if (rowGid != expectedRowGid)
741 "StructuredRAPFactory::GetStructuredGraph(" << graphSpec.
description
742 <<
"): coarse row-map GIDs are not locally contiguous and ordered.");
747 constexpr size_t maxNeighborRegions = 26;
748 Kokkos::Array<int, maxNeighborRegions> remoteRegionRanks{};
749 Kokkos::Array<StencilOffset, maxNeighborRegions> remoteRegionDirections{};
750 Kokkos::Array<GO, maxNeighborRegions> remoteRegionFirstNodes{};
751 Kokkos::Array<GO, maxNeighborRegions> remoteRegionNx{};
752 Kokkos::Array<GO, maxNeighborRegions> remoteRegionNy{};
753 Kokkos::Array<GO, maxNeighborRegions> remoteRegionNz{};
754 Kokkos::Array<size_t, maxNeighborRegions + 1> remoteRegionOffsets{};
755 size_t numRemoteRegions = 0;
761 for (
int procDz = minProcZ; procDz <= maxProcZ; ++procDz) {
762 for (
int procDy = minProcY; procDy <= maxProcY; ++procDy) {
763 for (
int procDx = -1; procDx <= 1; ++procDx) {
764 if (procDx == 0 && procDy == 0 && procDz == 0)
767 bool stencilReachesRegion =
false;
768 for (
size_t stencil = 0; stencil < stencilSize; ++stencil) {
770 const bool reachesX = procDx == 0 || offset.
x == procDx;
771 const bool reachesY = procDy == 0 || offset.
y == procDy;
772 const bool reachesZ = procDz == 0 || offset.
z == procDz;
773 if (reachesX && reachesY && reachesZ) {
774 stencilReachesRegion =
true;
778 if (!stencilReachesRegion)
781 const int neighborProcX = myProcX + procDx;
782 const int neighborProcY = myProcY + procDy;
783 const int neighborProcZ = myProcZ + procDz;
784 if (neighborProcX < 0 || neighborProcX >= procGrid[0] ||
785 neighborProcY < 0 || neighborProcY >= procGrid[1] ||
786 neighborProcZ < 0 || neighborProcZ >= procGrid[2])
789 const int neighborRank = neighborProcZ * procXY + neighborProcY * procGrid[0] + neighborProcX;
790 const GO neighborNx = rankData[4 * neighborRank + 1];
791 const GO neighborNy = rankData[4 * neighborRank + 2];
792 const GO neighborNz = rankData[4 * neighborRank + 3];
793 const size_t regionNodes = Teuchos::as<size_t>((procDx == 0 ? neighborNx : 1) *
794 (procDy == 0 ? neighborNy : 1) *
795 (procDz == 0 ? neighborNz : 1));
797 remoteRegionRanks[numRemoteRegions] = neighborRank;
798 remoteRegionDirections[numRemoteRegions] =
StencilOffset{procDx, procDy, procDz};
799 remoteRegionFirstNodes[numRemoteRegions] = rankData[4 * neighborRank];
800 remoteRegionNx[numRemoteRegions] = neighborNx;
801 remoteRegionNy[numRemoteRegions] = neighborNy;
802 remoteRegionNz[numRemoteRegions] = neighborNz;
803 remoteRegionOffsets[numRemoteRegions + 1] =
804 remoteRegionOffsets[numRemoteRegions] + regionNodes * rowsPerNode;
809 const size_t numRemoteColumns = remoteRegionOffsets[numRemoteRegions];
811 RCP<const Map> colMap;
812 if (numRemoteColumns == 0) {
815 Kokkos::View<GO*, device_type> colMapGids(
816 Kokkos::ViewAllocateWithoutInitializing(
"StructuredRAP: column map GIDs"),
817 localNumRows + numRemoteColumns);
818 const auto localRowGidsDevice = rowMap->getMyGlobalIndicesDevice();
819 Kokkos::parallel_for(
820 "StructuredRAP: fill column map", range_policy(executionSpace, 0, localNumRows + numRemoteColumns),
821 KOKKOS_LAMBDA(
const size_t entry) {
822 if (entry < localNumRows) {
823 colMapGids(entry) = localRowGidsDevice(entry);
827 const size_t remoteEntry = entry - localNumRows;
829 while (remoteEntry >= remoteRegionOffsets[region + 1])
832 const StencilOffset direction = remoteRegionDirections[region];
833 const GO neighborNx = remoteRegionNx[region];
834 const GO neighborNy = remoteRegionNy[region];
835 const GO neighborNz = remoteRegionNz[region];
836 size_t regionEntry = remoteEntry - remoteRegionOffsets[region];
837 const GO dof =
static_cast<GO
>(regionEntry % rowsPerNode);
838 size_t regionNode = regionEntry / rowsPerNode;
840 GO neighborX = direction.
x < 0 ? neighborNx - 1 : 0;
841 GO neighborY = direction.
y < 0 ? neighborNy - 1 : 0;
842 GO neighborZ = direction.
z < 0 ? neighborNz - 1 : 0;
843 if (direction.
x == 0) {
844 neighborX =
static_cast<GO
>(regionNode %
static_cast<size_t>(neighborNx));
845 regionNode /=
static_cast<size_t>(neighborNx);
847 if (direction.
y == 0) {
848 neighborY =
static_cast<GO
>(regionNode %
static_cast<size_t>(neighborNy));
849 regionNode /=
static_cast<size_t>(neighborNy);
851 if (direction.
z == 0)
852 neighborZ =
static_cast<GO
>(regionNode);
854 const GO neighborNode = remoteRegionFirstNodes[region] +
855 neighborZ * neighborNx * neighborNy + neighborY * neighborNx + neighborX;
856 colMapGids(entry) = globalMinGid + neighborNode * dofsPerNodeGO + dof;
858 executionSpace.fence(
"StructuredRAP: column map GIDs ready");
860 typename Map::global_indices_array_device_type constColMapGids = colMapGids;
861 colMap = MapFactory::Build(
862 rowMap->lib(), Teuchos::OrdinalTraits<Xpetra::global_size_t>::invalid(),
863 constColMapGids, rowMap->getIndexBase(), comm);
870 constexpr size_t numBoundaryClasses = 64;
871 Kokkos::Array<std::int64_t, numBoundaryClasses> prefixConstant{};
872 Kokkos::Array<std::int64_t, numBoundaryClasses> prefixX{};
873 Kokkos::Array<std::int64_t, numBoundaryClasses> prefixY{};
874 Kokkos::Array<std::int64_t, numBoundaryClasses> prefixZ{};
876 const int procCoordinates[3] = {myProcX, myProcY, myProcZ};
877 for (
size_t stencil = 0; stencil < stencilSize; ++stencil) {
879 const int offsets[3] = {offset.
x, offset.
y, offset.
z};
880 GO lower[3] = {0, 0, 0};
881 GO upper[3] = {localNodes[0], localNodes[1], localNodes[2]};
882 for (
int dim = 0; dim < 3; ++dim) {
883 if (offsets[dim] < 0 && procCoordinates[dim] == 0)
885 if (offsets[dim] > 0 && procCoordinates[dim] + 1 == procGrid[dim])
888 const std::int64_t lengths[3] = {
889 static_cast<std::int64_t
>(upper[0] - lower[0]),
890 static_cast<std::int64_t
>(upper[1] - lower[1]),
891 static_cast<std::int64_t
>(upper[2] - lower[2])};
892 localNnz +=
static_cast<size_t>(lengths[0] * lengths[1] * lengths[2]) *
893 rowsPerNode * rowsPerNode;
895 for (
size_t boundaryClass = 0; boundaryClass < numBoundaryClasses; ++boundaryClass) {
896 std::int64_t coordinates[3];
897 for (
int dim = 0; dim < 3; ++dim) {
898 const bool low = boundaryClass & (size_t(1) << (2 * dim));
899 const bool high = boundaryClass & (size_t(2) << (2 * dim));
900 coordinates[dim] = low ? 0 : high ?
static_cast<std::int64_t
>(localNodes[dim] - 1)
903 std::int64_t* coefficients[3] = {
904 &prefixX[boundaryClass], &prefixY[boundaryClass], &prefixZ[boundaryClass]};
905 auto addClamped = [&](
const int dim,
const std::int64_t multiplier) {
906 const std::int64_t begin =
static_cast<std::int64_t
>(lower[dim]);
907 const std::int64_t end =
static_cast<std::int64_t
>(upper[dim]);
908 if (coordinates[dim] >= end)
909 prefixConstant[boundaryClass] += (end - begin) * multiplier;
910 else if (coordinates[dim] >= begin) {
911 prefixConstant[boundaryClass] -= begin * multiplier;
912 *coefficients[dim] += multiplier;
915 const bool insideZ = coordinates[2] >= lower[2] && coordinates[2] < upper[2];
916 const bool insideY = coordinates[1] >= lower[1] && coordinates[1] < upper[1];
917 addClamped(2, lengths[0] * lengths[1]);
919 addClamped(1, lengths[0]);
920 if (insideZ && insideY)
926 Kokkos::ViewAllocateWithoutInitializing(
"StructuredRAP: graph row pointers"), localNumRows + 1);
929 Kokkos::ViewAllocateWithoutInitializing(
930 "StructuredRAP: graph column indices"),
933 const LO invalidLocalOrdinal = Teuchos::OrdinalTraits<LO>::invalid();
934 Kokkos::View<int, device_type> invalidColumn;
936 invalidColumn = Kokkos::View<int, device_type>(
"StructuredRAP: invalid column");
937 Kokkos::deep_copy(executionSpace, invalidColumn, 0);
942 Kokkos::parallel_for(
943 "StructuredRAP: fill graph column indices", range_policy(executionSpace, 0, localNumNodes),
944 KOKKOS_LAMBDA(
const size_t localNodeIndex) {
945 const GO localNode =
static_cast<GO
>(localNodeIndex);
946 GO x = 0, y = 0, z = 0;
948 const size_t boundaryClass =
949 (x == 0 ? size_t(1) : 0) | (x + 1 == localNodes[0] ?
size_t(2) : 0) |
950 (y == 0 ? size_t(4) : 0) | (y + 1 == localNodes[1] ?
size_t(8) : 0) |
951 (z == 0 ? size_t(16) : 0) | (z + 1 == localNodes[2] ?
size_t(32) : 0);
952 const size_t nodeRowStart =
static_cast<size_t>(
953 prefixConstant[boundaryClass] + prefixX[boundaryClass] *
static_cast<std::int64_t
>(x) +
954 prefixY[boundaryClass] *
static_cast<std::int64_t
>(y) +
955 prefixZ[boundaryClass] *
static_cast<std::int64_t
>(z)) *
956 rowsPerNode * rowsPerNode;
957 size_t columnOffset = 0;
958 const bool isInterior =
959 x > 0 && x + 1 < localNodes[0] &&
960 (numDimensions < 2 || (y > 0 && y + 1 < localNodes[1])) &&
961 (numDimensions < 3 || (z > 0 && z + 1 < localNodes[2]));
964 const size_t firstRow = localNodeIndex * rowsPerNode;
965 const size_t rowLength = stencilSize * rowsPerNode;
966 for (
size_t rowDof = 0; rowDof < rowsPerNode; ++rowDof)
967 rowptr(firstRow + rowDof) = nodeRowStart + rowDof * rowLength;
968 for (
size_t stencil = 0; stencil < stencilSize; ++stencil) {
969 const GO neighborLocalNode = localNode + localStencilNodeOffsets[stencil];
970 for (
size_t colDof = 0; colDof < rowsPerNode; ++colDof) {
971 const LO colLid =
static_cast<LO
>(
972 neighborLocalNode * dofsPerNodeGO +
static_cast<GO
>(colDof));
973 for (
size_t rowDof = 0; rowDof < rowsPerNode; ++rowDof)
974 colind(rowptr(firstRow + rowDof) + columnOffset) = colLid;
978 if (localNodeIndex + 1 == localNumNodes)
979 rowptr(localNumRows) = localNnz;
983 Kokkos::Array<LO, maxSupportedStencilSize * maxSupportedDofsPerNode> nodeColumns;
984 for (
size_t stencil = 0; stencil < stencilSize; ++stencil) {
985 int neighborRank = myRank;
988 x, y, z, stencilOffsets[stencil], localNodes, procGrid, rankDataDevice,
989 myProcX, myProcY, myProcZ, neighborRank, neighborNode))
992 for (
size_t colDof = 0; colDof < rowsPerNode; ++colDof) {
993 const GO colGid = globalMinGid + neighborNode * dofsPerNodeGO +
static_cast<GO
>(colDof);
994 LO colLid = invalidLocalOrdinal;
995 if (neighborRank == myRank) {
996 colLid =
static_cast<LO
>(colGid - localMinGid);
999 while (region < numRemoteRegions && remoteRegionRanks[region] != neighborRank)
1001 if (region < numRemoteRegions) {
1002 const GO neighborNx = remoteRegionNx[region];
1003 const GO neighborNy = remoteRegionNy[region];
1004 const GO localNeighborNode = neighborNode - remoteRegionFirstNodes[region];
1005 const GO neighborX = localNeighborNode % neighborNx;
1006 const GO neighborY = (localNeighborNode / neighborNx) % neighborNy;
1007 const GO neighborZ = localNeighborNode / (neighborNx * neighborNy);
1008 const StencilOffset direction = remoteRegionDirections[region];
1009 size_t regionNode = 0;
1011 if (direction.
x == 0) {
1012 regionNode +=
static_cast<size_t>(neighborX) * stride;
1013 stride *=
static_cast<size_t>(neighborNx);
1015 if (direction.
y == 0) {
1016 regionNode +=
static_cast<size_t>(neighborY) * stride;
1017 stride *=
static_cast<size_t>(neighborNy);
1019 if (direction.
z == 0)
1020 regionNode +=
static_cast<size_t>(neighborZ) * stride;
1021 colLid =
static_cast<LO
>(localNumRows + remoteRegionOffsets[region] +
1022 regionNode * rowsPerNode + colDof);
1026 if (debug && colLid == invalidLocalOrdinal)
1027 Kokkos::atomic_exchange(&invalidColumn(), 1);
1029 nodeColumns[columnOffset++] = colLid;
1033 for (
size_t entry = 1; entry < columnOffset; ++entry) {
1034 const LO value = nodeColumns[entry];
1035 size_t insertion = entry;
1036 while (insertion > 0 && value < nodeColumns[insertion - 1]) {
1037 nodeColumns[insertion] = nodeColumns[insertion - 1];
1040 nodeColumns[insertion] = value;
1043 const size_t firstRow = localNodeIndex * rowsPerNode;
1044 const size_t rowLength = columnOffset;
1045 for (
size_t rowDof = 0; rowDof < rowsPerNode; ++rowDof) {
1046 const size_t rowStart = nodeRowStart + rowDof * rowLength;
1047 rowptr(firstRow + rowDof) = rowStart;
1048 for (
size_t entry = 0; entry < columnOffset; ++entry)
1049 colind(rowStart + entry) = nodeColumns[entry];
1051 if (localNodeIndex + 1 == localNumNodes)
1052 rowptr(localNumRows) = localNnz;
1054 executionSpace.fence(
"StructuredRAP: graph column indices ready");
1058 int invalidColumnHost = 0;
1059 Kokkos::deep_copy(executionSpace, invalidColumnHost, invalidColumn);
1061 "StructuredRAPFactory::GetStructuredGraph(" << graphSpec.
description
1062 <<
"): a generated column GID was not found in the coarse column map.");
1064 size_t unsortedRows = 0;
1065 Kokkos::parallel_reduce(
1066 "StructuredRAP: validate sorted graph rows", range_policy(executionSpace, 0, localNumRows),
1067 KOKKOS_LAMBDA(
const size_t row,
size_t& invalid) {
1068 for (
size_t entry = rowptr(row) + 1; entry < rowptr(row + 1); ++entry) {
1069 if (colind(entry) < colind(entry - 1)) {
1077 "StructuredRAPFactory::GetStructuredGraph(" << graphSpec.
description
1078 <<
"): generated graph rows are not sorted.");
1081 local_graph_type localGraph(colind, rowptr);
1082 RCP<CrsGraph> graph = CrsGraphFactory::Build(
1083 localGraph, rowMap, colMap, rowMap, rowMap, paramList);
1084 using values_type =
typename Matrix::local_matrix_type::values_type;
1086 Kokkos::ViewAllocateWithoutInitializing(
1087 "StructuredRAP: matrix values"),
1089 Ac = MatrixFactory::Build(graph, values, paramList);
1094 const bool doTranspose =
true;
1095 const bool doFillComplete =
true;
1096 const bool doOptimizeStorage =
true;
1098 const bool useRAPDelegate =
1099 !pL.get<
bool>(
"rap: prebuild coarse graph");
1101 TEUCHOS_TEST_FOR_EXCEPTION(
1103 "StructuredRAPFactory requires \"transpose: use implicit\" = true because "
1104 "the prebuilt coarse graph assumes the Galerkin product P^T A P.");
1109 "MueLu::RAPFactory::Build(): CallDeclareInput has not been called before Build!");
1111 if (useRAPDelegate) {
1112 if (pL.get<std::string>(
"rap: triple product implementation") ==
1115 <<
"StructuredRAP: Coarse graph prebuilding is disabled, "
1116 "redirecting the structured triple product to Xpetra."
1119 if (coarseLevel.
IsAvailable(
"RAP reuse data",
this)) {
1120 RCP<ParameterList> RAPparams = coarseLevel.
Get<RCP<ParameterList>>(
"RAP reuse data",
this);
1129 Set(coarseLevel,
"A", Ac);
1132 RCP<ParameterList> RAPparams = coarseLevel.
Get<RCP<ParameterList>>(
"RAP reuse data",
rapFactoryDelegate_.get());
1133 Set(coarseLevel,
"RAP reuse data", RAPparams);
1143 std::ostringstream levelstr;
1146 TEUCHOS_TEST_FOR_EXCEPTION(
1148 "StructuredRAPFactory requires \"rap: triple product\" = true.");
1152 const std::string tripleProductImplementation =
1153 pL.get<std::string>(
"rap: triple product implementation");
1154 TEUCHOS_TEST_FOR_EXCEPTION(
1155 tripleProductImplementation !=
"unstructured" && tripleProductImplementation !=
"structured",
1157 "StructuredRAPFactory: unknown value \"" << tripleProductImplementation
1158 <<
"\" for \"rap: triple product implementation\". "
1159 "Valid values are \"unstructured\" and \"structured\".");
1161 const RCP<const FactoryBase> coarseDimensionsFactory =
1163 const RCP<const FactoryBase> interpolationOrderFactory =
1165 const Teuchos::Array<LocalOrdinal> lCoarseNodesPerDim =
1166 fineLevel.Get<Teuchos::Array<LocalOrdinal>>(
1167 "lCoarseNodesPerDim", coarseDimensionsFactory.get());
1168 const int interpolationOrder =
1169 fineLevel.Get<
int>(
"structuredInterpolationOrder",
1170 interpolationOrderFactory.get());
1171 const int numDimensions =
1172 fineLevel.GetLevelID() == 0
1174 :
Get<int>(fineLevel,
"numDimensions");
1175 const Teuchos::Array<LocalOrdinal> lFineNodesPerDim =
1176 fineLevel.GetLevelID() == 0
1177 ? fineLevel.Get<Teuchos::Array<LocalOrdinal>>(
1180 Teuchos::Array<int> structuredCoarseningRate;
1181 if (tripleProductImplementation ==
"structured") {
1187 const Factory* structuredFactory =
1188 dynamic_cast<const Factory*
>(coarseDimensionsFactory.get());
1189 TEUCHOS_TEST_FOR_EXCEPTION(
1191 "StructuredRAPFactory: the factory producing lCoarseNodesPerDim "
1192 "does not expose its aggregation parameters.");
1193 const ParameterList& structuredParameters =
1195 TEUCHOS_TEST_FOR_EXCEPTION(
1196 !structuredParameters.isType<std::string>(
1197 "aggregation: coarsening rate"),
1199 "StructuredRAPFactory: the factory producing lCoarseNodesPerDim "
1200 "does not provide the string parameter \"aggregation: coarsening "
1203 structuredCoarseningRate = Teuchos::fromStringToArray<int>(
1204 structuredParameters.get<std::string>(
1205 "aggregation: coarsening rate"));
1206 }
catch (
const Teuchos::InvalidArrayStringRepresentation& e) {
1208 <<
" *** \"aggregation: coarsening rate\" must be a string "
1209 "convertible into an array! *** "
1216 Set(coarseLevel,
"A", Ac);
1226 RCP<ParameterList> RAPparams;
1230 RAPparams = rcp(
new ParameterList);
1231 if (pL.isSublist(
"matrixmatrix: kernel params"))
1232 RAPparams->sublist(
"matrixmatrix: kernel params") = pL.sublist(
"matrixmatrix: kernel params");
1234 if (coarseLevel.IsAvailable(
"RAP reuse data",
this)) {
1237 RAPparams = coarseLevel.Get<RCP<ParameterList>>(
"RAP reuse data",
this);
1239 "StructuredRAPFactory::Build(): \"RAP reuse data\" does not contain the expected graph.");
1240 Ac = RAPparams->get<RCP<Matrix>>(
"graph");
1242 "StructuredRAPFactory::Build(): \"RAP reuse data\" graph is null.");
1243 Ac->SetMaxEigenvalueEstimate(-Teuchos::ScalarTraits<SC>::one());
1249 <<
" nodal entries." << std::endl;
1255 RAPparams->set(
"compute global constants: temporaries", RAPparams->get(
"compute global constants: temporaries",
false));
1256 RAPparams->set(
"compute global constants",
true);
1258 if (tripleProductImplementation ==
"unstructured") {
1259 SubFactoryMonitor m2(*
this,
"MxMxM: Xpetra P^T x A x P (implicit)", coarseLevel);
1260 Xpetra::TripleMatrixMultiply<SC, LO, GO, NO>::
1261 MultiplyRAP(*P, doTranspose, *A, !doTranspose, *P, !doTranspose, *Ac, doFillComplete,
1262 doOptimizeStorage, labelstr + std::string(
"MueLu::Xpetra-P^T*A*P-implicit-") + levelstr.str(),
1265 SubFactoryMonitor m2(*
this,
"MxMxM: Structured P^T x A x P (implicit)", coarseLevel);
1267 *A, *P, *Ac, fineStencil, interpolationOrder,
1268 lFineNodesPerDim, lCoarseNodesPerDim,
1269 structuredCoarseningRate, RAPparams);
1271 Ac->CreateView(
"stridedMaps", P,
true, P,
false);
1276 << Ac->getLocalNumEntries()
1277 <<
", global = " << Ac->getGlobalNumEntries() << std::endl;
1279 Teuchos::ArrayView<const double> relativeFloor = pL.get<Teuchos::Array<double>>(
"rap: relative diagonal floor")();
1280 if (relativeFloor.size() > 0) {
1281 Xpetra::MatrixUtils<SC, LO, GO, NO>::RelativeDiagonalBoost(Ac, relativeFloor,
GetOStream(
Statistics2));
1284 bool repairZeroDiagonals = pL.get<
bool>(
"RepairMainDiagonal") || pL.get<
bool>(
"rap: fix zero diagonals");
1285 bool checkAc = pL.get<
bool>(
"CheckMainDiagonal") || pL.get<
bool>(
"rap: fix zero diagonals");
1286 if (checkAc || repairZeroDiagonals) {
1287 using magnitudeType =
typename Teuchos::ScalarTraits<Scalar>::magnitudeType;
1288 magnitudeType threshold;
1289 if (pL.isType<magnitudeType>(
"rap: fix zero diagonals threshold"))
1290 threshold = pL.get<magnitudeType>(
"rap: fix zero diagonals threshold");
1292 threshold = Teuchos::as<magnitudeType>(pL.get<
double>(
"rap: fix zero diagonals threshold"));
1293 Scalar replacement = Teuchos::as<Scalar>(pL.get<
double>(
"rap: fix zero diagonals replacement"));
1294 Xpetra::MatrixUtils<SC, LO, GO, NO>::CheckRepairMainDiagonal(Ac, repairZeroDiagonals,
GetOStream(
Warnings1), threshold, replacement);
1298 RCP<ParameterList> params = rcp(
new ParameterList());
1299 params->set(
"printLoadBalancingInfo",
true);
1300 params->set(
"printCommInfo",
true);
1305 std::ostringstream oss;
1306 oss <<
"A_" << coarseLevel.GetLevelID();
1307 Ac->setObjectLabel(oss.str());
1308 Set(coarseLevel,
"A", Ac);
1310 RAPparams->set(
"graph", Ac);
1311 Set(coarseLevel,
"RAP reuse data", RAPparams);
1317 MatrixUtils::checkLocalRowMapMatchesColMap(*Ac);
1324 RCP<const FactoryBase> fac = *it;
1325 GetOStream(
Runtime0) <<
"RAPFactory: call transfer factory: " << fac->description() << std::endl;
1326 fac->CallBuild(coarseLevel);