Actual source code: imumps.c

  1: /*
  2:     Provides an interface to the MUMPS sparse solver
  3: */
  4: #include <petscpkg_version.h>
  5: #include <petscsf.h>
  6: #include <../src/mat/impls/aij/mpi/mpiaij.h>
  7: #include <../src/mat/impls/sbaij/mpi/mpisbaij.h>
  8: #include <../src/mat/impls/sell/mpi/mpisell.h>
  9: #include <petsc/private/vecimpl.h>

 11: #define MUMPS_MANUALS "(see users manual https://mumps-solver.org/index.php?page=doc \"Error and warning diagnostics\")"

 13: EXTERN_C_BEGIN
 14: #if PetscDefined(HAVE_MUMPS_MIXED_PRECISION)
 15:   #include <cmumps_c.h>
 16:   #include <zmumps_c.h>
 17:   #include <smumps_c.h>
 18:   #include <dmumps_c.h>
 19: #else
 20:   #if PetscDefined(USE_COMPLEX)
 21:     #if PetscDefined(USE_REAL_SINGLE)
 22:       #include <cmumps_c.h>
 23:       #define MUMPS_c     cmumps_c
 24:       #define MumpsScalar CMUMPS_COMPLEX
 25:     #else
 26:       #include <zmumps_c.h>
 27:       #define MUMPS_c     zmumps_c
 28:       #define MumpsScalar ZMUMPS_COMPLEX
 29:     #endif
 30:   #else
 31:     #if PetscDefined(USE_REAL_SINGLE)
 32:       #include <smumps_c.h>
 33:       #define MUMPS_c     smumps_c
 34:       #define MumpsScalar SMUMPS_REAL
 35:     #else
 36:       #include <dmumps_c.h>
 37:       #define MUMPS_c     dmumps_c
 38:       #define MumpsScalar DMUMPS_REAL
 39:     #endif
 40:   #endif
 41: #endif
 42: #if PetscDefined(USE_COMPLEX)
 43:   #if PetscDefined(USE_REAL_SINGLE)
 44:     #define MUMPS_STRUC_C CMUMPS_STRUC_C
 45:   #else
 46:     #define MUMPS_STRUC_C ZMUMPS_STRUC_C
 47:   #endif
 48: #else
 49:   #if PetscDefined(USE_REAL_SINGLE)
 50:     #define MUMPS_STRUC_C SMUMPS_STRUC_C
 51:   #else
 52:     #define MUMPS_STRUC_C DMUMPS_STRUC_C
 53:   #endif
 54: #endif
 55: EXTERN_C_END

 57: #define JOB_INIT         -1
 58: #define JOB_NULL         0
 59: #define JOB_FACTSYMBOLIC 1
 60: #define JOB_FACTNUMERIC  2
 61: #define JOB_SOLVE        3
 62: #define JOB_END          -2

 64: /* MUMPS uses MUMPS_INT for nonzero indices such as irn/jcn, irn_loc/jcn_loc and uses int64_t for
 65:    number of nonzeros such as nnz, nnz_loc. We typedef MUMPS_INT to PetscMUMPSInt to follow the
 66:    naming convention in PetscMPIInt, PetscBLASInt etc.
 67: */
 68: typedef MUMPS_INT PetscMUMPSInt;

 70: #if PETSC_PKG_MUMPS_VERSION_GE(5, 3, 0)
 71:   #if defined(MUMPS_INTSIZE64) /* MUMPS_INTSIZE64 is in MUMPS headers if it is built in full 64-bit mode, therefore the macro is more reliable */
 72:     #error "PETSc has not been tested with full 64-bit MUMPS and we choose to error out"
 73:   #endif
 74: #else
 75:   #if defined(INTSIZE64) /* INTSIZE64 is a command line macro one used to build MUMPS in full 64-bit mode */
 76:     #error "PETSc has not been tested with full 64-bit MUMPS and we choose to error out"
 77:   #endif
 78: #endif

 80: #define MPIU_MUMPSINT       MPI_INT
 81: #define PETSC_MUMPS_INT_MAX 2147483647
 82: #define PETSC_MUMPS_INT_MIN -2147483648

 84: /* Cast PetscInt to PetscMUMPSInt. Usually there is no overflow since <a> is row/col indices or some small integers*/
 85: static inline PetscErrorCode PetscMUMPSIntCast(PetscCount a, PetscMUMPSInt *b)
 86: {
 87:   PetscFunctionBegin;
 88:   PetscAssert(!PetscDefined(USE_64BIT_INDICES) || (a <= PETSC_MUMPS_INT_MAX && a >= PETSC_MUMPS_INT_MIN), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "PetscInt too long for PetscMUMPSInt");
 89:   *b = (PetscMUMPSInt)a;
 90:   PetscFunctionReturn(PETSC_SUCCESS);
 91: }

 93: /* Put these utility routines here since they are only used in this file */
 94: static inline PetscErrorCode PetscOptionsMUMPSInt_Private(PetscOptionItems PetscOptionsObject, const char opt[], const char text[], const char man[], PetscMUMPSInt currentvalue, PetscMUMPSInt *value, PetscBool *set, PetscMUMPSInt lb, PetscMUMPSInt ub)
 95: {
 96:   PetscInt  myval;
 97:   PetscBool myset;

 99:   PetscFunctionBegin;
100:   /* PetscInt's size should be always >= PetscMUMPSInt's. It is safe to call PetscOptionsInt_Private to read a PetscMUMPSInt */
101:   PetscCall(PetscOptionsInt_Private(PetscOptionsObject, opt, text, man, (PetscInt)currentvalue, &myval, &myset, lb, ub));
102:   if (myset) PetscCall(PetscMUMPSIntCast(myval, value));
103:   if (set) *set = myset;
104:   PetscFunctionReturn(PETSC_SUCCESS);
105: }
106: #define PetscOptionsMUMPSInt(a, b, c, d, e, f) PetscOptionsMUMPSInt_Private(PetscOptionsObject, a, b, c, d, e, f, PETSC_MUMPS_INT_MIN, PETSC_MUMPS_INT_MAX)

108: // An abstract type for specific MUMPS types {S,D,C,Z}MUMPS_STRUC_C.
109: //
110: // With the abstract (outer) type, we can write shared code. We call MUMPS through a type-to-be-determined inner field within the abstract type.
111: // Before/after calling MUMPS, we need to copy in/out fields between the outer and the inner, which seems expensive. But note that the large fixed size
112: // arrays within the types are directly linked. At the end, we only need to copy ~20 integers/pointers, which is doable. See PreMumpsCall()/PostMumpsCall().
113: //
114: // Not all fields in the specific types are exposed in the abstract type. We only need those used by the PETSc/MUMPS interface.
115: // Notably, DMUMPS_COMPLEX* and DMUMPS_REAL* fields are now declared as void *. Their type will be determined by the the actual precision to be used.
116: // Also note that we added some *_len fields not in specific types to track sizes of those MumpsScalar buffers.
117: typedef struct {
118:   PetscPrecision precision;   // precision used by MUMPS
119:   void          *internal_id; // the data structure passed to MUMPS, whose actual type {S,D,C,Z}MUMPS_STRUC_C is to be decided by precision and PETSc's use of complex

121:   // aliased fields from internal_id, so that we can use XMUMPS_STRUC_C to write shared code across different precisions.
122:   MUMPS_INT  sym, par, job;
123:   MUMPS_INT  comm_fortran; /* Fortran communicator */
124:   MUMPS_INT *icntl;
125:   void      *cntl; // MumpsReal, fixed size array
126:   MUMPS_INT  n;
127:   MUMPS_INT  nblk;

129:   /* Assembled entry */
130:   MUMPS_INT8 nnz;
131:   MUMPS_INT *irn;
132:   MUMPS_INT *jcn;
133:   void      *a; // MumpsScalar, centralized input
134:   PetscCount a_len;

136:   /* Distributed entry */
137:   MUMPS_INT8 nnz_loc;
138:   MUMPS_INT *irn_loc;
139:   MUMPS_INT *jcn_loc;
140:   void      *a_loc; // MumpsScalar, distributed input
141:   PetscCount a_loc_len;

143:   /* Matrix by blocks */
144:   MUMPS_INT *blkptr;
145:   MUMPS_INT *blkvar;

147:   /* Ordering, if given by user */
148:   MUMPS_INT *perm_in;

150:   /* RHS, solution, ouptput data and statistics */
151:   void      *rhs, *redrhs, *rhs_sparse, *sol_loc, *rhs_loc;                 // MumpsScalar buffers
152:   PetscCount rhs_len, redrhs_len, rhs_sparse_len, sol_loc_len, rhs_loc_len; // length of buffers (in MumpsScalar) IF allocated in a different precision than PetscScalar

154:   MUMPS_INT *irhs_sparse, *irhs_ptr, *isol_loc, *irhs_loc;
155:   MUMPS_INT  nrhs, lrhs, lredrhs, nz_rhs, lsol_loc, nloc_rhs, lrhs_loc;
156:   // MUMPS_INT  nsol_loc; // introduced in MUMPS-5.7, but PETSc doesn't use it; would cause compile errors with the widely used 5.6. If you add it, must also update PreMumpsCall() and guard this with #if PETSC_PKG_MUMPS_VERSION_GE(5, 7, 0)
157:   MUMPS_INT  schur_lld;
158:   MUMPS_INT *info, *infog;   // fixed size array
159:   void      *rinfo, *rinfog; // MumpsReal, fixed size array

161:   /* Null space */
162:   MUMPS_INT *pivnul_list; // allocated by MUMPS!
163:   MUMPS_INT *mapping;     // allocated by MUMPS!

165:   /* Schur */
166:   MUMPS_INT  size_schur;
167:   MUMPS_INT *listvar_schur;
168:   void      *schur; // MumpsScalar
169:   PetscCount schur_len;

171:   /* For out-of-core */
172:   char *ooc_tmpdir; // fixed size array
173:   char *ooc_prefix; // fixed size array
174: } XMUMPS_STRUC_C;

176: // Note: fixed-size arrays are allocated by MUMPS; redirect them to the outer struct
177: #define AllocateInternalID(MUMPS_STRUC_T, outer) \
178:   do { \
179:     MUMPS_STRUC_T *inner; \
180:     PetscCall(PetscNew(&inner)); \
181:     (outer)->icntl      = inner->icntl; \
182:     (outer)->cntl       = inner->cntl; \
183:     (outer)->info       = inner->info; \
184:     (outer)->infog      = inner->infog; \
185:     (outer)->rinfo      = inner->rinfo; \
186:     (outer)->rinfog     = inner->rinfog; \
187:     (outer)->ooc_tmpdir = inner->ooc_tmpdir; \
188:     (outer)->ooc_prefix = inner->ooc_prefix; \
189:     /* the three field should never change after init */ \
190:     inner->comm_fortran  = (outer)->comm_fortran; \
191:     inner->par           = (outer)->par; \
192:     inner->sym           = (outer)->sym; \
193:     (outer)->internal_id = inner; \
194:   } while (0)

196: // Allocate the internal [SDCZ]MUMPS_STRUC_C ID data structure in the given , and link fields of the outer and the inner
197: static inline PetscErrorCode MatMumpsAllocateInternalID(XMUMPS_STRUC_C *outer, PetscPrecision precision)
198: {
199:   PetscFunctionBegin;
200:   outer->precision = precision;
201: #if PetscDefined(HAVE_MUMPS_MIXED_PRECISION)
202:   #if PetscDefined(USE_COMPLEX)
203:   if (precision == PETSC_PRECISION_SINGLE) AllocateInternalID(CMUMPS_STRUC_C, outer);
204:   else AllocateInternalID(ZMUMPS_STRUC_C, outer);
205:   #else
206:   if (precision == PETSC_PRECISION_SINGLE) AllocateInternalID(SMUMPS_STRUC_C, outer);
207:   else AllocateInternalID(DMUMPS_STRUC_C, outer);
208:   #endif
209: #else
210:   AllocateInternalID(MUMPS_STRUC_C, outer);
211: #endif
212:   PetscFunctionReturn(PETSC_SUCCESS);
213: }

215: #define FreeInternalIDFields(MUMPS_STRUC_T, outer) \
216:   do { \
217:     MUMPS_STRUC_T *inner = (MUMPS_STRUC_T *)(outer)->internal_id; \
218:     PetscCall(PetscFree(inner->a)); \
219:     PetscCall(PetscFree(inner->a_loc)); \
220:     PetscCall(PetscFree(inner->rhs)); \
221:     PetscCall(PetscFree(inner->rhs_sparse)); \
222:     PetscCall(PetscFree(inner->rhs_loc)); \
223:     PetscCall(PetscFree(inner->sol_loc)); \
224:   } while (0)

226: static inline PetscErrorCode MatMumpsFreeInternalID(XMUMPS_STRUC_C *outer)
227: {
228:   PetscFunctionBegin;
229:   if (outer->internal_id) { // sometimes, the inner is never created before we destroy the outer
230: #if PetscDefined(HAVE_MUMPS_MIXED_PRECISION)
231:     const PetscPrecision mumps_precision = outer->precision;
232:     if (mumps_precision != PETSC_SCALAR_PRECISION) { // Free internal buffers if we used mixed precision
233:   #if PetscDefined(USE_COMPLEX)
234:       if (mumps_precision == PETSC_PRECISION_SINGLE) FreeInternalIDFields(CMUMPS_STRUC_C, outer);
235:       else FreeInternalIDFields(ZMUMPS_STRUC_C, outer);
236:   #else
237:       if (mumps_precision == PETSC_PRECISION_SINGLE) FreeInternalIDFields(SMUMPS_STRUC_C, outer);
238:       else FreeInternalIDFields(DMUMPS_STRUC_C, outer);
239:   #endif
240:     }
241: #endif
242:     PetscCall(PetscFree(outer->internal_id));
243:   }
244:   PetscFunctionReturn(PETSC_SUCCESS);
245: }

247: // Make a companion MumpsScalar array (with a given PetscScalar array), to hold at least  MumpsScalars in the given  and return the address at .
248: //  indicates if we need to convert PetscScalars to MumpsScalars after allocating the MumpsScalar array.
249: // (For brevity, we use  for array address and  for its length in MumpsScalar, though in code they should be <*ma> and <*m>)
250: // If  already points to a buffer/array, on input  should be its length. Note the buffer might be freed if it is not big enough for this request.
251: //
252: // The returned array is a companion, so how it is created depends on if PetscScalar and MumpsScalar are the same.
253: // 1) If they are different, a separate array will be made and its length and address will be provided at  and  on output.
254: // 2) Otherwise,  will be returned in , and  will be zero on output.
255: //
256: //
257: //   Input parameters:
258: // + convert   - whether to do PetscScalar to MumpsScalar conversion
259: // . n         - length of the PetscScalar array
260: // . pa        - [n]], points to the PetscScalar array
261: // . precision - precision of MumpsScalar
262: // . m         - on input, length of an existing MumpsScalar array  if any, otherwise *m is just zero.
263: // - ma        - on input, an existing MumpsScalar array if any.
264: //
265: //   Output parameters:
266: // + m  - length of the MumpsScalar buffer at  if MumpsScalar is different from PetscScalar, otherwise 0
267: // . ma - the MumpsScalar array, which could be an alias of  when the two types are the same.
268: //
269: //   Note:
270: //    New memory, if allocated, is done via PetscMalloc1(), and is owned by caller.
271: static PetscErrorCode MatMumpsMakeMumpsScalarArray(PetscBool convert, PetscCount n, const PetscScalar *pa, PetscPrecision precision, PetscCount *m, void **ma)
272: {
273:   PetscFunctionBegin;
274: #if PetscDefined(HAVE_MUMPS_MIXED_PRECISION)
275:   const PetscPrecision mumps_precision = precision;
276:   PetscCheck(precision == PETSC_PRECISION_SINGLE || precision == PETSC_PRECISION_DOUBLE, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Unsupported precicison (%d). Must be single or double", (int)precision);
277:   #if PetscDefined(USE_COMPLEX)
278:   if (mumps_precision != PETSC_SCALAR_PRECISION) {
279:     if (mumps_precision == PETSC_PRECISION_SINGLE) {
280:       if (*m < n) {
281:         PetscCall(PetscFree(*ma));
282:         PetscCall(PetscMalloc1(n, (CMUMPS_COMPLEX **)ma));
283:         *m = n;
284:       }
285:       if (convert) {
286:         CMUMPS_COMPLEX *b = *(CMUMPS_COMPLEX **)ma;
287:         for (PetscCount i = 0; i < n; i++) {
288:           b[i].r = PetscRealPart(pa[i]);
289:           b[i].i = PetscImaginaryPart(pa[i]);
290:         }
291:       }
292:     } else {
293:       if (*m < n) {
294:         PetscCall(PetscFree(*ma));
295:         PetscCall(PetscMalloc1(n, (ZMUMPS_COMPLEX **)ma));
296:         *m = n;
297:       }
298:       if (convert) {
299:         ZMUMPS_COMPLEX *b = *(ZMUMPS_COMPLEX **)ma;
300:         for (PetscCount i = 0; i < n; i++) {
301:           b[i].r = PetscRealPart(pa[i]);
302:           b[i].i = PetscImaginaryPart(pa[i]);
303:         }
304:       }
305:     }
306:   }
307:   #else
308:   if (mumps_precision != PETSC_SCALAR_PRECISION) {
309:     if (mumps_precision == PETSC_PRECISION_SINGLE) {
310:       if (*m < n) {
311:         PetscCall(PetscFree(*ma));
312:         PetscCall(PetscMalloc1(n, (SMUMPS_REAL **)ma));
313:         *m = n;
314:       }
315:       if (convert) {
316:         SMUMPS_REAL *b = *(SMUMPS_REAL **)ma;
317:         for (PetscCount i = 0; i < n; i++) b[i] = pa[i];
318:       }
319:     } else {
320:       if (*m < n) {
321:         PetscCall(PetscFree(*ma));
322:         PetscCall(PetscMalloc1(n, (DMUMPS_REAL **)ma));
323:         *m = n;
324:       }
325:       if (convert) {
326:         DMUMPS_REAL *b = *(DMUMPS_REAL **)ma;
327:         for (PetscCount i = 0; i < n; i++) b[i] = pa[i];
328:       }
329:     }
330:   }
331:   #endif
332:   else
333: #endif
334:   {
335:     if (*m != 0) PetscCall(PetscFree(*ma)); // free existing buffer if any
336:     *ma = (void *)pa;                       // same precision, make them alias
337:     *m  = 0;
338:   }
339:   PetscFunctionReturn(PETSC_SUCCESS);
340: }

342: // Cast a MumpsScalar array  in  to a PetscScalar array at address .
343: //
344: // 1) If the two types are different, cast array elements.
345: // 2) Otherwise, this works as a memcpy; of course, if the two addresses are equal, it is a no-op.
346: static PetscErrorCode MatMumpsCastMumpsScalarArray(PetscCount n, PetscPrecision mumps_precision, const void *ma, PetscScalar *pa)
347: {
348:   PetscFunctionBegin;
349: #if PetscDefined(HAVE_MUMPS_MIXED_PRECISION)
350:   if (mumps_precision != PETSC_SCALAR_PRECISION) {
351:   #if PetscDefined(USE_COMPLEX)
352:     if (mumps_precision == PETSC_PRECISION_SINGLE) {
353:       PetscReal         *a = (PetscReal *)pa;
354:       const SMUMPS_REAL *b = (const SMUMPS_REAL *)ma;
355:       for (PetscCount i = 0; i < 2 * n; i++) a[i] = b[i];
356:     } else {
357:       PetscReal         *a = (PetscReal *)pa;
358:       const DMUMPS_REAL *b = (const DMUMPS_REAL *)ma;
359:       for (PetscCount i = 0; i < 2 * n; i++) a[i] = b[i];
360:     }
361:   #else
362:     if (mumps_precision == PETSC_PRECISION_SINGLE) {
363:       const SMUMPS_REAL *b = (const SMUMPS_REAL *)ma;
364:       for (PetscCount i = 0; i < n; i++) pa[i] = b[i];
365:     } else {
366:       const DMUMPS_REAL *b = (const DMUMPS_REAL *)ma;
367:       for (PetscCount i = 0; i < n; i++) pa[i] = b[i];
368:     }
369:   #endif
370:   } else
371: #endif
372:     PetscCall(PetscArraycpy((PetscScalar *)pa, (PetscScalar *)ma, n));
373:   PetscFunctionReturn(PETSC_SUCCESS);
374: }

376: // Cast a PetscScalar array  to a MumpsScalar array in the given  at address .
377: //
378: // 1) If the two types are different, cast array elements.
379: // 2) Otherwise, this works as a memcpy; of course, if the two addresses are equal, it is a no-op.
380: static PetscErrorCode MatMumpsCastPetscScalarArray(PetscCount n, const PetscScalar *pa, PetscPrecision mumps_precision, const void *ma)
381: {
382:   PetscFunctionBegin;
383: #if PetscDefined(HAVE_MUMPS_MIXED_PRECISION)
384:   if (mumps_precision != PETSC_SCALAR_PRECISION) {
385:   #if PetscDefined(USE_COMPLEX)
386:     if (mumps_precision == PETSC_PRECISION_SINGLE) {
387:       CMUMPS_COMPLEX *b = (CMUMPS_COMPLEX *)ma;
388:       for (PetscCount i = 0; i < n; i++) {
389:         b[i].r = PetscRealPart(pa[i]);
390:         b[i].i = PetscImaginaryPart(pa[i]);
391:       }
392:     } else {
393:       ZMUMPS_COMPLEX *b = (ZMUMPS_COMPLEX *)ma;
394:       for (PetscCount i = 0; i < n; i++) {
395:         b[i].r = PetscRealPart(pa[i]);
396:         b[i].i = PetscImaginaryPart(pa[i]);
397:       }
398:     }
399:   #else
400:     if (mumps_precision == PETSC_PRECISION_SINGLE) {
401:       SMUMPS_REAL *b = (SMUMPS_REAL *)ma;
402:       for (PetscCount i = 0; i < n; i++) b[i] = pa[i];
403:     } else {
404:       DMUMPS_REAL *b = (DMUMPS_REAL *)ma;
405:       for (PetscCount i = 0; i < n; i++) b[i] = pa[i];
406:     }
407:   #endif
408:   } else
409: #endif
410:     PetscCall(PetscArraycpy((PetscScalar *)ma, (PetscScalar *)pa, n));
411:   PetscFunctionReturn(PETSC_SUCCESS);
412: }

414: static inline MPI_Datatype MPIU_MUMPSREAL(const XMUMPS_STRUC_C *id)
415: {
416:   return id->precision == PETSC_PRECISION_DOUBLE ? MPI_DOUBLE : MPI_FLOAT;
417: }

419: #define PreMumpsCall(inner, outer, mumpsscalar) \
420:   do { \
421:     (inner)->job           = (outer)->job; \
422:     (inner)->n             = (outer)->n; \
423:     (inner)->nblk          = (outer)->nblk; \
424:     (inner)->nnz           = (outer)->nnz; \
425:     (inner)->irn           = (outer)->irn; \
426:     (inner)->jcn           = (outer)->jcn; \
427:     (inner)->a             = (mumpsscalar *)(outer)->a; \
428:     (inner)->nnz_loc       = (outer)->nnz_loc; \
429:     (inner)->irn_loc       = (outer)->irn_loc; \
430:     (inner)->jcn_loc       = (outer)->jcn_loc; \
431:     (inner)->a_loc         = (mumpsscalar *)(outer)->a_loc; \
432:     (inner)->blkptr        = (outer)->blkptr; \
433:     (inner)->blkvar        = (outer)->blkvar; \
434:     (inner)->perm_in       = (outer)->perm_in; \
435:     (inner)->rhs           = (mumpsscalar *)(outer)->rhs; \
436:     (inner)->redrhs        = (mumpsscalar *)(outer)->redrhs; \
437:     (inner)->rhs_sparse    = (mumpsscalar *)(outer)->rhs_sparse; \
438:     (inner)->sol_loc       = (mumpsscalar *)(outer)->sol_loc; \
439:     (inner)->rhs_loc       = (mumpsscalar *)(outer)->rhs_loc; \
440:     (inner)->irhs_sparse   = (outer)->irhs_sparse; \
441:     (inner)->irhs_ptr      = (outer)->irhs_ptr; \
442:     (inner)->isol_loc      = (outer)->isol_loc; \
443:     (inner)->irhs_loc      = (outer)->irhs_loc; \
444:     (inner)->nrhs          = (outer)->nrhs; \
445:     (inner)->lrhs          = (outer)->lrhs; \
446:     (inner)->lredrhs       = (outer)->lredrhs; \
447:     (inner)->nz_rhs        = (outer)->nz_rhs; \
448:     (inner)->lsol_loc      = (outer)->lsol_loc; \
449:     (inner)->nloc_rhs      = (outer)->nloc_rhs; \
450:     (inner)->lrhs_loc      = (outer)->lrhs_loc; \
451:     (inner)->schur_lld     = (outer)->schur_lld; \
452:     (inner)->size_schur    = (outer)->size_schur; \
453:     (inner)->listvar_schur = (outer)->listvar_schur; \
454:     (inner)->schur         = (mumpsscalar *)(outer)->schur; \
455:   } while (0)

457: #define PostMumpsCall(inner, outer) \
458:   do { \
459:     (outer)->pivnul_list = (inner)->pivnul_list; \
460:     (outer)->mapping     = (inner)->mapping; \
461:   } while (0)

463: // Entry for PETSc to call mumps
464: static inline PetscErrorCode PetscCallMumps_Private(XMUMPS_STRUC_C *outer)
465: {
466:   PetscFunctionBegin;
467: #if PetscDefined(HAVE_MUMPS_MIXED_PRECISION)
468:   #if PetscDefined(USE_COMPLEX)
469:   if (outer->precision == PETSC_PRECISION_SINGLE) {
470:     CMUMPS_STRUC_C *inner = (CMUMPS_STRUC_C *)outer->internal_id;
471:     PreMumpsCall(inner, outer, CMUMPS_COMPLEX);
472:     PetscCallExternalVoid("cmumps_c", cmumps_c(inner));
473:     PostMumpsCall(inner, outer);
474:   } else {
475:     ZMUMPS_STRUC_C *inner = (ZMUMPS_STRUC_C *)outer->internal_id;
476:     PreMumpsCall(inner, outer, ZMUMPS_COMPLEX);
477:     PetscCallExternalVoid("zmumps_c", zmumps_c(inner));
478:     PostMumpsCall(inner, outer);
479:   }
480:   #else
481:   if (outer->precision == PETSC_PRECISION_SINGLE) {
482:     SMUMPS_STRUC_C *inner = (SMUMPS_STRUC_C *)outer->internal_id;
483:     PreMumpsCall(inner, outer, SMUMPS_REAL);
484:     PetscCallExternalVoid("smumps_c", smumps_c(inner));
485:     PostMumpsCall(inner, outer);
486:   } else {
487:     DMUMPS_STRUC_C *inner = (DMUMPS_STRUC_C *)outer->internal_id;
488:     PreMumpsCall(inner, outer, DMUMPS_REAL);
489:     PetscCallExternalVoid("dmumps_c", dmumps_c(inner));
490:     PostMumpsCall(inner, outer);
491:   }
492:   #endif
493: #else
494:   MUMPS_STRUC_C *inner = (MUMPS_STRUC_C *)outer->internal_id;
495:   PreMumpsCall(inner, outer, MumpsScalar);
496:   PetscCallExternalVoid(PetscStringize(MUMPS_c), MUMPS_c(inner));
497:   PostMumpsCall(inner, outer);
498: #endif
499:   PetscFunctionReturn(PETSC_SUCCESS);
500: }

502: /* macros s.t. indices match MUMPS documentation */
503: #define ICNTL(I) icntl[(I) - 1]
504: #define INFOG(I) infog[(I) - 1]
505: #define INFO(I)  info[(I) - 1]

507: // Get a value from a MumpsScalar array, which is the  field in the struct of MUMPS_STRUC_C. The value is convertible to PetscScalar. Note no minus 1 on I!
508: #if PetscDefined(USE_COMPLEX)
509:   #define ID_FIELD_GET(ID, F, I) ((ID).precision == PETSC_PRECISION_SINGLE ? ((CMUMPS_COMPLEX *)(ID).F)[I].r + PETSC_i * ((CMUMPS_COMPLEX *)(ID).F)[I].i : ((ZMUMPS_COMPLEX *)(ID).F)[I].r + PETSC_i * ((ZMUMPS_COMPLEX *)(ID).F)[I].i)
510: #else
511:   #define ID_FIELD_GET(ID, F, I) ((ID).precision == PETSC_PRECISION_SINGLE ? ((float *)(ID).F)[I] : ((double *)(ID).F)[I])
512: #endif

514: // Get a value from MumpsReal arrays. The value is convertible to PetscReal.
515: #define ID_CNTL_GET(ID, I)   ((ID).precision == PETSC_PRECISION_SINGLE ? ((float *)(ID).cntl)[(I) - 1] : ((double *)(ID).cntl)[(I) - 1])
516: #define ID_RINFOG_GET(ID, I) ((ID).precision == PETSC_PRECISION_SINGLE ? ((float *)(ID).rinfog)[(I) - 1] : ((double *)(ID).rinfog)[(I) - 1])
517: #define ID_RINFO_GET(ID, I)  ((ID).precision == PETSC_PRECISION_SINGLE ? ((float *)(ID).rinfo)[(I) - 1] : ((double *)(ID).rinfo)[(I) - 1])

519: // Set the I-th entry of the MumpsReal array id.cntl[] with a PetscReal 
520: #define ID_CNTL_SET(ID, I, VAL) \
521:   do { \
522:     if ((ID).precision == PETSC_PRECISION_SINGLE) ((float *)(ID).cntl)[(I) - 1] = (VAL); \
523:     else ((double *)(ID).cntl)[(I) - 1] = (VAL); \
524:   } while (0)

526: /* if using PETSc OpenMP support, we only call MUMPS on master ranks. Before/after the call, we change/restore CPUs the master ranks can run on */
527: #if PetscDefined(HAVE_OPENMP_SUPPORT)
528:   #define PetscMUMPS_c(mumps) \
529:     do { \
530:       if ((mumps)->use_petsc_omp_support) { \
531:         if ((mumps)->is_omp_master) { \
532:           PetscCall(PetscOmpCtrlOmpRegionOnMasterBegin((mumps)->omp_ctrl)); \
533:           PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF)); \
534:           PetscCall(PetscCallMumps_Private(&(mumps)->id)); \
535:           PetscCall(PetscFPTrapPop()); \
536:           PetscCall(PetscOmpCtrlOmpRegionOnMasterEnd((mumps)->omp_ctrl)); \
537:         } \
538:         PetscCall(PetscOmpCtrlBarrier((mumps)->omp_ctrl)); \
539:         /* Global info is same on all processes so we Bcast it within omp_comm. Local info is specific      \
540:          to processes, so we only Bcast info[1], an error code and leave others (since they do not have   \
541:          an easy translation between omp_comm and petsc_comm). See MUMPS-5.1.2 manual p82.                   \
542:          omp_comm is a small shared memory communicator, hence doing multiple Bcast as shown below is OK. \
543:       */ \
544:         MUMPS_STRUC_C tmp; /* All MUMPS_STRUC_C types have same lengths on these info arrays */ \
545:         PetscCallMPI(MPI_Bcast((mumps)->id.infog, PETSC_STATIC_ARRAY_LENGTH(tmp.infog), MPIU_MUMPSINT, 0, (mumps)->omp_comm)); \
546:         PetscCallMPI(MPI_Bcast((mumps)->id.info, PETSC_STATIC_ARRAY_LENGTH(tmp.info), MPIU_MUMPSINT, 0, (mumps)->omp_comm)); \
547:         PetscCallMPI(MPI_Bcast((mumps)->id.rinfog, PETSC_STATIC_ARRAY_LENGTH(tmp.rinfog), MPIU_MUMPSREAL(&(mumps)->id), 0, (mumps)->omp_comm)); \
548:         PetscCallMPI(MPI_Bcast((mumps)->id.rinfo, PETSC_STATIC_ARRAY_LENGTH(tmp.rinfo), MPIU_MUMPSREAL(&(mumps)->id), 0, (mumps)->omp_comm)); \
549:       } else { \
550:         PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF)); \
551:         PetscCall(PetscCallMumps_Private(&(mumps)->id)); \
552:         PetscCall(PetscFPTrapPop()); \
553:       } \
554:     } while (0)
555: #else
556:   #define PetscMUMPS_c(mumps) \
557:     do { \
558:       PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF)); \
559:       PetscCall(PetscCallMumps_Private(&(mumps)->id)); \
560:       PetscCall(PetscFPTrapPop()); \
561:     } while (0)
562: #endif

564: typedef struct Mat_MUMPS Mat_MUMPS;
565: struct Mat_MUMPS {
566:   XMUMPS_STRUC_C id;

568:   MatStructure   matstruc;
569:   PetscMPIInt    myid, petsc_size;
570:   PetscMUMPSInt *irn, *jcn;       /* the (i,j,v) triplets passed to mumps. */
571:   PetscScalar   *val, *val_alloc; /* For some matrices, we can directly access their data array without a buffer. For others, we need a buffer. So comes val_alloc. */
572:   PetscCount     nnz;             /* number of nonzeros. The type is called selective 64-bit in mumps */
573:   PetscMUMPSInt  sym;
574:   MPI_Comm       mumps_comm;
575:   PetscMUMPSInt *ICNTL_pre;
576:   PetscReal     *CNTL_pre;
577:   VecScatter     scat_rhs, scat_sol[2]; /* normal/transpose solution VecScatter shared for single- and multiple-RHS */
578:   PetscMUMPSInt  ICNTL20;               /* use centralized (0) or distributed (10) dense RHS */
579:   PetscMUMPSInt  ICNTL26;
580:   PetscMUMPSInt  lrhs_loc, nloc_rhs, *irhs_loc;
581: #if PetscDefined(HAVE_OPENMP_SUPPORT)
582:   PetscInt    *rhs_nrow, max_nrhs;
583:   PetscMPIInt *rhs_recvcounts, *rhs_disps;
584:   PetscScalar *rhs_loc, *rhs_recvbuf;
585: #endif
586:   Vec            b_seq, x_seq;
587:   PetscInt       ninfo, *info; /* which INFO to display */
588:   PetscInt       sizeredrhs;
589:   PetscScalar   *schur_sol;
590:   PetscInt       schur_sizesol;
591:   PetscScalar   *redrhs;              // buffer in PetscScalar in case MumpsScalar is in a different precision
592:   PetscMUMPSInt *ia_alloc, *ja_alloc; /* work arrays used for the CSR struct for sparse rhs */
593:   PetscCount     cur_ilen, cur_jlen;  /* current len of ia_alloc[], ja_alloc[] */
594:   PetscErrorCode (*ConvertToTriples)(Mat, PetscInt, MatReuse, Mat_MUMPS *);

596:   /* Support for MATNEST */
597:   PetscErrorCode (**nest_convert_to_triples)(Mat, PetscInt, MatReuse, Mat_MUMPS *);
598:   PetscCount  *nest_vals_start;
599:   PetscScalar *nest_vals;

601:   /* stuff used by petsc/mumps OpenMP support*/
602:   PetscBool    use_petsc_omp_support;
603:   PetscOmpCtrl omp_ctrl;             /* an OpenMP controller that blocked processes will release their CPU (MPI_Barrier does not have this guarantee) */
604:   MPI_Comm     petsc_comm, omp_comm; /* petsc_comm is PETSc matrix's comm */
605:   PetscCount  *recvcount;            /* a collection of nnz on omp_master */
606:   PetscMPIInt  tag, omp_comm_size;
607:   PetscBool    is_omp_master; /* is this rank the master of omp_comm */
608:   MPI_Request *reqs;
609: };

