KASKADE 7 development version
Loading...
Searching...
No Matches
bddc.hh
Go to the documentation of this file.
1
2/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3/* */
4/* This file is part of the library KASKADE 7 */
5/* https://www.zib.de/research/projects/kaskade7-finite-element-toolbox */
6/* */
7/* Copyright (C) 2022-2024 Zuse Institute Berlin */
8/* */
9/* KASKADE 7 is distributed under the terms of the ZIB Academic License. */
10/* see $KASKADE/academic.txt */
11/* */
12/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
13
14#ifndef BDDC_HH
15#define BDDC_HH
16
17#include <cstdint>
18#include <cmath>
19#include <cstring>
20#include <functional>
21#include <iostream>
22#include <limits>
23#include <memory>
24#include <stdexcept>
25#include <string>
26#include <utility>
27
28#include "fem/firstless.hh"
29#include "linalg/direct.hh"
32#include "mg/bddcMpi.hh"
34#include "mg/bddcMpiRouting.hh"
35#include "utilities/enums.hh"
36
37#include "dune/istl/bcrsmatrix.hh"
38
44
45
46namespace Kaskade::BDDC
47{
55 using CoarseConstraints = std::vector<std::pair<std::vector<int>,int>>;
56
64 template <class Subdomain>
66 {
67 public:
68 explicit OwnedSubdomainStorage(size_t size) : slots(size) {}
69
70 size_t size() const { return slots.size(); }
71 bool has(size_t id) const { return id < slots.size() && bool(slots[id]); }
72
74 {
75 if (!has(id))
76 throw std::runtime_error("access to non-owned BDDC subdomain");
77 return *slots[id];
78 }
79
80 Subdomain const& operator[](size_t id) const
81 {
82 if (!has(id))
83 throw std::runtime_error("access to non-owned BDDC subdomain");
84 return *slots[id];
85 }
86
87 template <class... Args>
88 void emplace(size_t id, Args&&... args)
89 {
90 slots[id] = std::make_unique<Subdomain>(std::forward<Args>(args)...);
91 }
92
93 private:
94 std::vector<std::unique_ptr<Subdomain>> slots;
95 };
96
108 struct LocalDof
109 {
110 int s; // subdomain number
111 int i; // local dof index in subdomain
112 };
113
118 enum InterfaceType { CORNER = 1, EDGE = 2, FACE = 4 };
119
127 template <int m=1, class Index=size_t>
129 {
130 public:
131 constexpr static int components = m;
132
141 InterfaceAverages(std::vector<std::vector<LocalDof>> const& sharedDofs,
142 std::vector<Index> const& subdomainSize,
143 int types = CORNER | FACE);
144
158 InterfaceAverages(std::vector<std::vector<LocalDof>> const& sharedDofs,
159 std::vector<Index> const& subdomainSize,
160 int types,
161 std::vector<int> const& partitions);
162
168 Interfaces const& interfaces(int id) const;
169
178 template <class Scalar=double>
180
188
192 std::array<int,3> interfaceCount() const
193 {
194 return ifCount;
195 }
196
197 std::vector<int> const& cornerDofs(int id) const
198 {
199 assert(0 <= id && id < static_cast<int>(cornerDofs_.size()));
200 return cornerDofs_[id];
201 }
202
204 {
205 assert(0 <= id && id < static_cast<int>(interfaceClassifications_.size()));
206 return interfaceClassifications_[id];
207 }
208
209 private:
210 std::vector<Interfaces> ifs;
212 std::vector<Index> subdomainSize;
213
214 std::vector<std::vector<std::vector<int>>> cifs; // coarse interfaces
215 std::array<int,3> ifCount; // number of corners, edges, faces
216 std::vector<std::vector<int>> cornerDofs_;
217 std::vector<InterfaceClassification> interfaceClassifications_;
218 };
219
220 // ----------------------------------------------------------------------------------------------
221
222
223 // ----------------------------------------------------------------------------------------------
224
225
262 template <int m, class Scalar_=double, class CoarseScalar=Scalar_,
263 class Transfer=SpaceTransfer<m,Scalar_>>
265 {
266 public:
270 static const int components = m;
271
275 using Scalar = Scalar_;
276 using TransferType = Transfer;
277
281
285 using TransmissionType = typename Transfer::TransmissionType;
286
287
289
292
297
298
311 template <int cComponents>
312 Subdomain(int id, AMatrix const& A,
313 Interfaces const& interfaces,
315
329 template <class Interface>
330 Subdomain(int id, AMatrix const& A, Interface const& interfaces,
331 bool excludeCornersFromCompression = false);
332
335
340 void setRhs(XVector const& f);
341
353
362
368 void getInterfaceAveragingWeights(int s, XVector& rho) const
369 {
370 trans.getInterfaceAveragingWeights(s,rho);
371 }
372
378 void setInterfaceAveragingWeights(int s, XVector const& rho)
379 {
380 trans.setInterfaceAveragingWeights(s,rho);
381 }
382
386
390 std::vector<int> neighbors() const;
391
424
425
426
434
442 {
443 trans.getInterfaceResidualUpdate(s,dres);
444 }
445
452 {
453 trans.setInterfaceResidualUpdate(s,dres);
454 }
455
456 // Access the space-transfer backend (e.g., compression/encoding state).
457 // SharedMemoryDomain uses this to coordinate shared codebooks across subdomains.
458 Transfer& transfer()
459 {
460 return trans;
461 }
462
463 // Const access for read-only queries (e.g., encoding enabled checks).
464 Transfer const& transfer() const
465 {
466 return trans;
467 }
468
472 void restrict();
473
475
481
492 void getS(SMatrix& S) const;
493
507 void getSchurResidual(Vector& lambda) const;
508
512 void setCorrection(Vector const& c);
513
515
543
550 {
551 trans.preProlongate(du);
552 }
553
559 void getInterfaceValues(int s, TransmissionType& values) const
560 {
561 trans.getInterfaceValues(s,values);
562 }
563
569 void setInterfaceValues(int s, TransmissionType const& values)
570 {
571 trans.setInterfaceValues(s,values);
572 }
573
574 void setActiveId(bool active)
575 {
576 activeId = active;
577 }
578
587
589
593 void updateSearchDirection(double beta);
594
596
601
607 void getSolution(XVector& x) const;
608
618
622 void set_solver_type(bool cg_solver);
625 void setCgUseOriginalResidual(bool enabled) { cgUseOriginalResidual = enabled; }
627 void setFlexibleCg(bool enabled)
628 {
629 flexibleCg = enabled;
630 if (enabled)
631 {
632 cgUseOriginalResidual = true;
633 previousCgResidual.resize(nx);
634 previousCgResidual = 0;
635 }
636 }
637 void updateIteration(int cg_itr);
643 void getCorrection(XVector& dx) const;
644 void getRawCorrection(XVector& dx) const;
645 void getResidual(XVector& rr) const;
646 Vector const& getRestrictedResidual() const { return restrictedResidual; }
647
649 Vector const& diagnosticSearchDirection() const { return q; }
650 Vector const& diagnosticPreconditionedResidual() const { return r_bar; }
651
653 Vector const& diagnosticRawCorrection() const { return rawCorrection; }
654
657 {
658 Vector result = du;
659 for (int i: globalIndex_notActive) result[i] = 0;
660 return result;
661 }
662
665 {
666 Vector weights(nx);
667 trans.diagnosticProlongationWeights(weights);
668 for (int i: globalIndex_notActive) weights[i] = 0;
669 return weights;
670 }
671
681
682
683 std::vector<bool> getActiveSubdomains()
684 {
685 return activeSubdomains_sub;
686 }
687
688 void setActiveSubdomains_sub(std::vector<bool> & activeSubdomains_)
689 {
690 activeSubdomains_sub.resize(activeSubdomains_.size());
691 // std::cout<< "activeSubdomains_.size() = "<<activeSubdomains_.size() <<std::endl;
692 for (int i = 0; i < activeSubdomains_.size(); ++i)
693 {
694 activeSubdomains_sub[i] = activeSubdomains_[i];
695 }
696 }
697
698 private:
700
701 // These variables describe problem size and connectivity
702 int id; // my own subdomain number
703 int N;
704 int nx, nc; // number of dofs and of constraints
705 Interfaces interfaces; // list of pairs (s,ids) of adjacent subdomain s and shared dofs
706 Transfer trans; // manages data conversion and averaging
707
708 Vector f; // the right hand side
709 Vector u; // approximate solution [x,lambda]
710 Vector r; // current residual [f-Au,0]
711 Vector rRes; // restricted residual
712
713 Vector q; // search direction for [CG]
714 Vector q_pre; // search direction for [CG]
715 Vector Aq; // for [CG]
716 Vector r_bar; // previous residual for [CG]
717 Scalar alpha; // step size for [CG]
718 bool cg_solver; // cg = false -> steepest descent method with BDDC, cg = true -> CG with BDDC
719 bool cgUseOriginalResidual = false;
720 bool flexibleCg = false;
721 Vector previousCgResidual; // allocated only for flexible CG
722 int cg_itr;
723
724 Vector du; // correction [dx,0]
725 Vector Adu; // matrix times correction
726
727 BMatrix A;
728 BMatrix C;
729 DirectSolver<Vector,Vector> Binv; // [ A C^T; C 0 ]^{-1}
730
731 bool activeId = true;
732
733 std::vector<int> interiorDofs; // the interior dof indices
734 std::vector<int> interfaceDofs; // the boundary/interface dof indices
735 std::vector<bool> activeSubdomains_sub;
736 // for debugging purposes
737 Vector rawCorrection, residual, restrictedResidual;
738
739 std::vector<int> globalIndex_notActive;
740
741BMatrix Aii;
743std::vector<int> cIndices;
744mutable DynamicMatrix<double> X; // const hack, move computation to constructor
745
746 // Solves the homogeneous Dirichlet problem A_ii x_i = r_i for the interior nodes only.
747 // Non-zero boundary values x_D can be imposed by exploiting the splitting
748 // [Aii AiD] [x_i x_D]^T = r_i <=> Aii x_i = r_i - AiD xD, i.e. modifying the right hand side.
749 // The interface nodes of x are not touched, nor is the constraint/multiplier part.
750 void solveDirichlet(Vector& x, Vector const& rhs) const;
751 };
752
753 // ----------------------------------------------------------------------------------------------
754 // ----------------------------------------------------------------------------------------------
755
760 template <class Subdomain, class Storage=std::vector<Subdomain>>
762 {
763 public:
765 using Scalar = typename Subdom::Scalar;
766 using Vector = typename Subdom::Vector;
767 using XVector = typename Subdom::XVector;
768 static constexpr int m = Subdom::components;
769
770 SharedMemoryDomain(Storage& subdomains, bool mpi_enabled=false,
771 bool master_worker=false);
772
781
788 void restrict();
789
790 void updateSearchDirection(double beta); // CG
791
795 int size() const
796 {
797 return subdomains->size();
798 }
799
800 std::vector<DynamicMatrix<Dune::FieldMatrix<Scalar,1,1>>> getS() const;
801 std::vector<Vector> getSchurResiduals();
802 void setCorrections(std::vector<Vector> const& dcs);
803
806
807 void set_solver_type(bool cg_solver);
809
814 void updateIteration(int iteration);
815
816 std::vector<bool> getActiveSubdomains()
817 {
818 return activeSubdomains;
819 }
820
821 void setActiveSubdomains(std::vector<int> & activeIds)
822 {
823 activeSubdomains.resize(size());
824 for (int i = 0; i < activeIds.size(); ++i)
825 activeSubdomains[activeIds[i]] = true;
826 }
827
835 std::array<int,6> traffic() const
836 {
837 return std::array<int,6>{exchangeCount,transfers,initTraffic,restrictionTraffic,
838 prolongationTraffic,coarseGridTraffic};
839 }
840
842 {
843 std::uint64_t originalSentBytes = 0;
844 std::uint64_t originalReceivedBytes = 0;
845 std::uint64_t sentBytes = 0;
846 std::uint64_t receivedBytes = 0;
847 double encodeTimeMs = 0.0;
848 double decodeTimeMs = 0.0;
849 std::uint64_t encodeCount = 0;
850 std::uint64_t decodeCount = 0;
851 std::uint64_t codebookBits = 0;
852 std::uint64_t streamBytes = 0;
853 std::uint64_t streamPaddingBytes = 0;
854 };
855
856 CompressionTraffic compressionTraffic() const;
857
858 // Write compression symbol histograms below the given directory. An empty
859 // directory disables histogram output.
860 void setHistogramOutput(std::string directory)
861 {
862 histogramOutputDirectory = std::move(directory);
863 }
864
866 void setSymbolHistogramOutput(std::string const& directory)
867 {
868 for (int i=0;i<subdomains->size();++i)
869 if (activeOnThisRank(i))
870 {
871 auto& transfer=(*subdomains)[i].transfer();
872 if constexpr (requires { transfer.setSymbolHistogramOutput(std::string{}); })
873 transfer.setSymbolHistogramOutput(directory.empty() ? std::string{} :
874 directory+"/subdomain"+std::to_string(i));
875 else if (!directory.empty())
876 throw std::runtime_error("Selected transfer cannot record packet histograms");
877 }
878 }
879
880 // The first exchange lazily trains each shared codebook. By default it is
881 // reused; set a positive interval for periodic retraining, or request a rebuild.
882 // interval <= 0 disables periodic rebuilds.
883 void setCodebookRebuildInterval(int interval)
884 {
885 codebookRebuildInterval = interval;
886 }
887
888 // Force a rebuild on the next restrict/prolongate call.
890 {
891 forceRestrictCodebookRebuild = true;
892 forceProlongateCodebookRebuild = true;
893 }
894
895 // Validate and record the optional MPI ownership layout. Numerical BDDC
896 // remains unchanged until the batched exchange layer is enabled.
897 void setMpiEnabled(bool enabled)
898 {
899 mpiLayout.configure(enabled, size());
900 }
901
902 bool mpiEnabled() const { return mpiLayout.enabled(); }
907 void setMpiDestinationRouting(bool enabled)
908 {
909 if (restrictionTraffic || prolongationTraffic)
910 throw std::logic_error("Configure MPI routing before the first BDDC exchange");
911 if (enabled && !mpiEnabled())
912 throw std::invalid_argument("Destination routing requires MPI BDDC");
913 destinationRouting = enabled;
914 if (enabled)
915 {
916 nodeTopology.configure();
917 if (mpiRankZero())
918 {
919 std::cout << "BDDC MPI routing: destination; shared-memory domains="
920 << nodeTopology.nodes() << "; rank leaders=";
921 for (auto leader : nodeTopology.leaders()) std::cout << ' ' << leader;
922 std::cout << "; compression policy=unchanged\n";
923 }
924 }
925 }
926
927 MpiRoutingTraffic const& routingTraffic() const { return routedTraffic; }
928 int mpiRank() const { return mpiLayout.rank(); }
929 int mpiSize() const { return mpiLayout.size(); }
930 bool mpiMasterWorker() const { return mpiLayout.masterWorker(); }
931 bool mpiIsMaster() const { return mpiLayout.isMaster(); }
932 bool mpiRankZero() const { return !mpiEnabled() || mpiRank() == 0; }
933 int mpiOwner(int subdomain) const { return mpiLayout.owner(subdomain); }
934 bool mpiOwns(int subdomain) const { return mpiLayout.owns(subdomain); }
935 bool storageHas(int subdomain) const
936 {
937 if constexpr (requires(Storage const& storage) { storage.has(0); })
938 return subdomains->has(subdomain);
939 else
940 return true;
941 }
942 bool activeOnThisRank(int subdomain) const
943 {
944 return storageHas(subdomain) && activeSubdomains[subdomain]
945 && (!mpiEnabled() || mpiOwns(subdomain));
946 }
947
948 private:
949 Storage* subdomains;
950 std::vector<std::pair<int,int>> neighbors;
951 std::vector<bool> activeSubdomains;
952
953 // Support for monitoring the amount of data exchanged between subdomains.
954 std::mutex mutex;
955 int exchangeCount = 0; // number of iterations
956 int transfers = 0; // number of bidirectional data transfers
957 int initTraffic = 0; // amount of data (in bytes) sent during initialization
958 int restrictionTraffic = 0; // amount of data (in bytes) sent during restriction
959 int prolongationTraffic = 0; // amount of data (in bytes) sent during prolongation
960 int coarseGridTraffic = 0; // amount of data (in bytes) sent to coarse grid solver
961
962 // Shared codebook rebuild policy (Huffman).
963 int codebookRebuildInterval = 0;
964 int restrictExchangeCount = 0;
965 int prolongateExchangeCount = 0;
966 bool forceRestrictCodebookRebuild = false;
967 bool forceProlongateCodebookRebuild = false;
968 std::string histogramOutputDirectory;
969 MpiDomainLayout mpiLayout;
970 bool destinationRouting = false;
971 MpiNodeTopology nodeTopology;
972 MpiRoutingTraffic routedTraffic;
973
974#ifdef KASKADE_HAVE_MPI
975 // Exchange averaging weights once when non-owned subdomains are absent.
976 void mpiInitializeAveragingWeights();
977 // Exchange existing raw/encoded packets. Legacy mode gathers all packets;
978 // destination mode delivers only the requested buckets, preserving receive order.
979 void mpiRestrictExchange();
980 void mpiProlongateExchange();
981#endif
982 };
983
984 // ----------------------------------------------------------------------------------------------
985 // ----------------------------------------------------------------------------------------------
986
1078 template <class Domain>
1080 {
1081 public:
1082 using Scalar = typename Domain::Scalar;
1083 using Constraint = std::tuple<int,int,int>;
1084
1085 private:
1087
1088 public:
1096 KKTSolver(Domain& domain_,
1097 CoarseConstraints const& constr)
1098 : domain(&domain_)
1099 , constraints(domain->size())
1100 , localConstraintsSize(domain->size())
1101 , sOffsets(constr.size()+1)
1102 {
1103 // Compute the offsets of individual slack vectors s_ij into the global slack vector
1104 // and the constraints in which each subdomain is involved.
1105 sOffsets[0] = 0;
1106 for (int k=0; k<constr.size(); ++k)
1107 {
1108 auto const& [s,m] = constr[k];
1109 for (auto i: s)
1110 {
1111 assert(0<=i && i<domain->size());
1112 constraints[i].push_back(k);
1113 localConstraintsSize[i] += m;
1114 }
1115 sOffsets[k+1] = m;
1116 }
1117 std::partial_sum(begin(sOffsets),end(sOffsets),begin(sOffsets));
1118
1119 // Create Schur complement matrix B. This is sparse, since each constraint, i.e.
1120 // slack variable, is only affected by two subdomains.
1121 int const ns = sOffsets.back(); // Total number of slacks.
1122 if (ns == 0) // If there are no coarse constraints,
1123 return; // we're done - there's nothing to do.
1124 NumaCRSPatternCreator<> sCreator(ns,ns,false,2);
1125 for (auto const& ss: constraints) // For each subdoman find all pairs
1126 for (int sRow: ss) // of incident slacks and add the
1127 for (int sCol: ss) // corresponding dense block into
1128 sCreator.addDenseBlock(sOffsets[sRow],sOffsets[sRow+1], // the sparsity pattern of S.
1129 sOffsets[sCol],sOffsets[sCol+1]);
1130
1131 using Entry = Dune::FieldMatrix<Scalar,1,1>;
1132 NumaBCRSMatrix<Entry> S(sCreator); // And then create the matrix.
1133
1134 // Assemble the Schur complement matrix.
1135 using SortedIdx = std::vector<std::pair<int,int>>;
1137 auto localSchurComplements = domain->getS();
1138 for (int i=0; i<domain->size(); ++i)
1139 {
1140 // In owner-only MPI mode, nonlocal slots deliberately have no
1141 // subdomain object and therefore no local Schur complement. Their
1142 // contributions are assembled by the owning rank and reduced below.
1143 if (!domain->storageHas(i) ||
1144 (domain->mpiEnabled() && !domain->mpiOwns(i)))
1145 continue;
1146
1147 SortedIdx rows;
1148 int localIndex = 0 ;
1149 for (int k: constraints[i])
1150 for (int l=sOffsets[k]; l<sOffsets[k+1]; ++l)
1151 rows.push_back({l,localIndex++});
1152 assert(std::is_sorted(rows.begin(),rows.end(),FirstLess()));
1153 lm.push_back(rows,rows);
1154 lm.back() = localSchurComplements[i]; // add local stiffness matrix Si
1155 }
1156 lm.scatter();
1157 S *= -1.0; // take care of correct Schur complement sign
1158
1159#ifdef KASKADE_HAVE_MPI
1160 if (domain->mpiEnabled())
1161 {
1162 // Each rank assembled only the Schur contributions of its owned
1163 // subdomains. Sum those local matrices so every rank can use the same
1164 // replicated coarse solve while the fine-grid work is owner-only.
1165 reduceCoarseMatrix(S);
1166 }
1167#endif
1168
1169 S_original = S;
1172 }
1173
1180 void solve()
1181 {
1182 int const ns = sOffsets.back(); // Total number of slacks.
1183
1184 if (ns==0)
1185 return;
1186
1187 // Obtain right hand side of the Schur complement system. This is the sum of right
1188 // hand sides from the subdomains, scattered into appropriate positions in the
1189 // right hand side vector f.
1190 Timings& timer = Timings::instance();
1191 timer.start("get Schur rhs");
1192 Vector f(ns);
1193 getRightHandSide(f);
1194 timer.stop("get Schur rhs");
1195
1196
1197 std::vector<int> d(ns,1);
1198 for (int i=0; i<domain->size(); ++i)
1199 {
1200 if(not domain->getActiveSubdomains()[i]) // vector d is a {0,1} where zero is for the interfaces
1201 { // belongs to inactive subdomains
1202 for (auto const k: constraints[i])
1203 {
1204 int const off = sOffsets[k];
1205 int const nsk = sOffsets[k+1]-off;
1206 for (int l=0; l<nsk; ++l)
1207 d[l+off] = 0;
1208 }
1209 }
1210 }
1211
1212 std::vector<size_t> d_AA;
1213 for (int i = 0; i < ns; ++i)
1214 {
1215 if(d[i]!=0) d_AA.push_back(i);
1216 }
1217
1218 bool solveHere = true;
1219#ifdef KASKADE_HAVE_MPI
1220 solveHere = !domain->mpiMasterWorker() || domain->mpiIsMaster();
1221#endif
1222 // S_original is fixed for this coarse solver's lifetime. The complete
1223 // system already has factors; reduced systems need refactoring only when
1224 // their active constraint indices change.
1225 bool const fullCoarseSystem = d_AA.size() == static_cast<size_t>(ns);
1226 if (solveHere && !fullCoarseSystem
1227 && (!activeFactorizationReady || factoredActiveDofs != d_AA))
1228 {
1229 using Entry = Dune::FieldMatrix<Scalar,1,1>;
1230 NumaBCRSMatrix<Entry> S_AA(d_AA,S_original);
1233 factoredActiveDofs = d_AA;
1234 activeFactorizationReady = true;
1235 }
1236
1237
1238 Vector f_AA(d_AA.size());
1239 for (int i = 0; i < d_AA.size(); ++i)
1240 {
1241 f_AA[i] = f[d_AA[i]]; // assign only the rhs for those belongs to active subdomain
1242 } // otherwise assignes to zero
1243
1244 timer.start("solve Schur system");
1245 Vector s_AA(ns);
1246 if (solveHere)
1247 {
1248 if (fullCoarseSystem)
1249 Sinv.apply(s_AA,f_AA);
1250 else
1251 Sinv_AA.apply(s_AA,f_AA);
1252 }
1253 timer.stop("solve Schur system");
1254
1255
1256 Vector s(ns); // Create zero initial slack vector
1257 s = 0; // assign zero on the slacks corresponding to
1258 // inactive subdomains via vector d
1259
1260 for (int i = 0; i < d_AA.size(); ++i)
1261 {
1262 s[d_AA[i]] = s_AA[i];
1263 }
1264
1265#ifdef KASKADE_HAVE_MPI
1266 if (domain->mpiMasterWorker())
1267 {
1268 std::vector<double> coarse(ns, 0.0);
1269 if (domain->mpiIsMaster())
1270 for (int i = 0; i < ns; ++i)
1271 coarse[i] = s[i][0];
1272 MPI_Bcast(coarse.data(), ns, MPI_DOUBLE, 0, MPI_COMM_WORLD);
1273 for (int i = 0; i < ns; ++i)
1274 s[i][0] = coarse[i];
1275 }
1276#endif
1277
1278 timer.start("set corrections");
1279 std::vector<Vector> dcs(domain->size());
1280 for (int i=0; i<domain->size(); ++i)
1281 {
1282 Vector si(localConstraintsSize[i]);
1283 if(domain->activeOnThisRank(i))
1284 {
1285 // gather the slacks corresponding to the
1286 int pos = 0; // constraints affecting active subdomain i
1287 for (auto const k: constraints[i]) // by concatenating all the slacks
1288 { // corresponding to constraints in which
1289 int const off = sOffsets[k]; // subdomain i is involved.
1290 int const nsk = sOffsets[k+1]-off;
1291 for (int l=0; l<nsk; ++l)
1292 si[pos++] = s[l+off];
1293 }
1294 dcs[i] = si;
1295 }
1296 else
1297 {
1298 si = 0;
1299 dcs[i] = si;
1300 }
1301 }
1302 domain->setCorrections(dcs);
1303 timer.stop("set corrections");
1304 }
1305
1306
1307 private:
1308
1309 void getRightHandSide(Vector& f) const
1310 {
1311 f = 0;
1312 auto floc = domain->getSchurResiduals();
1313
1314 for (int i=0; i<domain->size(); ++i)
1315 {
1316 if(domain->activeOnThisRank(i))
1317 {
1318 int pos = 0; // scatter the lambda solution component
1319 for (auto const k: constraints[i]) // into the right hand side vector
1320 {
1321 int const off = sOffsets[k];
1322 int const nsk = sOffsets[k+1]-off;
1323 for (int l=0; l<nsk; ++l)
1324 f[l+off] += floc[i][pos++];
1325 }
1326 }
1327 }
1328
1329#ifdef KASKADE_HAVE_MPI
1330 if (domain->mpiEnabled())
1331 {
1332 // The coarse right hand side is assembled from owner-local Schur
1333 // residuals and must be reduced before the replicated coarse solve.
1334 reduceCoarseRhs(f);
1335 }
1336#endif
1337 }
1338
1339
1340 Domain* domain;
1341 std::vector<std::vector<int>> constraints; // involved constraints by subdomain id
1342 std::vector<int> localConstraintsSize; // total number of constraints for subdomain id
1343 std::vector<int> sOffsets; // offset of slack vector in total slacks
1344 DirectSolver<Vector,Vector> Sinv; // inverse of Schur complement
1345 DirectSolver<Vector,Vector> Sinv_AA; // inverse of Schur complement of Algebraic adaptivity
1346 std::vector<size_t> factoredActiveDofs;
1347 bool activeFactorizationReady = false;
1348
1349 NumaBCRSMatrix<Dune::FieldMatrix<Scalar,1,1>> S_original; // a copy of S, keep for the first iteration
1350 };
1351
1352
1479 template <class Subdomain, class Storage=std::vector<Subdomain>>
1480 class BDDCSolver // TODO: implement in terms of SymmetricPreconditioner
1481 {
1482 public:
1483
1490
1500 struct CgStep
1501 {
1502 double alpha = 0;
1503 double beta = 0;
1504 bool applied = false;
1505 };
1506
1517 {
1518 bool restriction = false;
1519 int solverCall = 0;
1520 int pass = 0;
1521 double rho = std::numeric_limits<double>::quiet_NaN();
1522 double beta = std::numeric_limits<double>::quiet_NaN();
1523 double curvature = std::numeric_limits<double>::quiet_NaN();
1525 };
1526
1527 void setDiagnosticObserver(std::function<void(DiagnosticEvent const&)> observer)
1528 {
1529 diagnosticObserver_ = std::move(observer);
1530 }
1531
1543 void setFlexibleCg(bool enabled)
1544 {
1545 if (systemIteration != 0 || (enabled && !cg_solver))
1546 throw std::invalid_argument("Flexible CG requires CG and configuration before solving");
1547 flexibleCg_ = enabled;
1548 for (int i=0; i<subdomains->size(); ++i)
1549 if (domain.storageHas(i) && (!domain.mpiEnabled() || domain.mpiOwns(i)))
1550 (*subdomains)[i].setFlexibleCg(enabled);
1551 }
1552
1553
1555 using Scalar = typename Subdom::Scalar;
1556 using Vector = typename Subdom::Vector;
1557 static constexpr int m = Subdom::components;
1558
1564
1571 BDDCSolver(Storage& subdomains,
1572 CoarseConstraints const& constraints,
1573 bool mpi_enabled=false,
1574 bool master_worker=false);
1575
1576 BDDCSolver(Storage& subdomains,
1577 CoarseConstraints const& constraints,
1578 std::vector<int> & activeIds,
1579 bool cg_solver=false,
1580 bool BDDC_verbose=false,
1581 bool mpi_enabled=false,
1582 bool master_worker=false);
1583
1588 void setRhs(std::vector<XVector> & Fs)
1589 {
1590 parallelFor(0,subdomains->size(),[&](int i)
1591 {
1592 if (!domain.mpiEnabled() || domain.mpiOwns(i))
1593 (*subdomains)[i].setRhs(Fs[i]);
1594 });
1595 }
1596
1606 void restartRhs(std::vector<XVector> const& rhs)
1607 {
1608 if (rhs.size() != subdomains->size())
1609 throw std::invalid_argument("BDDC restart RHS has wrong subdomain count");
1610 systemIteration = 0;
1611 sigma_pre = 0;
1612 lastStatus_ = SolveStatus::updated;
1613 lastCgStep_ = {};
1614 initialP0_ = 0;
1615 previousNorm_ = std::numeric_limits<double>::infinity();
1616 stagnationCount_ = 0;
1617 parallelFor(0,subdomains->size(),[&](int i)
1618 {
1619 if (domain.storageHas(i) && (!domain.mpiEnabled() || domain.mpiOwns(i)))
1620 {
1621 (*subdomains)[i].resetForNewRhs();
1622 (*subdomains)[i].setRhs(rhs[i]);
1623 }
1624 });
1625 }
1626
1631 double solve();
1632
1644 void applyPreconditioner(std::vector<XVector> const& rhs,
1645 std::vector<XVector>& output)
1646 {
1647 restartRhs(rhs);
1648 domain.updateIteration(0);
1649 if (domain.size()>1)
1650 {
1651 for (int pass=0; pass<restrictionPasses_; ++pass) domain.restrict();
1652 coarseSolver.solve();
1653 // Existing prolongation computes unused scalars, but does not reject
1654 // negative rho. Retain its communication and count it normally.
1655 domain.prolongate();
1656 }
1657 output.resize(rhs.size());
1658 parallelFor(0,subdomains->size(),[&](int i)
1659 {
1660 if (domain.storageHas(i) && (!domain.mpiEnabled() || domain.mpiOwns(i)))
1661 {
1662 output[i].resize(rhs[i].size());
1663 (*subdomains)[i].getSolution(output[i]);
1664 if (domain.size()>1)
1665 {
1666 XVector correction(rhs[i].size());
1667 (*subdomains)[i].getCorrection(correction);
1668 output[i] += correction;
1669 }
1670 }
1671 });
1672 }
1673
1674 SolveStatus lastStatus() const { return lastStatus_; }
1675 bool stopped() const { return lastStatus_ != SolveStatus::updated; }
1676 bool stagnated() const { return lastStatus_ == SolveStatus::stagnated; }
1677 bool breakdown() const { return lastStatus_ == SolveStatus::breakdown; }
1678
1680 CgStep const& lastCgStep() const { return lastCgStep_; }
1681
1690 std::array<int,6> traffic() const
1691 {
1692 return domain.traffic();
1693 }
1694
1699
1700 void setHistogramOutput(std::string directory)
1701 {
1702 domain.setHistogramOutput(std::move(directory));
1703 }
1704
1706 void setSymbolHistogramOutput(std::string const& directory)
1707 {
1708 domain.setSymbolHistogramOutput(directory);
1709 }
1710
1711
1720 void setRestrictionPasses(int passes)
1721 {
1722 if (passes < 1)
1723 throw std::invalid_argument("BDDC restriction passes must be positive");
1724 restrictionPasses_ = passes;
1725 }
1726
1727 // Control how often shared Huffman codebooks are rebuilt.
1729 {
1730 domain.setCodebookRebuildInterval(interval);
1731 }
1732
1733 void setMpiEnabled(bool enabled)
1734 {
1735 domain.setMpiEnabled(enabled);
1736 if (enabled && domain.mpiRank() == 0)
1737 std::cout << "BDDC MPI layout: " << domain.mpiSize()
1738 << " ranks, " << domain.size()
1739 << " subdomains, deterministic round-robin ownership\n";
1740 }
1741
1742 void setMpiDestinationRouting(bool enabled) { domain.setMpiDestinationRouting(enabled); }
1743 MpiRoutingTraffic const& routingTraffic() const { return domain.routingTraffic(); }
1744
1745 // Force a shared codebook rebuild on the next restrict/prolongate.
1747 {
1748 domain.requestCodebookRebuild();
1749 }
1750
1751 private:
1753 Storage* subdomains;
1754 Domain domain;
1755 CoarseConstraints constraints;
1756 KKTSolver<Domain> coarseSolver;
1757 std::vector<XVector> const Fs;
1758 bool cg_solver;
1759 int systemIteration = 0;
1760 int restrictionPasses_ = 1;
1761 bool flexibleCg_ = false;
1762 double sigma_pre = 0;
1763 double BDDC_verbose = false;
1764 SolveStatus lastStatus_ = SolveStatus::updated;
1765 CgStep lastCgStep_;
1766 std::function<void(DiagnosticEvent const&)> diagnosticObserver_;
1767 double initialP0_ = 0;
1768 double previousNorm_ = std::numeric_limits<double>::infinity();
1769 int stagnationCount_ = 0;
1770
1771 // Treat a tiny search quantity as stagnation only when the correction norm
1772 // has also stopped decreasing, avoiding premature termination of CG.
1773 bool hasStagnated(double norm, double p0)
1774 {
1775 constexpr double p0RelativeThreshold = 1e-14;
1776 constexpr double relativeDecrease = 1e-3;
1777 // Require several consecutive plateau steps to filter round-off noise.
1778 constexpr int stagnationWindow = 3;
1779
1780 if (initialP0_ == 0)
1781 initialP0_ = std::abs(p0);
1782
1783 bool noMeaningfulDecrease = std::isfinite(previousNorm_)
1784 && norm >= previousNorm_ * (1.0 - relativeDecrease);
1785 stagnationCount_ = noMeaningfulDecrease ? stagnationCount_ + 1 : 0;
1786 previousNorm_ = norm;
1787
1788 return std::abs(p0) <= p0RelativeThreshold * initialP0_
1789 && stagnationCount_ >= stagnationWindow;
1790 }
1791 };
1792
1793}
1794
1795#endif
MpiRoutingTraffic const & routingTraffic() const
Definition bddc.hh:1743
SharedMemoryDomain< Subdomain, Storage >::CompressionTraffic compressionTraffic() const
Definition bddc.hh:1695
void restartRhs(std::vector< XVector > const &rhs)
Starts a new RHS solve from zero, retaining the fixed BDDC setup.
Definition bddc.hh:1606
void setSymbolHistogramOutput(std::string const &directory)
Definition bddc.hh:1706
Dune::FieldVector< Scalar, m > XEntry
The scalar field type used in coefficients.
Definition bddc.hh:1562
void setRhs(std::vector< XVector > &Fs)
update rhs for each subdomain
Definition bddc.hh:1588
void setDiagnosticObserver(std::function< void(DiagnosticEvent const &)> observer)
Definition bddc.hh:1527
SolveStatus lastStatus() const
Definition bddc.hh:1674
Dune::BlockVector< XEntry > XVector
Definition bddc.hh:1563
bool stagnated() const
Definition bddc.hh:1676
void setFlexibleCg(bool enabled)
Definition bddc.hh:1543
void setHistogramOutput(std::string directory)
Definition bddc.hh:1700
CgStep const & lastCgStep() const
Read-only diagnostic; no additional operator applications or reductions.
Definition bddc.hh:1680
void setRestrictionPasses(int passes)
Definition bddc.hh:1720
void applyPreconditioner(std::vector< XVector > const &rhs, std::vector< XVector > &output)
Apply one BDDC preconditioner sequence to a new subassembled RHS.
Definition bddc.hh:1644
void setCodebookRebuildInterval(int interval)
Definition bddc.hh:1728
bool stopped() const
Definition bddc.hh:1675
std::array< int, 6 > traffic() const
Reports the amount of data exchanged between subdomains.
Definition bddc.hh:1690
BDDCSolver(Storage &subdomains, CoarseConstraints const &constraints, bool mpi_enabled=false, bool master_worker=false)
Constructor.
typename Subdom::Scalar Scalar
Definition bddc.hh:1555
typename Subdom::Vector Vector
Definition bddc.hh:1556
BDDCSolver(Storage &subdomains, CoarseConstraints const &constraints, std::vector< int > &activeIds, bool cg_solver=false, bool BDDC_verbose=false, bool mpi_enabled=false, bool master_worker=false)
void setMpiEnabled(bool enabled)
Definition bddc.hh:1733
void setMpiDestinationRouting(bool enabled)
Definition bddc.hh:1742
bool breakdown() const
Definition bddc.hh:1677
double solve()
Performs a gradient step.
static constexpr int m
Definition bddc.hh:1557
std::vector< int > const & cornerDofs(int id) const
Definition bddc.hh:197
CoarseConstraints coarseConstraints() const
Provides information about subdomains sharing coarse constraints.
InterfaceAverages(std::vector< std::vector< LocalDof > > const &sharedDofs, std::vector< Index > const &subdomainSize, int types, std::vector< int > const &partitions)
Constructs averages with a caller-provided partition of shared dofs.
std::array< int, 3 > interfaceCount() const
Reports on number of corners, edges, and faces.
Definition bddc.hh:192
NumaBCRSMatrix< Dune::FieldMatrix< Scalar, m, m > > coarseConstraint(int id) const
Creates the subdomain-local constraints defining the coarse space.
static constexpr int components
Definition bddc.hh:131
InterfaceAverages(std::vector< std::vector< LocalDof > > const &sharedDofs, std::vector< Index > const &subdomainSize, int types=CORNER|FACE)
Constructor.
InterfaceClassification const & interfaceClassifications(int id) const
Definition bddc.hh:203
Interfaces const & interfaces(int id) const
For the given subdomain, tells with which neighboring domain which dofs are shared.
A class for solving a block-diagonal-structured KKT system.
Definition bddc.hh:1080
void solve()
solves the system.
Definition bddc.hh:1180
KKTSolver(Domain &domain_, CoarseConstraints const &constr)
Constructor.
Definition bddc.hh:1096
std::tuple< int, int, int > Constraint
Definition bddc.hh:1083
typename Domain::Scalar Scalar
Definition bddc.hh:1082
Cache the MPI_COMM_TYPE_SHARED partition without retaining communicators. configure() is collective o...
bool has(size_t id) const
Definition bddc.hh:71
void emplace(size_t id, Args &&... args)
Definition bddc.hh:88
Subdomain const & operator[](size_t id) const
Definition bddc.hh:80
Subdomain & operator[](size_t id)
Definition bddc.hh:73
A class that orchestrates the exchange of data between BDDC subdomains.
Definition bddc.hh:762
std::vector< Vector > getSchurResiduals()
Dune::FieldVector< double, 1 > updateSearchDirectionNorm()
void set_solver_type(bool cg_solver)
bool storageHas(int subdomain) const
Definition bddc.hh:935
typename Subdom::XVector XVector
Definition bddc.hh:767
void setMpiEnabled(bool enabled)
Definition bddc.hh:897
SharedMemoryDomain(Storage &subdomains, bool mpi_enabled=false, bool master_worker=false)
bool mpiOwns(int subdomain) const
Definition bddc.hh:934
int size() const
Reports the number of subdomains.
Definition bddc.hh:795
void updateSearchDirection(double beta)
void setActiveSubdomains(std::vector< int > &activeIds)
Definition bddc.hh:821
void restrict()
Performs restriction in BDDC.
MpiRoutingTraffic const & routingTraffic() const
Definition bddc.hh:927
void setMpiDestinationRouting(bool enabled)
Definition bddc.hh:907
typename Subdom::Scalar Scalar
Definition bddc.hh:765
std::vector< bool > getActiveSubdomains()
Definition bddc.hh:816
void updateIteration(int iteration)
Sets the iteration index within the current linear system.
bool activeOnThisRank(int subdomain) const
Definition bddc.hh:942
void setHistogramOutput(std::string directory)
Definition bddc.hh:860
typename Subdom::Vector Vector
Definition bddc.hh:766
void setCodebookRebuildInterval(int interval)
Definition bddc.hh:883
std::vector< DynamicMatrix< Dune::FieldMatrix< Scalar, 1, 1 > > > getS() const
int mpiOwner(int subdomain) const
Definition bddc.hh:933
void updateSolution(Scalar alpha)
CompressionTraffic compressionTraffic() const
std::array< int, 6 > traffic() const
Reports the amount of data exchanged between subdomains.
Definition bddc.hh:835
Dune::FieldVector< double, 2 > prolongate()
Performs prolongation in BDDC.
void setCorrections(std::vector< Vector > const &dcs)
void setSymbolHistogramOutput(std::string const &directory)
Definition bddc.hh:866
A class representing small KKT systems on a single subdomain.
Definition bddc.hh:265
void setFlexibleCg(bool enabled)
Configured by BDDCSolver before the first update; one previous residual.
Definition bddc.hh:627
void setCorrection(Vector const &c)
Computes the correction vector .
Subdomain(int id, AMatrix const &A, Interfaces const &interfaces, NumaBCRSMatrix< Dune::FieldMatrix< Scalar, cComponents, components > > const &C)
Constructor.
Vector diagnosticExactProlongation(Vector const &averaged) const
Diagnostic-only exact prolongation of the stored raw correction. Given the globally averaged raw inte...
Dune::FieldVector< Scalar, components > XEntry
Definition bddc.hh:278
Vector diagnosticProlongationWeights() const
Actual transfer averaging weights, including the inactive-interface mask.
Definition bddc.hh:664
Dune::FieldVector< double, 1 > updateSearchDirectionNorm()
std::vector< int > neighbors() const
Reports a list of its neighbor subdomains.
Vector const & diagnosticRawCorrection() const
Snapshot of the local/coarse correction before interface communication.
Definition bddc.hh:653
XVector getSolution() const
Provides the current solution vector .
void updateSolution(Scalar alpha)
Updates the solution approximation.
void preRestrict()
First step of the restriction: Dirichlet solve.
void setInterfaceAveragingWeights(int s, XVector const &rho)
Accumulates interface weights of adjacent subdomains.
Definition bddc.hh:378
Transfer const & transfer() const
Definition bddc.hh:464
void getRawCorrection(XVector &dx) const
Vector diagnosticProlongatedCorrection() const
Current prolongated correction with the solver's inactive-DOF mask.
Definition bddc.hh:656
void setActiveId(bool active)
Definition bddc.hh:574
void getCorrection(XVector &dx) const
Provides the current correction vector .
Vector const & getRestrictedResidual() const
Definition bddc.hh:646
Dune::FieldVector< double, 2 > prolongate()
Perform averaging on the shared interfaces, projecting the solution to the subspace of functions cont...
void getS(SMatrix &S) const
Compute .
static const int components
Number of (vectorial) components of .
Definition bddc.hh:270
void getResidual(XVector &rr) const
void set_solver_type(bool cg_solver)
Set solver type.
void preProlongate()
Prepares the exchange of interface values.
Definition bddc.hh:549
void setInterfaceResidualUpdate(int s, TransmissionType const &dres)
Sets interface residual of the correction from neighboring subdomains.
Definition bddc.hh:451
void setCgUseOriginalResidual(bool enabled)
Definition bddc.hh:625
Vector const & diagnosticSearchDirection() const
Read-only views for optional CG diagnostics, before the solution update.
Definition bddc.hh:649
std::vector< bool > getActiveSubdomains()
Definition bddc.hh:683
Scalar_ Scalar
The scalar field type used in coefficients.
Definition bddc.hh:275
void getInterfaceAveragingWeights(int s, XVector &rho) const
Reports own interface averaging weights.
Definition bddc.hh:368
void getSolution(XVector &x) const
Provides the current solution vector .
void resetForNewRhs()
Clears the solution and iteration work vectors for another RHS.
Dune::BlockVector< XEntry > XVector
Definition bddc.hh:279
Subdomain(int id, AMatrix const &A, Interface const &interfaces, bool excludeCornersFromCompression=false)
Constructor.
Dune::BlockVector< Dune::FieldVector< Scalar, 1 > > Vector
Definition bddc.hh:280
void imposeDC_inActiveInterface(Vector &Aq, Vector &q)
Vector const & diagnosticPreconditionedResidual() const
Definition bddc.hh:650
void imposeDCq(Vector &q)
DynamicMatrix< Dune::FieldMatrix< Scalar, 1, 1 > > SMatrix
A matrix type with scalar entries, used for the Schur complement matrix.
Definition bddc.hh:291
void getSchurResidual(Vector &lambda) const
Provides the Schur residual.
Transfer & transfer()
Definition bddc.hh:458
void resetForNewSystem()
Prepares a factorized subdomain for a new solver with the same operator.
void updateSearchDirection(double beta)
Update search direction q for cg solver.
void getInterfaceResidualUpdate(int s, TransmissionType &dres) const
Gets interface residual that shall be shared with neighboring subdomain.
Definition bddc.hh:441
void setRhs(XVector const &f)
Provides a (new) right hand side for the linear equation system to be solved.
void updateIteration(int cg_itr)
typename Transfer::TransmissionType TransmissionType
A container type used for exchanging coefficients between subdomains.
Definition bddc.hh:285
NumaBCRSMatrix< Dune::FieldMatrix< Scalar, components, components > > AMatrix
Definition bddc.hh:288
void setActiveSubdomains_sub(std::vector< bool > &activeSubdomains_)
Definition bddc.hh:688
void restrict()
Performs the restriction of the residual vector.
void getInterfaceValues(int s, TransmissionType &values) const
Gets boundary values that shall be shared with neighboring subdomain.
Definition bddc.hh:559
void setInterfaceValues(int s, TransmissionType const &values)
Sets boundary values of the correction from neighboring subdomains.
Definition bddc.hh:569
A LAPACK-compatible dense matrix class with shape specified at runtime.
A structure for holding a sequence of several local matrices to be filled sequentially and to be scat...
void scatter()
Scatters the local matrices into the global one and removes them from the local container.
value_type & back()
A reference to the last pushed local matrix.
void push_back(SortedRowIdx const &ridx, SortedColIdx const &cidx)
Appends another (zero-initialized) local matrix.
A NUMA-aware compressed row storage matrix adhering mostly to the Dune ISTL interface (to complete....
A NUMA-aware creator for matrix sparsity patterns.
void addDenseBlock(Index fromRow, Index toRow, Index fromCol, Index toCol)
Enters a contiguous dense block into the sparsity pattern.
Supports gathering and reporting execution times information for nested program parts.
Definition timing.hh:64
static Timings & instance()
Returns a reference to a single default instance.
void stop(std::string const &name)
Stops the timing of given section.
struct Times const * start(std::string const &name)
Starts or continues the timing of given section.
@ UMFPACK
UMFPack from SuiteSparse, using 32 bit integer indices.
Definition enums.hh:45
std::vector< std::pair< int, std::vector< int > > > Interfaces
A data structure describing the interfaces of a subdomain.
InterfaceType
Discrimination of different interface types.
Definition bddc.hh:118
void parallelFor(Func const &f, int maxTasks=std::numeric_limits< int >::max())
A parallel for loop that executes the given functor in parallel on different CPUs.
Definition threading.hh:502
std::vector< std::pair< std::vector< int >, int > > CoarseConstraints
A data structure describing coarse constraints.
Definition bddc.hh:55
std::vector< std::pair< int, int > > InterfaceClassification
Scalars of the last accepted preconditioned CG update.
Definition bddc.hh:1501
A pair of subdomain id and local dof index denotes a subdomain-local reference to a global dof.
Definition bddc.hh:109
Rank-local sent payload accounting for R/P and the three endpoint classes. Count each directed interf...
A comparator functor that supports sorting std::pair by their first component.
Definition firstless.hh:22