TRUST 1.9.8
HPC thermohydraulic platform
Loading...
Searching...
No Matches
Solv_Petsc.h
1/****************************************************************************
2* Copyright (c) 2026, CEA
3* All rights reserved.
4*
5* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
6* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
7* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
8* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
9*
10* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
11* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
12* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
13*
14*****************************************************************************/
15
16#ifndef Solv_Petsc_included
17#define Solv_Petsc_included
18
19#include <petsc_for_kernel.h>
20#include <EChaine.h>
21#include <Nom.h>
22#undef setbit // Sinon conflit de ArrOfBit.h avec Petsc
23#include <Solv_Externe.h>
24#include <ArrOfBit.h>
25#ifdef PETSCKSP_H
26#include <petscdm.h>
27#include <TRUSTTab.h>
28#endif
29#include <PCShell_base.h>
30#include <TRUST_Deriv.h>
31
33class Matrice_Morse;
34
35
36enum solveur_direct_ { no, mumps, superlu_dist, petsc, umfpack, pastix, cholmod, strumpack, cli };
37extern bool gmres_right_unpreconditionned;
38
39/* Struct to associate Petsc preconditionner to user-provided preconditioner */
40typedef struct
41{
43} PCstruct;
44
45
47{
48
49 Declare_instanciable_sans_constructeur_ni_destructeur(Solv_Petsc);
50
51public :
52
53 inline Solv_Petsc();
54 inline ~Solv_Petsc() override;
55 // Method which be called to create solver from chaine_lue_
56 inline void create_solver()
57 {
60 }
61 inline int solveur_direct() const override
62 {
63#ifdef PETSCKSP_H
64 if (SolveurPetsc_==nullptr) Process::exit("Can't call to Solv_Petsc::solveur_direct() yet.");
65#endif
66 return (solveur_direct_>0);
67 };
68 int resoudre_systeme(const Matrice_Base&, const DoubleVect&, DoubleVect& ) override;
69 inline int resoudre_systeme(const Matrice_Base& M, const DoubleVect& A, DoubleVect& B, int niter_max) override
70 {
71 return resoudre_systeme(M,A,B);
72 };
73 void create_solver(Entree&);
74#ifdef PETSCKSP_H
75 // To switch between solver definitions in one Solv_Petsc instance:
76 void reset_solver(const Nom& name)
77 {
78 // ToDo: regler option_prefix_ et numero_solveur dans create_solver et initialize...
79 reset();
80 Cout << "Setting PETSc solver: " << name << finl;
81 EChaine ech(name);
82 create_solver(ech);
83 }
84#endif
85 inline void reset();
86#ifdef PETSCKSP_H
87 inline Solv_Petsc& operator=(const Solv_Petsc&);
88 inline Solv_Petsc(const Solv_Petsc&);
89
90 inline void initialize();
91 inline bool gpu() const
92 {
93 return gpu_;
94 };
95 inline PCstruct& get_precond_user()
96 {
97 if (!pc_user_.pc_shell) create_solver();
98 return pc_user_;
99 }
100 inline bool amgx() const
101 {
102 return amgx_;
103 };
104 inline bool amgx_initialized()
105 {
106 return amgx_initialized_;
107 };
108#if PETSC_VERSION_GE(3,24,0)
109 PetscErrorCode set_convergence_test(PetscErrorCode (*converge)(KSP,PetscInt,PetscReal,KSPConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void**))
110#else
111 PetscErrorCode set_convergence_test(PetscErrorCode (*converge)(KSP,PetscInt,PetscReal,KSPConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
112#endif
113 {
114 if (SolveurPetsc_==nullptr) create_solver();
115 return KSPSetConvergenceTest(SolveurPetsc_, converge, cctx, destroy);
116 }
117 // Timers:
118 static PetscLogStage KSPSolve_Stage_;
119 static PetscLogStage Create_Stage_;
120 void set_rtol(const double& rtol)
121 {
122 seuil_relatif_ = rtol;
123 if (SolveurPetsc_!=nullptr) KSPSetTolerances(SolveurPetsc_, seuil_relatif_, seuil_, (divtol_==0 ? PETSC_DEFAULT : divtol_), nb_it_max_);
124 }
125#endif
126
127 public_for_cuda
128#ifdef PETSCKSP_H
129 virtual void Update_matrix(Mat& MatricePetsc, const Matrice_Morse& mat_morse); // Fill the (previously allocated) PETSc matrix with mat_morse coefficients
130#endif
131
132 static int instance; // Nombre d'instances en cours de la classe
133 static int numero_solveur; // Compte les solveurs crees et utilises pour le prefix des options
134
135protected :
136#ifdef PETSCKSP_H
137 using ArrOfPetscInt = TRUSTArray<PetscInt, PetscInt>;
138
139 bool isViennaCLVector();
140 bool isKokkosVector();
141 void check_aij(const Matrice_Morse&);
142 void Create_DM(const DoubleVect& ); // Construit un DM (Distributed Mesh)
143 virtual void Create_objects(const Matrice_Morse&, int); // Construit differents objets PETSC dont matrice
144 virtual void Create_vectors(const DoubleVect&); // Construit les vecteurs Petsc x et b
145 virtual void Update_vectors(const DoubleVect& secmem, DoubleVect& solution); // Remplit les vecteurs Petsc x et b
146 void Create_MatricePetsc(Mat&, int, const Matrice_Morse&); // Construit et remplit une matrice Petsc depuis la matrice_morse
147 virtual void Update_solution(DoubleVect& solution);
148 virtual int solve(ArrOfDouble& residual); // Solve Ax=b and return residual
149 virtual void finalize() {};
150 virtual bool detect_new_stencil(const Matrice_Morse&);
151 bool nouveau_stencil()
152 {
153 return nouveau_stencil_;
154 }; // ToDo: Remonter dans Solveur_Sys avec nouvelle_matrice
155 bool enable_ksp_view();
156 bool has_option(const Nom& option, Nom& current_value);
157 int add_option(const Nom& option, const double& value, int cli = 0);
158 int add_option(const Nom& option, const Nom& value, int cli = 0);
159 void add_amgx_option(const Nom& key, const Nom& value, const std::string& comment="");
160 void add_amgx_option(const Nom& key_value);
161 void SaveObjectsToFile(const DoubleVect& b, DoubleVect& x);
162 void RestoreMatrixFromFile();
163 PetscInt compute_nb_rows_petsc(PetscInt);
164
165 // Attributes
166 double seuil_;
167 double seuil_relatif_;
168 double divtol_;
169 bool nouveau_stencil_ = true;
170
171 // Objets Petsc
172 Mat MatricePetsc_;
173 Vec SecondMembrePetsc_;
174 Vec SolutionPetsc_; // Globale solution
175 KSP SolveurPetsc_;
176 PC PreconditionneurPetsc_;
177 PCstruct pc_user_; /* user-defined preconditioner context */
178 DM dm_; //description de champs PETSC
179 int preconditionnement_non_symetrique_; // Drapeau sur la symetrie de la matrice de preconditionnement
180 int nb_it_max_; // Maximal number of iterations
181 int convergence_with_nb_it_max_; // Convergence decided with nb_it_max_ specified and not by seuil threshold
182 int ignore_nb_it_max_;
183 int controle_residu_; // Verification si le residu ||Ax-B||<seuil
184 int block_size_; // Block size for SBAIJ matrix
185 Nom factored_matrix_; // Deal with the A=LU factorization on disk
186 int mataij_; // Force the use of a Mataij matrix
187 Nom type_pc_; // Preconditioner type
188 Nom type_ksp_; // KSP type
189 Nom option_prefix_; // Prefix des options CLI (permet de faire plusieurs solveurs en CLI)
190 Nom amgx_options_;
191
192 int petsc_nb_cpus_; // Number of CPUs used to solve the PETSc matrix
193 int petsc_cpus_selection_; // Selection of CPUs used to solve the PETSc matrix
194 int different_partition_; // Different partition for the TRUST matrix and the PETSc matrix
195 int petsc_decide_; // PETSc decide of the matrix partition
196 Vec LocalSolutionPetsc_; // Local solution in case of petsc_decide_=1
197 VecScatter VecScatter_; // Scatter context needed when petsc_decide_=1 to gather values of global to local solution
198#endif
199
200
201 int solveur_direct_ = no; // Pour savoir si l'on manipule un solveur direct et non iteratif
202 bool gpu_ = false; // Utilisation des solveurs GPU de PETSc
203 bool amgx_ = false; // Utilisation des solveurs GPU de AMGX
204 const Nom config(); // Nom du fichier de config eventuel
205 bool amgx_initialized_ = false; // Amgx initialise
206 // Options dev:
208 bool rebuild_matrix_ = false;
209 bool allow_realloc_ = true;
211 bool reduce_ram_ = false;
212 bool verbose = false; // Timing
213 bool reorder_matrix_ = false;
214 // Reuse preconditioner (for Inexact Newton):
215 int nb_it_previous_=-1; // Previous number of iterations
216 int reuse_preconditioner_nb_it_max_=-1; // Upper limit of iterations to reuse preconditioner
217#ifdef PETSCKSP_H
218 IS rowperm = nullptr, colperm = nullptr;
219 IS inv_rowperm = nullptr, inv_colperm = nullptr;
220#endif
221};
222
223#define NB_IT_MAX_DEFINED 10000
224
226{
227#ifdef PETSCKSP_H
228 initialize();
229 instance++;
230 // Journal()<<"creation solv_petsc "<<instance<<finl;
231#endif
232}
233
235{
236 reset();
237 instance--;
238 // Journal()<<" destr solv_petsc "<<instance<<finl;
239}
240inline void Solv_Petsc::reset()
241{
242#ifdef PETSCKSP_H
243 if (SolveurPetsc_!=nullptr)
244 {
245 KSPDestroy(&SolveurPetsc_);
246 finalize();
247 }
248 if (MatricePetsc_!=nullptr)
249 {
250 // Destruction des vecteurs
251 VecDestroy(&SecondMembrePetsc_);
252 VecDestroy(&SolutionPetsc_);
253 if (LocalSolutionPetsc_!=nullptr)
254 {
255 VecDestroy(&LocalSolutionPetsc_);
256 VecScatterDestroy(&VecScatter_);
257 }
258 // Destruction matrice
259 MatDestroy(&MatricePetsc_);
260 // Destruction DM
261 if (dm_!=nullptr)
262 DMDestroy(&dm_);
263 // Destruction IS
264 if (rowperm!=nullptr)
265 ISDestroy(&rowperm), ISDestroy(&inv_rowperm);
266 if (colperm!=nullptr)
267 ISDestroy(&colperm), ISDestroy(&inv_colperm);
268 }
269 initialize();
270#endif
271}
272#ifdef PETSCKSP_H
273#define _RTOL_MIN_ 1.e-24 // Would like to set to 1.e-14 but ALE test cases in TrioCFD needs rtol very low...
274inline void Solv_Petsc::initialize()
275{
277 preconditionnement_non_symetrique_=0;
278 seuil_ = 0;
279 seuil_relatif_ = _RTOL_MIN_;
280 divtol_ = 0;
281 nouveau_stencil_ = true;
282 petsc_cpus_selection_ = 0; // By default, 0 (no selection). 1 means: first petsc_nb_cpus_ CPUs is used, 2 means: every petsc_nb_cpus_ CPUs is used
283 petsc_nb_cpus_ = Process::nproc(); // By default the number of processes
284 different_partition_ = 0; // By default, same matrix partition
285 petsc_decide_ = 0; // By default, 0. 1 is OK but does NOT improve performance (rather decrease)
286 convergence_with_nb_it_max_ = 0;
287 ignore_nb_it_max_ = 0;
288 nb_it_max_ = NB_IT_MAX_DEFINED;
289 mataij_=0;
290 factored_matrix_="";
291 solveur_direct_=no;
292 controle_residu_=0;
293 gpu_=false;
294 amgx_=false;
295 amgx_initialized_=false;
296 block_size_=1;
297 option_prefix_="??";
298 dm_=nullptr;
299 MatricePetsc_ = nullptr;
300 SecondMembrePetsc_ = nullptr;
301 SolutionPetsc_ = nullptr;
302 SolveurPetsc_ = nullptr;
303 LocalSolutionPetsc_ = nullptr;
304 VecScatter_ = nullptr;
305 // Dev:
306 ignore_new_nonzero_ = false;
307 rebuild_matrix_ = false;
308 allow_realloc_ = true;
310 reorder_matrix_ = false;
311 reduce_ram_ = false;
312 if (instance==-1)
313 {
314 // First initialization:
315 instance=0;
316 char version[256];
317 PetscGetVersion(version,256);
318 Cerr << "******************************************************************************************" << finl;
319 Cerr << "Commands lines possible for " << version << ":" << finl;
320 Cerr << "-ksp_view : to have some informations on the solver/preconditioner used by PETSc." << finl;
321 Cerr << "-info : to have among other informations on storage of matrices of PETSc." << finl;
322 Cerr << "-log_summary : to have at the end of the calculation, informations about performances and memory." << finl;
323 Cerr << "-log_all : trace all PETSc calls." << finl;
324 Cerr << "-malloc_dump : to have at the end of the calculation the memory not deallocated by PETSc." << finl;
325 Cerr << "-help : to know all the commands lines of PETSc including those related to the solver/preconditioner selected." << finl;
326 Cerr << "******************************************************************************************" << finl;
327 if (!disable_TU)
328 Cerr << "NB: if you want to disable the wrinting of the *_petsc.TU file then specify the disable_TU flag in your datafile before reading the block of schema in time." << finl;
329 else
330 Cerr << "Reading of disable_TU flag => Disable the writing of the *_petsc.TU file."<< finl;
331 PetscLogStageRegister("CreateStage",&Create_Stage_);
332 PetscLogStageRegister("KSPSolve",&KSPSolve_Stage_);
333 }
334}
335
337{
338 initialize();
339 instance++;
340 // Journal()<<"copie solv_petsc "<<instance<<finl;
342 gpu_=org.gpu();
343 amgx_=org.amgx();
344 option_prefix_=org.option_prefix_;
345 // on relance la lecture ....
346 EChaine recup(org.get_chaine_lue());
347 readOn(recup);
348}
349
351{
352 Cerr<<"Solv_Petsc::operator=(const Solv_Petsc&) is not coded."<<finl;
353 exit();
354 return (*this);
355}
356
357#endif
358
360{
361public:
364};
365
366class option_string : public option
367{
368public:
370 {
371 defined=0;
372 name=n;
373 value_=v;
374 }
376 inline Nom& value()
377 {
378 return value_;
379 };
380};
381
382class option_int : public option
383{
384public:
385 option_int(Nom n, int v)
386 {
387 defined=0;
388 name=n;
389 value_=v;
390 }
392 inline int& value()
393 {
394 return value_;
395 };
396};
397
398class option_double : public option
399{
400public:
401 option_double(Nom n, double v)
402 {
403 defined=0;
404 name=n;
405 value_=v;
406 }
407 double value_;
408 inline double& value()
409 {
410 return value_;
411 };
412};
413
414#endif
415
416
Une entree dont la source est une chaine de caracteres.
Definition EChaine.h:31
Class defining operators and methods for all reading operation in an input flow (file,...
Definition Entree.h:42
Classe Matrice_Base Classe de base de la hierarchie des matrices.
Classe Matrice_Morse_Sym Represente une matrice M (creuse) symetrique stockee au format Morse.
Classe Matrice_Morse Represente une matrice M (creuse), non necessairement carree.
class Nom Une chaine de caractere pour nommer les objets de TRUST
Definition Nom.h:31
const Objet_U & operator=(const Objet_U &)
Operateur= : ne fait rien (on conserve le numero et l'identifiant).
Definition Objet_U.cpp:87
static bool disable_TU
Flag to disable or not the writing of the .TU files.
Definition Objet_U.h:125
virtual Entree & readOn(Entree &)
Lecture d'un Objet_U sur un flot d'entree Methode a surcharger.
Definition Objet_U.cpp:293
static int nproc()
renvoie le nombre de processeurs dans le groupe courant Voir Comm_Group::nproc() et PE_Groups::curren...
Definition Process.cpp:104
static void exit(int exit_code=-1)
Routine de sortie de TRUST dans une region Kokkos.
Definition Process.cpp:455
int matrice_symetrique_
void Update_solution(DoubleVect &x)
bool ignore_new_nonzero_
Definition Solv_Petsc.h:207
~Solv_Petsc() override
Definition Solv_Petsc.h:234
bool mat_ignore_zero_entries_
Definition Solv_Petsc.h:210
void reset()
Definition Solv_Petsc.h:240
bool allow_realloc_
Definition Solv_Petsc.h:209
int solveur_direct() const override
Definition Solv_Petsc.h:61
int resoudre_systeme(const Matrice_Base &M, const DoubleVect &A, DoubleVect &B, int niter_max) override
Definition Solv_Petsc.h:69
bool amgx_initialized_
Definition Solv_Petsc.h:205
static public_for_cuda int instance
Definition Solv_Petsc.h:132
bool reduce_ram_
Definition Solv_Petsc.h:211
int reuse_preconditioner_nb_it_max_
Definition Solv_Petsc.h:216
bool rebuild_matrix_
Definition Solv_Petsc.h:208
int solveur_direct_
Definition Solv_Petsc.h:201
void create_solver()
Definition Solv_Petsc.h:56
static int numero_solveur
Definition Solv_Petsc.h:133
int resoudre_systeme(const Matrice_Base &, const DoubleVect &, DoubleVect &) override
bool reorder_matrix_
Definition Solv_Petsc.h:213
const Nom config()
int nb_it_previous_
Definition Solv_Petsc.h:215
bool read_matrix() const
const Nom & get_chaine_lue() const
void set_read_matrix(bool flag)
Represents a an array of int/int64/double/... values.
Definition TRUSTArray.h:81
option_double(Nom n, double v)
Definition Solv_Petsc.h:401
double & value()
Definition Solv_Petsc.h:408
option_int(Nom n, int v)
Definition Solv_Petsc.h:385
int & value()
Definition Solv_Petsc.h:392
Nom & value()
Definition Solv_Petsc.h:376
option_string(Nom n, Nom v)
Definition Solv_Petsc.h:369
int defined
Definition Solv_Petsc.h:362
Nom name
Definition Solv_Petsc.h:363
OWN_PTR(PCShell_base) pc_shell