611: /* Cast a 1-based CSR represented by (nrow, ia, ja) of type PetscInt to a CSR of type PetscMUMPSInt.
612:    Here, nrow is number of rows, ia[] is row pointer and ja[] is column indices.
613:  */
614: static PetscErrorCode PetscMUMPSIntCSRCast(PETSC_UNUSED Mat_MUMPS *mumps, PetscInt nrow, PetscInt *ia, PetscInt *ja, PetscMUMPSInt **ia_mumps, PetscMUMPSInt **ja_mumps, PetscMUMPSInt *nnz_mumps)
615: {
616:   PetscInt nnz = ia[nrow] - 1; /* mumps uses 1-based indices. Uses PetscInt instead of PetscCount since mumps only uses PetscMUMPSInt for rhs */

618:   PetscFunctionBegin;
619: #if PetscDefined(USE_64BIT_INDICES)
620:   {
621:     if (nrow + 1 > mumps->cur_ilen) { /* realloc ia_alloc/ja_alloc to fit ia/ja */
622:       PetscCall(PetscFree(mumps->ia_alloc));
623:       PetscCall(PetscMalloc1(nrow + 1, &mumps->ia_alloc));
624:       mumps->cur_ilen = nrow + 1;
625:     }
626:     if (nnz > mumps->cur_jlen) {
627:       PetscCall(PetscFree(mumps->ja_alloc));
628:       PetscCall(PetscMalloc1(nnz, &mumps->ja_alloc));
629:       mumps->cur_jlen = nnz;
630:     }
631:     for (PetscInt i = 0; i < nrow + 1; i++) PetscCall(PetscMUMPSIntCast(ia[i], &mumps->ia_alloc[i]));
632:     for (PetscInt i = 0; i < nnz; i++) PetscCall(PetscMUMPSIntCast(ja[i], &mumps->ja_alloc[i]));
633:     *ia_mumps = mumps->ia_alloc;
634:     *ja_mumps = mumps->ja_alloc;
635:   }
636: #else
637:   *ia_mumps = ia;
638:   *ja_mumps = ja;
639: #endif
640:   PetscCall(PetscMUMPSIntCast(nnz, nnz_mumps));
641:   PetscFunctionReturn(PETSC_SUCCESS);
642: }

644: static PetscErrorCode MatMumpsEnsureSchurArray_Private(Mat F)
645: {
646:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

648:   PetscFunctionBegin;
649:   if (F->schur && !mumps->id.schur) {
650:     const PetscScalar *array;
651:     PetscCount         size = mumps->id.size_schur;

653:     PetscCall(MatDenseGetArrayRead(F->schur, &array));
654:     PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_FALSE, size * size, array, mumps->id.precision, &mumps->id.schur_len, &mumps->id.schur));
655:     PetscCall(MatDenseRestoreArrayRead(F->schur, &array));
656:   }
657:   PetscFunctionReturn(PETSC_SUCCESS);
658: }

660: static PetscErrorCode MatMumpsResetSchur_Private(Mat F)
661: {
662:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

664:   PetscFunctionBegin;
665:   PetscCall(PetscFree(mumps->id.listvar_schur));
666:   PetscCall(PetscFree(mumps->schur_sol));
667:   if (mumps->redrhs != mumps->id.redrhs) PetscCall(PetscFree(mumps->id.redrhs));
668:   else mumps->id.redrhs = NULL;
669:   PetscCall(PetscFree(mumps->redrhs));
670:   mumps->id.redrhs_len = 0;
671:   mumps->id.schur_len  = 0;
672:   mumps->id.lredrhs    = 0;
673:   mumps->sizeredrhs    = 0;
674:   mumps->id.size_schur = 0;
675:   mumps->id.schur_lld  = 0;
676:   if (mumps->id.internal_id) mumps->id.ICNTL(19) = 0; // sometimes, the inner id is yet built
677:   if (F->schur) {
678:     const PetscScalar *array;

680:     PetscCall(MatDenseGetArrayRead(F->schur, &array));
681:     if (array != mumps->id.schur) PetscCall(PetscFree(mumps->id.schur));
682:     else mumps->id.schur = NULL;
683:     PetscCall(MatDenseRestoreArrayRead(F->schur, &array));
684:   }
685:   PetscCall(MatDestroy(&F->schur));
686:   if (mumps->id.icntl) mumps->id.ICNTL(26) = 0;
687:   else mumps->ICNTL26 = 0;
688:   PetscFunctionReturn(PETSC_SUCCESS);
689: }

691: /* solve with rhs in mumps->id.redrhs and return in the same location */
692: static PetscErrorCode MatMumpsSolveSchur_Private(Mat F)
693: {
694:   Mat_MUMPS           *mumps = (Mat_MUMPS *)F->data;
695:   Mat                  S, B, X; // solve S*X = B; all three matrices are dense
696:   MatFactorSchurStatus schurstatus;
697:   PetscInt             sizesol;
698:   const PetscScalar   *xarray;

700:   PetscFunctionBegin;
701:   PetscCall(MatFactorFactorizeSchurComplement(F));
702:   PetscCall(MatFactorGetSchurComplement(F, &S, &schurstatus));
703:   PetscCall(MatMumpsCastMumpsScalarArray(mumps->sizeredrhs, mumps->id.precision, mumps->id.redrhs, mumps->redrhs));

705:   PetscCall(MatCreateSeqDense(PETSC_COMM_SELF, mumps->id.size_schur, mumps->id.nrhs, mumps->redrhs, &B));
706:   PetscCall(MatSetType(B, ((PetscObject)S)->type_name));
707: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA)
708:   PetscCall(MatBindToCPU(B, S->boundtocpu));
709: #endif
710:   switch (schurstatus) {
711:   case MAT_FACTOR_SCHUR_FACTORED:
712:     PetscCall(MatCreateSeqDense(PETSC_COMM_SELF, mumps->id.size_schur, mumps->id.nrhs, mumps->redrhs, &X));
713:     PetscCall(MatSetType(X, ((PetscObject)S)->type_name));
714: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA)
715:     PetscCall(MatBindToCPU(X, S->boundtocpu));
716: #endif
717:     if (!mumps->id.ICNTL(9)) { /* transpose solve */
718:       PetscCall(MatMatSolveTranspose(S, B, X));
719:     } else {
720:       PetscCall(MatMatSolve(S, B, X));
721:     }
722:     break;
723:   case MAT_FACTOR_SCHUR_INVERTED:
724:     sizesol = mumps->id.nrhs * mumps->id.size_schur;
725:     if (!mumps->schur_sol || sizesol > mumps->schur_sizesol) {
726:       PetscCall(PetscFree(mumps->schur_sol));
727:       PetscCall(PetscMalloc1(sizesol, &mumps->schur_sol));
728:       mumps->schur_sizesol = sizesol;
729:     }
730:     PetscCall(MatCreateSeqDense(PETSC_COMM_SELF, mumps->id.size_schur, mumps->id.nrhs, mumps->schur_sol, &X));
731:     PetscCall(MatSetType(X, ((PetscObject)S)->type_name));
732: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA)
733:     PetscCall(MatBindToCPU(X, S->boundtocpu));
734: #endif
735:     PetscCall(MatProductCreateWithMat(S, B, NULL, X));
736:     if (!mumps->id.ICNTL(9)) { /* transpose solve */
737:       PetscCall(MatProductSetType(X, MATPRODUCT_AtB));
738:     } else {
739:       PetscCall(MatProductSetType(X, MATPRODUCT_AB));
740:     }
741:     PetscCall(MatProductSetFromOptions(X));
742:     PetscCall(MatProductSymbolic(X));
743:     PetscCall(MatProductNumeric(X));

745:     PetscCall(MatCopy(X, B, SAME_NONZERO_PATTERN));
746:     break;
747:   default:
748:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
749:   }
750:   // MUST get the array from X (not B), though they share the same host array. We can only guarantee X has the correct data on device.
751:   PetscCall(MatDenseGetArrayRead(X, &xarray)); // xarray should be mumps->redrhs, but using MatDenseGetArrayRead is safer with GPUs.
752:   PetscCall(MatMumpsCastPetscScalarArray(mumps->sizeredrhs, xarray, mumps->id.precision, mumps->id.redrhs));
753:   PetscCall(MatDenseRestoreArrayRead(X, &xarray));
754:   PetscCall(MatFactorRestoreSchurComplement(F, &S, schurstatus));
755:   PetscCall(MatDestroy(&B));
756:   PetscCall(MatDestroy(&X));
757:   PetscFunctionReturn(PETSC_SUCCESS);
758: }

760: static PetscErrorCode MatMumpsHandleSchur_Private(Mat F, PetscBool expansion)
761: {
762:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

764:   PetscFunctionBegin;
765:   if (!mumps->id.ICNTL(19)) { /* do nothing when Schur complement has not been computed */
766:     PetscFunctionReturn(PETSC_SUCCESS);
767:   }
768:   if (!expansion) { /* prepare for the condensation step */
769:     PetscInt sizeredrhs = mumps->id.nrhs * mumps->id.size_schur;
770:     /* allocate MUMPS internal array to store reduced right-hand sides */
771:     if (!mumps->id.redrhs || sizeredrhs > mumps->sizeredrhs) {
772:       mumps->id.lredrhs = mumps->id.size_schur;
773:       mumps->sizeredrhs = mumps->id.nrhs * mumps->id.lredrhs;
774:       if (mumps->id.redrhs_len) PetscCall(PetscFree(mumps->id.redrhs));
775:       PetscCall(PetscFree(mumps->redrhs));
776:       PetscCall(PetscMalloc1(mumps->sizeredrhs, &mumps->redrhs));
777:       PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_FALSE, mumps->sizeredrhs, mumps->redrhs, mumps->id.precision, &mumps->id.redrhs_len, &mumps->id.redrhs));
778:     }
779:   } else {                                    /* prepare for the expansion step */
780:     PetscCall(MatMumpsSolveSchur_Private(F)); /* solve Schur complement, put solution in id.redrhs (this has to be done by the MUMPS user, so basically us) */
781:     mumps->id.ICNTL(26) = 2;                  /* expansion phase */
782:     PetscMUMPS_c(mumps);
783:     PetscCheck(mumps->id.INFOG(1) >= 0, PETSC_COMM_SELF, PETSC_ERR_LIB, "MUMPS error in solve: INFOG(1)=%d, INFO(2)=%d " MUMPS_MANUALS, mumps->id.INFOG(1), mumps->id.INFO(2));
784:     /* restore defaults */
785:     mumps->id.ICNTL(26) = -1;
786:     /* free MUMPS internal array for redrhs if we have solved for multiple rhs in order to save memory space */
787:     if (mumps->id.nrhs > 1) {
788:       if (mumps->redrhs != mumps->id.redrhs) PetscCall(PetscFree(mumps->id.redrhs));
789:       else mumps->id.redrhs = NULL;
790:       PetscCall(PetscFree(mumps->redrhs));
791:       mumps->id.redrhs_len = 0;
792:       mumps->id.lredrhs    = 0;
793:       mumps->sizeredrhs    = 0;
794:     }
795:   }
796:   PetscFunctionReturn(PETSC_SUCCESS);
797: }

799: /*
800:   MatConvertToTriples_A_B - convert PETSc matrix to triples: row[nz], col[nz], val[nz]

802:   input:
803:     A       - matrix in aij,baij or sbaij format
804:     shift   - 0: C style output triple; 1: Fortran style output triple.
805:     reuse   - MAT_INITIAL_MATRIX: spaces are allocated and values are set for the triple
806:               MAT_REUSE_MATRIX:   only the values in v array are updated
807:   output:
808:     nnz     - dim of r, c, and v (number of local nonzero entries of A)
809:     r, c, v - row and col index, matrix values (matrix triples)

811:   The returned values r, c, and sometimes v are obtained in a single PetscMalloc(). Then in MatDestroy_MUMPS() it is
812:   freed with PetscFree(mumps->irn);  This is not ideal code, the fact that v is ONLY sometimes part of mumps->irn means
813:   that the PetscMalloc() cannot easily be replaced with a PetscMalloc3().

815:  */

817: static PetscErrorCode MatConvertToTriples_seqaij_seqaij(Mat A, PetscInt shift, MatReuse reuse, Mat_MUMPS *mumps)
818: {
819:   const PetscScalar *av;
820:   const PetscInt    *ai, *aj, *ajj, M = A->rmap->n;
821:   PetscCount         nz, rnz, k;
822:   PetscMUMPSInt     *row, *col;
823:   Mat_SeqAIJ        *aa = (Mat_SeqAIJ *)A->data;

825:   PetscFunctionBegin;
826:   PetscCall(MatSeqAIJGetArrayRead(A, &av));
827:   if (reuse == MAT_INITIAL_MATRIX) {
828:     nz = aa->nz;
829:     ai = aa->i;
830:     aj = aa->j;
831:     PetscCall(PetscMalloc2(nz, &row, nz, &col));
832:     for (PetscCount i = k = 0; i < M; i++) {
833:       rnz = ai[i + 1] - ai[i];
834:       ajj = PetscSafePointerPlusOffset(aj, ai[i]);
835:       for (PetscCount j = 0; j < rnz; j++) {
836:         PetscCall(PetscMUMPSIntCast(i + shift, &row[k]));
837:         PetscCall(PetscMUMPSIntCast(ajj[j] + shift, &col[k]));
838:         k++;
839:       }
840:     }
841:     mumps->val = (PetscScalar *)av;
842:     mumps->irn = row;
843:     mumps->jcn = col;
844:     mumps->nnz = nz;
845:   } else if (mumps->nest_vals) PetscCall(PetscArraycpy(mumps->val, av, aa->nz)); /* MatConvertToTriples_nest_xaij() allocates mumps->val outside of MatConvertToTriples_seqaij_seqaij(), so one needs to copy the memory */
846:   else mumps->val = (PetscScalar *)av;                                           /* in the default case, mumps->val is never allocated, one just needs to update the mumps->val pointer */
847:   PetscCall(MatSeqAIJRestoreArrayRead(A, &av));
848:   PetscFunctionReturn(PETSC_SUCCESS);
849: }

851: static PetscErrorCode MatConvertToTriples_seqsell_seqaij(Mat A, PetscInt shift, MatReuse reuse, Mat_MUMPS *mumps)
852: {
853:   PetscCount     nz, i, j, k, r;
854:   Mat_SeqSELL   *a = (Mat_SeqSELL *)A->data;
855:   PetscMUMPSInt *row, *col;

857:   PetscFunctionBegin;
858:   nz = a->sliidx[a->totalslices];
859:   if (reuse == MAT_INITIAL_MATRIX) {
860:     PetscCall(PetscMalloc2(nz, &row, nz, &col));
861:     for (i = k = 0; i < a->totalslices; i++) {
862:       for (j = a->sliidx[i], r = 0; j < a->sliidx[i + 1]; j++, r = ((r + 1) & 0x07)) PetscCall(PetscMUMPSIntCast(8 * i + r + shift, &row[k++]));
863:     }
864:     for (i = 0; i < nz; i++) PetscCall(PetscMUMPSIntCast(a->colidx[i] + shift, &col[i]));
865:     mumps->irn = row;
866:     mumps->jcn = col;
867:     mumps->nnz = nz;
868:     mumps->val = a->val;
869:   } else if (mumps->nest_vals) PetscCall(PetscArraycpy(mumps->val, a->val, nz)); /* MatConvertToTriples_nest_xaij() allocates mumps->val outside of MatConvertToTriples_seqsell_seqaij(), so one needs to copy the memory */
870:   else mumps->val = a->val;                                                      /* in the default case, mumps->val is never allocated, one just needs to update the mumps->val pointer */
871:   PetscFunctionReturn(PETSC_SUCCESS);
872: }

874: static PetscErrorCode MatConvertToTriples_seqbaij_seqaij(Mat A, PetscInt shift, MatReuse reuse, Mat_MUMPS *mumps)
875: {
876:   Mat_SeqBAIJ    *aa = (Mat_SeqBAIJ *)A->data;
877:   const PetscInt *ai, *aj, *ajj, bs2 = aa->bs2;
878:   PetscCount      M, nz = bs2 * aa->nz, idx = 0, rnz, i, j, k, m;
879:   PetscInt        bs;
880:   PetscMUMPSInt  *row, *col;

882:   PetscFunctionBegin;
883:   if (reuse == MAT_INITIAL_MATRIX) {
884:     PetscCall(MatGetBlockSize(A, &bs));
885:     M  = A->rmap->N / bs;
886:     ai = aa->i;
887:     aj = aa->j;
888:     PetscCall(PetscMalloc2(nz, &row, nz, &col));
889:     for (i = 0; i < M; i++) {
890:       ajj = aj + ai[i];
891:       rnz = ai[i + 1] - ai[i];
892:       for (k = 0; k < rnz; k++) {
893:         for (j = 0; j < bs; j++) {
894:           for (m = 0; m < bs; m++) {
895:             PetscCall(PetscMUMPSIntCast(i * bs + m + shift, &row[idx]));
896:             PetscCall(PetscMUMPSIntCast(bs * ajj[k] + j + shift, &col[idx]));
897:             idx++;
898:           }
899:         }
900:       }
901:     }
902:     mumps->irn = row;
903:     mumps->jcn = col;
904:     mumps->nnz = nz;
905:     mumps->val = aa->a;
906:   } else if (mumps->nest_vals) PetscCall(PetscArraycpy(mumps->val, aa->a, nz)); /* MatConvertToTriples_nest_xaij() allocates mumps->val outside of MatConvertToTriples_seqbaij_seqaij(), so one needs to copy the memory */
907:   else mumps->val = aa->a;                                                      /* in the default case, mumps->val is never allocated, one just needs to update the mumps->val pointer */
908:   PetscFunctionReturn(PETSC_SUCCESS);
909: }

911: static PetscErrorCode MatConvertToTriples_seqsbaij_seqsbaij(Mat A, PetscInt shift, MatReuse reuse, Mat_MUMPS *mumps)
912: {
913:   const PetscInt *ai, *aj, *ajj;
914:   PetscInt        bs;
915:   PetscCount      nz, rnz, i, j, k, m;
916:   PetscMUMPSInt  *row, *col;
917:   PetscScalar    *val;
918:   Mat_SeqSBAIJ   *aa  = (Mat_SeqSBAIJ *)A->data;
919:   const PetscInt  bs2 = aa->bs2, mbs = aa->mbs;
920:   PetscBool       isset, hermitian;

922:   PetscFunctionBegin;
923:   if (PetscDefined(USE_COMPLEX)) {
924:     PetscCall(MatIsHermitianKnown(A, &isset, &hermitian));
925:     PetscCheck(!isset || !hermitian, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MUMPS does not support Hermitian symmetric matrices for Choleksy");
926:   }
927:   ai = aa->i;
928:   aj = aa->j;
929:   PetscCall(MatGetBlockSize(A, &bs));
930:   if (reuse == MAT_INITIAL_MATRIX) {
931:     const PetscCount alloc_size = aa->nz * bs2;

933:     PetscCall(PetscMalloc2(alloc_size, &row, alloc_size, &col));
934:     if (bs > 1) {
935:       PetscCall(PetscMalloc1(alloc_size, &mumps->val_alloc));
936:       mumps->val = mumps->val_alloc;
937:     } else {
938:       mumps->val = aa->a;
939:     }
940:     mumps->irn = row;
941:     mumps->jcn = col;
942:   } else {
943:     row = mumps->irn;
944:     col = mumps->jcn;
945:   }
946:   val = mumps->val;

948:   nz = 0;
949:   if (bs > 1) {
950:     for (i = 0; i < mbs; i++) {
951:       rnz = ai[i + 1] - ai[i];
952:       ajj = aj + ai[i];
953:       for (j = 0; j < rnz; j++) {
954:         for (k = 0; k < bs; k++) {
955:           for (m = 0; m < bs; m++) {
956:             if (ajj[j] > i || k >= m) {
957:               if (reuse == MAT_INITIAL_MATRIX) {
958:                 PetscCall(PetscMUMPSIntCast(i * bs + m + shift, &row[nz]));
959:                 PetscCall(PetscMUMPSIntCast(ajj[j] * bs + k + shift, &col[nz]));
960:               }
961:               val[nz++] = aa->a[(ai[i] + j) * bs2 + m + k * bs];
962:             }
963:           }
964:         }
965:       }
966:     }
967:   } else if (reuse == MAT_INITIAL_MATRIX) {
968:     for (i = 0; i < mbs; i++) {
969:       rnz = ai[i + 1] - ai[i];
970:       ajj = aj + ai[i];
971:       for (j = 0; j < rnz; j++) {
972:         PetscCall(PetscMUMPSIntCast(i + shift, &row[nz]));
973:         PetscCall(PetscMUMPSIntCast(ajj[j] + shift, &col[nz]));
974:         nz++;
975:       }
976:     }
977:     PetscCheck(nz == aa->nz, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Different numbers of nonzeros %" PetscCount_FMT " != %" PetscInt_FMT, nz, aa->nz);
978:   } else if (mumps->nest_vals)
979:     PetscCall(PetscArraycpy(mumps->val, aa->a, aa->nz)); /* bs == 1 and MAT_REUSE_MATRIX, MatConvertToTriples_nest_xaij() allocates mumps->val outside of MatConvertToTriples_seqsbaij_seqsbaij(), so one needs to copy the memory */
980:   else mumps->val = aa->a;                               /* in the default case, mumps->val is never allocated, one just needs to update the mumps->val pointer */
981:   if (reuse == MAT_INITIAL_MATRIX) mumps->nnz = nz;
982:   PetscFunctionReturn(PETSC_SUCCESS);
983: }

985: static PetscErrorCode MatConvertToTriples_seqaij_seqsbaij(Mat A, PetscInt shift, MatReuse reuse, Mat_MUMPS *mumps)
986: {
987:   const PetscInt    *ai, *aj, *ajj, *adiag, M = A->rmap->n;
988:   PetscCount         nz, rnz, i, j;
989:   const PetscScalar *av, *v1;
990:   PetscScalar       *val;
991:   PetscMUMPSInt     *row, *col;
992:   Mat_SeqAIJ        *aa = (Mat_SeqAIJ *)A->data;
993:   PetscBool          diagDense;
994:   PetscBool          hermitian, isset;

996:   PetscFunctionBegin;
997:   if (PetscDefined(USE_COMPLEX)) {
998:     PetscCall(MatIsHermitianKnown(A, &isset, &hermitian));
999:     PetscCheck(!isset || !hermitian, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MUMPS does not support Hermitian symmetric matrices for Choleksy");
1000:   }
1001:   PetscCall(MatSeqAIJGetArrayRead(A, &av));
1002:   ai = aa->i;
1003:   aj = aa->j;
1004:   PetscCall(MatGetDiagonalMarkers_SeqAIJ(A, &adiag, &diagDense));
1005:   if (reuse == MAT_INITIAL_MATRIX) {
1006:     /* count nz in the upper triangular part of A */
1007:     nz = 0;
1008:     if (!diagDense) {
1009:       for (i = 0; i < M; i++) {
1010:         if (PetscUnlikely(adiag[i] >= ai[i + 1])) {
1011:           for (j = ai[i]; j < ai[i + 1]; j++) {
1012:             if (aj[j] < i) continue;
1013:             nz++;
1014:           }
1015:         } else {
1016:           nz += ai[i + 1] - adiag[i];
1017:         }
1018:       }
1019:     } else {
1020:       for (i = 0; i < M; i++) nz += ai[i + 1] - adiag[i];
1021:     }
1022:     PetscCall(PetscMalloc2(nz, &row, nz, &col));
1023:     PetscCall(PetscMalloc1(nz, &val));
1024:     mumps->nnz = nz;
1025:     mumps->irn = row;
1026:     mumps->jcn = col;
1027:     mumps->val = mumps->val_alloc = val;

1029:     nz = 0;
1030:     if (!diagDense) {
1031:       for (i = 0; i < M; i++) {
1032:         if (PetscUnlikely(adiag[i] >= ai[i + 1])) {
1033:           for (j = ai[i]; j < ai[i + 1]; j++) {
1034:             if (aj[j] < i) continue;
1035:             PetscCall(PetscMUMPSIntCast(i + shift, &row[nz]));
1036:             PetscCall(PetscMUMPSIntCast(aj[j] + shift, &col[nz]));
1037:             val[nz] = av[j];
1038:             nz++;
1039:           }
1040:         } else {
1041:           rnz = ai[i + 1] - adiag[i];
1042:           ajj = aj + adiag[i];
1043:           v1  = av + adiag[i];
1044:           for (j = 0; j < rnz; j++) {
1045:             PetscCall(PetscMUMPSIntCast(i + shift, &row[nz]));
1046:             PetscCall(PetscMUMPSIntCast(ajj[j] + shift, &col[nz]));
1047:             val[nz++] = v1[j];
1048:           }
1049:         }
1050:       }
1051:     } else {
1052:       for (i = 0; i < M; i++) {
1053:         rnz = ai[i + 1] - adiag[i];
1054:         ajj = aj + adiag[i];
1055:         v1  = av + adiag[i];
1056:         for (j = 0; j < rnz; j++) {
1057:           PetscCall(PetscMUMPSIntCast(i + shift, &row[nz]));
1058:           PetscCall(PetscMUMPSIntCast(ajj[j] + shift, &col[nz]));
1059:           val[nz++] = v1[j];
1060:         }
1061:       }
1062:     }
1063:   } else {
1064:     nz  = 0;
1065:     val = mumps->val;
1066:     if (!diagDense) {
1067:       for (i = 0; i < M; i++) {
1068:         if (PetscUnlikely(adiag[i] >= ai[i + 1])) {
1069:           for (j = ai[i]; j < ai[i + 1]; j++) {
1070:             if (aj[j] < i) continue;
1071:             val[nz++] = av[j];
1072:           }
1073:         } else {
1074:           rnz = ai[i + 1] - adiag[i];
1075:           v1  = av + adiag[i];
1076:           for (j = 0; j < rnz; j++) val[nz++] = v1[j];
1077:         }
1078:       }
1079:     } else {
1080:       for (i = 0; i < M; i++) {
1081:         rnz = ai[i + 1] - adiag[i];
1082:         v1  = av + adiag[i];
1083:         for (j = 0; j < rnz; j++) val[nz++] = v1[j];
1084:       }
1085:     }
1086:   }
1087:   PetscCall(MatSeqAIJRestoreArrayRead(A, &av));
1088:   PetscFunctionReturn(PETSC_SUCCESS);
1089: }

1091: static PetscErrorCode MatConvertToTriples_mpisbaij_mpisbaij(Mat A, PetscInt shift, MatReuse reuse, Mat_MUMPS *mumps)
1092: {
1093:   const PetscInt    *ai, *aj, *bi, *bj, *garray, *ajj, *bjj;
1094:   PetscInt           bs;
1095:   PetscCount         rstart, nz, i, j, k, m, jj, irow, countA, countB;
1096:   PetscMUMPSInt     *row, *col;
1097:   const PetscScalar *av, *bv, *v1, *v2;
1098:   PetscScalar       *val;
1099:   Mat_MPISBAIJ      *mat = (Mat_MPISBAIJ *)A->data;
1100:   Mat_SeqSBAIJ      *aa  = (Mat_SeqSBAIJ *)mat->A->data;
1101:   Mat_SeqBAIJ       *bb  = (Mat_SeqBAIJ *)mat->B->data;
1102:   const PetscInt     bs2 = aa->bs2, mbs = aa->mbs;
1103:   PetscBool          hermitian, isset;

1105:   PetscFunctionBegin;
1106:   if (PetscDefined(USE_COMPLEX)) {
1107:     PetscCall(MatIsHermitianKnown(A, &isset, &hermitian));
1108:     PetscCheck(!isset || !hermitian, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MUMPS does not support Hermitian symmetric matrices for Choleksy");
1109:   }
1110:   PetscCall(MatGetBlockSize(A, &bs));
1111:   rstart = A->rmap->rstart;
1112:   ai     = aa->i;
1113:   aj     = aa->j;
1114:   bi     = bb->i;
1115:   bj     = bb->j;
1116:   av     = aa->a;
1117:   bv     = bb->a;

1119:   garray = mat->garray;

1121:   if (reuse == MAT_INITIAL_MATRIX) {
1122:     nz = (aa->nz + bb->nz) * bs2; /* just a conservative estimate */
1123:     PetscCall(PetscMalloc2(nz, &row, nz, &col));
1124:     PetscCall(PetscMalloc1(nz, &val));
1125:     /* can not decide the exact mumps->nnz now because of the SBAIJ */
1126:     mumps->irn = row;
1127:     mumps->jcn = col;
1128:     mumps->val = mumps->val_alloc = val;
1129:   } else {
1130:     val = mumps->val;
1131:   }

1133:   jj   = 0;
1134:   irow = rstart;
1135:   for (i = 0; i < mbs; i++) {
1136:     ajj    = PetscSafePointerPlusOffset(aj, ai[i]); /* ptr to the beginning of this row */
1137:     countA = ai[i + 1] - ai[i];
1138:     countB = bi[i + 1] - bi[i];
1139:     bjj    = PetscSafePointerPlusOffset(bj, bi[i]);
1140:     v1     = PetscSafePointerPlusOffset(av, ai[i] * bs2);
1141:     v2     = PetscSafePointerPlusOffset(bv, bi[i] * bs2);

1143:     if (bs > 1) {
1144:       /* A-part */
1145:       for (j = 0; j < countA; j++) {
1146:         for (k = 0; k < bs; k++) {
1147:           for (m = 0; m < bs; m++) {
1148:             if (rstart + ajj[j] * bs > irow || k >= m) {
1149:               if (reuse == MAT_INITIAL_MATRIX) {
1150:                 PetscCall(PetscMUMPSIntCast(irow + m + shift, &row[jj]));
1151:                 PetscCall(PetscMUMPSIntCast(rstart + ajj[j] * bs + k + shift, &col[jj]));
1152:               }
1153:               val[jj++] = v1[j * bs2 + m + k * bs];
1154:             }
1155:           }
1156:         }
1157:       }

1159:       /* B-part */
1160:       for (j = 0; j < countB; j++) {
1161:         for (k = 0; k < bs; k++) {
1162:           for (m = 0; m < bs; m++) {
1163:             if (reuse == MAT_INITIAL_MATRIX) {
1164:               PetscCall(PetscMUMPSIntCast(irow + m + shift, &row[jj]));
1165:               PetscCall(PetscMUMPSIntCast(garray[bjj[j]] * bs + k + shift, &col[jj]));
1166:             }
1167:             val[jj++] = v2[j * bs2 + m + k * bs];
1168:           }
1169:         }
1170:       }
1171:     } else {
1172:       /* A-part */
1173:       for (j = 0; j < countA; j++) {
1174:         if (reuse == MAT_INITIAL_MATRIX) {
1175:           PetscCall(PetscMUMPSIntCast(irow + shift, &row[jj]));
1176:           PetscCall(PetscMUMPSIntCast(rstart + ajj[j] + shift, &col[jj]));
1177:         }
1178:         val[jj++] = v1[j];
1179:       }

1181:       /* B-part */
1182:       for (j = 0; j < countB; j++) {
1183:         if (reuse == MAT_INITIAL_MATRIX) {
1184:           PetscCall(PetscMUMPSIntCast(irow + shift, &row[jj]));
1185:           PetscCall(PetscMUMPSIntCast(garray[bjj[j]] + shift, &col[jj]));
1186:         }
1187:         val[jj++] = v2[j];
1188:       }
1189:     }
1190:     irow += bs;
1191:   }
1192:   if (reuse == MAT_INITIAL_MATRIX) mumps->nnz = jj;
1193:   PetscFunctionReturn(PETSC_SUCCESS);
1194: }

1196: static PetscErrorCode MatConvertToTriples_mpiaij_mpiaij(Mat A, PetscInt shift, MatReuse reuse, Mat_MUMPS *mumps)
1197: {
1198:   const PetscInt    *ai, *aj, *bi, *bj, *garray, m = A->rmap->n, *ajj, *bjj;
1199:   PetscCount         rstart, cstart, nz, i, j, jj, irow, countA, countB;
1200:   PetscMUMPSInt     *row, *col;
1201:   const PetscScalar *av, *bv, *v1, *v2;
1202:   PetscScalar       *val;
1203:   Mat                Ad, Ao;
1204:   Mat_SeqAIJ        *aa;
1205:   Mat_SeqAIJ        *bb;

1207:   PetscFunctionBegin;
1208:   PetscCall(MatMPIAIJGetSeqAIJ(A, &Ad, &Ao, &garray));
1209:   PetscCall(MatSeqAIJGetArrayRead(Ad, &av));
1210:   PetscCall(MatSeqAIJGetArrayRead(Ao, &bv));

1212:   aa = (Mat_SeqAIJ *)Ad->data;
1213:   bb = (Mat_SeqAIJ *)Ao->data;
1214:   ai = aa->i;
1215:   aj = aa->j;
1216:   bi = bb->i;
1217:   bj = bb->j;

1219:   rstart = A->rmap->rstart;
1220:   cstart = A->cmap->rstart;

1222:   if (reuse == MAT_INITIAL_MATRIX) {
1223:     nz = (PetscCount)aa->nz + bb->nz; /* make sure the sum won't overflow PetscInt */
1224:     PetscCall(PetscMalloc2(nz, &row, nz, &col));
1225:     PetscCall(PetscMalloc1(nz, &val));
1226:     mumps->nnz = nz;
1227:     mumps->irn = row;
1228:     mumps->jcn = col;
1229:     mumps->val = mumps->val_alloc = val;
1230:   } else {
1231:     val = mumps->val;
1232:   }

1234:   jj   = 0;
1235:   irow = rstart;
1236:   for (i = 0; i < m; i++) {
1237:     ajj    = PetscSafePointerPlusOffset(aj, ai[i]); /* ptr to the beginning of this row */
1238:     countA = ai[i + 1] - ai[i];
1239:     countB = bi[i + 1] - bi[i];
1240:     bjj    = PetscSafePointerPlusOffset(bj, bi[i]);
1241:     v1     = PetscSafePointerPlusOffset(av, ai[i]);
1242:     v2     = PetscSafePointerPlusOffset(bv, bi[i]);

1244:     /* A-part */
1245:     for (j = 0; j < countA; j++) {
1246:       if (reuse == MAT_INITIAL_MATRIX) {
1247:         PetscCall(PetscMUMPSIntCast(irow + shift, &row[jj]));
1248:         PetscCall(PetscMUMPSIntCast(cstart + ajj[j] + shift, &col[jj]));
1249:       }
1250:       val[jj++] = v1[j];
1251:     }

1253:     /* B-part */
1254:     for (j = 0; j < countB; j++) {
1255:       if (reuse == MAT_INITIAL_MATRIX) {
1256:         PetscCall(PetscMUMPSIntCast(irow + shift, &row[jj]));
1257:         PetscCall(PetscMUMPSIntCast(garray[bjj[j]] + shift, &col[jj]));
1258:       }
1259:       val[jj++] = v2[j];
1260:     }
1261:     irow++;
1262:   }
1263:   PetscCall(MatSeqAIJRestoreArrayRead(Ad, &av));
1264:   PetscCall(MatSeqAIJRestoreArrayRead(Ao, &bv));
1265:   PetscFunctionReturn(PETSC_SUCCESS);
1266: }

1268: static PetscErrorCode MatConvertToTriples_mpibaij_mpiaij(Mat A, PetscInt shift, MatReuse reuse, Mat_MUMPS *mumps)
1269: {
1270:   Mat_MPIBAIJ       *mat = (Mat_MPIBAIJ *)A->data;
1271:   Mat_SeqBAIJ       *aa  = (Mat_SeqBAIJ *)mat->A->data;
1272:   Mat_SeqBAIJ       *bb  = (Mat_SeqBAIJ *)mat->B->data;
1273:   const PetscInt    *ai = aa->i, *bi = bb->i, *aj = aa->j, *bj = bb->j, *ajj, *bjj;
1274:   const PetscInt    *garray = mat->garray, mbs = mat->mbs, rstart = A->rmap->rstart, cstart = A->cmap->rstart;
1275:   const PetscInt     bs2 = mat->bs2;
1276:   PetscInt           bs;
1277:   PetscCount         nz, i, j, k, n, jj, irow, countA, countB, idx;
1278:   PetscMUMPSInt     *row, *col;
1279:   const PetscScalar *av = aa->a, *bv = bb->a, *v1, *v2;
1280:   PetscScalar       *val;

1282:   PetscFunctionBegin;
1283:   PetscCall(MatGetBlockSize(A, &bs));
1284:   if (reuse == MAT_INITIAL_MATRIX) {
1285:     nz = bs2 * (aa->nz + bb->nz);
1286:     PetscCall(PetscMalloc2(nz, &row, nz, &col));
1287:     PetscCall(PetscMalloc1(nz, &val));
1288:     mumps->nnz = nz;
1289:     mumps->irn = row;
1290:     mumps->jcn = col;
1291:     mumps->val = mumps->val_alloc = val;
1292:   } else {
1293:     val = mumps->val;
1294:   }

1296:   jj   = 0;
1297:   irow = rstart;
1298:   for (i = 0; i < mbs; i++) {
1299:     countA = ai[i + 1] - ai[i];
1300:     countB = bi[i + 1] - bi[i];
1301:     ajj    = aj + ai[i];
1302:     bjj    = bj + bi[i];
1303:     v1     = av + bs2 * ai[i];
1304:     v2     = bv + bs2 * bi[i];

1306:     idx = 0;
1307:     /* A-part */
1308:     for (k = 0; k < countA; k++) {
1309:       for (j = 0; j < bs; j++) {
1310:         for (n = 0; n < bs; n++) {
1311:           if (reuse == MAT_INITIAL_MATRIX) {
1312:             PetscCall(PetscMUMPSIntCast(irow + n + shift, &row[jj]));
1313:             PetscCall(PetscMUMPSIntCast(cstart + bs * ajj[k] + j + shift, &col[jj]));
1314:           }
1315:           val[jj++] = v1[idx++];
1316:         }
1317:       }
1318:     }

1320:     idx = 0;
1321:     /* B-part */
1322:     for (k = 0; k < countB; k++) {
1323:       for (j = 0; j < bs; j++) {
1324:         for (n = 0; n < bs; n++) {
1325:           if (reuse == MAT_INITIAL_MATRIX) {
1326:             PetscCall(PetscMUMPSIntCast(irow + n + shift, &row[jj]));
1327:             PetscCall(PetscMUMPSIntCast(bs * garray[bjj[k]] + j + shift, &col[jj]));
1328:           }
1329:           val[jj++] = v2[idx++];
1330:         }
1331:       }
1332:     }
1333:     irow += bs;
1334:   }
1335:   PetscFunctionReturn(PETSC_SUCCESS);
1336: }

1338: static PetscErrorCode MatConvertToTriples_mpiaij_mpisbaij(Mat A, PetscInt shift, MatReuse reuse, Mat_MUMPS *mumps)
1339: {
1340:   const PetscInt    *ai, *aj, *adiag, *bi, *bj, *garray, m = A->rmap->n, *ajj, *bjj;
1341:   PetscCount         rstart, nz, nza, nzb, i, j, jj, irow, countA, countB;
1342:   PetscMUMPSInt     *row, *col;
1343:   const PetscScalar *av, *bv, *v1, *v2;
1344:   PetscScalar       *val;
1345:   Mat                Ad, Ao;
1346:   Mat_SeqAIJ        *aa;
1347:   Mat_SeqAIJ        *bb;
1348:   PetscBool          hermitian, isset;

1350:   PetscFunctionBegin;
1351:   if (PetscDefined(USE_COMPLEX)) {
1352:     PetscCall(MatIsHermitianKnown(A, &isset, &hermitian));
1353:     PetscCheck(!isset || !hermitian, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MUMPS does not support Hermitian symmetric matrices for Choleksy");
1354:   }
1355:   PetscCall(MatMPIAIJGetSeqAIJ(A, &Ad, &Ao, &garray));
1356:   PetscCall(MatSeqAIJGetArrayRead(Ad, &av));
1357:   PetscCall(MatSeqAIJGetArrayRead(Ao, &bv));

1359:   aa = (Mat_SeqAIJ *)Ad->data;
1360:   bb = (Mat_SeqAIJ *)Ao->data;
1361:   ai = aa->i;
1362:   aj = aa->j;
1363:   bi = bb->i;
1364:   bj = bb->j;
1365:   PetscCall(MatGetDiagonalMarkers_SeqAIJ(Ad, &adiag, NULL));
1366:   rstart = A->rmap->rstart;

1368:   if (reuse == MAT_INITIAL_MATRIX) {
1369:     nza = 0; /* num of upper triangular entries in mat->A, including diagonals */
1370:     nzb = 0; /* num of upper triangular entries in mat->B */
1371:     for (i = 0; i < m; i++) {
1372:       nza += (ai[i + 1] - adiag[i]);
1373:       countB = bi[i + 1] - bi[i];
1374:       bjj    = PetscSafePointerPlusOffset(bj, bi[i]);
1375:       for (j = 0; j < countB; j++) {
1376:         if (garray[bjj[j]] > rstart) nzb++;
1377:       }
1378:     }

1380:     nz = nza + nzb; /* total nz of upper triangular part of mat */
1381:     PetscCall(PetscMalloc2(nz, &row, nz, &col));
1382:     PetscCall(PetscMalloc1(nz, &val));
1383:     mumps->nnz = nz;
1384:     mumps->irn = row;
1385:     mumps->jcn = col;
1386:     mumps->val = mumps->val_alloc = val;
1387:   } else {
1388:     val = mumps->val;
1389:   }

1391:   jj   = 0;
1392:   irow = rstart;
1393:   for (i = 0; i < m; i++) {
1394:     ajj    = PetscSafePointerPlusOffset(aj, adiag[i]); /* ptr to the beginning of the diagonal of this row */
1395:     v1     = PetscSafePointerPlusOffset(av, adiag[i]);
1396:     countA = ai[i + 1] - adiag[i];
1397:     countB = bi[i + 1] - bi[i];
1398:     bjj    = PetscSafePointerPlusOffset(bj, bi[i]);
1399:     v2     = PetscSafePointerPlusOffset(bv, bi[i]);

1401:     /* A-part */
1402:     for (j = 0; j < countA; j++) {
1403:       if (reuse == MAT_INITIAL_MATRIX) {
1404:         PetscCall(PetscMUMPSIntCast(irow + shift, &row[jj]));
1405:         PetscCall(PetscMUMPSIntCast(rstart + ajj[j] + shift, &col[jj]));
1406:       }
1407:       val[jj++] = v1[j];
1408:     }

1410:     /* B-part */
1411:     for (j = 0; j < countB; j++) {
1412:       if (garray[bjj[j]] > rstart) {
1413:         if (reuse == MAT_INITIAL_MATRIX) {
1414:           PetscCall(PetscMUMPSIntCast(irow + shift, &row[jj]));
1415:           PetscCall(PetscMUMPSIntCast(garray[bjj[j]] + shift, &col[jj]));
1416:         }
1417:         val[jj++] = v2[j];
1418:       }
1419:     }
1420:     irow++;
1421:   }
1422:   PetscCall(MatSeqAIJRestoreArrayRead(Ad, &av));
1423:   PetscCall(MatSeqAIJRestoreArrayRead(Ao, &bv));
1424:   PetscFunctionReturn(PETSC_SUCCESS);
1425: }

1427: static PetscErrorCode MatConvertToTriples_diagonal_xaij(Mat A, PETSC_UNUSED PetscInt shift, MatReuse reuse, Mat_MUMPS *mumps)
1428: {
1429:   const PetscScalar *av;
1430:   const PetscInt     M = A->rmap->n;
1431:   PetscCount         i;
1432:   PetscMUMPSInt     *row, *col;
1433:   Vec                v;

1435:   PetscFunctionBegin;
1436:   PetscCall(MatDiagonalGetDiagonal(A, &v));
1437:   PetscCall(VecGetArrayRead(v, &av));
1438:   if (reuse == MAT_INITIAL_MATRIX) {
1439:     PetscCall(PetscMalloc2(M, &row, M, &col));
1440:     for (i = 0; i < M; i++) {
1441:       PetscCall(PetscMUMPSIntCast(i + A->rmap->rstart, &row[i]));
1442:       col[i] = row[i];
1443:     }
1444:     mumps->val = (PetscScalar *)av;
1445:     mumps->irn = row;
1446:     mumps->jcn = col;
1447:     mumps->nnz = M;
1448:   } else if (mumps->nest_vals) PetscCall(PetscArraycpy(mumps->val, av, M)); /* MatConvertToTriples_nest_xaij() allocates mumps->val outside of MatConvertToTriples_diagonal_xaij(), so one needs to copy the memory */
1449:   else mumps->val = (PetscScalar *)av;                                      /* in the default case, mumps->val is never allocated, one just needs to update the mumps->val pointer */
1450:   PetscCall(VecRestoreArrayRead(v, &av));
1451:   PetscFunctionReturn(PETSC_SUCCESS);
1452: }

1454: static PetscErrorCode MatConvertToTriples_dense_xaij(Mat A, PETSC_UNUSED PetscInt shift, MatReuse reuse, Mat_MUMPS *mumps)
1455: {
1456:   PetscScalar   *v;
1457:   const PetscInt m = A->rmap->n, N = A->cmap->N;
1458:   PetscInt       lda;
1459:   PetscCount     i, j;
1460:   PetscMUMPSInt *row, *col;

1462:   PetscFunctionBegin;
1463:   PetscCall(MatDenseGetArray(A, &v));
1464:   PetscCall(MatDenseGetLDA(A, &lda));
1465:   if (reuse == MAT_INITIAL_MATRIX) {
1466:     PetscCall(PetscMalloc2(m * N, &row, m * N, &col));
1467:     for (i = 0; i < m; i++) {
1468:       col[i] = 0;
1469:       PetscCall(PetscMUMPSIntCast(i + A->rmap->rstart, &row[i]));
1470:     }
1471:     for (j = 1; j < N; j++) {
1472:       for (i = 0; i < m; i++) PetscCall(PetscMUMPSIntCast(j, col + i + m * j));
1473:       PetscCall(PetscArraycpy(row + m * j, row + m * (j - 1), m));
1474:     }
1475:     if (lda == m) mumps->val = v;
1476:     else {
1477:       PetscCall(PetscMalloc1(m * N, &mumps->val));
1478:       mumps->val_alloc = mumps->val;
1479:       for (j = 0; j < N; j++) PetscCall(PetscArraycpy(mumps->val + m * j, v + lda * j, m));
1480:     }
1481:     mumps->irn = row;
1482:     mumps->jcn = col;
1483:     mumps->nnz = m * N;
1484:   } else {
1485:     if (lda == m && !mumps->nest_vals) mumps->val = v;
1486:     else {
1487:       for (j = 0; j < N; j++) PetscCall(PetscArraycpy(mumps->val + m * j, v + lda * j, m));
1488:     }
1489:   }
1490:   PetscCall(MatDenseRestoreArray(A, &v));
1491:   PetscFunctionReturn(PETSC_SUCCESS);
1492: }

1494: // If the input Mat (sub) is either MATTRANSPOSEVIRTUAL or MATHERMITIANTRANSPOSEVIRTUAL, this function gets the parent Mat until it is not a
1495: // MATTRANSPOSEVIRTUAL or MATHERMITIANTRANSPOSEVIRTUAL itself and returns the appropriate shift, scaling, and whether the parent Mat should be conjugated
1496: // and its rows and columns permuted
1497: // TODO FIXME: this should not be in this file and should instead be refactored where the same logic applies, e.g., MatAXPY_Dense_Nest()
1498: static PetscErrorCode MatGetTranspose_TransposeVirtual(Mat *sub, PetscBool *conjugate, PetscScalar *vshift, PetscScalar *vscale, PetscBool *swap)
1499: {
1500:   Mat         A;
1501:   PetscScalar s[2];
1502:   PetscBool   isTrans, isHTrans, compare;

1504:   PetscFunctionBegin;
1505:   do {
1506:     PetscCall(PetscObjectTypeCompare((PetscObject)*sub, MATTRANSPOSEVIRTUAL, &isTrans));
1507:     if (isTrans) {
1508:       PetscCall(MatTransposeGetMat(*sub, &A));
1509:       isHTrans = PETSC_FALSE;
1510:     } else {
1511:       PetscCall(PetscObjectTypeCompare((PetscObject)*sub, MATHERMITIANTRANSPOSEVIRTUAL, &isHTrans));
1512:       if (isHTrans) PetscCall(MatHermitianTransposeGetMat(*sub, &A));
1513:     }
1514:     compare = (PetscBool)(isTrans || isHTrans);
1515:     if (compare) {
1516:       if (vshift && vscale) {
1517:         PetscCall(MatShellGetScalingShifts(*sub, s, s + 1, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Mat *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED));
1518:         if (!*conjugate) {
1519:           *vshift += s[0] * *vscale;
1520:           *vscale *= s[1];
1521:         } else {
1522:           *vshift += PetscConj(s[0]) * *vscale;
1523:           *vscale *= PetscConj(s[1]);
1524:         }
1525:       }
1526:       if (swap) *swap = (PetscBool)!*swap;
1527:       if (isHTrans && conjugate) *conjugate = (PetscBool)!*conjugate;
1528:       *sub = A;
1529:     }
1530:   } while (compare);
1531:   PetscFunctionReturn(PETSC_SUCCESS);
1532: }

1534: static PetscErrorCode MatConvertToTriples_nest_xaij(Mat A, PetscInt shift, MatReuse reuse, Mat_MUMPS *mumps)
1535: {
1536:   Mat     **mats;
1537:   PetscInt  nr, nc;
1538:   PetscBool chol = mumps->sym ? PETSC_TRUE : PETSC_FALSE;

1540:   PetscFunctionBegin;
1541:   PetscCall(MatNestGetSubMats(A, &nr, &nc, &mats));
1542:   if (reuse == MAT_INITIAL_MATRIX) {
1543:     PetscMUMPSInt *irns, *jcns;
1544:     PetscScalar   *vals;
1545:     PetscCount     totnnz, cumnnz, maxnnz;
1546:     PetscInt      *pjcns_w, Mbs = 0;
1547:     IS            *rows, *cols;
1548:     PetscInt     **rows_idx, **cols_idx;

1550:     cumnnz = 0;
1551:     maxnnz = 0;
1552:     PetscCall(PetscMalloc2(nr * nc + 1, &mumps->nest_vals_start, nr * nc, &mumps->nest_convert_to_triples));
1553:     for (PetscInt r = 0; r < nr; r++) {
1554:       for (PetscInt c = 0; c < nc; c++) {
1555:         Mat sub = mats[r][c];

1557:         mumps->nest_convert_to_triples[r * nc + c] = NULL;
1558:         if (chol && c < r) continue; /* skip lower-triangular block for Cholesky */
1559:         if (sub) {
1560:           PetscErrorCode (*convert_to_triples)(Mat, PetscInt, MatReuse, Mat_MUMPS *) = NULL;
1561:           PetscBool isSeqAIJ, isMPIAIJ, isSeqBAIJ, isMPIBAIJ, isSeqSBAIJ, isMPISBAIJ, isDiag, isDense;
1562:           MatInfo   info;

1564:           PetscCall(MatGetTranspose_TransposeVirtual(&sub, NULL, NULL, NULL, NULL));
1565:           PetscCall(PetscObjectBaseTypeCompare((PetscObject)sub, MATSEQAIJ, &isSeqAIJ));
1566:           PetscCall(PetscObjectBaseTypeCompare((PetscObject)sub, MATMPIAIJ, &isMPIAIJ));
1567:           PetscCall(PetscObjectBaseTypeCompare((PetscObject)sub, MATSEQBAIJ, &isSeqBAIJ));
1568:           PetscCall(PetscObjectBaseTypeCompare((PetscObject)sub, MATMPIBAIJ, &isMPIBAIJ));
1569:           PetscCall(PetscObjectBaseTypeCompare((PetscObject)sub, MATSEQSBAIJ, &isSeqSBAIJ));
1570:           PetscCall(PetscObjectBaseTypeCompare((PetscObject)sub, MATMPISBAIJ, &isMPISBAIJ));
1571:           PetscCall(PetscObjectTypeCompare((PetscObject)sub, MATDIAGONAL, &isDiag));
1572:           PetscCall(PetscObjectTypeCompareAny((PetscObject)sub, &isDense, MATSEQDENSE, MATMPIDENSE, NULL));

1574:           if (chol) {
1575:             if (r == c) {
1576:               if (isSeqAIJ) convert_to_triples = MatConvertToTriples_seqaij_seqsbaij;
1577:               else if (isMPIAIJ) convert_to_triples = MatConvertToTriples_mpiaij_mpisbaij;
1578:               else if (isSeqSBAIJ) convert_to_triples = MatConvertToTriples_seqsbaij_seqsbaij;
1579:               else if (isMPISBAIJ) convert_to_triples = MatConvertToTriples_mpisbaij_mpisbaij;
1580:               else if (isDiag) convert_to_triples = MatConvertToTriples_diagonal_xaij;
1581:               else if (isDense) convert_to_triples = MatConvertToTriples_dense_xaij;
1582:             } else {
1583:               if (isSeqAIJ) convert_to_triples = MatConvertToTriples_seqaij_seqaij;
1584:               else if (isMPIAIJ) convert_to_triples = MatConvertToTriples_mpiaij_mpiaij;
1585:               else if (isSeqBAIJ) convert_to_triples = MatConvertToTriples_seqbaij_seqaij;
1586:               else if (isMPIBAIJ) convert_to_triples = MatConvertToTriples_mpibaij_mpiaij;
1587:               else if (isDiag) convert_to_triples = MatConvertToTriples_diagonal_xaij;
1588:               else if (isDense) convert_to_triples = MatConvertToTriples_dense_xaij;
1589:             }
1590:           } else {
1591:             if (isSeqAIJ) convert_to_triples = MatConvertToTriples_seqaij_seqaij;
1592:             else if (isMPIAIJ) convert_to_triples = MatConvertToTriples_mpiaij_mpiaij;
1593:             else if (isSeqBAIJ) convert_to_triples = MatConvertToTriples_seqbaij_seqaij;
1594:             else if (isMPIBAIJ) convert_to_triples = MatConvertToTriples_mpibaij_mpiaij;
1595:             else if (isDiag) convert_to_triples = MatConvertToTriples_diagonal_xaij;
1596:             else if (isDense) convert_to_triples = MatConvertToTriples_dense_xaij;
1597:           }
1598:           PetscCheck(convert_to_triples, PetscObjectComm((PetscObject)sub), PETSC_ERR_SUP, "Not for block of type %s", ((PetscObject)sub)->type_name);
1599:           mumps->nest_convert_to_triples[r * nc + c] = convert_to_triples;
1600:           PetscCall(MatGetInfo(sub, MAT_LOCAL, &info));
1601:           cumnnz += (PetscCount)info.nz_used; /* can be overestimated for Cholesky */
1602:           maxnnz = PetscMax(maxnnz, info.nz_used);
1603:         }
1604:       }
1605:     }

1607:     /* Allocate total COO */
1608:     totnnz = cumnnz;
1609:     PetscCall(PetscMalloc2(totnnz, &irns, totnnz, &jcns));
1610:     PetscCall(PetscMalloc1(totnnz, &vals));

1612:     /* Handle rows and column maps
1613:        We directly map rows and use an SF for the columns */
1614:     PetscCall(PetscMalloc4(nr, &rows, nc, &cols, nr, &rows_idx, nc, &cols_idx));
1615:     PetscCall(MatNestGetISs(A, rows, cols));
1616:     for (PetscInt r = 0; r < nr; r++) PetscCall(ISGetIndices(rows[r], (const PetscInt **)&rows_idx[r]));
1617:     for (PetscInt c = 0; c < nc; c++) PetscCall(ISGetIndices(cols[c], (const PetscInt **)&cols_idx[c]));
1618:     if (PetscDefined(USE_64BIT_INDICES)) PetscCall(PetscMalloc1(maxnnz, &pjcns_w));
1619:     else (void)maxnnz;

1621:     cumnnz = 0;
1622:     for (PetscInt r = 0; r < nr; r++) {
1623:       for (PetscInt c = 0; c < nc; c++) {
1624:         Mat             sub    = mats[r][c];
1625:         const PetscInt *ridx   = rows_idx[r];
1626:         const PetscInt *cidx   = cols_idx[c];
1627:         PetscScalar     vscale = 1.0, vshift = 0.0;
1628:         PetscInt        rst, size, bs;
1629:         PetscSF         csf;
1630:         PetscBool       conjugate = PETSC_FALSE, swap = PETSC_FALSE;
1631:         PetscLayout     cmap;
1632:         PetscInt        innz;

1634:         mumps->nest_vals_start[r * nc + c] = cumnnz;
1635:         if (c == r) {
1636:           PetscCall(ISGetSize(rows[r], &size));
1637:           if (!mumps->nest_convert_to_triples[r * nc + c]) {
1638:             for (PetscInt c = 0; c < nc && !sub; ++c) sub = mats[r][c]; // diagonal Mat is NULL, so start over from the beginning of the current row
1639:           }
1640:           PetscCall(MatGetBlockSize(sub, &bs));
1641:           Mbs += size / bs;
1642:         }
1643:         if (!mumps->nest_convert_to_triples[r * nc + c]) continue;

1645:         /* Extract inner blocks if needed */
1646:         PetscCall(MatGetTranspose_TransposeVirtual(&sub, &conjugate, &vshift, &vscale, &swap));
1647:         PetscCheck(vshift == 0.0, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Nonzero shift in parent MatShell");

1649:         /* Get column layout to map off-process columns */
1650:         PetscCall(MatGetLayouts(sub, NULL, &cmap));

1652:         /* Get row start to map on-process rows */
1653:         PetscCall(MatGetOwnershipRange(sub, &rst, NULL));

1655:         /* Directly use the mumps datastructure and use C ordering for now */
1656:         PetscCall((*mumps->nest_convert_to_triples[r * nc + c])(sub, 0, MAT_INITIAL_MATRIX, mumps));

1658:         /* Swap the role of rows and columns indices for transposed blocks
1659:            since we need values with global final ordering */
1660:         if (swap) {
1661:           cidx = rows_idx[r];
1662:           ridx = cols_idx[c];
1663:         }

1665:         /* Communicate column indices
1666:            This could have been done with a single SF but it would have complicated the code a lot.
1667:            But since we do it only once, we pay the price of setting up an SF for each block */
1668:         if (PetscDefined(USE_64BIT_INDICES)) {
1669:           for (PetscInt k = 0; k < mumps->nnz; k++) pjcns_w[k] = mumps->jcn[k];
1670:         } else pjcns_w = (PetscInt *)mumps->jcn; /* This cast is needed only to silence warnings for 64bit integers builds */
1671:         PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)A), &csf));
1672:         PetscCall(PetscIntCast(mumps->nnz, &innz));
1673:         PetscCall(PetscSFSetGraphLayout(csf, cmap, innz, NULL, PETSC_OWN_POINTER, pjcns_w));
1674:         PetscCall(PetscSFBcastBegin(csf, MPIU_INT, cidx, pjcns_w, MPI_REPLACE));
1675:         PetscCall(PetscSFBcastEnd(csf, MPIU_INT, cidx, pjcns_w, MPI_REPLACE));
1676:         PetscCall(PetscSFDestroy(&csf));

1678:         /* Import indices: use direct map for rows and mapped indices for columns */
1679:         if (swap) {
1680:           for (PetscInt k = 0; k < mumps->nnz; k++) {
1681:             PetscCall(PetscMUMPSIntCast(ridx[mumps->irn[k] - rst] + shift, &jcns[cumnnz + k]));
1682:             PetscCall(PetscMUMPSIntCast(pjcns_w[k] + shift, &irns[cumnnz + k]));
1683:           }
1684:         } else {
1685:           for (PetscInt k = 0; k < mumps->nnz; k++) {
1686:             PetscCall(PetscMUMPSIntCast(ridx[mumps->irn[k] - rst] + shift, &irns[cumnnz + k]));
1687:             PetscCall(PetscMUMPSIntCast(pjcns_w[k] + shift, &jcns[cumnnz + k]));
1688:           }
1689:         }

1691:         /* Import values to full COO */
1692:         if (conjugate) { /* conjugate the entries */
1693:           PetscScalar *v = vals + cumnnz;
1694:           for (PetscInt k = 0; k < mumps->nnz; k++) v[k] = vscale * PetscConj(mumps->val[k]);
1695:         } else if (vscale != 1.0) {
1696:           PetscScalar *v = vals + cumnnz;
1697:           for (PetscInt k = 0; k < mumps->nnz; k++) v[k] = vscale * mumps->val[k];
1698:         } else PetscCall(PetscArraycpy(vals + cumnnz, mumps->val, mumps->nnz));

1700:         /* Shift new starting point and sanity check */
1701:         cumnnz += mumps->nnz;
1702:         PetscCheck(cumnnz <= totnnz, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Unexpected number of nonzeros %" PetscCount_FMT " != %" PetscCount_FMT, cumnnz, totnnz);

1704:         /* Free scratch memory */
1705:         PetscCall(PetscFree2(mumps->irn, mumps->jcn));
1706:         PetscCall(PetscFree(mumps->val_alloc));
1707:         mumps->val = NULL;
1708:         mumps->nnz = 0;
1709:       }
1710:     }
1711:     if (mumps->id.ICNTL(15) == 1) {
1712:       if (Mbs != A->rmap->N) {
1713:         PetscMPIInt rank, size;

1715:         PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank));
1716:         PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
1717:         if (rank == 0) {
1718:           PetscInt shift = 0;

1720:           PetscCall(PetscMUMPSIntCast(Mbs, &mumps->id.nblk));
1721:           PetscCall(PetscFree(mumps->id.blkptr));
1722:           PetscCall(PetscMalloc1(Mbs + 1, &mumps->id.blkptr));
1723:           mumps->id.blkptr[0] = 1;
1724:           for (PetscInt i = 0; i < size; ++i) {
1725:             for (PetscInt r = 0; r < nr; r++) {
1726:               Mat             sub = mats[r][r];
1727:               const PetscInt *ranges;
1728:               PetscInt        bs;

1730:               for (PetscInt c = 0; c < nc && !sub; ++c) sub = mats[r][c]; // diagonal Mat is NULL, so start over from the beginning of the current row
1731:               PetscCall(MatGetOwnershipRanges(sub, &ranges));
1732:               PetscCall(MatGetBlockSize(sub, &bs));
1733:               for (PetscInt j = 0, start = mumps->id.blkptr[shift] + bs; j < ranges[i + 1] - ranges[i]; j += bs) PetscCall(PetscMUMPSIntCast(start + j, mumps->id.blkptr + shift + j / bs + 1));
1734:               shift += (ranges[i + 1] - ranges[i]) / bs;
1735:             }
1736:           }
1737:         }
1738:       } else mumps->id.ICNTL(15) = 0;
1739:     }
1740:     if (PetscDefined(USE_64BIT_INDICES)) PetscCall(PetscFree(pjcns_w));
1741:     for (PetscInt r = 0; r < nr; r++) PetscCall(ISRestoreIndices(rows[r], (const PetscInt **)&rows_idx[r]));
1742:     for (PetscInt c = 0; c < nc; c++) PetscCall(ISRestoreIndices(cols[c], (const PetscInt **)&cols_idx[c]));
1743:     PetscCall(PetscFree4(rows, cols, rows_idx, cols_idx));
1744:     if (!chol) PetscCheck(cumnnz == totnnz, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Different number of nonzeros %" PetscCount_FMT " != %" PetscCount_FMT, cumnnz, totnnz);
1745:     mumps->nest_vals_start[nr * nc] = cumnnz;

1747:     /* Set pointers for final MUMPS data structure */
1748:     mumps->nest_vals = vals;
1749:     mumps->val_alloc = NULL; /* do not use val_alloc since it may be reallocated with the OMP callpath */
1750:     mumps->val       = vals;
1751:     mumps->irn       = irns;
1752:     mumps->jcn       = jcns;
1753:     mumps->nnz       = cumnnz;
1754:   } else {
1755:     PetscScalar *oval = mumps->nest_vals;
1756:     for (PetscInt r = 0; r < nr; r++) {
1757:       for (PetscInt c = 0; c < nc; c++) {
1758:         PetscBool   conjugate = PETSC_FALSE;
1759:         Mat         sub       = mats[r][c];
1760:         PetscScalar vscale = 1.0, vshift = 0.0;
1761:         PetscInt    midx = r * nc + c;

1763:         if (!mumps->nest_convert_to_triples[midx]) continue;
1764:         PetscCall(MatGetTranspose_TransposeVirtual(&sub, &conjugate, &vshift, &vscale, NULL));
1765:         PetscCheck(vshift == 0.0, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Nonzero shift in parent MatShell");
1766:         mumps->val = oval + mumps->nest_vals_start[midx];
1767:         PetscCall((*mumps->nest_convert_to_triples[midx])(sub, shift, MAT_REUSE_MATRIX, mumps));
1768:         if (conjugate) {
1769:           PetscCount nnz = mumps->nest_vals_start[midx + 1] - mumps->nest_vals_start[midx];
1770:           for (PetscCount k = 0; k < nnz; k++) mumps->val[k] = vscale * PetscConj(mumps->val[k]);
1771:         } else if (vscale != 1.0) {
1772:           PetscCount nnz = mumps->nest_vals_start[midx + 1] - mumps->nest_vals_start[midx];
1773:           for (PetscCount k = 0; k < nnz; k++) mumps->val[k] *= vscale;
1774:         }
1775:       }
1776:     }
1777:     mumps->val = oval;
1778:   }
1779:   PetscFunctionReturn(PETSC_SUCCESS);
1780: }

1782: static PetscErrorCode MatDestroy_MUMPS(Mat F)
1783: {
1784:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

1786:   PetscFunctionBegin;
1787:   PetscCall(MatMumpsResetSchur_Private(F));
1788:   PetscCall(PetscFree(mumps->id.isol_loc));
1789:   PetscCall(VecScatterDestroy(&mumps->scat_rhs));
1790:   for (size_t i = 0; i < PETSC_STATIC_ARRAY_LENGTH(mumps->scat_sol); ++i) PetscCall(VecScatterDestroy(&mumps->scat_sol[i]));
1791:   PetscCall(VecDestroy(&mumps->b_seq));
1792:   PetscCall(VecDestroy(&mumps->x_seq));
1793:   PetscCall(PetscFree(mumps->id.perm_in));
1794:   PetscCall(PetscFree(mumps->id.blkvar));
1795:   PetscCall(PetscFree(mumps->id.blkptr));
1796:   PetscCall(PetscFree2(mumps->irn, mumps->jcn));
1797:   PetscCall(PetscFree(mumps->val_alloc));
1798:   PetscCall(PetscFree(mumps->info));
1799:   PetscCall(PetscFree(mumps->ICNTL_pre));
1800:   PetscCall(PetscFree(mumps->CNTL_pre));
1801:   if (mumps->id.job != JOB_NULL) { /* cannot call PetscMUMPS_c() if JOB_INIT has never been called for this instance */
1802:     mumps->id.job = JOB_END;
1803:     PetscMUMPS_c(mumps);
1804:     PetscCheck(mumps->id.INFOG(1) >= 0, PETSC_COMM_SELF, PETSC_ERR_LIB, "MUMPS error in termination: INFOG(1)=%d, INFO(2)=%d " MUMPS_MANUALS, mumps->id.INFOG(1), mumps->id.INFO(2));
1805:     if (mumps->mumps_comm != MPI_COMM_NULL) {
1806:       if (PetscDefined(HAVE_OPENMP_SUPPORT) && mumps->use_petsc_omp_support) PetscCallMPI(MPI_Comm_free(&mumps->mumps_comm));
1807:       else PetscCall(PetscCommRestoreComm(PetscObjectComm((PetscObject)F), &mumps->mumps_comm));
1808:     }
1809:   }
1810:   PetscCall(MatMumpsFreeInternalID(&mumps->id));
1811: #if PetscDefined(HAVE_OPENMP_SUPPORT)
1812:   if (mumps->use_petsc_omp_support) {
1813:     PetscCall(PetscOmpCtrlDestroy(&mumps->omp_ctrl));
1814:     PetscCall(PetscFree2(mumps->rhs_loc, mumps->rhs_recvbuf));
1815:     PetscCall(PetscFree3(mumps->rhs_nrow, mumps->rhs_recvcounts, mumps->rhs_disps));
1816:   }
1817: #endif
1818:   PetscCall(PetscFree(mumps->ia_alloc));
1819:   PetscCall(PetscFree(mumps->ja_alloc));
1820:   PetscCall(PetscFree(mumps->recvcount));
1821:   PetscCall(PetscFree(mumps->reqs));
1822:   PetscCall(PetscFree(mumps->irhs_loc));
1823:   PetscCall(PetscFree2(mumps->nest_vals_start, mumps->nest_convert_to_triples));
1824:   PetscCall(PetscFree(mumps->nest_vals));
1825:   PetscCall(PetscFree(F->data));

1827:   /* clear composed functions */
1828:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatFactorGetSolverType_C", NULL));
1829:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatFactorSetSchurIS_C", NULL));
1830:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatFactorCreateSchurComplement_C", NULL));
1831:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatMumpsSetIcntl_C", NULL));
1832:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatMumpsGetIcntl_C", NULL));
1833:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatMumpsSetCntl_C", NULL));
1834:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatMumpsGetCntl_C", NULL));
1835:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatMumpsGetInfo_C", NULL));
1836:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatMumpsGetInfog_C", NULL));
1837:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatMumpsGetRinfo_C", NULL));
1838:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatMumpsGetRinfog_C", NULL));
1839:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatMumpsGetNullPivots_C", NULL));
1840:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatMumpsGetInverse_C", NULL));
1841:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatMumpsGetInverseTranspose_C", NULL));
1842:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatMumpsSetBlk_C", NULL));
1843:   PetscFunctionReturn(PETSC_SUCCESS);
1844: }

1846: /* Set up the distributed RHS info for MUMPS. <nrhs> is the number of RHS. <array> points to start of RHS on the local processor. */
1847: static PetscErrorCode MatMumpsSetUpDistRHSInfo(Mat A, PetscInt nrhs, const PetscScalar *array)
1848: {
1849:   Mat_MUMPS        *mumps   = (Mat_MUMPS *)A->data;
1850:   const PetscMPIInt ompsize = mumps->omp_comm_size;
1851:   PetscInt          i, m, M, rstart;

1853:   PetscFunctionBegin;
1854:   PetscCall(MatGetSize(A, &M, NULL));
1855:   PetscCall(MatGetLocalSize(A, &m, NULL));
1856:   PetscCheck(M <= PETSC_MUMPS_INT_MAX, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "PetscInt too long for PetscMUMPSInt");
1857:   if (ompsize == 1) {
1858:     if (!mumps->irhs_loc) {
1859:       mumps->nloc_rhs = (PetscMUMPSInt)m;
1860:       PetscCall(PetscMalloc1(m, &mumps->irhs_loc));
1861:       PetscCall(MatGetOwnershipRange(A, &rstart, NULL));
1862:       for (i = 0; i < m; i++) PetscCall(PetscMUMPSIntCast(rstart + i + 1, &mumps->irhs_loc[i])); /* use 1-based indices */
1863:     }
1864:     PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, m * nrhs, array, mumps->id.precision, &mumps->id.rhs_loc_len, &mumps->id.rhs_loc));
1865:   } else {
1866: #if PetscDefined(HAVE_OPENMP_SUPPORT)
1867:     const PetscInt *ranges;
1868:     PetscMPIInt     j, k, sendcount, *petsc_ranks, *omp_ranks;
1869:     MPI_Group       petsc_group, omp_group;
1870:     PetscScalar    *recvbuf = NULL;

1872:     if (mumps->is_omp_master) {
1873:       /* Lazily initialize the omp stuff for distributed rhs */
1874:       if (!mumps->irhs_loc) {
1875:         PetscCall(PetscMalloc2(ompsize, &omp_ranks, ompsize, &petsc_ranks));
1876:         PetscCall(PetscMalloc3(ompsize, &mumps->rhs_nrow, ompsize, &mumps->rhs_recvcounts, ompsize, &mumps->rhs_disps));
1877:         PetscCallMPI(MPI_Comm_group(mumps->petsc_comm, &petsc_group));
1878:         PetscCallMPI(MPI_Comm_group(mumps->omp_comm, &omp_group));
1879:         for (j = 0; j < ompsize; j++) omp_ranks[j] = j;
1880:         PetscCallMPI(MPI_Group_translate_ranks(omp_group, ompsize, omp_ranks, petsc_group, petsc_ranks));

1882:         /* Populate mumps->irhs_loc[], rhs_nrow[] */
1883:         mumps->nloc_rhs = 0;
1884:         PetscCall(MatGetOwnershipRanges(A, &ranges));
1885:         for (j = 0; j < ompsize; j++) {
1886:           mumps->rhs_nrow[j] = ranges[petsc_ranks[j] + 1] - ranges[petsc_ranks[j]];
1887:           mumps->nloc_rhs += mumps->rhs_nrow[j];
1888:         }
1889:         PetscCall(PetscMalloc1(mumps->nloc_rhs, &mumps->irhs_loc));
1890:         for (j = k = 0; j < ompsize; j++) {
1891:           for (i = ranges[petsc_ranks[j]]; i < ranges[petsc_ranks[j] + 1]; i++, k++) PetscCall(PetscMUMPSIntCast(i + 1, &mumps->irhs_loc[k])); /* uses 1-based indices */
1892:         }

1894:         PetscCall(PetscFree2(omp_ranks, petsc_ranks));
1895:         PetscCallMPI(MPI_Group_free(&petsc_group));
1896:         PetscCallMPI(MPI_Group_free(&omp_group));
1897:       }

1899:       /* Realloc buffers when current nrhs is bigger than what we have met */
1900:       if (nrhs > mumps->max_nrhs) {
1901:         PetscCall(PetscFree2(mumps->rhs_loc, mumps->rhs_recvbuf));
1902:         PetscCall(PetscMalloc2(mumps->nloc_rhs * nrhs, &mumps->rhs_loc, mumps->nloc_rhs * nrhs, &mumps->rhs_recvbuf));
1903:         mumps->max_nrhs = nrhs;
1904:       }

1906:       /* Setup recvcounts[], disps[], recvbuf on omp rank 0 for the upcoming MPI_Gatherv */
1907:       for (j = 0; j < ompsize; j++) PetscCall(PetscMPIIntCast(mumps->rhs_nrow[j] * nrhs, &mumps->rhs_recvcounts[j]));
1908:       mumps->rhs_disps[0] = 0;
1909:       for (j = 1; j < ompsize; j++) {
1910:         mumps->rhs_disps[j] = mumps->rhs_disps[j - 1] + mumps->rhs_recvcounts[j - 1];
1911:         PetscCheck(mumps->rhs_disps[j] >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "PetscMPIInt overflow!");
1912:       }
1913:       recvbuf = (nrhs == 1) ? mumps->rhs_loc : mumps->rhs_recvbuf; /* Directly use rhs_loc[] as recvbuf. Single rhs is common in Ax=b */
1914:     }

1916:     PetscCall(PetscMPIIntCast(m * nrhs, &sendcount));
1917:     PetscCallMPI(MPI_Gatherv(array, sendcount, MPIU_SCALAR, recvbuf, mumps->rhs_recvcounts, mumps->rhs_disps, MPIU_SCALAR, 0, mumps->omp_comm));

1919:     if (mumps->is_omp_master) {
1920:       if (nrhs > 1) { /* Copy & re-arrange data from rhs_recvbuf[] to mumps->rhs_loc[] only when there are multiple rhs */
1921:         PetscScalar *dst, *dstbase = mumps->rhs_loc;
1922:         for (j = 0; j < ompsize; j++) {
1923:           const PetscScalar *src = mumps->rhs_recvbuf + mumps->rhs_disps[j];
1924:           dst                    = dstbase;
1925:           for (i = 0; i < nrhs; i++) {
1926:             PetscCall(PetscArraycpy(dst, src, mumps->rhs_nrow[j]));
1927:             src += mumps->rhs_nrow[j];
1928:             dst += mumps->nloc_rhs;
1929:           }
1930:           dstbase += mumps->rhs_nrow[j];
1931:         }
1932:       }
1933:       PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, mumps->nloc_rhs * nrhs, mumps->rhs_loc, mumps->id.precision, &mumps->id.rhs_loc_len, &mumps->id.rhs_loc));
1934:     }
1935: #endif /* PETSC_HAVE_OPENMP_SUPPORT */
1936:   }
1937:   mumps->id.nrhs     = (PetscMUMPSInt)nrhs;
1938:   mumps->id.nloc_rhs = (PetscMUMPSInt)mumps->nloc_rhs;
1939:   mumps->id.lrhs_loc = mumps->nloc_rhs;
1940:   mumps->id.irhs_loc = mumps->irhs_loc;
1941:   PetscFunctionReturn(PETSC_SUCCESS);
1942: }

1944: static PetscErrorCode MatMumpsSetUpSolutionVecScatter_Private(Mat A, VecScatter *scatter)
1945: {
1946:   Mat_MUMPS  *mumps     = (Mat_MUMPS *)A->data;
1947:   PetscBool   transpose = (PetscBool)(mumps->sym == 0 && mumps->id.ICNTL(9) != 1);
1948:   VecScatter *cache     = &mumps->scat_sol[transpose];

1950:   PetscFunctionBegin;
1951:   /* isol_loc may differ between normal and transpose solves for unsymmetric factors */
1952:   if (*cache == NULL) {
1953:     Vec         x;
1954:     IS          is;
1955:     PetscLayout layout;
1956:     PetscInt   *indices;

1958:     PetscCall(MatGetLayouts(A, transpose == PETSC_TRUE ? &layout : NULL, transpose == PETSC_TRUE ? NULL : &layout));
1959:     PetscCall(PetscMalloc1(mumps->id.lsol_loc, &indices));
1960:     for (PetscInt i = 0; i < mumps->id.lsol_loc; ++i) indices[i] = mumps->id.isol_loc[i] - 1;
1961:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, mumps->id.lsol_loc, indices, PETSC_OWN_POINTER, &is));
1962:     PetscCall(VecCreateMPIWithLayoutAndArray_Private(layout, NULL, &x));
1963:     PetscCall(VecScatterCreate(mumps->x_seq, NULL, x, is, cache));
1964:     PetscCall(VecDestroy(&x));
1965:     PetscCall(ISDestroy(&is));
1966:   }
1967:   *scatter = *cache;
1968:   PetscFunctionReturn(PETSC_SUCCESS);
1969: }

1971: static PetscErrorCode MatSolve_MUMPS(Mat A, Vec b, Vec x)
1972: {
1973:   Mat_MUMPS         *mumps  = (Mat_MUMPS *)A->data;
1974:   const PetscScalar *barray = NULL;
1975:   PetscScalar       *array;
1976:   PetscBool          second_solve = PETSC_FALSE;
1977:   static PetscBool   cite1 = PETSC_FALSE, cite2 = PETSC_FALSE;

1979:   PetscFunctionBegin;
1980:   PetscCall(PetscCitationsRegister("@article{MUMPS01,\n  author = {P.~R. Amestoy and I.~S. Duff and J.-Y. L'Excellent and J. Koster},\n  title = {A fully asynchronous multifrontal solver using distributed dynamic scheduling},\n  journal = {SIAM "
1981:                                    "Journal on Matrix Analysis and Applications},\n  volume = {23},\n  number = {1},\n  pages = {15--41},\n  year = {2001}\n}\n",
1982:                                    &cite1));
1983:   PetscCall(PetscCitationsRegister("@article{MUMPS02,\n  author = {P.~R. Amestoy and A. Guermouche and J.-Y. L'Excellent and S. Pralet},\n  title = {Hybrid scheduling for the parallel solution of linear systems},\n  journal = {Parallel "
1984:                                    "Computing},\n  volume = {32},\n  number = {2},\n  pages = {136--156},\n  year = {2006}\n}\n",
1985:                                    &cite2));

1987:   PetscCall(VecFlag(x, A->factorerrortype));
1988:   if (A->factorerrortype) {
1989:     PetscCall(PetscInfo(A, "MatSolve() is called with singular matrix factor, INFOG(1)=%d, INFO(2)=%d\n", mumps->id.INFOG(1), mumps->id.INFO(2)));
1990:     PetscFunctionReturn(PETSC_SUCCESS);
1991:   }

1993:   mumps->id.nrhs = 1;
1994:   if (mumps->petsc_size > 1) {
1995:     if (mumps->ICNTL20 == 10) {
1996:       mumps->id.ICNTL(20) = 10; /* dense distributed RHS, need to set rhs_loc[], irhs_loc[] */
1997:       PetscCall(VecGetArrayRead(b, &barray));
1998:       PetscCall(MatMumpsSetUpDistRHSInfo(A, 1, barray));
1999:     } else {
2000:       mumps->id.ICNTL(20) = 0; /* dense centralized RHS; Scatter b into a sequential b_seq vector*/
2001:       PetscCall(VecScatterBegin(mumps->scat_rhs, b, mumps->b_seq, INSERT_VALUES, SCATTER_FORWARD));
2002:       PetscCall(VecScatterEnd(mumps->scat_rhs, b, mumps->b_seq, INSERT_VALUES, SCATTER_FORWARD));
2003:       if (!mumps->myid) {
2004:         PetscCall(VecGetArray(mumps->b_seq, &array));
2005:         PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, mumps->b_seq->map->n, array, mumps->id.precision, &mumps->id.rhs_len, &mumps->id.rhs));
2006:       }
2007:     }
2008:   } else { /* petsc_size == 1, use MUMPS's dense centralized RHS feature, so that we don't need to bother with isol_loc[] to get the solution */
2009:     mumps->id.ICNTL(20) = 0;
2010:     PetscCall(VecCopy(b, x));
2011:     PetscCall(VecGetArray(x, &array));
2012:     PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, x->map->n, array, mumps->id.precision, &mumps->id.rhs_len, &mumps->id.rhs));
2013:   }

2015:   /*
2016:      handle condensation step of Schur complement (if any)
2017:      We set by default ICNTL(26) == -1 when Schur indices have been provided by the user.
2018:      According to MUMPS (5.0.0) manual, any value should be harmful during the factorization phase
2019:      Unless the user provides a valid value for ICNTL(26), MatSolve and MatMatSolve routines solve the full system.
2020:      This requires an extra call to PetscMUMPS_c and the computation of the factors for S
2021:   */
2022:   if (mumps->id.size_schur > 0) {
2023:     PetscCheck(mumps->petsc_size <= 1, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Parallel Schur complements not yet supported from PETSc");
2024:     if (mumps->id.ICNTL(26) < 0 || mumps->id.ICNTL(26) > 2) {
2025:       second_solve = PETSC_TRUE;
2026:       PetscCall(MatMumpsHandleSchur_Private(A, PETSC_FALSE)); // allocate id.redrhs
2027:       mumps->id.ICNTL(26) = 1;                                /* condensation phase */
2028:     } else if (mumps->id.ICNTL(26) == 1) PetscCall(MatMumpsHandleSchur_Private(A, PETSC_FALSE));
2029:   }

2031:   mumps->id.job = JOB_SOLVE;
2032:   PetscMUMPS_c(mumps); // reduced solve, put solution in id.redrhs
2033:   PetscCheck(mumps->id.INFOG(1) >= 0, PETSC_COMM_SELF, PETSC_ERR_LIB, "MUMPS error in solve: INFOG(1)=%d, INFO(2)=%d " MUMPS_MANUALS, mumps->id.INFOG(1), mumps->id.INFO(2));

2035:   /* handle expansion step of Schur complement (if any) */
2036:   if (second_solve) PetscCall(MatMumpsHandleSchur_Private(A, PETSC_TRUE));
2037:   else if (mumps->id.ICNTL(26) == 1) { // condense the right hand side
2038:     PetscCall(MatMumpsSolveSchur_Private(A));
2039:     for (PetscInt i = 0; i < mumps->id.size_schur; ++i) array[mumps->id.listvar_schur[i] - 1] = ID_FIELD_GET(mumps->id, redrhs, i);
2040:   }

2042:   if (mumps->petsc_size > 1) { /* convert mumps distributed solution to PETSc mpi x */
2043:     PetscScalar *xarray;
2044:     VecScatter   scatter;

2046:     PetscCall(MatMumpsSetUpSolutionVecScatter_Private(A, &scatter));
2047:     PetscCall(VecGetArray(mumps->x_seq, &xarray));
2048:     PetscCall(MatMumpsCastMumpsScalarArray(mumps->id.lsol_loc, mumps->id.precision, mumps->id.sol_loc, xarray));
2049:     PetscCall(VecRestoreArray(mumps->x_seq, &xarray));
2050:     PetscCall(VecScatterBegin(scatter, mumps->x_seq, x, INSERT_VALUES, SCATTER_FORWARD));
2051:     PetscCall(VecScatterEnd(scatter, mumps->x_seq, x, INSERT_VALUES, SCATTER_FORWARD));

2053:     if (mumps->ICNTL20 == 10) { // distributed RHS
2054:       PetscCall(VecRestoreArrayRead(b, &barray));
2055:     } else if (!mumps->myid) { // centralized RHS
2056:       PetscCall(VecRestoreArray(mumps->b_seq, &array));
2057:     }
2058:   } else {
2059:     // id.rhs has the solution in mumps precision
2060:     PetscCall(MatMumpsCastMumpsScalarArray(x->map->n, mumps->id.precision, mumps->id.rhs, array));
2061:     PetscCall(VecRestoreArray(x, &array));
2062:   }

2064:   /* Structural estimate per RHS: 2z-p for LU, 4z-3p for LDL^T.
2065:      INFO(28) counts factor entries z and INFO(23) counts eliminated pivots p. */
2066:   if (!mumps->use_petsc_omp_support || mumps->is_omp_master)
2067:     PetscCall(PetscLogFlops(mumps->id.nrhs * PetscMax(0.0, (mumps->sym ? 4.0 : 2.0) * (mumps->id.INFO(28) >= 0 ? mumps->id.INFO(28) : -1.0e6 * mumps->id.INFO(28)) - (mumps->sym ? 3.0 : 1.0) * mumps->id.INFO(23))));
2068:   PetscFunctionReturn(PETSC_SUCCESS);
2069: }

2071: static PetscErrorCode MatSolveTranspose_MUMPS(Mat A, Vec b, Vec x)
2072: {
2073:   Mat_MUMPS          *mumps = (Mat_MUMPS *)A->data;
2074:   const PetscMUMPSInt value = mumps->id.ICNTL(9);

2076:   PetscFunctionBegin;
2077:   mumps->id.ICNTL(9) = 0;
2078:   PetscCall(MatSolve_MUMPS(A, b, x));
2079:   mumps->id.ICNTL(9) = value;
2080:   PetscFunctionReturn(PETSC_SUCCESS);
2081: }

2083: static PetscErrorCode MatMatSolve_MUMPS(Mat A, Mat B, Mat X)
2084: {
2085:   Mat                Bt = NULL, solution;
2086:   PetscBool          denseX, denseB, flg, flgT;
2087:   Mat_MUMPS         *mumps = (Mat_MUMPS *)A->data;
2088:   PetscInt           i, nrhs, M, nrhsM, ldb = 0, ldx;
2089:   PetscScalar       *array, *rhsalloc = NULL, *solalloc = NULL;
2090:   const PetscScalar *barray, *rhsarray;
2091:   PetscInt           lsol_loc, nlsol_loc;
2092:   PetscMUMPSInt     *isol_loc, *isol_loc_save;
2093:   PetscScalar       *sol_loc;
2094:   void              *sol_loc_save;
2095:   PetscCount         sol_loc_len_save;
2096:   IS                 is_to, is_from;
2097:   PetscInt           k, proc, j, m;
2098:   const PetscInt    *rstart;
2099:   Vec                v_mpi = NULL;
2100:   Vec                b_seq;
2101:   VecScatter         scat_rhs, scat_sol;
2102:   PetscScalar       *aa;
2103:   PetscInt           spnr, *ia, *ja;
2104:   Mat_MPIAIJ        *b = NULL;

2106:   PetscFunctionBegin;
2107:   PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)X, &denseX, MATSEQDENSE, MATMPIDENSE, NULL));
2108:   PetscCheck(denseX, PetscObjectComm((PetscObject)X), PETSC_ERR_ARG_WRONG, "Matrix X must be MATDENSE matrix");

2110:   PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)B, &denseB, MATSEQDENSE, MATMPIDENSE, NULL));

2112:   if (denseB) {
2113:     PetscCheck(B->rmap->n == X->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Matrix B and X must have same row distribution");
2114:     mumps->id.ICNTL(20) = 0; /* dense RHS */
2115:   } else {                   /* sparse B */
2116:     PetscCheck(X != B, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_IDN, "X and B must be different matrices");
2117:     PetscCall(PetscObjectTypeCompare((PetscObject)B, MATTRANSPOSEVIRTUAL, &flgT));
2118:     PetscCheck(flgT, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONG, "Matrix B must be MATTRANSPOSEVIRTUAL matrix");
2119:     PetscCall(MatShellGetScalingShifts(B, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Mat *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED));
2120:     /* input B is transpose of actual RHS matrix,
2121:      because mumps requires sparse compressed COLUMN storage! See MatMatTransposeSolve_MUMPS() */
2122:     PetscCall(MatTransposeGetMat(B, &Bt));
2123:     mumps->id.ICNTL(20) = 1; /* sparse RHS */
2124:   }

2126:   PetscCall(MatDenseGetLDA(X, &ldx));
2127:   if (denseB) PetscCall(MatDenseGetLDA(B, &ldb));
2128:   PetscCall(MatGetSize(B, &M, &nrhs));
2129:   PetscCall(PetscIntMultError(nrhs, M, &nrhsM));
2130:   mumps->id.nrhs = (PetscMUMPSInt)nrhs;
2131:   mumps->id.lrhs = (PetscMUMPSInt)M;

2133:   if (mumps->petsc_size == 1) { // handle this easy case specially and return early
2134:     PetscScalar *aa, *xarray;
2135:     PetscInt     spnr, ldrhs;
2136:     PetscInt    *ia, *ja;
2137:     PetscBool    second_solve = PETSC_FALSE;

2139:     if (B == X) PetscCall(MatDenseGetArray(X, &array));
2140:     else PetscCall(MatDenseGetArrayWrite(X, &array));
2141:     // use the output stride directly unless precision conversion needs contiguous storage
2142:     if (ldx != M && mumps->id.precision != PETSC_SCALAR_PRECISION) PetscCall(PetscMalloc1(nrhsM, &solalloc));
2143:     xarray = solalloc ? solalloc : array;
2144:     ldrhs  = solalloc ? M : ldx;
2145:     PetscCall(PetscMUMPSIntCast(ldrhs, &mumps->id.lrhs));
2146:     if (denseB) {
2147:       /* copy B to X */
2148:       PetscCall(MatDenseGetArrayRead(B, &barray));
2149:       if (ldb == M && ldrhs == M) PetscCall(PetscArraycpy(xarray, barray, nrhsM));
2150:       else {
2151:         for (j = 0; j < nrhs; ++j) PetscCall(PetscArraycpy(xarray + (size_t)j * ldrhs, barray + (size_t)j * ldb, M));
2152:       }
2153:       PetscCall(MatDenseRestoreArrayRead(B, &barray));
2154:     } else { /* sparse B */
2155:       PetscCall(MatSeqAIJGetArray(Bt, &aa));
2156:       PetscCall(MatGetRowIJ(Bt, 1, PETSC_FALSE, PETSC_FALSE, &spnr, (const PetscInt **)&ia, (const PetscInt **)&ja, &flg));
2157:       PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot get IJ structure");
2158:       PetscCall(PetscMUMPSIntCSRCast(mumps, spnr, ia, ja, &mumps->id.irhs_ptr, &mumps->id.irhs_sparse, &mumps->id.nz_rhs));
2159:       PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, mumps->id.nz_rhs, aa, mumps->id.precision, &mumps->id.rhs_sparse_len, &mumps->id.rhs_sparse));
2160:     }
2161:     PetscCall(MatMumpsMakeMumpsScalarArray(denseB, nrhsM, xarray, mumps->id.precision, &mumps->id.rhs_len, &mumps->id.rhs));

2163:     /* handle condensation step of Schur complement (if any) */
2164:     if (mumps->id.size_schur > 0) {
2165:       if (mumps->id.ICNTL(26) < 0 || mumps->id.ICNTL(26) > 2) {
2166:         second_solve = PETSC_TRUE;
2167:         PetscCall(MatMumpsHandleSchur_Private(A, PETSC_FALSE)); // allocate id.redrhs
2168:         mumps->id.ICNTL(26) = 1;                                /* condensation phase, i.e, to solve id.redrhs */
2169:       } else if (mumps->id.ICNTL(26) == 1) PetscCall(MatMumpsHandleSchur_Private(A, PETSC_FALSE));
2170:     }

2172:     mumps->id.job = JOB_SOLVE;
2173:     PetscMUMPS_c(mumps);
2174:     PetscCheck(mumps->id.INFOG(1) >= 0, PETSC_COMM_SELF, PETSC_ERR_LIB, "MUMPS error in solve: INFOG(1)=%d, INFO(2)=%d " MUMPS_MANUALS, mumps->id.INFOG(1), mumps->id.INFO(2));

2176:     /* handle expansion step of Schur complement (if any) */
2177:     if (second_solve) PetscCall(MatMumpsHandleSchur_Private(A, PETSC_TRUE));
2178:     else if (mumps->id.ICNTL(26) == 1) { // condense the right hand side
2179:       PetscCall(MatMumpsSolveSchur_Private(A));
2180:       for (j = 0; j < nrhs; ++j)
2181:         for (i = 0; i < mumps->id.size_schur; ++i) xarray[mumps->id.listvar_schur[i] - 1 + (size_t)j * ldrhs] = ID_FIELD_GET(mumps->id, redrhs, i + j * mumps->id.lredrhs);
2182:     }

2184:     if (!denseB) { /* sparse B, restore ia, ja */
2185:       PetscCall(MatSeqAIJRestoreArray(Bt, &aa));
2186:       PetscCall(MatRestoreRowIJ(Bt, 1, PETSC_FALSE, PETSC_FALSE, &spnr, (const PetscInt **)&ia, (const PetscInt **)&ja, &flg));
2187:       PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot restore IJ structure");
2188:     }

2190:     // no matter dense B or sparse B, solution is in id.rhs; convert it to array of X.
2191:     PetscCall(MatMumpsCastMumpsScalarArray(nrhsM, mumps->id.precision, mumps->id.rhs, xarray));
2192:     if (solalloc) {
2193:       for (j = 0; j < nrhs; ++j) PetscCall(PetscArraycpy(array + (size_t)j * ldx, solalloc + j * M, M));
2194:       PetscCall(PetscFree(solalloc));
2195:     }
2196:     if (B == X) PetscCall(MatDenseRestoreArray(X, &array));
2197:     else PetscCall(MatDenseRestoreArrayWrite(X, &array));
2198:     if (!mumps->use_petsc_omp_support || mumps->is_omp_master)
2199:       PetscCall(PetscLogFlops(mumps->id.nrhs * PetscMax(0.0, (mumps->sym ? 4.0 : 2.0) * (mumps->id.INFO(28) >= 0 ? mumps->id.INFO(28) : -1.0e6 * mumps->id.INFO(28)) - (mumps->sym ? 3.0 : 1.0) * mumps->id.INFO(23))));
2200:     PetscFunctionReturn(PETSC_SUCCESS);
2201:   }

2203:   /* parallel case: MUMPS requires rhs B to be centralized on the host! */
2204:   PetscCheck(!mumps->id.ICNTL(19), PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Parallel Schur complements not yet supported from PETSc");

2206:   isol_loc_save         = mumps->id.isol_loc; /* save these, as we want to reuse them in MatSolve() */
2207:   sol_loc_save          = mumps->id.sol_loc;
2208:   sol_loc_len_save      = mumps->id.sol_loc_len;
2209:   mumps->id.isol_loc    = NULL; // an init state
2210:   mumps->id.sol_loc     = NULL;
2211:   mumps->id.sol_loc_len = 0;

2213:   lsol_loc  = mumps->id.lsol_loc;
2214:   nlsol_loc = nrhs * lsol_loc; /* length of sol_loc */
2215:   PetscCall(PetscMalloc2(nlsol_loc, &sol_loc, lsol_loc, &isol_loc));
2216:   PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_FALSE, nlsol_loc, sol_loc, mumps->id.precision, &mumps->id.sol_loc_len, &mumps->id.sol_loc));
2217:   mumps->id.isol_loc = isol_loc;

2219:   if (denseB) {
2220:     PetscCall(MatGetLocalSize(B, &m, NULL));
2221:     PetscCall(MatDenseGetArrayRead(B, &barray));
2222:     if (ldb != m && m) {
2223:       PetscCall(PetscMalloc1((size_t)nrhs * m, &rhsalloc));
2224:       for (j = 0; j < nrhs; ++j) PetscCall(PetscArraycpy(rhsalloc + j * m, barray + (size_t)j * ldb, m));
2225:     }
2226:     rhsarray = rhsalloc ? rhsalloc : barray;
2227:     if (mumps->ICNTL20 == 10) {
2228:       mumps->id.ICNTL(20) = 10; /* dense distributed RHS */
2229:       PetscCall(MatMumpsSetUpDistRHSInfo(A, nrhs, rhsarray));
2230:     } else {
2231:       PetscLayout layout;
2232:       PetscInt   *ranges;

2234:       mumps->id.ICNTL(20) = 0; /* dense centralized RHS */
2235:       /* TODO: Because of non-contiguous indices, the created vecscatter scat_rhs is not done in MPI_Gather, resulting in
2236:         very inefficient communication. An optimization is to use VecScatterCreateToZero to gather B to rank 0. Then on rank
2237:         0, re-arrange B into desired order, which is a local operation.
2238:       */

2240:       /* scatter v_mpi to b_seq because MUMPS before 5.3.0 only supports centralized rhs */
2241:       /* wrap dense rhs matrix B into a vector v_mpi */
2242:       PetscCall(MatGetOwnershipRanges(B, &rstart));
2243:       PetscCall(PetscMalloc1(mumps->petsc_size + 1, &ranges));
2244:       for (i = 0; i <= mumps->petsc_size; ++i) ranges[i] = nrhs * rstart[i];
2245:       PetscCall(PetscLayoutCreateFromRanges(PetscObjectComm((PetscObject)B), ranges, PETSC_OWN_POINTER, 1, &layout));
2246:       PetscCall(VecCreateMPIWithLayoutAndArray_Private(layout, rhsarray, &v_mpi));
2247:       PetscCall(PetscLayoutDestroy(&layout));

2249:       /* scatter v_mpi to b_seq in proc[0]. With ICNTL(20) = 0, MUMPS requires rhs to be centralized on the host! */
2250:       if (!mumps->myid) {
2251:         PetscInt *idx;
2252:         /* idx: maps from k-th index of v_mpi to (i,j)-th global entry of B */
2253:         PetscCall(PetscMalloc1(nrhsM, &idx));
2254:         for (proc = 0, k = 0; proc < mumps->petsc_size; proc++) {
2255:           for (j = 0; j < nrhs; j++) {
2256:             for (i = rstart[proc]; i < rstart[proc + 1]; i++) idx[k++] = j * M + i;
2257:           }
2258:         }

2260:         PetscCall(VecCreateSeq(PETSC_COMM_SELF, nrhsM, &b_seq));
2261:         PetscCall(ISCreateGeneral(PETSC_COMM_SELF, nrhsM, idx, PETSC_OWN_POINTER, &is_to));
2262:         PetscCall(ISCreateStride(PETSC_COMM_SELF, nrhsM, 0, 1, &is_from));
2263:       } else {
2264:         PetscCall(VecCreateSeq(PETSC_COMM_SELF, 0, &b_seq));
2265:         PetscCall(ISCreateStride(PETSC_COMM_SELF, 0, 0, 1, &is_to));
2266:         PetscCall(ISCreateStride(PETSC_COMM_SELF, 0, 0, 1, &is_from));
2267:       }

2269:       PetscCall(VecScatterCreate(v_mpi, is_from, b_seq, is_to, &scat_rhs));
2270:       PetscCall(VecScatterBegin(scat_rhs, v_mpi, b_seq, INSERT_VALUES, SCATTER_FORWARD));
2271:       PetscCall(ISDestroy(&is_to));
2272:       PetscCall(ISDestroy(&is_from));
2273:       PetscCall(VecScatterEnd(scat_rhs, v_mpi, b_seq, INSERT_VALUES, SCATTER_FORWARD));

2275:       if (!mumps->myid) { /* define rhs on the host */
2276:         PetscCall(VecGetArrayRead(b_seq, &rhsarray));
2277:         PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, nrhsM, rhsarray, mumps->id.precision, &mumps->id.rhs_len, &mumps->id.rhs));
2278:         PetscCall(VecRestoreArrayRead(b_seq, &rhsarray));
2279:       }
2280:     }
2281:   } else { /* sparse B */
2282:     b = (Mat_MPIAIJ *)Bt->data;

2284:     if (!mumps->myid) {
2285:       PetscCall(MatSeqAIJGetArray(b->A, &aa));
2286:       PetscCall(MatGetRowIJ(b->A, 1, PETSC_FALSE, PETSC_FALSE, &spnr, (const PetscInt **)&ia, (const PetscInt **)&ja, &flg));
2287:       PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot get IJ structure");
2288:       PetscCall(PetscMUMPSIntCSRCast(mumps, spnr, ia, ja, &mumps->id.irhs_ptr, &mumps->id.irhs_sparse, &mumps->id.nz_rhs));
2289:       PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, ((Mat_SeqAIJ *)b->A->data)->nz, aa, mumps->id.precision, &mumps->id.rhs_sparse_len, &mumps->id.rhs_sparse));
2290:     } else {
2291:       mumps->id.irhs_ptr    = NULL;
2292:       mumps->id.irhs_sparse = NULL;
2293:       mumps->id.nz_rhs      = 0;
2294:       if (mumps->id.rhs_sparse_len) {
2295:         PetscCall(PetscFree(mumps->id.rhs_sparse));
2296:         mumps->id.rhs_sparse_len = 0;
2297:       }
2298:     }
2299:   }

2301:   /* solve phase */
2302:   mumps->id.job = JOB_SOLVE;
2303:   PetscMUMPS_c(mumps);
2304:   PetscCheck(mumps->id.INFOG(1) >= 0, PETSC_COMM_SELF, PETSC_ERR_LIB, "MUMPS error in solve: INFOG(1)=%d, INFO(2)=%d " MUMPS_MANUALS, mumps->id.INFOG(1), mumps->id.INFO(2));

2306:   if (denseB) PetscCall(MatDenseRestoreArrayRead(B, &barray));

2308:   PetscCall(MatMumpsSetUpSolutionVecScatter_Private(A, &scat_sol));
2309:   PetscCall(MatMumpsCastMumpsScalarArray(nlsol_loc, mumps->id.precision, mumps->id.sol_loc, sol_loc));
2310:   PetscCall(MatCreateSeqDense(PETSC_COMM_SELF, lsol_loc, nrhs, sol_loc, &solution));
2311:   PetscCall(MatDenseScatter_Private(scat_sol, solution, X, INSERT_VALUES, SCATTER_FORWARD));
2312:   PetscCall(MatDestroy(&solution));

2314:   if (mumps->id.sol_loc_len) { // in case we allocated intermediate buffers
2315:     mumps->id.sol_loc_len = 0;
2316:     PetscCall(PetscFree(mumps->id.sol_loc));
2317:   }

2319:   // restore old values
2320:   mumps->id.sol_loc     = sol_loc_save;
2321:   mumps->id.sol_loc_len = sol_loc_len_save;
2322:   mumps->id.isol_loc    = isol_loc_save;

2324:   PetscCall(PetscFree2(sol_loc, isol_loc));
2325:   PetscCall(VecDestroy(&v_mpi));
2326:   if (!denseB) {
2327:     if (!mumps->myid) {
2328:       b = (Mat_MPIAIJ *)Bt->data;
2329:       PetscCall(MatSeqAIJRestoreArray(b->A, &aa));
2330:       PetscCall(MatRestoreRowIJ(b->A, 1, PETSC_FALSE, PETSC_FALSE, &spnr, (const PetscInt **)&ia, (const PetscInt **)&ja, &flg));
2331:       PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot restore IJ structure");
2332:     }
2333:   } else {
2334:     if (mumps->ICNTL20 == 0) {
2335:       PetscCall(VecDestroy(&b_seq));
2336:       PetscCall(VecScatterDestroy(&scat_rhs));
2337:     }
2338:   }
2339:   PetscCall(PetscFree(rhsalloc));
2340:   PetscCall(PetscFree(solalloc));
2341:   if (!mumps->use_petsc_omp_support || mumps->is_omp_master)
2342:     PetscCall(PetscLogFlops(mumps->id.nrhs * PetscMax(0.0, (mumps->sym ? 4.0 : 2.0) * (mumps->id.INFO(28) >= 0 ? mumps->id.INFO(28) : -1.0e6 * mumps->id.INFO(28)) - (mumps->sym ? 3.0 : 1.0) * mumps->id.INFO(23))));
2343:   PetscFunctionReturn(PETSC_SUCCESS);
2344: }

2346: static PetscErrorCode MatMatSolveTranspose_MUMPS(Mat A, Mat B, Mat X)
2347: {
2348:   Mat_MUMPS          *mumps = (Mat_MUMPS *)A->data;
2349:   const PetscMUMPSInt value = mumps->id.ICNTL(9);

2351:   PetscFunctionBegin;
2352:   mumps->id.ICNTL(9) = 0;
2353:   PetscCall(MatMatSolve_MUMPS(A, B, X));
2354:   mumps->id.ICNTL(9) = value;
2355:   PetscFunctionReturn(PETSC_SUCCESS);
2356: }

2358: static PetscErrorCode MatMatTransposeSolve_MUMPS(Mat A, Mat Bt, Mat X)
2359: {
2360:   PetscBool flg;
2361:   Mat       B;

2363:   PetscFunctionBegin;
2364:   PetscCall(PetscObjectTypeCompareAny((PetscObject)Bt, &flg, MATSEQAIJ, MATMPIAIJ, NULL));
2365:   PetscCheck(flg, PetscObjectComm((PetscObject)Bt), PETSC_ERR_ARG_WRONG, "Matrix Bt must be MATAIJ matrix");

2367:   /* Create B=Bt^T that uses Bt's data structure */
2368:   PetscCall(MatCreateTranspose(Bt, &B));

2370:   PetscCall(MatMatSolve_MUMPS(A, B, X));
2371:   PetscCall(MatDestroy(&B));
2372:   PetscFunctionReturn(PETSC_SUCCESS);
2373: }

2375: #if !PetscDefined(USE_COMPLEX)
2376: /*
2377:   input:
2378:    F:        numeric factor
2379:   output:
2380:    nneg:     total number of negative pivots
2381:    nzero:    total number of zero pivots
2382:    npos:     (global dimension of F) - nneg - nzero
2383: */
2384: static PetscErrorCode MatGetInertia_SBAIJMUMPS(Mat F, PetscInt *nneg, PetscInt *nzero, PetscInt *npos)
2385: {
2386:   Mat_MUMPS  *mumps = (Mat_MUMPS *)F->data;
2387:   PetscMPIInt size;

2389:   PetscFunctionBegin;
2390:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)F), &size));
2391:   /* MUMPS 4.3.1 calls ScaLAPACK when ICNTL(13)=0 (default), which does not offer the possibility to compute the inertia of a dense matrix. Set ICNTL(13)=1 to skip ScaLAPACK */
2392:   PetscCheck(size <= 1 || mumps->id.ICNTL(13) == 1, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "ICNTL(13)=%d. -mat_mumps_icntl_13 must be set as 1 for correct global matrix inertia", mumps->id.INFOG(13));

2394:   if (nneg) *nneg = mumps->id.INFOG(12);
2395:   if (nzero || npos) {
2396:     PetscCheck(mumps->id.ICNTL(24) == 1, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "-mat_mumps_icntl_24 must be set as 1 for null pivot row detection");
2397:     if (nzero) *nzero = mumps->id.INFOG(28);
2398:     if (npos) *npos = F->rmap->N - (mumps->id.INFOG(12) + mumps->id.INFOG(28));
2399:   }
2400:   PetscFunctionReturn(PETSC_SUCCESS);
2401: }
2402: #endif

2404: static PetscErrorCode MatMumpsGatherNonzerosOnMaster(MatReuse reuse, Mat_MUMPS *mumps)
2405: {
2406:   PetscMPIInt    nreqs;
2407:   PetscMUMPSInt *irn, *jcn;
2408:   PetscMPIInt    count;
2409:   PetscCount     totnnz, remain;
2410:   const PetscInt osize = mumps->omp_comm_size;
2411:   PetscScalar   *val;

2413:   PetscFunctionBegin;
2414:   if (osize > 1) {
2415:     if (reuse == MAT_INITIAL_MATRIX) {
2416:       /* master first gathers counts of nonzeros to receive */
2417:       if (mumps->is_omp_master) PetscCall(PetscMalloc1(osize, &mumps->recvcount));
2418:       PetscCallMPI(MPI_Gather(&mumps->nnz, 1, MPIU_INT64, mumps->recvcount, 1, MPIU_INT64, 0 /*master*/, mumps->omp_comm));

2420:       /* Then each computes number of send/recvs */
2421:       if (mumps->is_omp_master) {
2422:         /* Start from 1 since self communication is not done in MPI */
2423:         nreqs = 0;
2424:         for (PetscMPIInt i = 1; i < osize; i++) nreqs += (mumps->recvcount[i] + PETSC_MPI_INT_MAX - 1) / PETSC_MPI_INT_MAX;
2425:       } else {
2426:         nreqs = (PetscMPIInt)((mumps->nnz + PETSC_MPI_INT_MAX - 1) / PETSC_MPI_INT_MAX);
2427:       }
2428:       PetscCall(PetscMalloc1(nreqs * 3, &mumps->reqs)); /* Triple the requests since we send irn, jcn and val separately */

2430:       /* The following code is doing a very simple thing: omp_master rank gathers irn/jcn/val from others.
2431:          MPI_Gatherv would be enough if it supports big counts > 2^31-1. Since it does not, and mumps->nnz
2432:          might be a prime number > 2^31-1, we have to slice the message. Note omp_comm_size
2433:          is very small, the current approach should have no extra overhead compared to MPI_Gatherv.
2434:        */
2435:       nreqs = 0; /* counter for actual send/recvs */
2436:       if (mumps->is_omp_master) {
2437:         totnnz = 0;

2439:         for (PetscMPIInt i = 0; i < osize; i++) totnnz += mumps->recvcount[i]; /* totnnz = sum of nnz over omp_comm */
2440:         PetscCall(PetscMalloc2(totnnz, &irn, totnnz, &jcn));
2441:         PetscCall(PetscMalloc1(totnnz, &val));

2443:         /* Self communication */
2444:         PetscCall(PetscArraycpy(irn, mumps->irn, mumps->nnz));
2445:         PetscCall(PetscArraycpy(jcn, mumps->jcn, mumps->nnz));
2446:         PetscCall(PetscArraycpy(val, mumps->val, mumps->nnz));

2448:         /* Replace mumps->irn/jcn etc on master with the newly allocated bigger arrays */
2449:         PetscCall(PetscFree2(mumps->irn, mumps->jcn));
2450:         PetscCall(PetscFree(mumps->val_alloc));
2451:         mumps->nnz = totnnz;
2452:         mumps->irn = irn;
2453:         mumps->jcn = jcn;
2454:         mumps->val = mumps->val_alloc = val;

2456:         irn += mumps->recvcount[0]; /* recvcount[0] is old mumps->nnz on omp rank 0 */
2457:         jcn += mumps->recvcount[0];
2458:         val += mumps->recvcount[0];

2460:         /* Remote communication */
2461:         for (PetscMPIInt i = 1; i < osize; i++) {
2462:           count  = (PetscMPIInt)PetscMin(mumps->recvcount[i], (PetscMPIInt)PETSC_MPI_INT_MAX);
2463:           remain = mumps->recvcount[i] - count;
2464:           while (count > 0) {
2465:             PetscCallMPI(MPIU_Irecv(irn, count, MPIU_MUMPSINT, i, mumps->tag, mumps->omp_comm, &mumps->reqs[nreqs++]));
2466:             PetscCallMPI(MPIU_Irecv(jcn, count, MPIU_MUMPSINT, i, mumps->tag, mumps->omp_comm, &mumps->reqs[nreqs++]));
2467:             PetscCallMPI(MPIU_Irecv(val, count, MPIU_SCALAR, i, mumps->tag, mumps->omp_comm, &mumps->reqs[nreqs++]));
2468:             irn += count;
2469:             jcn += count;
2470:             val += count;
2471:             count = (PetscMPIInt)PetscMin(remain, (PetscMPIInt)PETSC_MPI_INT_MAX);
2472:             remain -= count;
2473:           }
2474:         }
2475:       } else {
2476:         irn    = mumps->irn;
2477:         jcn    = mumps->jcn;
2478:         val    = mumps->val;
2479:         count  = (PetscMPIInt)PetscMin(mumps->nnz, (PetscMPIInt)PETSC_MPI_INT_MAX);
2480:         remain = mumps->nnz - count;
2481:         while (count > 0) {
2482:           PetscCallMPI(MPIU_Isend(irn, count, MPIU_MUMPSINT, 0, mumps->tag, mumps->omp_comm, &mumps->reqs[nreqs++]));
2483:           PetscCallMPI(MPIU_Isend(jcn, count, MPIU_MUMPSINT, 0, mumps->tag, mumps->omp_comm, &mumps->reqs[nreqs++]));
2484:           PetscCallMPI(MPIU_Isend(val, count, MPIU_SCALAR, 0, mumps->tag, mumps->omp_comm, &mumps->reqs[nreqs++]));
2485:           irn += count;
2486:           jcn += count;
2487:           val += count;
2488:           count = (PetscMPIInt)PetscMin(remain, (PetscMPIInt)PETSC_MPI_INT_MAX);
2489:           remain -= count;
2490:         }
2491:       }
2492:     } else {
2493:       nreqs = 0;
2494:       if (mumps->is_omp_master) {
2495:         val = mumps->val + mumps->recvcount[0];
2496:         for (PetscMPIInt i = 1; i < osize; i++) { /* Remote communication only since self data is already in place */
2497:           count  = (PetscMPIInt)PetscMin(mumps->recvcount[i], (PetscMPIInt)PETSC_MPI_INT_MAX);
2498:           remain = mumps->recvcount[i] - count;
2499:           while (count > 0) {
2500:             PetscCallMPI(MPIU_Irecv(val, count, MPIU_SCALAR, i, mumps->tag, mumps->omp_comm, &mumps->reqs[nreqs++]));
2501:             val += count;
2502:             count = (PetscMPIInt)PetscMin(remain, (PetscMPIInt)PETSC_MPI_INT_MAX);
2503:             remain -= count;
2504:           }
2505:         }
2506:       } else {
2507:         val    = mumps->val;
2508:         count  = (PetscMPIInt)PetscMin(mumps->nnz, (PetscMPIInt)PETSC_MPI_INT_MAX);
2509:         remain = mumps->nnz - count;
2510:         while (count > 0) {
2511:           PetscCallMPI(MPIU_Isend(val, count, MPIU_SCALAR, 0, mumps->tag, mumps->omp_comm, &mumps->reqs[nreqs++]));
2512:           val += count;
2513:           count = (PetscMPIInt)PetscMin(remain, (PetscMPIInt)PETSC_MPI_INT_MAX);
2514:           remain -= count;
2515:         }
2516:       }
2517:     }
2518:     PetscCallMPI(MPI_Waitall(nreqs, mumps->reqs, MPI_STATUSES_IGNORE));
2519:     mumps->tag++; /* It is totally fine for above send/recvs to share one mpi tag */
2520:   }
2521:   PetscFunctionReturn(PETSC_SUCCESS);
2522: }

2524: static PetscErrorCode MatFactorNumeric_MUMPS(Mat F, Mat A, PETSC_UNUSED const MatFactorInfo *info)
2525: {
2526:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

2528:   PetscFunctionBegin;
2529:   if (mumps->id.INFOG(1) < 0 && !(mumps->id.INFOG(1) == -16 && mumps->id.INFOG(1) == 0)) {
2530:     if (mumps->id.INFOG(1) == -6) PetscCall(PetscInfo(A, "MatFactorNumeric is called with singular matrix structure, INFOG(1)=%d, INFO(2)=%d\n", mumps->id.INFOG(1), mumps->id.INFO(2)));
2531:     PetscCall(PetscInfo(A, "MatFactorNumeric is called after analysis phase fails, INFOG(1)=%d, INFO(2)=%d\n", mumps->id.INFOG(1), mumps->id.INFO(2)));
2532:     PetscFunctionReturn(PETSC_SUCCESS);
2533:   }

2535:   PetscCall((*mumps->ConvertToTriples)(A, 1, MAT_REUSE_MATRIX, mumps));
2536:   PetscCall(MatMumpsGatherNonzerosOnMaster(MAT_REUSE_MATRIX, mumps));
2537:   PetscCall(MatMumpsEnsureSchurArray_Private(F));

2539:   /* numerical factorization phase */
2540:   mumps->id.job = JOB_FACTNUMERIC;
2541:   if (!mumps->id.ICNTL(18)) { /* A is centralized */
2542:     if (!mumps->myid) PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, mumps->nnz, mumps->val, mumps->id.precision, &mumps->id.a_len, &mumps->id.a));
2543:   } else {
2544:     PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, mumps->nnz, mumps->val, mumps->id.precision, &mumps->id.a_loc_len, &mumps->id.a_loc));
2545:   }

2547:   if (mumps->id.ICNTL(22)) PetscCall(PetscStrncpy(mumps->id.ooc_prefix, ((PetscObject)F)->prefix, sizeof(((MUMPS_STRUC_C *)NULL)->ooc_prefix)));
2548:   if (A->rmap->N && A->cmap->N) PetscMUMPS_c(mumps);
2549:   if (mumps->id.INFOG(1) < 0) {
2550:     PetscCheck(!A->erroriffailure, PETSC_COMM_SELF, PETSC_ERR_LIB, "MUMPS error in numerical factorization: INFOG(1)=%d, INFO(2)=%d " MUMPS_MANUALS, mumps->id.INFOG(1), mumps->id.INFO(2));
2551:     if (mumps->id.INFOG(1) == -10) {
2552:       PetscCall(PetscInfo(F, "MUMPS error in numerical factorization: matrix is numerically singular, INFOG(1)=%d, INFO(2)=%d\n", mumps->id.INFOG(1), mumps->id.INFO(2)));
2553:       F->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
2554:     } else if (mumps->id.INFOG(1) == -13) {
2555:       PetscCall(PetscInfo(F, "MUMPS error in numerical factorization: INFOG(1)=%d, cannot allocate required memory %d megabytes\n", mumps->id.INFOG(1), mumps->id.INFO(2)));
2556:       F->factorerrortype = MAT_FACTOR_OUTMEMORY;
2557:     } else if (mumps->id.INFOG(1) == -8 || mumps->id.INFOG(1) == -9 || (-16 < mumps->id.INFOG(1) && mumps->id.INFOG(1) < -10)) {
2558:       PetscCall(PetscInfo(F, "MUMPS error in numerical factorization: INFOG(1)=%d, INFO(2)=%d, problem with work array\n", mumps->id.INFOG(1), mumps->id.INFO(2)));
2559:       F->factorerrortype = MAT_FACTOR_OUTMEMORY;
2560:     } else {
2561:       PetscCall(PetscInfo(F, "MUMPS error in numerical factorization: INFOG(1)=%d, INFO(2)=%d\n", mumps->id.INFOG(1), mumps->id.INFO(2)));
2562:       F->factorerrortype = MAT_FACTOR_OTHER;
2563:     }
2564:   }
2565:   PetscCheck(mumps->myid || mumps->id.ICNTL(16) <= 0, PETSC_COMM_SELF, PETSC_ERR_LIB, "MUMPS error in numerical factorization: ICNTL(16)=%d " MUMPS_MANUALS, mumps->id.INFOG(16));

2567:   F->assembled = PETSC_TRUE;

2569:   if (F->schur) { /* reset Schur status to unfactored */
2570: #if PetscDefined(HAVE_CUDA)
2571:     F->schur->offloadmask = PETSC_OFFLOAD_CPU;
2572: #endif
2573:     PetscScalar *array;
2574:     PetscCall(MatDenseGetArray(F->schur, &array));
2575:     PetscCall(MatMumpsCastMumpsScalarArray(mumps->id.size_schur * mumps->id.size_schur, mumps->id.precision, mumps->id.schur, array));
2576:     PetscCall(MatDenseRestoreArray(F->schur, &array));
2577:     if (mumps->id.ICNTL(19) == 1) { /* stored by rows */
2578:       mumps->id.ICNTL(19) = 2;
2579:       PetscCall(MatTranspose(F->schur, MAT_INPLACE_MATRIX, &F->schur));
2580:     }
2581:     PetscCall(MatFactorRestoreSchurComplement(F, NULL, MAT_FACTOR_SCHUR_UNFACTORED));
2582:   }

2584:   /* just to be sure that ICNTL(19) value returned by a call from MatMumpsGetIcntl is always consistent */
2585:   if (!mumps->sym && mumps->id.ICNTL(19) && mumps->id.ICNTL(19) != 1) mumps->id.ICNTL(19) = 3;

2587:   if (!mumps->is_omp_master) mumps->id.INFO(23) = 0;
2588:   // MUMPS userguide: ISOL_loc should be allocated by the user between the factorization and the
2589:   // solve phases. On exit from the solve phase, ISOL_loc(i) contains the index of the variables for
2590:   // which the solution (in SOL_loc) is available on the local processor.
2591:   // If successive calls to the solve phase (JOB= 3) are performed for a given matrix, ISOL_loc will
2592:   // normally have the same contents for each of these calls. The only exception is the case of
2593:   // unsymmetric matrices (SYM=1) when the transpose option is changed (see ICNTL(9)) and non
2594:   // symmetric row/column exchanges (see ICNTL(6)) have occurred before the solve phase.
2595:   if (mumps->petsc_size > 1) {
2596:     PetscInt     lsol_loc;
2597:     PetscScalar *array;

2599:     /* distributed solution; Create x_seq=sol_loc for repeated use */
2600:     if (mumps->x_seq) {
2601:       for (size_t i = 0; i < PETSC_STATIC_ARRAY_LENGTH(mumps->scat_sol); ++i) PetscCall(VecScatterDestroy(&mumps->scat_sol[i]));
2602:       PetscCall(PetscFree(mumps->id.isol_loc));
2603:       PetscCall(VecDestroy(&mumps->x_seq));
2604:     }
2605:     lsol_loc = mumps->id.INFO(23); /* length of sol_loc */
2606:     PetscCall(PetscMalloc1(lsol_loc, &mumps->id.isol_loc));
2607:     PetscCall(VecCreateSeq(PETSC_COMM_SELF, lsol_loc, &mumps->x_seq));
2608:     PetscCall(VecGetArray(mumps->x_seq, &array));
2609:     PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_FALSE, lsol_loc, array, mumps->id.precision, &mumps->id.sol_loc_len, &mumps->id.sol_loc));
2610:     PetscCall(VecRestoreArray(mumps->x_seq, &array));
2611:     mumps->id.lsol_loc = (PetscMUMPSInt)lsol_loc;
2612:   }
2613:   PetscCall(PetscLogFlops((double)ID_RINFO_GET(mumps->id, 2)));
2614:   PetscFunctionReturn(PETSC_SUCCESS);
2615: }

2617: /* Sets MUMPS options from the options database */
2618: static PetscErrorCode MatSetFromOptions_MUMPS(Mat F, Mat A)
2619: {
2620:   Mat_MUMPS    *mumps = (Mat_MUMPS *)F->data;
2621:   PetscReal     cntl;
2622:   PetscMUMPSInt icntl = 0, size, *listvar_schur;
2623:   PetscInt      info[80], i, ninfo = 80, rbs, cbs;
2624:   PetscBool     flg   = PETSC_FALSE;
2625:   PetscBool     schur = mumps->id.icntl ? (PetscBool)(mumps->id.ICNTL(26) == -1) : (PetscBool)(mumps->ICNTL26 == -1);
2626:   void         *arr;

2628:   PetscFunctionBegin;
2629:   PetscOptionsBegin(PetscObjectComm((PetscObject)F), ((PetscObject)F)->prefix, "MUMPS Options", "Mat");
2630:   if (mumps->id.job == JOB_NULL) { /* MatSetFromOptions_MUMPS() has never been called before */
2631:     PetscPrecision precision  = PetscDefined(USE_REAL_SINGLE) ? PETSC_PRECISION_SINGLE : PETSC_PRECISION_DOUBLE;
2632:     PetscInt       nthreads   = 0;
2633:     PetscInt       nCNTL_pre  = mumps->CNTL_pre ? mumps->CNTL_pre[0] : 0;
2634:     PetscInt       nICNTL_pre = mumps->ICNTL_pre ? mumps->ICNTL_pre[0] : 0;
2635:     PetscMUMPSInt  nblk, *blkvar, *blkptr;

2637:     mumps->petsc_comm = PetscObjectComm((PetscObject)A);
2638:     PetscCallMPI(MPI_Comm_size(mumps->petsc_comm, &mumps->petsc_size));
2639:     PetscCallMPI(MPI_Comm_rank(mumps->petsc_comm, &mumps->myid)); /* "if (!myid)" still works even if mumps_comm is different */

2641:     PetscCall(PetscOptionsName("-mat_mumps_use_omp_threads", "Convert MPI processes into OpenMP threads", "None", &mumps->use_petsc_omp_support));
2642:     if (mumps->use_petsc_omp_support) nthreads = -1; /* -1 will let PetscOmpCtrlCreate() guess a proper value when user did not supply one */
2643:     /* do not use PetscOptionsInt() so that the option -mat_mumps_use_omp_threads is not displayed twice in the help */
2644:     PetscCall(PetscOptionsGetInt(NULL, ((PetscObject)F)->prefix, "-mat_mumps_use_omp_threads", &nthreads, NULL));
2645:     if (mumps->use_petsc_omp_support) {
2646:       PetscCheck(!schur, PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot use -%smat_mumps_use_omp_threads with the Schur complement feature", ((PetscObject)F)->prefix ? ((PetscObject)F)->prefix : "");
2647: #if PetscDefined(HAVE_OPENMP_SUPPORT)
2648:       PetscCall(PetscOmpCtrlCreate(mumps->petsc_comm, nthreads, &mumps->omp_ctrl));
2649:       PetscCall(PetscOmpCtrlGetOmpComms(mumps->omp_ctrl, &mumps->omp_comm, &mumps->mumps_comm, &mumps->is_omp_master));
2650: #else
2651:       SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP_SYS, "The system does not have PETSc OpenMP support but you added the -%smat_mumps_use_omp_threads option. Configure PETSc with --with-openmp --download-hwloc (or --with-hwloc) to enable it, see more in MATSOLVERMUMPS manual",
2652:               ((PetscObject)F)->prefix ? ((PetscObject)F)->prefix : "");
2653: #endif
2654:     } else {
2655:       mumps->omp_comm      = PETSC_COMM_SELF;
2656:       mumps->mumps_comm    = mumps->petsc_comm;
2657:       mumps->is_omp_master = PETSC_TRUE;
2658:     }
2659:     PetscCallMPI(MPI_Comm_size(mumps->omp_comm, &mumps->omp_comm_size));
2660:     mumps->reqs = NULL;
2661:     mumps->tag  = 0;

2663:     if (mumps->mumps_comm != MPI_COMM_NULL) {
2664:       if (PetscDefined(HAVE_OPENMP_SUPPORT) && mumps->use_petsc_omp_support) {
2665:         /* It looks like MUMPS does not dup the input comm. Dup a new comm for MUMPS to avoid any tag mismatches. */
2666:         MPI_Comm comm;
2667:         PetscCallMPI(MPI_Comm_dup(mumps->mumps_comm, &comm));
2668:         mumps->mumps_comm = comm;
2669:       } else PetscCall(PetscCommGetComm(mumps->petsc_comm, &mumps->mumps_comm));
2670:     }

2672:     mumps->id.comm_fortran = MPI_Comm_c2f(mumps->mumps_comm);
2673:     mumps->id.job          = JOB_INIT;
2674:     mumps->id.par          = 1; /* host participates factorizaton and solve */
2675:     mumps->id.sym          = mumps->sym;

2677:     size          = mumps->id.size_schur;
2678:     arr           = mumps->id.schur;
2679:     listvar_schur = mumps->id.listvar_schur;
2680:     nblk          = mumps->id.nblk;
2681:     blkvar        = mumps->id.blkvar;
2682:     blkptr        = mumps->id.blkptr;
2683:     if (PetscDefined(USE_DEBUG)) {
2684:       for (PetscInt i = 0; i < size; i++)
2685:         PetscCheck(listvar_schur[i] - 1 >= 0 && listvar_schur[i] - 1 < A->rmap->N, PETSC_COMM_SELF, PETSC_ERR_USER, "Invalid Schur index at position %" PetscInt_FMT "! %" PetscInt_FMT " must be in [0, %" PetscInt_FMT ")", i, (PetscInt)listvar_schur[i] - 1,
2686:                    A->rmap->N);
2687:     }

2689:     PetscCall(PetscOptionsEnum("-pc_precision", "Precision used by MUMPS", "MATSOLVERMUMPS", PetscPrecisionTypes, (PetscEnum)precision, (PetscEnum *)&precision, NULL));
2690:     PetscCheck(precision == PETSC_PRECISION_SINGLE || precision == PETSC_PRECISION_DOUBLE, PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "MUMPS does not support %s precision", PetscPrecisionTypes[precision]);
2691:     PetscCheck(precision == PETSC_SCALAR_PRECISION || PetscDefined(HAVE_MUMPS_MIXED_PRECISION), PetscObjectComm((PetscObject)F), PETSC_ERR_USER, "Your MUMPS library does not support mixed precision, but which is needed with your specified PetscScalar");
2692:     PetscCall(MatMumpsAllocateInternalID(&mumps->id, precision));

2694:     PetscMUMPS_c(mumps);
2695:     PetscCheck(mumps->id.INFOG(1) >= 0, PETSC_COMM_SELF, PETSC_ERR_LIB, "MUMPS error: INFOG(1)=%d, INFO(2)=%d " MUMPS_MANUALS, mumps->id.INFOG(1), mumps->id.INFO(2));

2697:     /* set PETSc-MUMPS default options - override MUMPS default */
2698:     mumps->id.ICNTL(3) = 0;
2699:     mumps->id.ICNTL(4) = 0;
2700:     if (mumps->petsc_size == 1) {
2701:       mumps->id.ICNTL(18) = 0; /* centralized assembled matrix input */
2702:       mumps->id.ICNTL(7)  = 7; /* automatic choice of ordering done by the package */
2703:     } else {
2704:       mumps->id.ICNTL(18) = 3; /* distributed assembled matrix input */
2705:       mumps->id.ICNTL(21) = 1; /* distributed solution */
2706:     }
2707:     if (nblk && blkptr) {
2708:       mumps->id.ICNTL(15) = 1;
2709:       mumps->id.nblk      = nblk;
2710:       mumps->id.blkvar    = blkvar;
2711:       mumps->id.blkptr    = blkptr;
2712:     } else mumps->id.ICNTL(15) = 0;

2714:     /* restore cached ICNTL and CNTL values */
2715:     for (icntl = 0; icntl < nICNTL_pre; ++icntl) mumps->id.ICNTL(mumps->ICNTL_pre[1 + 2 * icntl]) = mumps->ICNTL_pre[2 + 2 * icntl];
2716:     for (icntl = 0; icntl < nCNTL_pre; ++icntl) ID_CNTL_SET(mumps->id, (PetscInt)mumps->CNTL_pre[1 + 2 * icntl], mumps->CNTL_pre[2 + 2 * icntl]);

2718:     PetscCall(PetscFree(mumps->ICNTL_pre));
2719:     PetscCall(PetscFree(mumps->CNTL_pre));

2721:     if (schur) {
2722:       mumps->id.size_schur    = size;
2723:       mumps->id.schur_lld     = size;
2724:       mumps->id.schur         = arr;
2725:       mumps->id.listvar_schur = listvar_schur;
2726:       if (mumps->petsc_size > 1) {
2727:         PetscBool gs; /* gs is false if any rank other than root has non-empty IS */

2729:         mumps->id.ICNTL(19) = 1;                                                                            /* MUMPS returns Schur centralized on the host */
2730:         gs                  = mumps->myid ? (mumps->id.size_schur ? PETSC_FALSE : PETSC_TRUE) : PETSC_TRUE; /* always true on root; false on others if their size != 0 */
2731:         PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &gs, 1, MPI_C_BOOL, MPI_LAND, mumps->petsc_comm));
2732:         PetscCheck(gs, PETSC_COMM_SELF, PETSC_ERR_SUP, "MUMPS distributed parallel Schur complements not yet supported from PETSc");
2733:       } else {
2734:         if (F->factortype == MAT_FACTOR_LU) {
2735:           mumps->id.ICNTL(19) = 3; /* MUMPS returns full matrix */
2736:         } else {
2737:           mumps->id.ICNTL(19) = 2; /* MUMPS returns lower triangular part */
2738:         }
2739:       }
2740:       mumps->id.ICNTL(26) = -1;
2741:     }

2743:     /* copy MUMPS default control values from master to slaves. Although slaves do not call MUMPS, they may access these values in code.
2744:        For example, ICNTL(9) is initialized to 1 by MUMPS and slaves check ICNTL(9) in MatSolve_MUMPS.
2745:      */
2746:     PetscCallMPI(MPI_Bcast(mumps->id.icntl, 40, MPI_INT, 0, mumps->omp_comm));
2747:     PetscCallMPI(MPI_Bcast(mumps->id.cntl, 15, MPIU_MUMPSREAL(&mumps->id), 0, mumps->omp_comm));

2749:     mumps->scat_rhs    = NULL;
2750:     mumps->scat_sol[0] = mumps->scat_sol[1] = NULL;
2751:   }
2752:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_1", "ICNTL(1): output stream for error messages", "None", mumps->id.ICNTL(1), &icntl, &flg));
2753:   if (flg) mumps->id.ICNTL(1) = icntl;
2754:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_2", "ICNTL(2): output stream for diagnostic printing, statistics, and warning", "None", mumps->id.ICNTL(2), &icntl, &flg));
2755:   if (flg) mumps->id.ICNTL(2) = icntl;
2756:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_3", "ICNTL(3): output stream for global information, collected on the host", "None", mumps->id.ICNTL(3), &icntl, &flg));
2757:   if (flg) mumps->id.ICNTL(3) = icntl;

2759:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_4", "ICNTL(4): level of printing (0 to 4)", "None", mumps->id.ICNTL(4), &icntl, &flg));
2760:   if (flg) mumps->id.ICNTL(4) = icntl;
2761:   if (mumps->id.ICNTL(4) || PetscLogPrintInfo) mumps->id.ICNTL(3) = 6; /* resume MUMPS default id.ICNTL(3) = 6 */

2763:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_6", "ICNTL(6): permutes to a zero-free diagonal and/or scale the matrix (0 to 7)", "None", mumps->id.ICNTL(6), &icntl, &flg));
2764:   if (flg) mumps->id.ICNTL(6) = icntl;

2766:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_7", "ICNTL(7): computes a symmetric permutation in sequential analysis. 0=AMD, 2=AMF, 3=Scotch, 4=PORD, 5=METIS, 6=QAMD, and 7=auto(default)", "None", mumps->id.ICNTL(7), &icntl, &flg));
2767:   if (flg) {
2768:     PetscCheck(icntl != 1 && icntl >= 0 && icntl <= 7, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Valid values are 0=AMD, 2=AMF, 3=Scotch, 4=PORD, 5=METIS, 6=QAMD, and 7=auto");
2769:     mumps->id.ICNTL(7) = icntl;
2770:   }

2772:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_8", "ICNTL(8): scaling strategy (-2 to 8 or 77)", "None", mumps->id.ICNTL(8), &mumps->id.ICNTL(8), NULL));
2773:   /* PetscCall(PetscOptionsInt("-mat_mumps_icntl_9","ICNTL(9): computes the solution using A or A^T","None",mumps->id.ICNTL(9),&mumps->id.ICNTL(9),NULL)); handled by MatSolveTranspose_MUMPS() */
2774:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_10", "ICNTL(10): max num of refinements", "None", mumps->id.ICNTL(10), &mumps->id.ICNTL(10), NULL));
2775:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_11", "ICNTL(11): statistics related to an error analysis (via -ksp_view)", "None", mumps->id.ICNTL(11), &mumps->id.ICNTL(11), NULL));
2776:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_12", "ICNTL(12): an ordering strategy for symmetric matrices (0 to 3)", "None", mumps->id.ICNTL(12), &mumps->id.ICNTL(12), NULL));
2777:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_13", "ICNTL(13): parallelism of the root node (enable ScaLAPACK) and its splitting", "None", mumps->id.ICNTL(13), &mumps->id.ICNTL(13), NULL));
2778:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_14", "ICNTL(14): percentage increase in the estimated working space", "None", mumps->id.ICNTL(14), &mumps->id.ICNTL(14), NULL));
2779:   PetscCall(MatGetBlockSizes(A, &rbs, &cbs));
2780:   if (rbs == cbs && rbs > 1) mumps->id.ICNTL(15) = (PetscMUMPSInt)-rbs;
2781:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_15", "ICNTL(15): compression of the input matrix resulting from a block format", "None", mumps->id.ICNTL(15), &mumps->id.ICNTL(15), &flg));
2782:   if (flg) {
2783:     if (mumps->id.ICNTL(15) < 0) PetscCheck((-mumps->id.ICNTL(15) % cbs == 0) && (-mumps->id.ICNTL(15) % rbs == 0), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "The opposite of -mat_mumps_icntl_15 must be a multiple of the column and row blocksizes");
2784:     else if (mumps->id.ICNTL(15) > 0) {
2785:       const PetscInt *bsizes;
2786:       PetscInt        nblocks, p, *blkptr = NULL;
2787:       PetscMPIInt    *recvcounts, *displs, n;
2788:       PetscMPIInt     rank, size = 0;

2790:       PetscCall(MatGetVariableBlockSizes(A, &nblocks, &bsizes));
2791:       flg = PETSC_TRUE;
2792:       for (p = 0; p < nblocks; ++p) {
2793:         if (bsizes[p] > 1) break;
2794:       }
2795:       if (p == nblocks) flg = PETSC_FALSE;
2796:       PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &flg, 1, MPI_C_BOOL, MPI_LOR, PetscObjectComm((PetscObject)A)));
2797:       if (flg) { // if at least one process supplies variable block sizes and they are not all set to 1
2798:         PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank));
2799:         if (rank == 0) PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
2800:         PetscCall(PetscCalloc2(size, &recvcounts, size + 1, &displs));
2801:         PetscCall(PetscMPIIntCast(nblocks, &n));
2802:         PetscCallMPI(MPI_Gather(&n, 1, MPI_INT, recvcounts, 1, MPI_INT, 0, PetscObjectComm((PetscObject)A)));
2803:         for (PetscInt p = 0; p < size; ++p) displs[p + 1] = displs[p] + recvcounts[p];
2804:         PetscCall(PetscMalloc1(displs[size] + 1, &blkptr));
2805:         PetscCallMPI(MPI_Bcast(displs + size, 1, MPIU_INT, 0, PetscObjectComm((PetscObject)A)));
2806:         PetscCallMPI(MPI_Gatherv(bsizes, n, MPIU_INT, blkptr + 1, recvcounts, displs, MPIU_INT, 0, PetscObjectComm((PetscObject)A)));
2807:         if (rank == 0) {
2808:           blkptr[0] = 1;
2809:           for (PetscInt p = 0; p < n; ++p) blkptr[p + 1] += blkptr[p];
2810:           PetscCall(MatMumpsSetBlk(F, displs[size], NULL, blkptr));
2811:         }
2812:         PetscCall(PetscFree2(recvcounts, displs));
2813:         PetscCall(PetscFree(blkptr));
2814:       }
2815:     }
2816:   }
2817:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_19", "ICNTL(19): computes the Schur complement", "None", mumps->id.ICNTL(19), &mumps->id.ICNTL(19), NULL));
2818:   if (mumps->id.ICNTL(19) <= 0 || mumps->id.ICNTL(19) > 3) { /* reset any Schur data (if any) */
2819:     PetscCall(MatMumpsResetSchur_Private(F));
2820:   }

2822:   /* Two MPICH Fortran MPI_IN_PLACE binding bugs prevented the use of 'mpich + mumps'. One happened with "mpi4py + mpich + mumps",
2823:      and was reported by Firedrake. See https://bitbucket.org/mpi4py/mpi4py/issues/162/mpi4py-initialization-breaks-fortran
2824:      and a petsc-maint mailing list thread with subject 'MUMPS segfaults in parallel because of ...'
2825:      This bug was fixed by https://github.com/pmodels/mpich/pull/4149. But the fix brought a new bug,
2826:      see https://github.com/pmodels/mpich/issues/5589. This bug was fixed by https://github.com/pmodels/mpich/pull/5590.
2827:      In short, we could not use distributed RHS until with MPICH v4.0b1 or we enabled a workaround in mumps-5.6.2+
2828:    */
2829:   mumps->ICNTL20 = 10; /* Distributed dense RHS, by default */
2830: #if PETSC_PKG_MUMPS_VERSION_LT(5, 3, 0) || (PetscDefined(HAVE_MPICH) && MPICH_NUMVERSION < 40000101) || PetscDefined(HAVE_MSMPI)
2831:   mumps->ICNTL20 = 0; /* Centralized dense RHS, if need be */
2832: #endif
2833:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_20", "ICNTL(20): give mumps centralized (0) or distributed (10) dense right-hand sides", "None", mumps->ICNTL20, &mumps->ICNTL20, &flg));
2834:   PetscCheck(!flg || mumps->ICNTL20 == 10 || mumps->ICNTL20 == 0, PETSC_COMM_SELF, PETSC_ERR_SUP, "ICNTL(20)=%d is not supported by the PETSc/MUMPS interface. Allowed values are 0, 10", (int)mumps->ICNTL20);
2835: #if PETSC_PKG_MUMPS_VERSION_LT(5, 3, 0)
2836:   PetscCheck(!flg || mumps->ICNTL20 != 10, PETSC_COMM_SELF, PETSC_ERR_SUP, "ICNTL(20)=10 is not supported before MUMPS-5.3.0");
2837: #endif
2838:   /* PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_21","ICNTL(21): the distribution (centralized or distributed) of the solution vectors","None",mumps->id.ICNTL(21),&mumps->id.ICNTL(21),NULL)); we only use distributed solution vector */

2840:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_22", "ICNTL(22): in-core/out-of-core factorization and solve (0 or 1)", "None", mumps->id.ICNTL(22), &mumps->id.ICNTL(22), &flg));
2841:   if (flg && mumps->id.ICNTL(22) != 1) mumps->id.ICNTL(22) = 0; // MUMPS treats values other than 1 as 0. Normalize it so we can safely use 'if (mumps->id.ICNTL(22))'
2842:   if (mumps->id.ICNTL(22)) {
2843:     // MUMPS will use the /tmp directory if -mat_mumps_ooc_tmpdir is not set by user.
2844:     // We don't provide option -mat_mumps_ooc_prefix, as we use F's prefix as OOC_PREFIX, which is set later during MatFactorNumeric_MUMPS() to also handle cases where users enable OOC via MatMumpsSetIcntl().
2845:     PetscCall(PetscOptionsString("-mat_mumps_ooc_tmpdir", "Out of core directory", "None", mumps->id.ooc_tmpdir, mumps->id.ooc_tmpdir, sizeof(((MUMPS_STRUC_C *)NULL)->ooc_tmpdir), NULL));
2846:   }
2847:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_23", "ICNTL(23): max size of the working memory (MB) that can allocate per processor", "None", mumps->id.ICNTL(23), &mumps->id.ICNTL(23), NULL));
2848:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_24", "ICNTL(24): detection of null pivot rows (0 or 1)", "None", mumps->id.ICNTL(24), &mumps->id.ICNTL(24), NULL));
2849:   if (mumps->id.ICNTL(24)) mumps->id.ICNTL(13) = 1; /* turn-off ScaLAPACK to help with the correct detection of null pivots */

2851:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_25", "ICNTL(25): computes a solution of a deficient matrix and a null space basis", "None", mumps->id.ICNTL(25), &mumps->id.ICNTL(25), NULL));
2852:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_26", "ICNTL(26): drives the solution phase if a Schur complement matrix", "None", mumps->id.ICNTL(26), &mumps->id.ICNTL(26), NULL));
2853:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_27", "ICNTL(27): controls the blocking size for multiple right-hand sides", "None", mumps->id.ICNTL(27), &mumps->id.ICNTL(27), NULL));
2854:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_28", "ICNTL(28): use 1 for sequential analysis and ICNTL(7) ordering, or 2 for parallel analysis and ICNTL(29) ordering", "None", mumps->id.ICNTL(28), &mumps->id.ICNTL(28), NULL));
2855:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_29", "ICNTL(29): parallel ordering 1 = PTScotch, 2 = ParMETIS", "None", mumps->id.ICNTL(29), &mumps->id.ICNTL(29), NULL));
2856:   /* PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_30","ICNTL(30): compute user-specified set of entries in inv(A)","None",mumps->id.ICNTL(30),&mumps->id.ICNTL(30),NULL)); */ /* call MatMumpsGetInverse() directly */
2857:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_31", "ICNTL(31): indicates which factors may be discarded during factorization", "None", mumps->id.ICNTL(31), &mumps->id.ICNTL(31), NULL));
2858:   /* PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_32","ICNTL(32): performs the forward elimination of the right-hand sides during factorization","None",mumps->id.ICNTL(32),&mumps->id.ICNTL(32),NULL));  -- not supported by PETSc API */
2859:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_33", "ICNTL(33): compute determinant", "None", mumps->id.ICNTL(33), &mumps->id.ICNTL(33), NULL));
2860:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_35", "ICNTL(35): activates Block Low Rank (BLR) based factorization", "None", mumps->id.ICNTL(35), &mumps->id.ICNTL(35), NULL));
2861:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_36", "ICNTL(36): choice of BLR factorization variant", "None", mumps->id.ICNTL(36), &mumps->id.ICNTL(36), NULL));
2862:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_37", "ICNTL(37): compression of the contribution blocks (CB)", "None", mumps->id.ICNTL(37), &mumps->id.ICNTL(37), NULL));
2863:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_38", "ICNTL(38): estimated compression rate of LU factors with BLR", "None", mumps->id.ICNTL(38), &mumps->id.ICNTL(38), NULL));
2864:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_40", "ICNTL(40): adaptive BLR precision feature", "None", mumps->id.ICNTL(40), &mumps->id.ICNTL(40), NULL));
2865:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_47", "ICNTL(47): single precision factorization in a double precision instance", "None", mumps->id.ICNTL(47), &mumps->id.ICNTL(47), NULL));
2866:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_48", "ICNTL(48): multithreading with tree parallelism", "None", mumps->id.ICNTL(48), &mumps->id.ICNTL(48), NULL));
2867:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_49", "ICNTL(49): compact workarray at the end of factorization phase", "None", mumps->id.ICNTL(49), &mumps->id.ICNTL(49), NULL));
2868:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_56", "ICNTL(56): postponing and rank-revealing factorization", "None", mumps->id.ICNTL(56), &mumps->id.ICNTL(56), NULL));
2869:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_58", "ICNTL(58): defines options for symbolic factorization", "None", mumps->id.ICNTL(58), &mumps->id.ICNTL(58), NULL));

2871:   PetscCall(PetscOptionsReal("-mat_mumps_cntl_1", "CNTL(1): relative pivoting threshold", "None", (PetscReal)ID_CNTL_GET(mumps->id, 1), &cntl, &flg));
2872:   if (flg) ID_CNTL_SET(mumps->id, 1, cntl);
2873:   PetscCall(PetscOptionsReal("-mat_mumps_cntl_2", "CNTL(2): stopping criterion of refinement", "None", (PetscReal)ID_CNTL_GET(mumps->id, 2), &cntl, &flg));
2874:   if (flg) ID_CNTL_SET(mumps->id, 2, cntl);
2875:   PetscCall(PetscOptionsReal("-mat_mumps_cntl_3", "CNTL(3): absolute pivoting threshold", "None", (PetscReal)ID_CNTL_GET(mumps->id, 3), &cntl, &flg));
2876:   if (flg) ID_CNTL_SET(mumps->id, 3, cntl);
2877:   PetscCall(PetscOptionsReal("-mat_mumps_cntl_4", "CNTL(4): value for static pivoting", "None", (PetscReal)ID_CNTL_GET(mumps->id, 4), &cntl, &flg));
2878:   if (flg) ID_CNTL_SET(mumps->id, 4, cntl);
2879:   PetscCall(PetscOptionsReal("-mat_mumps_cntl_5", "CNTL(5): fixation for null pivots", "None", (PetscReal)ID_CNTL_GET(mumps->id, 5), &cntl, &flg));
2880:   if (flg) ID_CNTL_SET(mumps->id, 5, cntl);
2881:   PetscCall(PetscOptionsReal("-mat_mumps_cntl_7", "CNTL(7): dropping parameter used during BLR", "None", (PetscReal)ID_CNTL_GET(mumps->id, 7), &cntl, &flg));
2882:   if (flg) ID_CNTL_SET(mumps->id, 7, cntl);

2884:   PetscCall(PetscOptionsIntArray("-mat_mumps_view_info", "request INFO local to each processor", "", info, &ninfo, NULL));
2885:   if (ninfo) {
2886:     PetscCheck(ninfo <= 80, PETSC_COMM_SELF, PETSC_ERR_USER, "number of INFO %" PetscInt_FMT " must <= 80", ninfo);
2887:     PetscCall(PetscMalloc1(ninfo, &mumps->info));
2888:     mumps->ninfo = ninfo;
2889:     for (i = 0; i < ninfo; i++) {
2890:       PetscCheck(info[i] >= 0 && info[i] <= 80, PETSC_COMM_SELF, PETSC_ERR_USER, "index of INFO %" PetscInt_FMT " must between 1 and 80", ninfo);
2891:       mumps->info[i] = info[i];
2892:     }
2893:   }
2894:   PetscOptionsEnd();
2895:   PetscFunctionReturn(PETSC_SUCCESS);
2896: }

2898: static PetscErrorCode MatFactorSymbolic_MUMPS_ReportIfError(Mat F, Mat A, PETSC_UNUSED const MatFactorInfo *info, Mat_MUMPS *mumps)
2899: {
2900:   PetscFunctionBegin;
2901:   if (mumps->id.INFOG(1) < 0) {
2902:     PetscCheck(!A->erroriffailure, PETSC_COMM_SELF, PETSC_ERR_LIB, "MUMPS error in analysis: INFOG(1)=%d, INFO(2)=%d " MUMPS_MANUALS, mumps->id.INFOG(1), mumps->id.INFO(2));
2903:     if (mumps->id.INFOG(1) == -6) {
2904:       PetscCall(PetscInfo(F, "MUMPS error in analysis: matrix is singular, INFOG(1)=%d, INFO(2)=%d\n", mumps->id.INFOG(1), mumps->id.INFO(2)));
2905:       F->factorerrortype = MAT_FACTOR_STRUCT_ZEROPIVOT;
2906:     } else if (mumps->id.INFOG(1) == -5 || mumps->id.INFOG(1) == -7) {
2907:       PetscCall(PetscInfo(F, "MUMPS error in analysis: problem with work array, INFOG(1)=%d, INFO(2)=%d\n", mumps->id.INFOG(1), mumps->id.INFO(2)));
2908:       F->factorerrortype = MAT_FACTOR_OUTMEMORY;
2909:     } else {
2910:       PetscCall(PetscInfo(F, "MUMPS error in analysis: INFOG(1)=%d, INFO(2)=%d " MUMPS_MANUALS "\n", mumps->id.INFOG(1), mumps->id.INFO(2)));
2911:       F->factorerrortype = MAT_FACTOR_OTHER;
2912:     }
2913:   }
2914:   if (!mumps->id.n) F->factorerrortype = MAT_FACTOR_NOERROR;
2915:   PetscFunctionReturn(PETSC_SUCCESS);
2916: }

2918: static PetscErrorCode MatLUFactorSymbolic_AIJMUMPS(Mat F, Mat A, IS r, PETSC_UNUSED IS c, const MatFactorInfo *info)
2919: {
2920:   Mat_MUMPS     *mumps = (Mat_MUMPS *)F->data;
2921:   Vec            b;
2922:   const PetscInt M = A->rmap->N;

2924:   PetscFunctionBegin;
2925:   if (mumps->matstruc == SAME_NONZERO_PATTERN) {
2926:     /* F is assembled by a previous call of MatLUFactorSymbolic_AIJMUMPS() */
2927:     PetscFunctionReturn(PETSC_SUCCESS);
2928:   }

2930:   /* Set MUMPS options from the options database */
2931:   PetscCall(MatSetFromOptions_MUMPS(F, A));

2933:   PetscCall((*mumps->ConvertToTriples)(A, 1, MAT_INITIAL_MATRIX, mumps));
2934:   PetscCall(MatMumpsGatherNonzerosOnMaster(MAT_INITIAL_MATRIX, mumps));
2935:   PetscCall(MatMumpsEnsureSchurArray_Private(F));

2937:   /* analysis phase */
2938:   mumps->id.job = JOB_FACTSYMBOLIC;
2939:   PetscCall(PetscMUMPSIntCast(M, &mumps->id.n));
2940:   switch (mumps->id.ICNTL(18)) {
2941:   case 0: /* centralized assembled matrix input */
2942:     if (!mumps->myid) {
2943:       mumps->id.nnz = mumps->nnz;
2944:       mumps->id.irn = mumps->irn;
2945:       mumps->id.jcn = mumps->jcn;
2946:       if (1 < mumps->id.ICNTL(6) && mumps->id.ICNTL(6) < 7) PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, mumps->nnz, mumps->val, mumps->id.precision, &mumps->id.a_len, &mumps->id.a));
2947:       if (r && mumps->id.ICNTL(7) == 7 && !F->schur) {
2948:         mumps->id.ICNTL(7) = 1;
2949:         if (!mumps->myid) {
2950:           const PetscInt *idx;

2952:           PetscCall(PetscMalloc1(M, &mumps->id.perm_in));
2953:           PetscCall(ISGetIndices(r, &idx));
2954:           for (PetscInt i = 0; i < M; i++) PetscCall(PetscMUMPSIntCast(idx[i] + 1, &mumps->id.perm_in[i])); /* perm_in[]: start from 1, not 0! */
2955:           PetscCall(ISRestoreIndices(r, &idx));
2956:         }
2957:       }
2958:     }
2959:     break;
2960:   case 3: /* distributed assembled matrix input (size>1) */
2961:     mumps->id.nnz_loc = mumps->nnz;
2962:     mumps->id.irn_loc = mumps->irn;
2963:     mumps->id.jcn_loc = mumps->jcn;
2964:     if (1 < mumps->id.ICNTL(6) && mumps->id.ICNTL(6) < 7) PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, mumps->nnz, mumps->val, mumps->id.precision, &mumps->id.a_loc_len, &mumps->id.a_loc));
2965:     if (mumps->ICNTL20 == 0) { /* Centralized rhs. Create scatter scat_rhs for repeated use in MatSolve() */
2966:       PetscCall(MatCreateVecs(A, NULL, &b));
2967:       PetscCall(VecScatterCreateToZero(b, &mumps->scat_rhs, &mumps->b_seq));
2968:       PetscCall(VecDestroy(&b));
2969:     }
2970:     break;
2971:   }
2972:   if (A->rmap->N && A->cmap->N) {
2973:     PetscMUMPS_c(mumps);
2974:     PetscCall(MatFactorSymbolic_MUMPS_ReportIfError(F, A, info, mumps));
2975:   }
2976:   F->ops->lufactornumeric   = MatFactorNumeric_MUMPS;
2977:   F->ops->solve             = MatSolve_MUMPS;
2978:   F->ops->solvetranspose    = MatSolveTranspose_MUMPS;
2979:   F->ops->matsolve          = MatMatSolve_MUMPS;
2980:   F->ops->mattransposesolve = MatMatTransposeSolve_MUMPS;
2981:   F->ops->matsolvetranspose = MatMatSolveTranspose_MUMPS;

2983:   mumps->matstruc = SAME_NONZERO_PATTERN;
2984:   PetscFunctionReturn(PETSC_SUCCESS);
2985: }

2987: /* Note the PETSc r and c permutations are ignored */
2988: static PetscErrorCode MatLUFactorSymbolic_BAIJMUMPS(Mat F, Mat A, PETSC_UNUSED IS r, PETSC_UNUSED IS c, const MatFactorInfo *info)
2989: {
2990:   Mat_MUMPS     *mumps = (Mat_MUMPS *)F->data;
2991:   Vec            b;
2992:   const PetscInt M = A->rmap->N;

2994:   PetscFunctionBegin;
2995:   if (mumps->matstruc == SAME_NONZERO_PATTERN) {
2996:     /* F is assembled by a previous call of MatLUFactorSymbolic_BAIJMUMPS() */
2997:     PetscFunctionReturn(PETSC_SUCCESS);
2998:   }

3000:   /* Set MUMPS options from the options database */
3001:   PetscCall(MatSetFromOptions_MUMPS(F, A));

3003:   PetscCall((*mumps->ConvertToTriples)(A, 1, MAT_INITIAL_MATRIX, mumps));
3004:   PetscCall(MatMumpsGatherNonzerosOnMaster(MAT_INITIAL_MATRIX, mumps));
3005:   PetscCall(MatMumpsEnsureSchurArray_Private(F));

3007:   /* analysis phase */
3008:   mumps->id.job = JOB_FACTSYMBOLIC;
3009:   PetscCall(PetscMUMPSIntCast(M, &mumps->id.n));
3010:   switch (mumps->id.ICNTL(18)) {
3011:   case 0: /* centralized assembled matrix input */
3012:     if (!mumps->myid) {
3013:       mumps->id.nnz = mumps->nnz;
3014:       mumps->id.irn = mumps->irn;
3015:       mumps->id.jcn = mumps->jcn;
3016:       if (1 < mumps->id.ICNTL(6) && mumps->id.ICNTL(6) < 7) PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, mumps->nnz, mumps->val, mumps->id.precision, &mumps->id.a_len, &mumps->id.a));
3017:     }
3018:     break;
3019:   case 3: /* distributed assembled matrix input (size>1) */
3020:     mumps->id.nnz_loc = mumps->nnz;
3021:     mumps->id.irn_loc = mumps->irn;
3022:     mumps->id.jcn_loc = mumps->jcn;
3023:     if (1 < mumps->id.ICNTL(6) && mumps->id.ICNTL(6) < 7) PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, mumps->nnz, mumps->val, mumps->id.precision, &mumps->id.a_loc_len, &mumps->id.a_loc));
3024:     if (mumps->ICNTL20 == 0) { /* Centralized rhs. Create scatter scat_rhs for repeated use in MatSolve() */
3025:       PetscCall(MatCreateVecs(A, NULL, &b));
3026:       PetscCall(VecScatterCreateToZero(b, &mumps->scat_rhs, &mumps->b_seq));
3027:       PetscCall(VecDestroy(&b));
3028:     }
3029:     break;
3030:   }
3031:   if (A->rmap->N && A->cmap->N) {
3032:     PetscMUMPS_c(mumps);
3033:     PetscCall(MatFactorSymbolic_MUMPS_ReportIfError(F, A, info, mumps));
3034:   }
3035:   F->ops->lufactornumeric   = MatFactorNumeric_MUMPS;
3036:   F->ops->solve             = MatSolve_MUMPS;
3037:   F->ops->solvetranspose    = MatSolveTranspose_MUMPS;
3038:   F->ops->matsolve          = MatMatSolve_MUMPS;
3039:   F->ops->mattransposesolve = MatMatTransposeSolve_MUMPS;
3040:   F->ops->matsolvetranspose = MatMatSolveTranspose_MUMPS;

3042:   mumps->matstruc = SAME_NONZERO_PATTERN;
3043:   PetscFunctionReturn(PETSC_SUCCESS);
3044: }

3046: /* Note the PETSc r permutation and factor info are ignored */
3047: static PetscErrorCode MatCholeskyFactorSymbolic_MUMPS(Mat F, Mat A, PETSC_UNUSED IS r, const MatFactorInfo *info)
3048: {
3049:   Mat_MUMPS     *mumps = (Mat_MUMPS *)F->data;
3050:   Vec            b;
3051:   const PetscInt M = A->rmap->N;

3053:   PetscFunctionBegin;
3054:   if (mumps->matstruc == SAME_NONZERO_PATTERN) {
3055:     /* F is assembled by a previous call of MatCholeskyFactorSymbolic_MUMPS() */
3056:     PetscFunctionReturn(PETSC_SUCCESS);
3057:   }

3059:   /* Set MUMPS options from the options database */
3060:   PetscCall(MatSetFromOptions_MUMPS(F, A));

3062:   PetscCall((*mumps->ConvertToTriples)(A, 1, MAT_INITIAL_MATRIX, mumps));
3063:   PetscCall(MatMumpsGatherNonzerosOnMaster(MAT_INITIAL_MATRIX, mumps));
3064:   PetscCall(MatMumpsEnsureSchurArray_Private(F));

3066:   /* analysis phase */
3067:   mumps->id.job = JOB_FACTSYMBOLIC;
3068:   PetscCall(PetscMUMPSIntCast(M, &mumps->id.n));
3069:   switch (mumps->id.ICNTL(18)) {
3070:   case 0: /* centralized assembled matrix input */
3071:     if (!mumps->myid) {
3072:       mumps->id.nnz = mumps->nnz;
3073:       mumps->id.irn = mumps->irn;
3074:       mumps->id.jcn = mumps->jcn;
3075:       if (1 < mumps->id.ICNTL(6) && mumps->id.ICNTL(6) < 7) PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, mumps->nnz, mumps->val, mumps->id.precision, &mumps->id.a_len, &mumps->id.a));
3076:     }
3077:     break;
3078:   case 3: /* distributed assembled matrix input (size>1) */
3079:     mumps->id.nnz_loc = mumps->nnz;
3080:     mumps->id.irn_loc = mumps->irn;
3081:     mumps->id.jcn_loc = mumps->jcn;
3082:     if (1 < mumps->id.ICNTL(6) && mumps->id.ICNTL(6) < 7) PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, mumps->nnz, mumps->val, mumps->id.precision, &mumps->id.a_loc_len, &mumps->id.a_loc));
3083:     if (mumps->ICNTL20 == 0) { /* Centralized rhs. Create scatter scat_rhs for repeated use in MatSolve() */
3084:       PetscCall(MatCreateVecs(A, NULL, &b));
3085:       PetscCall(VecScatterCreateToZero(b, &mumps->scat_rhs, &mumps->b_seq));
3086:       PetscCall(VecDestroy(&b));
3087:     }
3088:     break;
3089:   }
3090:   if (A->rmap->N && A->cmap->N) {
3091:     PetscMUMPS_c(mumps);
3092:     PetscCall(MatFactorSymbolic_MUMPS_ReportIfError(F, A, info, mumps));
3093:   }
3094:   F->ops->choleskyfactornumeric = MatFactorNumeric_MUMPS;
3095:   F->ops->solve                 = MatSolve_MUMPS;
3096:   F->ops->solvetranspose        = MatSolve_MUMPS;
3097:   F->ops->matsolve              = MatMatSolve_MUMPS;
3098:   F->ops->mattransposesolve     = MatMatTransposeSolve_MUMPS;
3099:   F->ops->matsolvetranspose     = MatMatSolveTranspose_MUMPS;
3100: #if PetscDefined(USE_COMPLEX)
3101:   F->ops->getinertia = NULL;
3102: #else
3103:   F->ops->getinertia = MatGetInertia_SBAIJMUMPS;
3104: #endif

3106:   mumps->matstruc = SAME_NONZERO_PATTERN;
3107:   PetscFunctionReturn(PETSC_SUCCESS);
3108: }

3110: static PetscErrorCode MatView_MUMPS(Mat A, PetscViewer viewer)
3111: {
3112:   PetscBool         isascii;
3113:   PetscViewerFormat format;
3114:   Mat_MUMPS        *mumps = (Mat_MUMPS *)A->data;

3116:   PetscFunctionBegin;
3117:   /* check if matrix is mumps type */
3118:   if (A->ops->solve != MatSolve_MUMPS) PetscFunctionReturn(PETSC_SUCCESS);

3120:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
3121:   if (isascii) {
3122:     PetscCall(PetscViewerGetFormat(viewer, &format));
3123:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
3124:       PetscCall(PetscViewerASCIIPrintf(viewer, "MUMPS run parameters:\n"));
3125:       PetscCall(PetscViewerASCIIPrintf(viewer, "  precision:                           %s\n", PetscPrecisionTypes[mumps->id.precision]));
3126:       if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
3127:         PetscCall(PetscViewerASCIIPrintf(viewer, "  SYM (matrix type):                   %d\n", mumps->id.sym));
3128:         PetscCall(PetscViewerASCIIPrintf(viewer, "  PAR (host participation):            %d\n", mumps->id.par));
3129:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(1) (output for error):         %d\n", mumps->id.ICNTL(1)));
3130:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(2) (output of diagnostic msg): %d\n", mumps->id.ICNTL(2)));
3131:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(3) (output for global info):   %d\n", mumps->id.ICNTL(3)));
3132:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(4) (level of printing):        %d\n", mumps->id.ICNTL(4)));
3133:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(5) (input mat struct):         %d\n", mumps->id.ICNTL(5)));
3134:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(6) (matrix prescaling):        %d\n", mumps->id.ICNTL(6)));
3135:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(7) (sequential matrix ordering):%d\n", mumps->id.ICNTL(7)));
3136:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(8) (scaling strategy):         %d\n", mumps->id.ICNTL(8)));
3137:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(10) (max num of refinements):  %d\n", mumps->id.ICNTL(10)));
3138:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(11) (error analysis):          %d\n", mumps->id.ICNTL(11)));
3139:         if (mumps->id.ICNTL(11) > 0) {
3140:           PetscCall(PetscViewerASCIIPrintf(viewer, "    RINFOG(4) (inf norm of input mat):        %g\n", (double)ID_RINFOG_GET(mumps->id, 4)));
3141:           PetscCall(PetscViewerASCIIPrintf(viewer, "    RINFOG(5) (inf norm of solution):         %g\n", (double)ID_RINFOG_GET(mumps->id, 5)));
3142:           PetscCall(PetscViewerASCIIPrintf(viewer, "    RINFOG(6) (inf norm of residual):         %g\n", (double)ID_RINFOG_GET(mumps->id, 6)));
3143:           PetscCall(PetscViewerASCIIPrintf(viewer, "    RINFOG(7),RINFOG(8) (backward error est): %g, %g\n", (double)ID_RINFOG_GET(mumps->id, 7), (double)ID_RINFOG_GET(mumps->id, 8)));
3144:           PetscCall(PetscViewerASCIIPrintf(viewer, "    RINFOG(9) (error estimate):               %g\n", (double)ID_RINFOG_GET(mumps->id, 9)));
3145:           PetscCall(PetscViewerASCIIPrintf(viewer, "    RINFOG(10),RINFOG(11)(condition numbers): %g, %g\n", (double)ID_RINFOG_GET(mumps->id, 10), (double)ID_RINFOG_GET(mumps->id, 11)));
3146:         }
3147:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(12) (efficiency control):                         %d\n", mumps->id.ICNTL(12)));
3148:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(13) (sequential factorization of the root node):  %d\n", mumps->id.ICNTL(13)));
3149:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(14) (percentage of estimated workspace increase): %d\n", mumps->id.ICNTL(14)));
3150:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(15) (compression of the input matrix):            %d\n", mumps->id.ICNTL(15)));
3151:         /* ICNTL(15-17) not used */
3152:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(18) (input mat struct):                           %d\n", mumps->id.ICNTL(18)));
3153:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(19) (Schur complement info):                      %d\n", mumps->id.ICNTL(19)));
3154:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(20) (RHS sparse pattern):                         %d\n", mumps->id.ICNTL(20)));
3155:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(21) (solution struct):                            %d\n", mumps->id.ICNTL(21)));
3156:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(22) (in-core/out-of-core facility):               %d\n", mumps->id.ICNTL(22)));
3157:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(23) (max size of memory allocated locally):       %d\n", mumps->id.ICNTL(23)));

3159:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(24) (detection of null pivot rows):               %d\n", mumps->id.ICNTL(24)));
3160:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(25) (computation of a null space basis):          %d\n", mumps->id.ICNTL(25)));
3161:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(26) (Schur options for RHS or solution):          %d\n", mumps->id.ICNTL(26)));
3162:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(27) (blocking size for multiple RHS):             %d\n", mumps->id.ICNTL(27)));
3163:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(28) (use parallel or sequential ordering):        %d\n", mumps->id.ICNTL(28)));
3164:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(29) (parallel ordering):                          %d\n", mumps->id.ICNTL(29)));

3166:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(30) (user-specified set of entries in inv(A)):    %d\n", mumps->id.ICNTL(30)));
3167:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(31) (factors is discarded in the solve phase):    %d\n", mumps->id.ICNTL(31)));
3168:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(33) (compute determinant):                        %d\n", mumps->id.ICNTL(33)));
3169:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(35) (activate BLR based factorization):           %d\n", mumps->id.ICNTL(35)));
3170:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(36) (choice of BLR factorization variant):        %d\n", mumps->id.ICNTL(36)));
3171:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(37) (compression of the contribution blocks):     %d\n", mumps->id.ICNTL(37)));
3172:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(38) (estimated compression rate of LU factors):   %d\n", mumps->id.ICNTL(38)));
3173:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(40) (adaptive BLR precision feature):             %d\n", mumps->id.ICNTL(40)));
3174:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(47) (single precision factorization in a double precision instance): %d\n", mumps->id.ICNTL(47)));
3175:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(48) (multithreading with tree parallelism):       %d\n", mumps->id.ICNTL(48)));
3176:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(49) (compact workarray at the end of factorization phase):%d\n", mumps->id.ICNTL(49)));
3177:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(56) (postponing and rank-revealing factorization):%d\n", mumps->id.ICNTL(56)));
3178:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(58) (options for symbolic factorization):         %d\n", mumps->id.ICNTL(58)));

3180:         PetscCall(PetscViewerASCIIPrintf(viewer, "  CNTL(1) (relative pivoting threshold):      %g\n", (double)ID_CNTL_GET(mumps->id, 1)));
3181:         PetscCall(PetscViewerASCIIPrintf(viewer, "  CNTL(2) (stopping criterion of refinement): %g\n", (double)ID_CNTL_GET(mumps->id, 2)));
3182:         PetscCall(PetscViewerASCIIPrintf(viewer, "  CNTL(3) (absolute pivoting threshold):      %g\n", (double)ID_CNTL_GET(mumps->id, 3)));
3183:         PetscCall(PetscViewerASCIIPrintf(viewer, "  CNTL(4) (value of static pivoting):         %g\n", (double)ID_CNTL_GET(mumps->id, 4)));
3184:         PetscCall(PetscViewerASCIIPrintf(viewer, "  CNTL(5) (fixation for null pivots):         %g\n", (double)ID_CNTL_GET(mumps->id, 5)));
3185:         PetscCall(PetscViewerASCIIPrintf(viewer, "  CNTL(7) (dropping parameter for BLR):       %g\n", (double)ID_CNTL_GET(mumps->id, 7)));

3187:         /* information local to each processor */
3188:         PetscCall(PetscViewerASCIIPrintf(viewer, "  RINFO(1) (local estimated flops for the elimination after analysis):\n"));
3189:         PetscCall(PetscViewerASCIIPushSynchronized(viewer));
3190:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "    [%d] %g\n", mumps->myid, (double)ID_RINFO_GET(mumps->id, 1)));
3191:         PetscCall(PetscViewerFlush(viewer));
3192:         PetscCall(PetscViewerASCIIPrintf(viewer, "  RINFO(2) (local estimated flops for the assembly after factorization):\n"));
3193:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "    [%d] %g\n", mumps->myid, (double)ID_RINFO_GET(mumps->id, 2)));
3194:         PetscCall(PetscViewerFlush(viewer));
3195:         PetscCall(PetscViewerASCIIPrintf(viewer, "  RINFO(3) (local estimated flops for the elimination after factorization):\n"));
3196:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "    [%d] %g\n", mumps->myid, (double)ID_RINFO_GET(mumps->id, 3)));
3197:         PetscCall(PetscViewerFlush(viewer));

3199:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFO(15) (estimated size of (in MB) MUMPS internal data for running numerical factorization):\n"));
3200:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "    [%d] %d\n", mumps->myid, mumps->id.INFO(15)));
3201:         PetscCall(PetscViewerFlush(viewer));

3203:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFO(16) (size of (in MB) MUMPS internal data used during numerical factorization):\n"));
3204:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "    [%d] %d\n", mumps->myid, mumps->id.INFO(16)));
3205:         PetscCall(PetscViewerFlush(viewer));

3207:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFO(23) (num of pivots eliminated on this processor after factorization):\n"));
3208:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "    [%d] %d\n", mumps->myid, mumps->id.INFO(23)));
3209:         PetscCall(PetscViewerFlush(viewer));

3211:         if (mumps->ninfo && mumps->ninfo <= 80) {
3212:           for (PetscInt i = 0; i < mumps->ninfo; i++) {
3213:             PetscCall(PetscViewerASCIIPrintf(viewer, "  INFO(%" PetscInt_FMT "):\n", mumps->info[i]));
3214:             PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "    [%d] %d\n", mumps->myid, mumps->id.INFO(mumps->info[i])));
3215:             PetscCall(PetscViewerFlush(viewer));
3216:           }
3217:         }
3218:         PetscCall(PetscViewerASCIIPopSynchronized(viewer));
3219:       } else PetscCall(PetscViewerASCIIPrintf(viewer, "  Use -%sksp_view ::ascii_info_detail to display information for all processes\n", ((PetscObject)A)->prefix ? ((PetscObject)A)->prefix : ""));

3221:       if (mumps->myid == 0) { /* information from the host */
3222:         PetscCall(PetscViewerASCIIPrintf(viewer, "  RINFOG(1) (global estimated flops for the elimination after analysis): %g\n", (double)ID_RINFOG_GET(mumps->id, 1)));
3223:         PetscCall(PetscViewerASCIIPrintf(viewer, "  RINFOG(2) (global estimated flops for the assembly after factorization): %g\n", (double)ID_RINFOG_GET(mumps->id, 2)));
3224:         PetscCall(PetscViewerASCIIPrintf(viewer, "  RINFOG(3) (global estimated flops for the elimination after factorization): %g\n", (double)ID_RINFOG_GET(mumps->id, 3)));
3225:         PetscCall(PetscViewerASCIIPrintf(viewer, "  (RINFOG(12) RINFOG(13))*2^INFOG(34) (determinant): (%g,%g)*(2^%d)\n", (double)ID_RINFOG_GET(mumps->id, 12), (double)ID_RINFOG_GET(mumps->id, 13), mumps->id.INFOG(34)));

3227:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(3) (estimated real workspace for factors on all processors after analysis): %d\n", mumps->id.INFOG(3)));
3228:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(4) (estimated integer workspace for factors on all processors after analysis): %d\n", mumps->id.INFOG(4)));
3229:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(5) (estimated maximum front size in the complete tree): %d\n", mumps->id.INFOG(5)));
3230:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(6) (number of nodes in the complete tree): %d\n", mumps->id.INFOG(6)));
3231:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(7) (ordering option effectively used after analysis): %d\n", mumps->id.INFOG(7)));
3232:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(8) (structural symmetry in percent of the permuted matrix after analysis): %d\n", mumps->id.INFOG(8)));
3233:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(9) (total real/complex workspace to store the matrix factors after factorization): %d\n", mumps->id.INFOG(9)));
3234:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(10) (total integer space store the matrix factors after factorization): %d\n", mumps->id.INFOG(10)));
3235:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(11) (order of largest frontal matrix after factorization): %d\n", mumps->id.INFOG(11)));
3236:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(12) (number of off-diagonal pivots): %d\n", mumps->id.INFOG(12)));
3237:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(13) (number of delayed pivots after factorization): %d\n", mumps->id.INFOG(13)));
3238:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(14) (number of memory compress after factorization): %d\n", mumps->id.INFOG(14)));
3239:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(15) (number of steps of iterative refinement after solution): %d\n", mumps->id.INFOG(15)));
3240:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(16) (estimated size (in MB) of all MUMPS internal data for factorization after analysis: value on the most memory consuming processor): %d\n", mumps->id.INFOG(16)));
3241:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(17) (estimated size of all MUMPS internal data for factorization after analysis: sum over all processors): %d\n", mumps->id.INFOG(17)));
3242:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(18) (size of all MUMPS internal data allocated during factorization: value on the most memory consuming processor): %d\n", mumps->id.INFOG(18)));
3243:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(19) (size of all MUMPS internal data allocated during factorization: sum over all processors): %d\n", mumps->id.INFOG(19)));
3244:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(20) (estimated number of entries in the factors): %d\n", mumps->id.INFOG(20)));
3245:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(21) (size in MB of memory effectively used during factorization - value on the most memory consuming processor): %d\n", mumps->id.INFOG(21)));
3246:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(22) (size in MB of memory effectively used during factorization - sum over all processors): %d\n", mumps->id.INFOG(22)));
3247:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(23) (after analysis: value of ICNTL(6) effectively used): %d\n", mumps->id.INFOG(23)));
3248:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(24) (after analysis: value of ICNTL(12) effectively used): %d\n", mumps->id.INFOG(24)));
3249:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(25) (after factorization: number of pivots modified by static pivoting): %d\n", mumps->id.INFOG(25)));
3250:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(28) (after factorization: number of null pivots encountered): %d\n", mumps->id.INFOG(28)));
3251:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(29) (after factorization: effective number of entries in the factors (sum over all processors)): %d\n", mumps->id.INFOG(29)));
3252:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(30, 31) (after solution: size in Mbytes of memory used during solution phase): %d, %d\n", mumps->id.INFOG(30), mumps->id.INFOG(31)));
3253:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(32) (after analysis: type of analysis done): %d\n", mumps->id.INFOG(32)));
3254:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(33) (value used for ICNTL(8)): %d\n", mumps->id.INFOG(33)));
3255:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(34) (exponent of the determinant if determinant is requested): %d\n", mumps->id.INFOG(34)));
3256:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(35) (after factorization: number of entries taking into account BLR factor compression - sum over all processors): %d\n", mumps->id.INFOG(35)));
3257:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(36) (after analysis: estimated size of all MUMPS internal data for running BLR in-core - value on the most memory consuming processor): %d\n", mumps->id.INFOG(36)));
3258:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(37) (after analysis: estimated size of all MUMPS internal data for running BLR in-core - sum over all processors): %d\n", mumps->id.INFOG(37)));
3259:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(38) (after analysis: estimated size of all MUMPS internal data for running BLR out-of-core - value on the most memory consuming processor): %d\n", mumps->id.INFOG(38)));
3260:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(39) (after analysis: estimated size of all MUMPS internal data for running BLR out-of-core - sum over all processors): %d\n", mumps->id.INFOG(39)));
3261:       }
3262:     }
3263:   }
3264:   PetscFunctionReturn(PETSC_SUCCESS);
3265: }

3267: static PetscErrorCode MatGetInfo_MUMPS(Mat A, PETSC_UNUSED MatInfoType flag, MatInfo *info)
3268: {
3269:   Mat_MUMPS *mumps = (Mat_MUMPS *)A->data;

3271:   PetscFunctionBegin;
3272:   info->block_size        = 1.0;
3273:   info->nz_allocated      = mumps->id.INFOG(20) >= 0 ? mumps->id.INFOG(20) : -1.0e6 * mumps->id.INFOG(20);
3274:   info->nz_used           = mumps->id.INFOG(20) >= 0 ? mumps->id.INFOG(20) : -1.0e6 * mumps->id.INFOG(20);
3275:   info->nz_unneeded       = 0.0;
3276:   info->assemblies        = 0.0;
3277:   info->mallocs           = 0.0;
3278:   info->memory            = 0.0;
3279:   info->fill_ratio_given  = 0;
3280:   info->fill_ratio_needed = 0;
3281:   info->factor_mallocs    = 0;
3282:   PetscFunctionReturn(PETSC_SUCCESS);
3283: }

3285: static PetscErrorCode MatFactorSetSchurIS_MUMPS(Mat F, IS is)
3286: {
3287:   Mat_MUMPS      *mumps = (Mat_MUMPS *)F->data;
3288:   const PetscInt *idxs;
3289:   PetscInt        size, i;

3291:   PetscFunctionBegin;
3292:   PetscCall(MatMumpsResetSchur_Private(F));
3293:   if (!is) PetscFunctionReturn(PETSC_SUCCESS);
3294:   /* Schur complement matrix */
3295:   PetscCall(ISGetLocalSize(is, &size));
3296:   PetscCall(MatCreateSeqDense(PETSC_COMM_SELF, size, size, NULL, &F->schur));
3297:   // don't allocate mumps->id.schur[] now as its precision is yet to be known
3298:   PetscCall(PetscMUMPSIntCast(size, &mumps->id.size_schur));
3299:   PetscCall(PetscMUMPSIntCast(size, &mumps->id.schur_lld));
3300:   if (mumps->sym == 1) PetscCall(MatSetOption(F->schur, MAT_SPD, PETSC_TRUE));

3302:   /* MUMPS expects Fortran style indices */
3303:   PetscCall(PetscMalloc1(size, &mumps->id.listvar_schur));
3304:   PetscCall(ISGetIndices(is, &idxs));
3305:   for (i = 0; i < size; i++) PetscCall(PetscMUMPSIntCast(idxs[i] + 1, &mumps->id.listvar_schur[i]));
3306:   PetscCall(ISRestoreIndices(is, &idxs));
3307:   /* set a special value of ICNTL (not handled my MUMPS) to be used in the solve phase by PETSc */
3308:   if (mumps->id.icntl) mumps->id.ICNTL(26) = -1;
3309:   else mumps->ICNTL26 = -1;
3310:   PetscFunctionReturn(PETSC_SUCCESS);
3311: }

3313: static PetscErrorCode MatFactorCreateSchurComplement_MUMPS(Mat F, Mat *S)
3314: {
3315:   Mat          St;
3316:   Mat_MUMPS   *mumps = (Mat_MUMPS *)F->data;
3317:   PetscScalar *array;
3318:   PetscInt     i, j, N = mumps->id.size_schur;

3320:   PetscFunctionBegin;
3321:   PetscCheck(mumps->id.ICNTL(19), PetscObjectComm((PetscObject)F), PETSC_ERR_ORDER, "Schur complement mode not selected! Call MatFactorSetSchurIS() to enable it");
3322:   PetscCall(MatCreate(PETSC_COMM_SELF, &St));
3323:   PetscCall(MatSetSizes(St, PETSC_DECIDE, PETSC_DECIDE, mumps->id.size_schur, mumps->id.size_schur));
3324:   PetscCall(MatSetType(St, MATDENSE));
3325:   PetscCall(MatSetUp(St));
3326:   PetscCall(MatDenseGetArray(St, &array));
3327:   PetscCall(MatMumpsEnsureSchurArray_Private(F));
3328:   if (!mumps->sym) {                /* MUMPS always returns a full matrix */
3329:     if (mumps->id.ICNTL(19) == 1) { /* stored by rows */
3330:       for (i = 0; i < N; i++) {
3331:         for (j = 0; j < N; j++) array[j * N + i] = ID_FIELD_GET(mumps->id, schur, i * N + j);
3332:       }
3333:     } else { /* stored by columns */
3334:       PetscCall(MatMumpsCastMumpsScalarArray(N * N, mumps->id.precision, mumps->id.schur, array));
3335:     }
3336:   } else {                          /* either full or lower-triangular (not packed) */
3337:     if (mumps->id.ICNTL(19) == 2) { /* lower triangular stored by columns */
3338:       for (i = 0; i < N; i++) {
3339:         for (j = i; j < N; j++) array[i * N + j] = array[j * N + i] = ID_FIELD_GET(mumps->id, schur, i * N + j);
3340:       }
3341:     } else if (mumps->id.ICNTL(19) == 3) { /* full matrix */
3342:       PetscCall(MatMumpsCastMumpsScalarArray(N * N, mumps->id.precision, mumps->id.schur, array));
3343:     } else { /* ICNTL(19) == 1 lower triangular stored by rows */
3344:       for (i = 0; i < N; i++) {
3345:         for (j = 0; j < i + 1; j++) array[i * N + j] = array[j * N + i] = ID_FIELD_GET(mumps->id, schur, i * N + j);
3346:       }
3347:     }
3348:   }
3349:   PetscCall(MatDenseRestoreArray(St, &array));
3350:   *S = St;
3351:   PetscFunctionReturn(PETSC_SUCCESS);
3352: }

3354: static PetscErrorCode MatMumpsSetIcntl_MUMPS(Mat F, PetscInt icntl, PetscInt ival)
3355: {
3356:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3358:   PetscFunctionBegin;
3359:   PetscCheck((icntl >= 1 && icntl <= 38) || icntl == 40 || icntl == 47 || icntl == 48 || icntl == 49 || icntl == 56 || icntl == 58, PetscObjectComm((PetscObject)F), PETSC_ERR_ARG_WRONG, "Unsupported ICNTL value %" PetscInt_FMT, icntl);
3360:   if (mumps->id.job == JOB_NULL) {                                            /* need to cache icntl and ival since PetscMUMPS_c() has never been called */
3361:     PetscMUMPSInt i, nICNTL_pre = mumps->ICNTL_pre ? mumps->ICNTL_pre[0] : 0; /* number of already cached ICNTL */
3362:     for (i = 0; i < nICNTL_pre; ++i)
3363:       if (mumps->ICNTL_pre[1 + 2 * i] == icntl) break; /* is this ICNTL already cached? */
3364:     if (i == nICNTL_pre) {                             /* not already cached */
3365:       if (i > 0) PetscCall(PetscRealloc(sizeof(PetscMUMPSInt) * (2 * nICNTL_pre + 3), &mumps->ICNTL_pre));
3366:       else PetscCall(PetscCalloc(sizeof(PetscMUMPSInt) * 3, &mumps->ICNTL_pre));
3367:       mumps->ICNTL_pre[0]++;
3368:     }
3369:     mumps->ICNTL_pre[1 + 2 * i] = (PetscMUMPSInt)icntl;
3370:     PetscCall(PetscMUMPSIntCast(ival, mumps->ICNTL_pre + 2 + 2 * i));
3371:   } else PetscCall(PetscMUMPSIntCast(ival, &mumps->id.ICNTL(icntl)));
3372:   PetscFunctionReturn(PETSC_SUCCESS);
3373: }

3375: static PetscErrorCode MatMumpsGetIcntl_MUMPS(Mat F, PetscInt icntl, PetscInt *ival)
3376: {
3377:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3379:   PetscFunctionBegin;
3380:   PetscCheck((icntl >= 1 && icntl <= 38) || icntl == 40 || icntl == 47 || icntl == 48 || icntl == 49 || icntl == 56 || icntl == 58, PetscObjectComm((PetscObject)F), PETSC_ERR_ARG_WRONG, "Unsupported ICNTL value %" PetscInt_FMT, icntl);
3381:   if (mumps->id.job == JOB_NULL) {
3382:     PetscInt i, nICNTL_pre = mumps->ICNTL_pre ? mumps->ICNTL_pre[0] : 0;
3383:     *ival = 0;
3384:     for (i = 0; i < nICNTL_pre; ++i) {
3385:       if (mumps->ICNTL_pre[1 + 2 * i] == icntl) *ival = mumps->ICNTL_pre[2 + 2 * i];
3386:     }
3387:   } else *ival = mumps->id.ICNTL(icntl);
3388:   PetscFunctionReturn(PETSC_SUCCESS);
3389: }

3391: static PetscErrorCode MatMumpsSetCntl_MUMPS(Mat F, PetscInt icntl, PetscReal val)
3392: {
3393:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3395:   PetscFunctionBegin;
3396:   PetscCheck(icntl >= 1 && icntl <= 7, PetscObjectComm((PetscObject)F), PETSC_ERR_ARG_WRONG, "Unsupported CNTL value %" PetscInt_FMT, icntl);
3397:   if (mumps->id.job == JOB_NULL) {
3398:     PetscInt i, nCNTL_pre = mumps->CNTL_pre ? mumps->CNTL_pre[0] : 0;
3399:     for (i = 0; i < nCNTL_pre; ++i)
3400:       if (mumps->CNTL_pre[1 + 2 * i] == icntl) break;
3401:     if (i == nCNTL_pre) {
3402:       if (i > 0) PetscCall(PetscRealloc(sizeof(PetscReal) * (2 * nCNTL_pre + 3), &mumps->CNTL_pre));
3403:       else PetscCall(PetscCalloc(sizeof(PetscReal) * 3, &mumps->CNTL_pre));
3404:       mumps->CNTL_pre[0]++;
3405:     }
3406:     mumps->CNTL_pre[1 + 2 * i] = icntl;
3407:     mumps->CNTL_pre[2 + 2 * i] = val;
3408:   } else ID_CNTL_SET(mumps->id, icntl, val);
3409:   PetscFunctionReturn(PETSC_SUCCESS);
3410: }

3412: static PetscErrorCode MatMumpsGetCntl_MUMPS(Mat F, PetscInt icntl, PetscReal *val)
3413: {
3414:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3416:   PetscFunctionBegin;
3417:   PetscCheck(icntl >= 1 && icntl <= 7, PetscObjectComm((PetscObject)F), PETSC_ERR_ARG_WRONG, "Unsupported CNTL value %" PetscInt_FMT, icntl);
3418:   if (mumps->id.job == JOB_NULL) {
3419:     PetscInt i, nCNTL_pre = mumps->CNTL_pre ? mumps->CNTL_pre[0] : 0;
3420:     *val = 0.0;
3421:     for (i = 0; i < nCNTL_pre; ++i) {
3422:       if (mumps->CNTL_pre[1 + 2 * i] == icntl) *val = mumps->CNTL_pre[2 + 2 * i];
3423:     }
3424:   } else *val = ID_CNTL_GET(mumps->id, icntl);
3425:   PetscFunctionReturn(PETSC_SUCCESS);
3426: }

3428: /*@
3429:   MatMumpsSetOocTmpDir - Set MUMPS out-of-core `OOC_TMPDIR` <https://mumps-solver.org/index.php?page=doc>

3431:   Logically Collective

3433:   Input Parameters:
3434: + F      - the factored matrix obtained by calling `MatGetFactor()` with a `MatSolverType` of `MATSOLVERMUMPS` and a `MatFactorType` of `MAT_FACTOR_LU` or `MAT_FACTOR_CHOLESKY`.
3435: - tmpdir - temporary directory for out-of-core facility.

3437:   Level: beginner

3439:   Note:
3440:   To make it effective, this routine must be called before the numeric factorization, i.e., `PCSetUp()`.
3441:   If `ooc_tmpdir` is not set, MUMPS will also check the environment variable `MUMPS_OOC_TMPDIR`. But if neither was defined, it will use /tmp by default.

3443: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatMumpsGetOocTmpDir`, `MatMumpsSetIcntl()`, `MatMumpsGetIcntl()`, `MatMumpsSetCntl()`, `MatMumpsGetInfo()`, `MatMumpsGetInfog()`, `MatMumpsGetRinfo()`, `MatMumpsGetRinfog()`
3444: @*/
3445: PetscErrorCode MatMumpsSetOocTmpDir(Mat F, const char *tmpdir)
3446: {
3447:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3449:   PetscFunctionBegin;
3452:   PetscCall(PetscStrncpy(mumps->id.ooc_tmpdir, tmpdir, sizeof(((MUMPS_STRUC_C *)NULL)->ooc_tmpdir)));
3453:   PetscFunctionReturn(PETSC_SUCCESS);
3454: }

3456: /*@
3457:   MatMumpsGetOocTmpDir - Get MUMPS out-of-core `OOC_TMPDIR` <https://mumps-solver.org/index.php?page=doc>

3459:   Logically Collective

3461:   Input Parameter:
3462: . F - the factored matrix obtained by calling `MatGetFactor()` with a `MatSolverType` of `MATSOLVERMUMPS` and a `MatFactorType` of `MAT_FACTOR_LU` or `MAT_FACTOR_CHOLESKY`.

3464:   Output Parameter:
3465: . tmpdir - temporary directory for out-of-core facility.

3467:   Level: beginner

3469:   Note:
3470:   The returned string is read-only and user should not try to change it.

3472: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatMumpsSetOocTmpDir`, `MatMumpsSetIcntl()`, `MatMumpsGetIcntl()`, `MatMumpsSetCntl()`, `MatMumpsGetInfo()`, `MatMumpsGetInfog()`, `MatMumpsGetRinfo()`, `MatMumpsGetRinfog()`
3473: @*/
3474: PetscErrorCode MatMumpsGetOocTmpDir(Mat F, const char *tmpdir[])
3475: {
3476:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3478:   PetscFunctionBegin;
3481:   if (tmpdir) *tmpdir = mumps->id.ooc_tmpdir;
3482:   PetscFunctionReturn(PETSC_SUCCESS);
3483: }

3485: static PetscErrorCode MatMumpsGetInfo_MUMPS(Mat F, PetscInt icntl, PetscInt *info)
3486: {
3487:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3489:   PetscFunctionBegin;
3490:   *info = mumps->id.INFO(icntl);
3491:   PetscFunctionReturn(PETSC_SUCCESS);
3492: }

3494: static PetscErrorCode MatMumpsGetInfog_MUMPS(Mat F, PetscInt icntl, PetscInt *infog)
3495: {
3496:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3498:   PetscFunctionBegin;
3499:   *infog = mumps->id.INFOG(icntl);
3500:   PetscFunctionReturn(PETSC_SUCCESS);
3501: }

3503: static PetscErrorCode MatMumpsGetRinfo_MUMPS(Mat F, PetscInt icntl, PetscReal *rinfo)
3504: {
3505:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3507:   PetscFunctionBegin;
3508:   *rinfo = ID_RINFO_GET(mumps->id, icntl);
3509:   PetscFunctionReturn(PETSC_SUCCESS);
3510: }

3512: static PetscErrorCode MatMumpsGetRinfog_MUMPS(Mat F, PetscInt icntl, PetscReal *rinfog)
3513: {
3514:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3516:   PetscFunctionBegin;
3517:   *rinfog = ID_RINFOG_GET(mumps->id, icntl);
3518:   PetscFunctionReturn(PETSC_SUCCESS);
3519: }

3521: static PetscErrorCode MatMumpsGetNullPivots_MUMPS(Mat F, PetscInt *size, PetscInt **array)
3522: {
3523:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3525:   PetscFunctionBegin;
3526:   PetscCheck(mumps->id.ICNTL(24) == 1, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "-mat_mumps_icntl_24 must be set as 1 for null pivot row detection");
3527:   *size  = 0;
3528:   *array = NULL;
3529:   if (!mumps->myid) {
3530:     *size = mumps->id.INFOG(28);
3531:     PetscCall(PetscMalloc1(*size, array));
3532:     for (int i = 0; i < *size; i++) (*array)[i] = mumps->id.pivnul_list[i] - 1;
3533:   }
3534:   PetscFunctionReturn(PETSC_SUCCESS);
3535: }

3537: static PetscErrorCode MatMumpsGetInverse_MUMPS(Mat F, Mat spRHS)
3538: {
3539:   Mat          Bt = NULL, Btseq = NULL;
3540:   PetscBool    flg;
3541:   Mat_MUMPS   *mumps = (Mat_MUMPS *)F->data;
3542:   PetscScalar *aa;
3543:   PetscInt     spnr, *ia, *ja, M, nrhs;

3545:   PetscFunctionBegin;
3546:   PetscAssertPointer(spRHS, 2);
3547:   PetscCall(PetscObjectTypeCompare((PetscObject)spRHS, MATTRANSPOSEVIRTUAL, &flg));
3548:   PetscCheck(flg, PetscObjectComm((PetscObject)spRHS), PETSC_ERR_ARG_WRONG, "Matrix spRHS must be type MATTRANSPOSEVIRTUAL matrix");
3549:   PetscCall(MatShellGetScalingShifts(spRHS, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Mat *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED));
3550:   PetscCall(MatTransposeGetMat(spRHS, &Bt));

3552:   PetscCall(MatMumpsSetIcntl(F, 30, 1));

3554:   if (mumps->petsc_size > 1) {
3555:     Mat_MPIAIJ *b = (Mat_MPIAIJ *)Bt->data;
3556:     Btseq         = b->A;
3557:   } else {
3558:     Btseq = Bt;
3559:   }

3561:   PetscCall(MatGetSize(spRHS, &M, &nrhs));
3562:   mumps->id.nrhs = (PetscMUMPSInt)nrhs;
3563:   PetscCall(PetscMUMPSIntCast(M, &mumps->id.lrhs));
3564:   mumps->id.rhs = NULL;

3566:   if (!mumps->myid) {
3567:     PetscCall(MatSeqAIJGetArray(Btseq, &aa));
3568:     PetscCall(MatGetRowIJ(Btseq, 1, PETSC_FALSE, PETSC_FALSE, &spnr, (const PetscInt **)&ia, (const PetscInt **)&ja, &flg));
3569:     PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot get IJ structure");
3570:     PetscCall(PetscMUMPSIntCSRCast(mumps, spnr, ia, ja, &mumps->id.irhs_ptr, &mumps->id.irhs_sparse, &mumps->id.nz_rhs));
3571:     PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, ((Mat_SeqAIJ *)Btseq->data)->nz, aa, mumps->id.precision, &mumps->id.rhs_sparse_len, &mumps->id.rhs_sparse));
3572:   } else {
3573:     mumps->id.irhs_ptr    = NULL;
3574:     mumps->id.irhs_sparse = NULL;
3575:     mumps->id.nz_rhs      = 0;
3576:     if (mumps->id.rhs_sparse_len) {
3577:       PetscCall(PetscFree(mumps->id.rhs_sparse));
3578:       mumps->id.rhs_sparse_len = 0;
3579:     }
3580:   }
3581:   mumps->id.ICNTL(20) = 1; /* rhs is sparse */
3582:   mumps->id.ICNTL(21) = 0; /* solution is in assembled centralized format */

3584:   /* solve phase */
3585:   mumps->id.job = JOB_SOLVE;
3586:   PetscMUMPS_c(mumps);
3587:   PetscCheck(mumps->id.INFOG(1) >= 0, PETSC_COMM_SELF, PETSC_ERR_LIB, "MUMPS error in solve: INFOG(1)=%d, INFO(2)=%d " MUMPS_MANUALS, mumps->id.INFOG(1), mumps->id.INFO(2));

3589:   if (!mumps->myid) {
3590:     PetscCall(MatSeqAIJRestoreArray(Btseq, &aa));
3591:     PetscCall(MatRestoreRowIJ(Btseq, 1, PETSC_FALSE, PETSC_FALSE, &spnr, (const PetscInt **)&ia, (const PetscInt **)&ja, &flg));
3592:     PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot restore IJ structure");
3593:   }
3594:   PetscFunctionReturn(PETSC_SUCCESS);
3595: }

3597: static PetscErrorCode MatMumpsGetInverseTranspose_MUMPS(Mat F, Mat spRHST)
3598: {
3599:   Mat spRHS;

3601:   PetscFunctionBegin;
3602:   PetscCall(MatCreateTranspose(spRHST, &spRHS));
3603:   PetscCall(MatMumpsGetInverse_MUMPS(F, spRHS));
3604:   PetscCall(MatDestroy(&spRHS));
3605:   PetscFunctionReturn(PETSC_SUCCESS);
3606: }

3608: static PetscErrorCode MatMumpsSetBlk_MUMPS(Mat F, PetscInt nblk, const PetscInt blkvar[], const PetscInt blkptr[])
3609: {
3610:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3612:   PetscFunctionBegin;
3613:   if (nblk) {
3614:     PetscAssertPointer(blkptr, 4);
3615:     PetscCall(PetscMUMPSIntCast(nblk, &mumps->id.nblk));
3616:     PetscCall(PetscFree(mumps->id.blkptr));
3617:     PetscCall(PetscMalloc1(nblk + 1, &mumps->id.blkptr));
3618:     for (PetscInt i = 0; i < nblk + 1; ++i) PetscCall(PetscMUMPSIntCast(blkptr[i], mumps->id.blkptr + i));
3619:     // mumps->id.icntl[] might have not been allocated, which is done in MatSetFromOptions_MUMPS(). So we don't assign ICNTL(15).
3620:     // We use id.nblk and id.blkptr to know what values to set to ICNTL(15) in MatSetFromOptions_MUMPS().
3621:     // mumps->id.ICNTL(15) = 1;
3622:     if (blkvar) {
3623:       PetscCall(PetscFree(mumps->id.blkvar));
3624:       PetscCall(PetscMalloc1(F->rmap->N, &mumps->id.blkvar));
3625:       for (PetscInt i = 0; i < F->rmap->N; ++i) PetscCall(PetscMUMPSIntCast(blkvar[i], mumps->id.blkvar + i));
3626:     }
3627:   } else {
3628:     PetscCall(PetscFree(mumps->id.blkptr));
3629:     PetscCall(PetscFree(mumps->id.blkvar));
3630:     // mumps->id.ICNTL(15) = 0;
3631:     mumps->id.nblk = 0;
3632:   }
3633:   PetscFunctionReturn(PETSC_SUCCESS);
3634: }

3636: /*MC
3637:   MATSOLVERMUMPS -  A matrix type providing direct solvers (LU and Cholesky) for
3638:   MPI distributed and sequential matrices via the external package MUMPS <https://mumps-solver.org/index.php?page=doc>

3640:   Works with `MATAIJ` and `MATSBAIJ` matrices

3642:   Use `./configure --download-mumps --download-scalapack --download-parmetis --download-metis --download-ptscotch` to have PETSc installed with MUMPS

3644:   Use ./configure --with-openmp --download-hwloc (or --with-hwloc) to enable running MUMPS in MPI+OpenMP hybrid mode and non-MUMPS in flat-MPI mode.
3645:   See details below.

3647:   Use `-pc_type cholesky` or `lu` `-pc_factor_mat_solver_type mumps` to use this direct solver

3649:   Options Database Keys:
3650: +  -mat_mumps_icntl_1           - ICNTL(1): output stream for error messages
3651: .  -mat_mumps_icntl_2           - ICNTL(2): output stream for diagnostic printing, statistics, and warning
3652: .  -mat_mumps_icntl_3           - ICNTL(3): output stream for global information, collected on the host
3653: .  -mat_mumps_icntl_4           - ICNTL(4): level of printing (0 to 4)
3654: .  -mat_mumps_icntl_6           - ICNTL(6): permutes to a zero-free diagonal and/or scale the matrix (0 to 7)
3655: .  -mat_mumps_icntl_7           - ICNTL(7): computes a symmetric permutation in sequential analysis, 0=AMD, 2=AMF, 3=Scotch, 4=PORD, 5=METIS, 6=QAMD, and 7=auto
3656:                                   Use -pc_factor_mat_ordering_type type to have PETSc perform the ordering (sequential only)
3657: .  -mat_mumps_icntl_8           - ICNTL(8): scaling strategy (-2 to 8 or 77)
3658: .  -mat_mumps_icntl_10          - ICNTL(10): max num of refinements
3659: .  -mat_mumps_icntl_11          - ICNTL(11): statistics related to an error analysis (via -ksp_view)
3660: .  -mat_mumps_icntl_12          - ICNTL(12): an ordering strategy for symmetric matrices (0 to 3)
3661: .  -mat_mumps_icntl_13          - ICNTL(13): parallelism of the root node (enable ScaLAPACK) and its splitting
3662: .  -mat_mumps_icntl_14          - ICNTL(14): percentage increase in the estimated working space
3663: .  -mat_mumps_icntl_15          - ICNTL(15): compression of the input matrix resulting from a block format
3664: .  -mat_mumps_icntl_19          - ICNTL(19): computes the Schur complement
3665: .  -mat_mumps_icntl_20          - ICNTL(20): give MUMPS centralized (0) or distributed (10) dense RHS
3666: .  -mat_mumps_icntl_22          - ICNTL(22): in-core/out-of-core factorization and solve (0 or 1)
3667: .  -mat_mumps_icntl_23          - ICNTL(23): max size of the working memory (MB) that can allocate per processor
3668: .  -mat_mumps_icntl_24          - ICNTL(24): detection of null pivot rows (0 or 1)
3669: .  -mat_mumps_icntl_25          - ICNTL(25): compute a solution of a deficient matrix and a null space basis
3670: .  -mat_mumps_icntl_26          - ICNTL(26): drives the solution phase if a Schur complement matrix
3671: .  -mat_mumps_icntl_28          - ICNTL(28): use 1 for sequential analysis and ICNTL(7) ordering, or 2 for parallel analysis and ICNTL(29) ordering
3672: .  -mat_mumps_icntl_29          - ICNTL(29): parallel ordering 1 = PTScotch, 2 = ParMETIS
3673: .  -mat_mumps_icntl_30          - ICNTL(30): compute user-specified set of entries in inv(A)
3674: .  -mat_mumps_icntl_31          - ICNTL(31): indicates which factors may be discarded during factorization
3675: .  -mat_mumps_icntl_33          - ICNTL(33): compute determinant
3676: .  -mat_mumps_icntl_35          - ICNTL(35): level of activation of BLR (Block Low-Rank) feature
3677: .  -mat_mumps_icntl_36          - ICNTL(36): controls the choice of BLR factorization variant
3678: .  -mat_mumps_icntl_37          - ICNTL(37): compression of the contribution blocks (CB)
3679: .  -mat_mumps_icntl_38          - ICNTL(38): sets the estimated compression rate of LU factors with BLR
3680: .  -mat_mumps_icntl_40          - ICNTL(40): adaptive BLR precision feature
3681: .  -mat_mumps_icntl_47          - ICNTL(47): single precision factorization in a double precision instance
3682: .  -mat_mumps_icntl_48          - ICNTL(48): multithreading with tree parallelism
3683: .  -mat_mumps_icntl_49          - ICNTL(49): compact workarray at the end of factorization phase
3684: .  -mat_mumps_icntl_58          - ICNTL(58): options for symbolic factorization
3685: .  -mat_mumps_cntl_1            - CNTL(1): relative pivoting threshold
3686: .  -mat_mumps_cntl_2            - CNTL(2): stopping criterion of refinement
3687: .  -mat_mumps_cntl_3            - CNTL(3): absolute pivoting threshold
3688: .  -mat_mumps_cntl_4            - CNTL(4): value for static pivoting
3689: .  -mat_mumps_cntl_5            - CNTL(5): fixation for null pivots
3690: .  -mat_mumps_cntl_7            - CNTL(7): precision of the dropping parameter used during BLR factorization
3691: -  -mat_mumps_use_omp_threads m - run MUMPS in MPI+OpenMP hybrid mode as if omp_set_num_threads(m) is called before calling MUMPS.
3692:                                   Default might be the number of cores per CPU package (socket) as reported by hwloc and suggested by the MUMPS manual.

3694:   Level: beginner

3696:   Notes:
3697:   MUMPS Cholesky does not handle (complex) Hermitian matrices (see User's Guide at <https://mumps-solver.org/index.php?page=doc>) so using it will
3698:   error if the matrix is Hermitian.

3700:   When used within a `KSP`/`PC` solve the options are prefixed with that of the `PC`. Otherwise one can set the options prefix by calling
3701:   `MatSetOptionsPrefixFactor()` on the matrix from which the factor was obtained or `MatSetOptionsPrefix()` on the factor matrix.

3703:   When a MUMPS factorization fails inside a KSP solve, for example with a `KSP_DIVERGED_PC_FAILED`, one can find the MUMPS information about
3704:   the failure with
3705: .vb
3706:           KSPGetPC(ksp,&pc);
3707:           PCFactorGetMatrix(pc,&mat);
3708:           MatMumpsGetInfo(mat,....);
3709:           MatMumpsGetInfog(mat,....); etc.
3710: .ve
3711:   Or run with `-ksp_error_if_not_converged` and the program will be stopped and the information printed in the error message.

3713:   MUMPS provides 64-bit integer support in two build modes:
3714:   full 64-bit: here MUMPS is built with C preprocessing flag -DINTSIZE64 and Fortran compiler option -i8, -fdefault-integer-8 or equivalent, and
3715:   requires all dependent libraries MPI, ScaLAPACK, LAPACK and BLAS built the same way with 64-bit integers (for example ILP64 Intel MKL and MPI).

3717:   selective 64-bit: with the default MUMPS build, 64-bit integers have been introduced where needed. In compressed sparse row (CSR) storage of matrices,
3718:   MUMPS stores column indices in 32-bit, but row offsets in 64-bit, so you can have a huge number of non-zeros, but must have less than 2^31 rows and
3719:   columns. This can lead to significant memory and performance gains with respect to a full 64-bit integer MUMPS version. This requires a regular (32-bit
3720:   integer) build of all dependent libraries MPI, ScaLAPACK, LAPACK and BLAS.

3722:   With --download-mumps=1, PETSc always build MUMPS in selective 64-bit mode, which can be used by both --with-64-bit-indices=0/1 variants of PETSc.

3724:   Two modes to run MUMPS/PETSc with OpenMP
3725: .vb
3726:    Set `OMP_NUM_THREADS` and run with fewer MPI processes than cores. For example, if you want to have 16 OpenMP
3727:    threads per rank, then you may use "export `OMP_NUM_THREADS` = 16 && mpiexec -n 4 ./test".
3728: .ve

3730: .vb
3731:    `-mat_mumps_use_omp_threads` [m] and run your code with as many MPI processes as the number of cores. For example,
3732:    if a compute node has 32 cores and you run on two nodes, you may use "mpiexec -n 64 ./test -mat_mumps_use_omp_threads 16"
3733: .ve

3735:    To run MUMPS in MPI+OpenMP hybrid mode (i.e., enable multithreading in MUMPS), but still run the non-MUMPS part
3736:    (i.e., PETSc part) of your code in the so-called flat-MPI (aka pure-MPI) mode, you need to configure PETSc with `--with-openmp` `--download-hwloc`
3737:    (or `--with-hwloc`), and have an MPI that supports MPI-3.0's process shared memory (which is usually available). Since MUMPS calls BLAS
3738:    libraries, to really get performance, you should have multithreaded BLAS libraries such as Intel MKL, AMD ACML, Cray libSci or OpenBLAS
3739:    (PETSc will automatically try to utilized a threaded BLAS if `--with-openmp` is provided).

3741:    If you run your code through a job submission system, there are caveats in MPI process mapping. We use MPI_Comm_split_type() to obtain MPI
3742:    processes on each compute node. Listing the processes in rank ascending order, we split processes on a node into consecutive groups of
3743:    size m and create a communicator called omp_comm for each group. Rank 0 in an omp_comm is called the master rank, and others in the omp_comm
3744:    are called slave ranks (or slaves). Only master ranks are seen to MUMPS and slaves are not. We will free CPUs assigned to slaves (might be set
3745:    by CPU binding policies in job scripts) and make the CPUs available to the master so that OMP threads spawned by MUMPS can run on the CPUs.
3746:    In a multi-socket compute node, MPI process mapping is an issue. Still use the above example and suppose your compute node has two sockets,
3747:    if you interleave MPI processes on the two sockets, in other words, even ranks are placed on socket 0, and odd ranks are on socket 1, and bind
3748:    MPI processes to cores, then with `-mat_mumps_use_omp_threads` 16, a master rank (and threads it spawns) will use half cores in socket 0, and half
3749:    cores in socket 1, that definitely hurts locality. On the other hand, if you map MPI processes consecutively on the two sockets, then the
3750:    problem will not happen. Therefore, when you use `-mat_mumps_use_omp_threads`, you need to keep an eye on your MPI process mapping and CPU binding.
3751:    For example, with the Slurm job scheduler, one can use srun `--cpu-bind`=verbose -m block:block to map MPI processes with consecutive ranks to sockets and
3752:    examine the mapping result.

3754:    PETSc does not control thread binding in MUMPS. So to get best performance, one still has to set `OMP_PROC_BIND` and `OMP_PLACES` in job scripts,
3755:    for example, export `OMP_PLACES`=threads and export `OMP_PROC_BIND`=spread. One does not need to export `OMP_NUM_THREADS`=m in job scripts as PETSc
3756:    calls `omp_set_num_threads`(m) internally before calling MUMPS.

3758:    See {cite}`heroux2011bi` and {cite}`gutierrez2017accommodating`

3760: .seealso: [](ch_matrices), `Mat`, `PCFactorSetMatSolverType()`, `MatSolverType`, `MatMumpsSetIcntl()`, `MatMumpsGetIcntl()`, `MatMumpsSetCntl()`, `MatMumpsGetCntl()`, `MatMumpsGetInfo()`, `MatMumpsGetInfog()`, `MatMumpsGetRinfo()`, `MatMumpsGetRinfog()`, `MatMumpsSetBlk()`, `KSPGetPC()`, `PCFactorGetMatrix()`
3761: M*/

3763: static PetscErrorCode MatFactorGetSolverType_mumps(PETSC_UNUSED Mat A, MatSolverType *type)
3764: {
3765:   PetscFunctionBegin;
3766:   *type = MATSOLVERMUMPS;
3767:   PetscFunctionReturn(PETSC_SUCCESS);
3768: }

3770: /* MatGetFactor for Seq and MPI AIJ matrices */
3771: static PetscErrorCode MatGetFactor_aij_mumps(Mat A, MatFactorType ftype, Mat *F)
3772: {
3773:   Mat         B;
3774:   Mat_MUMPS  *mumps;
3775:   PetscBool   isSeqAIJ, isDiag, isDense;
3776:   PetscMPIInt size;

3778:   PetscFunctionBegin;
3779:   if (PetscDefined(USE_COMPLEX) && ftype == MAT_FACTOR_CHOLESKY && A->hermitian == PETSC_BOOL3_TRUE && A->symmetric != PETSC_BOOL3_TRUE) {
3780:     PetscCall(PetscInfo(A, "Hermitian MAT_FACTOR_CHOLESKY is not supported. Use MAT_FACTOR_LU instead.\n"));
3781:     *F = NULL;
3782:     PetscFunctionReturn(PETSC_SUCCESS);
3783:   }
3784:   /* Create the factorization matrix */
3785:   PetscCall(PetscObjectBaseTypeCompare((PetscObject)A, MATSEQAIJ, &isSeqAIJ));
3786:   PetscCall(PetscObjectBaseTypeCompare((PetscObject)A, MATDIAGONAL, &isDiag));
3787:   PetscCall(PetscObjectTypeCompareAny((PetscObject)A, &isDense, MATSEQDENSE, MATMPIDENSE, NULL));
3788:   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &B));
3789:   PetscCall(MatSetSizes(B, A->rmap->n, A->cmap->n, A->rmap->N, A->cmap->N));
3790:   PetscCall(PetscStrallocpy(MATSOLVERMUMPS, &((PetscObject)B)->type_name));
3791:   PetscCall(MatSetUp(B));

3793:   PetscCall(PetscNew(&mumps));

3795:   B->ops->view    = MatView_MUMPS;
3796:   B->ops->getinfo = MatGetInfo_MUMPS;

3798:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorGetSolverType_C", MatFactorGetSolverType_mumps));
3799:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorSetSchurIS_C", MatFactorSetSchurIS_MUMPS));
3800:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorCreateSchurComplement_C", MatFactorCreateSchurComplement_MUMPS));
3801:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetIcntl_C", MatMumpsSetIcntl_MUMPS));
3802:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetIcntl_C", MatMumpsGetIcntl_MUMPS));
3803:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetCntl_C", MatMumpsSetCntl_MUMPS));
3804:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetCntl_C", MatMumpsGetCntl_MUMPS));
3805:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInfo_C", MatMumpsGetInfo_MUMPS));
3806:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInfog_C", MatMumpsGetInfog_MUMPS));
3807:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetRinfo_C", MatMumpsGetRinfo_MUMPS));
3808:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetRinfog_C", MatMumpsGetRinfog_MUMPS));
3809:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetNullPivots_C", MatMumpsGetNullPivots_MUMPS));
3810:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInverse_C", MatMumpsGetInverse_MUMPS));
3811:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInverseTranspose_C", MatMumpsGetInverseTranspose_MUMPS));
3812:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetBlk_C", MatMumpsSetBlk_MUMPS));

3814:   if (ftype == MAT_FACTOR_LU) {
3815:     B->ops->lufactorsymbolic = MatLUFactorSymbolic_AIJMUMPS;
3816:     B->factortype            = MAT_FACTOR_LU;
3817:     if (isSeqAIJ) mumps->ConvertToTriples = MatConvertToTriples_seqaij_seqaij;
3818:     else if (isDiag) mumps->ConvertToTriples = MatConvertToTriples_diagonal_xaij;
3819:     else if (isDense) mumps->ConvertToTriples = MatConvertToTriples_dense_xaij;
3820:     else mumps->ConvertToTriples = MatConvertToTriples_mpiaij_mpiaij;
3821:     PetscCall(PetscStrallocpy(MATORDERINGEXTERNAL, (char **)&B->preferredordering[MAT_FACTOR_LU]));
3822:     mumps->sym = 0;
3823:   } else {
3824:     B->ops->choleskyfactorsymbolic = MatCholeskyFactorSymbolic_MUMPS;
3825:     B->factortype                  = MAT_FACTOR_CHOLESKY;
3826:     if (isSeqAIJ) mumps->ConvertToTriples = MatConvertToTriples_seqaij_seqsbaij;
3827:     else if (isDiag) mumps->ConvertToTriples = MatConvertToTriples_diagonal_xaij;
3828:     else if (isDense) mumps->ConvertToTriples = MatConvertToTriples_dense_xaij;
3829:     else mumps->ConvertToTriples = MatConvertToTriples_mpiaij_mpisbaij;
3830:     PetscCall(PetscStrallocpy(MATORDERINGEXTERNAL, (char **)&B->preferredordering[MAT_FACTOR_CHOLESKY]));
3831:     if (PetscDefined(USE_COMPLEX)) mumps->sym = 2;
3832:     else if (A->spd == PETSC_BOOL3_TRUE) mumps->sym = 1;
3833:     else mumps->sym = 2;
3834:   }

3836:   /* set solvertype */
3837:   PetscCall(PetscFree(B->solvertype));
3838:   PetscCall(PetscStrallocpy(MATSOLVERMUMPS, &B->solvertype));
3839:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
3840:   if (size == 1) {
3841:     /* MUMPS option -mat_mumps_icntl_7 1 is automatically set if PETSc ordering is passed into symbolic factorization */
3842:     B->canuseordering = PETSC_TRUE;
3843:   }
3844:   B->ops->destroy = MatDestroy_MUMPS;
3845:   B->data         = (void *)mumps;

3847:   *F               = B;
3848:   mumps->id.job    = JOB_NULL;
3849:   mumps->ICNTL_pre = NULL;
3850:   mumps->CNTL_pre  = NULL;
3851:   mumps->matstruc  = DIFFERENT_NONZERO_PATTERN;
3852:   PetscFunctionReturn(PETSC_SUCCESS);
3853: }

3855: /* MatGetFactor for Seq and MPI SBAIJ matrices */
3856: static PetscErrorCode MatGetFactor_sbaij_mumps(Mat A, PETSC_UNUSED MatFactorType ftype, Mat *F)
3857: {
3858:   Mat         B;
3859:   Mat_MUMPS  *mumps;
3860:   PetscBool   isSeqSBAIJ;
3861:   PetscMPIInt size;

3863:   PetscFunctionBegin;
3864:   if (PetscDefined(USE_COMPLEX) && ftype == MAT_FACTOR_CHOLESKY && A->hermitian == PETSC_BOOL3_TRUE && A->symmetric != PETSC_BOOL3_TRUE) {
3865:     PetscCall(PetscInfo(A, "Hermitian MAT_FACTOR_CHOLESKY is not supported. Use MAT_FACTOR_LU instead.\n"));
3866:     *F = NULL;
3867:     PetscFunctionReturn(PETSC_SUCCESS);
3868:   }
3869:   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &B));
3870:   PetscCall(MatSetSizes(B, A->rmap->n, A->cmap->n, A->rmap->N, A->cmap->N));
3871:   PetscCall(PetscStrallocpy(MATSOLVERMUMPS, &((PetscObject)B)->type_name));
3872:   PetscCall(MatSetUp(B));

3874:   PetscCall(PetscNew(&mumps));
3875:   PetscCall(PetscObjectTypeCompare((PetscObject)A, MATSEQSBAIJ, &isSeqSBAIJ));
3876:   if (isSeqSBAIJ) {
3877:     mumps->ConvertToTriples = MatConvertToTriples_seqsbaij_seqsbaij;
3878:   } else {
3879:     mumps->ConvertToTriples = MatConvertToTriples_mpisbaij_mpisbaij;
3880:   }

3882:   B->ops->choleskyfactorsymbolic = MatCholeskyFactorSymbolic_MUMPS;
3883:   B->ops->view                   = MatView_MUMPS;
3884:   B->ops->getinfo                = MatGetInfo_MUMPS;

3886:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorGetSolverType_C", MatFactorGetSolverType_mumps));
3887:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorSetSchurIS_C", MatFactorSetSchurIS_MUMPS));
3888:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorCreateSchurComplement_C", MatFactorCreateSchurComplement_MUMPS));
3889:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetIcntl_C", MatMumpsSetIcntl_MUMPS));
3890:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetIcntl_C", MatMumpsGetIcntl_MUMPS));
3891:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetCntl_C", MatMumpsSetCntl_MUMPS));
3892:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetCntl_C", MatMumpsGetCntl_MUMPS));
3893:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInfo_C", MatMumpsGetInfo_MUMPS));
3894:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInfog_C", MatMumpsGetInfog_MUMPS));
3895:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetRinfo_C", MatMumpsGetRinfo_MUMPS));
3896:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetRinfog_C", MatMumpsGetRinfog_MUMPS));
3897:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetNullPivots_C", MatMumpsGetNullPivots_MUMPS));
3898:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInverse_C", MatMumpsGetInverse_MUMPS));
3899:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInverseTranspose_C", MatMumpsGetInverseTranspose_MUMPS));
3900:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetBlk_C", MatMumpsSetBlk_MUMPS));

3902:   B->factortype = MAT_FACTOR_CHOLESKY;
3903:   if (PetscDefined(USE_COMPLEX)) mumps->sym = 2;
3904:   else if (A->spd == PETSC_BOOL3_TRUE) mumps->sym = 1;
3905:   else mumps->sym = 2;

3907:   /* set solvertype */
3908:   PetscCall(PetscFree(B->solvertype));
3909:   PetscCall(PetscStrallocpy(MATSOLVERMUMPS, &B->solvertype));
3910:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
3911:   if (size == 1) {
3912:     /* MUMPS option -mat_mumps_icntl_7 1 is automatically set if PETSc ordering is passed into symbolic factorization */
3913:     B->canuseordering = PETSC_TRUE;
3914:   }
3915:   PetscCall(PetscStrallocpy(MATORDERINGEXTERNAL, (char **)&B->preferredordering[MAT_FACTOR_CHOLESKY]));
3916:   B->ops->destroy = MatDestroy_MUMPS;
3917:   B->data         = (void *)mumps;

3919:   *F               = B;
3920:   mumps->id.job    = JOB_NULL;
3921:   mumps->ICNTL_pre = NULL;
3922:   mumps->CNTL_pre  = NULL;
3923:   mumps->matstruc  = DIFFERENT_NONZERO_PATTERN;
3924:   PetscFunctionReturn(PETSC_SUCCESS);
3925: }

3927: static PetscErrorCode MatGetFactor_baij_mumps(Mat A, MatFactorType ftype, Mat *F)
3928: {
3929:   Mat         B;
3930:   Mat_MUMPS  *mumps;
3931:   PetscBool   isSeqBAIJ;
3932:   PetscMPIInt size;

3934:   PetscFunctionBegin;
3935:   /* Create the factorization matrix */
3936:   PetscCall(PetscObjectTypeCompare((PetscObject)A, MATSEQBAIJ, &isSeqBAIJ));
3937:   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &B));
3938:   PetscCall(MatSetSizes(B, A->rmap->n, A->cmap->n, A->rmap->N, A->cmap->N));
3939:   PetscCall(PetscStrallocpy(MATSOLVERMUMPS, &((PetscObject)B)->type_name));
3940:   PetscCall(MatSetUp(B));

3942:   PetscCall(PetscNew(&mumps));
3943:   PetscCheck(ftype == MAT_FACTOR_LU, PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot use PETSc BAIJ matrices with MUMPS Cholesky, use SBAIJ or AIJ matrix instead");
3944:   B->ops->lufactorsymbolic = MatLUFactorSymbolic_BAIJMUMPS;
3945:   B->factortype            = MAT_FACTOR_LU;
3946:   if (isSeqBAIJ) mumps->ConvertToTriples = MatConvertToTriples_seqbaij_seqaij;
3947:   else mumps->ConvertToTriples = MatConvertToTriples_mpibaij_mpiaij;
3948:   mumps->sym = 0;
3949:   PetscCall(PetscStrallocpy(MATORDERINGEXTERNAL, (char **)&B->preferredordering[MAT_FACTOR_LU]));

3951:   B->ops->view    = MatView_MUMPS;
3952:   B->ops->getinfo = MatGetInfo_MUMPS;

3954:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorGetSolverType_C", MatFactorGetSolverType_mumps));
3955:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorSetSchurIS_C", MatFactorSetSchurIS_MUMPS));
3956:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorCreateSchurComplement_C", MatFactorCreateSchurComplement_MUMPS));
3957:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetIcntl_C", MatMumpsSetIcntl_MUMPS));
3958:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetIcntl_C", MatMumpsGetIcntl_MUMPS));
3959:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetCntl_C", MatMumpsSetCntl_MUMPS));
3960:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetCntl_C", MatMumpsGetCntl_MUMPS));
3961:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInfo_C", MatMumpsGetInfo_MUMPS));
3962:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInfog_C", MatMumpsGetInfog_MUMPS));
3963:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetRinfo_C", MatMumpsGetRinfo_MUMPS));
3964:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetRinfog_C", MatMumpsGetRinfog_MUMPS));
3965:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetNullPivots_C", MatMumpsGetNullPivots_MUMPS));
3966:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInverse_C", MatMumpsGetInverse_MUMPS));
3967:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInverseTranspose_C", MatMumpsGetInverseTranspose_MUMPS));
3968:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetBlk_C", MatMumpsSetBlk_MUMPS));

3970:   /* set solvertype */
3971:   PetscCall(PetscFree(B->solvertype));
3972:   PetscCall(PetscStrallocpy(MATSOLVERMUMPS, &B->solvertype));
3973:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
3974:   if (size == 1) {
3975:     /* MUMPS option -mat_mumps_icntl_7 1 is automatically set if PETSc ordering is passed into symbolic factorization */
3976:     B->canuseordering = PETSC_TRUE;
3977:   }
3978:   B->ops->destroy = MatDestroy_MUMPS;
3979:   B->data         = (void *)mumps;

3981:   *F               = B;
3982:   mumps->id.job    = JOB_NULL;
3983:   mumps->ICNTL_pre = NULL;
3984:   mumps->CNTL_pre  = NULL;
3985:   mumps->matstruc  = DIFFERENT_NONZERO_PATTERN;
3986:   PetscFunctionReturn(PETSC_SUCCESS);
3987: }

3989: /* MatGetFactor for Seq and MPI SELL matrices */
3990: static PetscErrorCode MatGetFactor_sell_mumps(Mat A, MatFactorType ftype, Mat *F)
3991: {
3992:   Mat         B;
3993:   Mat_MUMPS  *mumps;
3994:   PetscBool   isSeqSELL;
3995:   PetscMPIInt size;

3997:   PetscFunctionBegin;
3998:   /* Create the factorization matrix */
3999:   PetscCall(PetscObjectTypeCompare((PetscObject)A, MATSEQSELL, &isSeqSELL));
4000:   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &B));
4001:   PetscCall(MatSetSizes(B, A->rmap->n, A->cmap->n, A->rmap->N, A->cmap->N));
4002:   PetscCall(PetscStrallocpy(MATSOLVERMUMPS, &((PetscObject)B)->type_name));
4003:   PetscCall(MatSetUp(B));

4005:   PetscCall(PetscNew(&mumps));

4007:   B->ops->view    = MatView_MUMPS;
4008:   B->ops->getinfo = MatGetInfo_MUMPS;

4010:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorGetSolverType_C", MatFactorGetSolverType_mumps));
4011:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorSetSchurIS_C", MatFactorSetSchurIS_MUMPS));
4012:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorCreateSchurComplement_C", MatFactorCreateSchurComplement_MUMPS));
4013:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetIcntl_C", MatMumpsSetIcntl_MUMPS));
4014:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetIcntl_C", MatMumpsGetIcntl_MUMPS));
4015:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetCntl_C", MatMumpsSetCntl_MUMPS));
4016:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetCntl_C", MatMumpsGetCntl_MUMPS));
4017:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInfo_C", MatMumpsGetInfo_MUMPS));
4018:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInfog_C", MatMumpsGetInfog_MUMPS));
4019:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetRinfo_C", MatMumpsGetRinfo_MUMPS));
4020:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetRinfog_C", MatMumpsGetRinfog_MUMPS));
4021:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetNullPivots_C", MatMumpsGetNullPivots_MUMPS));

4023:   PetscCheck(ftype == MAT_FACTOR_LU, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "To be implemented");
4024:   B->ops->lufactorsymbolic = MatLUFactorSymbolic_AIJMUMPS;
4025:   B->factortype            = MAT_FACTOR_LU;
4026:   PetscCheck(isSeqSELL, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "To be implemented");
4027:   mumps->ConvertToTriples = MatConvertToTriples_seqsell_seqaij;
4028:   mumps->sym              = 0;
4029:   PetscCall(PetscStrallocpy(MATORDERINGEXTERNAL, (char **)&B->preferredordering[MAT_FACTOR_LU]));

4031:   /* set solvertype */
4032:   PetscCall(PetscFree(B->solvertype));
4033:   PetscCall(PetscStrallocpy(MATSOLVERMUMPS, &B->solvertype));
4034:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
4035:   if (size == 1) {
4036:     /* MUMPS option -mat_mumps_icntl_7 1 is automatically set if PETSc ordering is passed into symbolic factorization  */
4037:     B->canuseordering = PETSC_TRUE;
4038:   }
4039:   B->ops->destroy = MatDestroy_MUMPS;
4040:   B->data         = (void *)mumps;

4042:   *F               = B;
4043:   mumps->id.job    = JOB_NULL;
4044:   mumps->ICNTL_pre = NULL;
4045:   mumps->CNTL_pre  = NULL;
4046:   mumps->matstruc  = DIFFERENT_NONZERO_PATTERN;
4047:   PetscFunctionReturn(PETSC_SUCCESS);
4048: }

4050: /* MatGetFactor for MATNEST matrices */
4051: static PetscErrorCode MatGetFactor_nest_mumps(Mat A, MatFactorType ftype, Mat *F)
4052: {
4053:   Mat         B, **mats;
4054:   Mat_MUMPS  *mumps;
4055:   PetscInt    nr, nc;
4056:   PetscMPIInt size;
4057:   PetscBool   flg = PETSC_TRUE;

4059:   PetscFunctionBegin;
4060:   if (PetscDefined(USE_COMPLEX) && ftype == MAT_FACTOR_CHOLESKY && A->hermitian == PETSC_BOOL3_TRUE && A->symmetric != PETSC_BOOL3_TRUE) {
4061:     PetscCall(PetscInfo(A, "Hermitian MAT_FACTOR_CHOLESKY is not supported. Use MAT_FACTOR_LU instead.\n"));
4062:     *F = NULL;
4063:     PetscFunctionReturn(PETSC_SUCCESS);
4064:   }

4066:   /* Return if some condition is not satisfied */
4067:   *F = NULL;
4068:   PetscCall(MatNestGetSubMats(A, &nr, &nc, &mats));
4069:   if (ftype == MAT_FACTOR_CHOLESKY) {
4070:     IS       *rows, *cols;
4071:     PetscInt *m, *M;

4073:     PetscCheck(nr == nc, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MAT_FACTOR_CHOLESKY not supported for nest sizes %" PetscInt_FMT " != %" PetscInt_FMT ". Use MAT_FACTOR_LU.", nr, nc);
4074:     PetscCall(PetscMalloc2(nr, &rows, nc, &cols));
4075:     PetscCall(MatNestGetISs(A, rows, cols));
4076:     for (PetscInt r = 0; flg && r < nr; r++) PetscCall(ISEqualUnsorted(rows[r], cols[r], &flg));
4077:     if (!flg) {
4078:       PetscCall(PetscFree2(rows, cols));
4079:       PetscCall(PetscInfo(A, "MAT_FACTOR_CHOLESKY not supported for unequal row and column maps. Use MAT_FACTOR_LU.\n"));
4080:       PetscFunctionReturn(PETSC_SUCCESS);
4081:     }
4082:     PetscCall(PetscMalloc2(nr, &m, nr, &M));
4083:     for (PetscInt r = 0; r < nr; r++) PetscCall(ISGetMinMax(rows[r], &m[r], &M[r]));
4084:     for (PetscInt r = 0; flg && r < nr; r++)
4085:       for (PetscInt k = r + 1; flg && k < nr; k++)
4086:         if ((m[k] <= m[r] && m[r] <= M[k]) || (m[k] <= M[r] && M[r] <= M[k])) flg = PETSC_FALSE;
4087:     PetscCall(PetscFree2(m, M));
4088:     PetscCall(PetscFree2(rows, cols));
4089:     if (!flg) {
4090:       PetscCall(PetscInfo(A, "MAT_FACTOR_CHOLESKY not supported for intersecting row maps. Use MAT_FACTOR_LU.\n"));
4091:       PetscFunctionReturn(PETSC_SUCCESS);
4092:     }
4093:   }

4095:   for (PetscInt r = 0; r < nr; r++) {
4096:     for (PetscInt c = 0; c < nc; c++) {
4097:       Mat       sub = mats[r][c];
4098:       PetscBool isSeqAIJ, isMPIAIJ, isSeqBAIJ, isMPIBAIJ, isSeqSBAIJ, isMPISBAIJ, isDiag, isDense;

4100:       if (!sub || (ftype == MAT_FACTOR_CHOLESKY && c < r)) continue;
4101:       PetscCall(MatGetTranspose_TransposeVirtual(&sub, NULL, NULL, NULL, NULL));
4102:       PetscCall(PetscObjectBaseTypeCompare((PetscObject)sub, MATSEQAIJ, &isSeqAIJ));
4103:       PetscCall(PetscObjectBaseTypeCompare((PetscObject)sub, MATMPIAIJ, &isMPIAIJ));
4104:       PetscCall(PetscObjectBaseTypeCompare((PetscObject)sub, MATSEQBAIJ, &isSeqBAIJ));
4105:       PetscCall(PetscObjectBaseTypeCompare((PetscObject)sub, MATMPIBAIJ, &isMPIBAIJ));
4106:       PetscCall(PetscObjectBaseTypeCompare((PetscObject)sub, MATSEQSBAIJ, &isSeqSBAIJ));
4107:       PetscCall(PetscObjectBaseTypeCompare((PetscObject)sub, MATMPISBAIJ, &isMPISBAIJ));
4108:       PetscCall(PetscObjectTypeCompare((PetscObject)sub, MATDIAGONAL, &isDiag));
4109:       PetscCall(PetscObjectTypeCompareAny((PetscObject)sub, &isDense, MATSEQDENSE, MATMPIDENSE, NULL));
4110:       if (ftype == MAT_FACTOR_CHOLESKY) {
4111:         if (r == c) {
4112:           if (!isSeqAIJ && !isMPIAIJ && !isSeqBAIJ && !isMPIBAIJ && !isSeqSBAIJ && !isMPISBAIJ && !isDiag && !isDense) {
4113:             PetscCall(PetscInfo(sub, "MAT_FACTOR_CHOLESKY not supported for diagonal block of type %s.\n", ((PetscObject)sub)->type_name));
4114:             flg = PETSC_FALSE;
4115:           }
4116:         } else if (!isSeqAIJ && !isMPIAIJ && !isSeqBAIJ && !isMPIBAIJ && !isDiag && !isDense) {
4117:           PetscCall(PetscInfo(sub, "MAT_FACTOR_CHOLESKY not supported for off-diagonal block of type %s.\n", ((PetscObject)sub)->type_name));
4118:           flg = PETSC_FALSE;
4119:         }
4120:       } else if (!isSeqAIJ && !isMPIAIJ && !isSeqBAIJ && !isMPIBAIJ && !isDiag && !isDense) {
4121:         PetscCall(PetscInfo(sub, "MAT_FACTOR_LU not supported for block of type %s.\n", ((PetscObject)sub)->type_name));
4122:         flg = PETSC_FALSE;
4123:       }
4124:     }
4125:   }
4126:   if (!flg) PetscFunctionReturn(PETSC_SUCCESS);

4128:   /* Create the factorization matrix */
4129:   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &B));
4130:   PetscCall(MatSetSizes(B, A->rmap->n, A->cmap->n, A->rmap->N, A->cmap->N));
4131:   PetscCall(PetscStrallocpy(MATSOLVERMUMPS, &((PetscObject)B)->type_name));
4132:   PetscCall(MatSetUp(B));

4134:   PetscCall(PetscNew(&mumps));

4136:   B->ops->view    = MatView_MUMPS;
4137:   B->ops->getinfo = MatGetInfo_MUMPS;

4139:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorGetSolverType_C", MatFactorGetSolverType_mumps));
4140:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorSetSchurIS_C", MatFactorSetSchurIS_MUMPS));
4141:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorCreateSchurComplement_C", MatFactorCreateSchurComplement_MUMPS));
4142:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetIcntl_C", MatMumpsSetIcntl_MUMPS));
4143:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetIcntl_C", MatMumpsGetIcntl_MUMPS));
4144:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetCntl_C", MatMumpsSetCntl_MUMPS));
4145:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetCntl_C", MatMumpsGetCntl_MUMPS));
4146:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInfo_C", MatMumpsGetInfo_MUMPS));
4147:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInfog_C", MatMumpsGetInfog_MUMPS));
4148:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetRinfo_C", MatMumpsGetRinfo_MUMPS));
4149:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetRinfog_C", MatMumpsGetRinfog_MUMPS));
4150:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetNullPivots_C", MatMumpsGetNullPivots_MUMPS));
4151:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInverse_C", MatMumpsGetInverse_MUMPS));
4152:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInverseTranspose_C", MatMumpsGetInverseTranspose_MUMPS));
4153:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetBlk_C", MatMumpsSetBlk_MUMPS));

4155:   if (ftype == MAT_FACTOR_LU) {
4156:     B->ops->lufactorsymbolic = MatLUFactorSymbolic_AIJMUMPS;
4157:     B->factortype            = MAT_FACTOR_LU;
4158:     mumps->sym               = 0;
4159:   } else {
4160:     B->ops->choleskyfactorsymbolic = MatCholeskyFactorSymbolic_MUMPS;
4161:     B->factortype                  = MAT_FACTOR_CHOLESKY;
4162:     if (PetscDefined(USE_COMPLEX)) mumps->sym = 2;
4163:     else if (A->spd == PETSC_BOOL3_TRUE) mumps->sym = 1;
4164:     else mumps->sym = 2;
4165:   }
4166:   mumps->ConvertToTriples = MatConvertToTriples_nest_xaij;
4167:   PetscCall(PetscStrallocpy(MATORDERINGEXTERNAL, (char **)&B->preferredordering[ftype]));

4169:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
4170:   if (size == 1) {
4171:     /* MUMPS option -mat_mumps_icntl_7 1 is automatically set if PETSc ordering is passed into symbolic factorization */
4172:     B->canuseordering = PETSC_TRUE;
4173:   }

4175:   /* set solvertype */
4176:   PetscCall(PetscFree(B->solvertype));
4177:   PetscCall(PetscStrallocpy(MATSOLVERMUMPS, &B->solvertype));
4178:   B->ops->destroy = MatDestroy_MUMPS;
4179:   B->data         = (void *)mumps;

4181:   *F               = B;
4182:   mumps->id.job    = JOB_NULL;
4183:   mumps->ICNTL_pre = NULL;
4184:   mumps->CNTL_pre  = NULL;
4185:   mumps->matstruc  = DIFFERENT_NONZERO_PATTERN;
4186:   PetscFunctionReturn(PETSC_SUCCESS);
4187: }

4189: PETSC_INTERN PetscErrorCode MatSolverTypeRegister_MUMPS(void)
4190: {
4191:   PetscFunctionBegin;
4192:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATMPIAIJ, MAT_FACTOR_LU, MatGetFactor_aij_mumps));
4193:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATMPIAIJ, MAT_FACTOR_CHOLESKY, MatGetFactor_aij_mumps));
4194:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATMPIBAIJ, MAT_FACTOR_LU, MatGetFactor_baij_mumps));
4195:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATMPIBAIJ, MAT_FACTOR_CHOLESKY, MatGetFactor_baij_mumps));
4196:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATMPISBAIJ, MAT_FACTOR_CHOLESKY, MatGetFactor_sbaij_mumps));
4197:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATSEQAIJ, MAT_FACTOR_LU, MatGetFactor_aij_mumps));
4198:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATSEQAIJ, MAT_FACTOR_CHOLESKY, MatGetFactor_aij_mumps));
4199:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATSEQBAIJ, MAT_FACTOR_LU, MatGetFactor_baij_mumps));
4200:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATSEQBAIJ, MAT_FACTOR_CHOLESKY, MatGetFactor_baij_mumps));
4201:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATSEQSBAIJ, MAT_FACTOR_CHOLESKY, MatGetFactor_sbaij_mumps));
4202:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATSEQSELL, MAT_FACTOR_LU, MatGetFactor_sell_mumps));
4203:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATDIAGONAL, MAT_FACTOR_LU, MatGetFactor_aij_mumps));
4204:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATDIAGONAL, MAT_FACTOR_CHOLESKY, MatGetFactor_aij_mumps));
4205:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATSEQDENSE, MAT_FACTOR_LU, MatGetFactor_aij_mumps));
4206:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATSEQDENSE, MAT_FACTOR_CHOLESKY, MatGetFactor_aij_mumps));
4207:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATMPIDENSE, MAT_FACTOR_LU, MatGetFactor_aij_mumps));
4208:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATMPIDENSE, MAT_FACTOR_CHOLESKY, MatGetFactor_aij_mumps));
4209:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATNEST, MAT_FACTOR_LU, MatGetFactor_nest_mumps));
4210:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATNEST, MAT_FACTOR_CHOLESKY, MatGetFactor_nest_mumps));
4211:   PetscFunctionReturn(PETSC_SUCCESS);
4212: }