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:   PetscMUMPSInt  ICNTL9_pre;         /* check if ICNTL(9) is changed from previous MatSolve */
578:   VecScatter     scat_rhs, scat_sol; /* used by MatSolve() */
579:   PetscMUMPSInt  ICNTL20;            /* use centralized (0) or distributed (10) dense RHS */
580:   PetscMUMPSInt  ICNTL26;
581:   PetscMUMPSInt  lrhs_loc, nloc_rhs, *irhs_loc;
582: #if PetscDefined(HAVE_OPENMP_SUPPORT)
583:   PetscInt    *rhs_nrow, max_nrhs;
584:   PetscMPIInt *rhs_recvcounts, *rhs_disps;
585:   PetscScalar *rhs_loc, *rhs_recvbuf;
586: #endif
587:   Vec            b_seq, x_seq;
588:   PetscInt       ninfo, *info; /* which INFO to display */
589:   PetscInt       sizeredrhs;
590:   PetscScalar   *schur_sol;
591:   PetscInt       schur_sizesol;
592:   PetscScalar   *redrhs;              // buffer in PetscScalar in case MumpsScalar is in a different precision
593:   PetscMUMPSInt *ia_alloc, *ja_alloc; /* work arrays used for the CSR struct for sparse rhs */
594:   PetscCount     cur_ilen, cur_jlen;  /* current len of ia_alloc[], ja_alloc[] */
595:   PetscErrorCode (*ConvertToTriples)(Mat, PetscInt, MatReuse, Mat_MUMPS *);

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

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

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

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

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

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

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

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

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

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

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

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

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

746:     PetscCall(MatCopy(X, B, SAME_NONZERO_PATTERN));
747:     break;
748:   default:
749:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
750:   }
751:   // 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.
752:   PetscCall(MatDenseGetArrayRead(X, &xarray)); // xarray should be mumps->redrhs, but using MatDenseGetArrayRead is safer with GPUs.
753:   PetscCall(MatMumpsCastPetscScalarArray(mumps->sizeredrhs, xarray, mumps->id.precision, mumps->id.redrhs));
754:   PetscCall(MatDenseRestoreArrayRead(X, &xarray));
755:   PetscCall(MatFactorRestoreSchurComplement(F, &S, schurstatus));
756:   PetscCall(MatDestroy(&B));
757:   PetscCall(MatDestroy(&X));
758:   PetscFunctionReturn(PETSC_SUCCESS);
759: }

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

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

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

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

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

816:  */

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

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

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

858:   PetscFunctionBegin;
859:   nz = a->sliidx[a->totalslices];
860:   if (reuse == MAT_INITIAL_MATRIX) {
861:     PetscCall(PetscMalloc2(nz, &row, nz, &col));
862:     for (i = k = 0; i < a->totalslices; i++) {
863:       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++]));
864:     }
865:     for (i = 0; i < nz; i++) PetscCall(PetscMUMPSIntCast(a->colidx[i] + shift, &col[i]));
866:     mumps->irn = row;
867:     mumps->jcn = col;
868:     mumps->nnz = nz;
869:     mumps->val = a->val;
870:   } 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 */
871:   else mumps->val = a->val;                                                      /* in the default case, mumps->val is never allocated, one just needs to update the mumps->val pointer */
872:   PetscFunctionReturn(PETSC_SUCCESS);
873: }

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

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

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

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

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

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

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

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

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

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

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

1120:   garray = mat->garray;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1635:         mumps->nest_vals_start[r * nc + c] = cumnnz;
1636:         if (c == r) {
1637:           PetscCall(ISGetSize(rows[r], &size));
1638:           if (!mumps->nest_convert_to_triples[r * nc + c]) {
1639:             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
1640:           }
1641:           PetscCall(MatGetBlockSize(sub, &bs));
1642:           Mbs += size / bs;
1643:         }
1644:         if (!mumps->nest_convert_to_triples[r * nc + c]) continue;

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

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

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

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

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

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

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

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

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

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

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

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

1731:               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
1732:               PetscCall(MatGetOwnershipRanges(sub, &ranges));
1733:               PetscCall(MatGetBlockSize(sub, &bs));
1734:               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));
1735:               shift += (ranges[i + 1] - ranges[i]) / bs;
1736:             }
1737:           }
1738:         }
1739:       } else mumps->id.ICNTL(15) = 0;
1740:     }
1741:     if (PetscDefined(USE_64BIT_INDICES)) PetscCall(PetscFree(pjcns_w));
1742:     for (PetscInt r = 0; r < nr; r++) PetscCall(ISRestoreIndices(rows[r], (const PetscInt **)&rows_idx[r]));
1743:     for (PetscInt c = 0; c < nc; c++) PetscCall(ISRestoreIndices(cols[c], (const PetscInt **)&cols_idx[c]));
1744:     PetscCall(PetscFree4(rows, cols, rows_idx, cols_idx));
1745:     if (!chol) PetscCheck(cumnnz == totnnz, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Different number of nonzeros %" PetscCount_FMT " != %" PetscCount_FMT, cumnnz, totnnz);
1746:     mumps->nest_vals_start[nr * nc] = cumnnz;

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

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

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

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

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

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

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

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

1883:         /* Populate mumps->irhs_loc[], rhs_nrow[] */
1884:         mumps->nloc_rhs = 0;
1885:         PetscCall(MatGetOwnershipRanges(A, &ranges));
1886:         for (j = 0; j < ompsize; j++) {
1887:           mumps->rhs_nrow[j] = ranges[petsc_ranks[j] + 1] - ranges[petsc_ranks[j]];
1888:           mumps->nloc_rhs += mumps->rhs_nrow[j];
1889:         }
1890:         PetscCall(PetscMalloc1(mumps->nloc_rhs, &mumps->irhs_loc));
1891:         for (j = k = 0; j < ompsize; j++) {
1892:           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 */
1893:         }

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

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

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

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

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

1945: static PetscErrorCode MatSolve_MUMPS(Mat A, Vec b, Vec x)
1946: {
1947:   Mat_MUMPS         *mumps  = (Mat_MUMPS *)A->data;
1948:   const PetscScalar *barray = NULL;
1949:   PetscScalar       *array;
1950:   IS                 is_iden, is_petsc;
1951:   PetscBool          second_solve = PETSC_FALSE;
1952:   static PetscBool   cite1 = PETSC_FALSE, cite2 = PETSC_FALSE;

1954:   PetscFunctionBegin;
1955:   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 "
1956:                                    "Journal on Matrix Analysis and Applications},\n  volume = {23},\n  number = {1},\n  pages = {15--41},\n  year = {2001}\n}\n",
1957:                                    &cite1));
1958:   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 "
1959:                                    "Computing},\n  volume = {32},\n  number = {2},\n  pages = {136--156},\n  year = {2006}\n}\n",
1960:                                    &cite2));

1962:   PetscCall(VecFlag(x, A->factorerrortype));
1963:   if (A->factorerrortype) {
1964:     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)));
1965:     PetscFunctionReturn(PETSC_SUCCESS);
1966:   }

1968:   mumps->id.nrhs = 1;
1969:   if (mumps->petsc_size > 1) {
1970:     if (mumps->ICNTL20 == 10) {
1971:       mumps->id.ICNTL(20) = 10; /* dense distributed RHS, need to set rhs_loc[], irhs_loc[] */
1972:       PetscCall(VecGetArrayRead(b, &barray));
1973:       PetscCall(MatMumpsSetUpDistRHSInfo(A, 1, barray));
1974:     } else {
1975:       mumps->id.ICNTL(20) = 0; /* dense centralized RHS; Scatter b into a sequential b_seq vector*/
1976:       PetscCall(VecScatterBegin(mumps->scat_rhs, b, mumps->b_seq, INSERT_VALUES, SCATTER_FORWARD));
1977:       PetscCall(VecScatterEnd(mumps->scat_rhs, b, mumps->b_seq, INSERT_VALUES, SCATTER_FORWARD));
1978:       if (!mumps->myid) {
1979:         PetscCall(VecGetArray(mumps->b_seq, &array));
1980:         PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, mumps->b_seq->map->n, array, mumps->id.precision, &mumps->id.rhs_len, &mumps->id.rhs));
1981:       }
1982:     }
1983:   } 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 */
1984:     mumps->id.ICNTL(20) = 0;
1985:     PetscCall(VecCopy(b, x));
1986:     PetscCall(VecGetArray(x, &array));
1987:     PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, x->map->n, array, mumps->id.precision, &mumps->id.rhs_len, &mumps->id.rhs));
1988:   }

1990:   /*
1991:      handle condensation step of Schur complement (if any)
1992:      We set by default ICNTL(26) == -1 when Schur indices have been provided by the user.
1993:      According to MUMPS (5.0.0) manual, any value should be harmful during the factorization phase
1994:      Unless the user provides a valid value for ICNTL(26), MatSolve and MatMatSolve routines solve the full system.
1995:      This requires an extra call to PetscMUMPS_c and the computation of the factors for S
1996:   */
1997:   if (mumps->id.size_schur > 0) {
1998:     PetscCheck(mumps->petsc_size <= 1, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Parallel Schur complements not yet supported from PETSc");
1999:     if (mumps->id.ICNTL(26) < 0 || mumps->id.ICNTL(26) > 2) {
2000:       second_solve = PETSC_TRUE;
2001:       PetscCall(MatMumpsHandleSchur_Private(A, PETSC_FALSE)); // allocate id.redrhs
2002:       mumps->id.ICNTL(26) = 1;                                /* condensation phase */
2003:     } else if (mumps->id.ICNTL(26) == 1) PetscCall(MatMumpsHandleSchur_Private(A, PETSC_FALSE));
2004:   }

2006:   mumps->id.job = JOB_SOLVE;
2007:   PetscMUMPS_c(mumps); // reduced solve, put solution in id.redrhs
2008:   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));

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

2017:   if (mumps->petsc_size > 1) { /* convert mumps distributed solution to PETSc mpi x */
2018:     if (mumps->scat_sol && mumps->ICNTL9_pre != mumps->id.ICNTL(9)) {
2019:       /* when id.ICNTL(9) changes, the contents of ilsol_loc may change (not its size, lsol_loc), recreates scat_sol */
2020:       PetscCall(VecScatterDestroy(&mumps->scat_sol));
2021:     }
2022:     if (!mumps->scat_sol) { /* create scatter scat_sol */
2023:       PetscInt *isol2_loc = NULL;
2024:       PetscCall(ISCreateStride(PETSC_COMM_SELF, mumps->id.lsol_loc, 0, 1, &is_iden)); /* from */
2025:       PetscCall(PetscMalloc1(mumps->id.lsol_loc, &isol2_loc));
2026:       for (PetscInt i = 0; i < mumps->id.lsol_loc; i++) isol2_loc[i] = mumps->id.isol_loc[i] - 1;               /* change Fortran style to C style */
2027:       PetscCall(ISCreateGeneral(PETSC_COMM_SELF, mumps->id.lsol_loc, isol2_loc, PETSC_OWN_POINTER, &is_petsc)); /* to */
2028:       PetscCall(VecScatterCreate(mumps->x_seq, is_iden, x, is_petsc, &mumps->scat_sol));
2029:       PetscCall(ISDestroy(&is_iden));
2030:       PetscCall(ISDestroy(&is_petsc));
2031:       mumps->ICNTL9_pre = mumps->id.ICNTL(9); /* save current value of id.ICNTL(9) */
2032:     }

2034:     PetscScalar *xarray;
2035:     PetscCall(VecGetArray(mumps->x_seq, &xarray));
2036:     PetscCall(MatMumpsCastMumpsScalarArray(mumps->id.lsol_loc, mumps->id.precision, mumps->id.sol_loc, xarray));
2037:     PetscCall(VecRestoreArray(mumps->x_seq, &xarray));
2038:     PetscCall(VecScatterBegin(mumps->scat_sol, mumps->x_seq, x, INSERT_VALUES, SCATTER_FORWARD));
2039:     PetscCall(VecScatterEnd(mumps->scat_sol, mumps->x_seq, x, INSERT_VALUES, SCATTER_FORWARD));

2041:     if (mumps->ICNTL20 == 10) { // distributed RHS
2042:       PetscCall(VecRestoreArrayRead(b, &barray));
2043:     } else if (!mumps->myid) { // centralized RHS
2044:       PetscCall(VecRestoreArray(mumps->b_seq, &array));
2045:     }
2046:   } else {
2047:     // id.rhs has the solution in mumps precision
2048:     PetscCall(MatMumpsCastMumpsScalarArray(x->map->n, mumps->id.precision, mumps->id.rhs, array));
2049:     PetscCall(VecRestoreArray(x, &array));
2050:   }

2052:   /* Structural estimate per RHS: 2z-p for LU, 4z-3p for LDL^T.
2053:      INFO(28) counts factor entries z and INFO(23) counts eliminated pivots p. */
2054:   if (!mumps->use_petsc_omp_support || mumps->is_omp_master)
2055:     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))));
2056:   PetscFunctionReturn(PETSC_SUCCESS);
2057: }

2059: static PetscErrorCode MatSolveTranspose_MUMPS(Mat A, Vec b, Vec x)
2060: {
2061:   Mat_MUMPS          *mumps = (Mat_MUMPS *)A->data;
2062:   const PetscMUMPSInt value = mumps->id.ICNTL(9);

2064:   PetscFunctionBegin;
2065:   mumps->id.ICNTL(9) = 0;
2066:   PetscCall(MatSolve_MUMPS(A, b, x));
2067:   mumps->id.ICNTL(9) = value;
2068:   PetscFunctionReturn(PETSC_SUCCESS);
2069: }

2071: static PetscErrorCode MatMatSolve_MUMPS(Mat A, Mat B, Mat X)
2072: {
2073:   Mat                Bt = NULL;
2074:   PetscBool          denseX, denseB, flg, flgT;
2075:   Mat_MUMPS         *mumps = (Mat_MUMPS *)A->data;
2076:   PetscInt           i, nrhs, M, nrhsM, ldb = 0, ldx;
2077:   PetscScalar       *array, *rhsalloc = NULL, *solalloc = NULL;
2078:   const PetscScalar *barray, *rhsarray;
2079:   PetscInt           lsol_loc, nlsol_loc, *idxx, iidx = 0;
2080:   PetscMUMPSInt     *isol_loc, *isol_loc_save;
2081:   PetscScalar       *sol_loc;
2082:   void              *sol_loc_save;
2083:   PetscCount         sol_loc_len_save;
2084:   IS                 is_to, is_from;
2085:   PetscInt           k, proc, j, m, myrstart;
2086:   const PetscInt    *rstart;
2087:   Vec                v_mpi, msol_loc;
2088:   VecScatter         scat_sol;
2089:   Vec                b_seq;
2090:   VecScatter         scat_rhs;
2091:   PetscScalar       *aa;
2092:   PetscInt           spnr, *ia, *ja;
2093:   Mat_MPIAIJ        *b = NULL;

2095:   PetscFunctionBegin;
2096:   PetscCall(PetscObjectTypeCompareAny((PetscObject)X, &denseX, MATSEQDENSE, MATMPIDENSE, NULL));
2097:   PetscCheck(denseX, PetscObjectComm((PetscObject)X), PETSC_ERR_ARG_WRONG, "Matrix X must be MATDENSE matrix");

2099:   PetscCall(PetscObjectTypeCompareAny((PetscObject)B, &denseB, MATSEQDENSE, MATMPIDENSE, NULL));

2101:   if (denseB) {
2102:     PetscCheck(B->rmap->n == X->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Matrix B and X must have same row distribution");
2103:     mumps->id.ICNTL(20) = 0; /* dense RHS */
2104:   } else {                   /* sparse B */
2105:     PetscCheck(X != B, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_IDN, "X and B must be different matrices");
2106:     PetscCall(PetscObjectTypeCompare((PetscObject)B, MATTRANSPOSEVIRTUAL, &flgT));
2107:     PetscCheck(flgT, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONG, "Matrix B must be MATTRANSPOSEVIRTUAL matrix");
2108:     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));
2109:     /* input B is transpose of actual RHS matrix,
2110:      because mumps requires sparse compressed COLUMN storage! See MatMatTransposeSolve_MUMPS() */
2111:     PetscCall(MatTransposeGetMat(B, &Bt));
2112:     mumps->id.ICNTL(20) = 1; /* sparse RHS */
2113:   }

2115:   PetscCall(MatDenseGetLDA(X, &ldx));
2116:   if (denseB) PetscCall(MatDenseGetLDA(B, &ldb));
2117:   PetscCall(MatGetSize(B, &M, &nrhs));
2118:   PetscCall(PetscIntMultError(nrhs, M, &nrhsM));
2119:   mumps->id.nrhs = (PetscMUMPSInt)nrhs;
2120:   mumps->id.lrhs = (PetscMUMPSInt)M;

2122:   if (mumps->petsc_size == 1) { // handle this easy case specially and return early
2123:     PetscScalar *aa, *xarray;
2124:     PetscInt     spnr, ldrhs;
2125:     PetscInt    *ia, *ja;
2126:     PetscBool    second_solve = PETSC_FALSE;

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

2151:     /* handle condensation step of Schur complement (if any) */
2152:     if (mumps->id.size_schur > 0) {
2153:       if (mumps->id.ICNTL(26) < 0 || mumps->id.ICNTL(26) > 2) {
2154:         second_solve = PETSC_TRUE;
2155:         PetscCall(MatMumpsHandleSchur_Private(A, PETSC_FALSE)); // allocate id.redrhs
2156:         mumps->id.ICNTL(26) = 1;                                /* condensation phase, i.e, to solve id.redrhs */
2157:       } else if (mumps->id.ICNTL(26) == 1) PetscCall(MatMumpsHandleSchur_Private(A, PETSC_FALSE));
2158:     }

2160:     mumps->id.job = JOB_SOLVE;
2161:     PetscMUMPS_c(mumps);
2162:     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));

2164:     /* handle expansion step of Schur complement (if any) */
2165:     if (second_solve) PetscCall(MatMumpsHandleSchur_Private(A, PETSC_TRUE));
2166:     else if (mumps->id.ICNTL(26) == 1) { // condense the right hand side
2167:       PetscCall(MatMumpsSolveSchur_Private(A));
2168:       for (j = 0; j < nrhs; ++j)
2169:         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);
2170:     }

2172:     if (!denseB) { /* sparse B, restore ia, ja */
2173:       PetscCall(MatSeqAIJRestoreArray(Bt, &aa));
2174:       PetscCall(MatRestoreRowIJ(Bt, 1, PETSC_FALSE, PETSC_FALSE, &spnr, (const PetscInt **)&ia, (const PetscInt **)&ja, &flg));
2175:       PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot restore IJ structure");
2176:     }

2178:     // no matter dense B or sparse B, solution is in id.rhs; convert it to array of X.
2179:     PetscCall(MatMumpsCastMumpsScalarArray(nrhsM, mumps->id.precision, mumps->id.rhs, xarray));
2180:     if (solalloc) {
2181:       for (j = 0; j < nrhs; ++j) PetscCall(PetscArraycpy(array + (size_t)j * ldx, solalloc + j * M, M));
2182:       PetscCall(PetscFree(solalloc));
2183:     }
2184:     PetscCall(MatDenseRestoreArray(X, &array));
2185:     if (!mumps->use_petsc_omp_support || mumps->is_omp_master)
2186:       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))));
2187:     PetscFunctionReturn(PETSC_SUCCESS);
2188:   }

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

2193:   /* create msol_loc to hold mumps local solution */
2194:   isol_loc_save         = mumps->id.isol_loc; /* save these, as we want to reuse them in MatSolve() */
2195:   sol_loc_save          = mumps->id.sol_loc;
2196:   sol_loc_len_save      = mumps->id.sol_loc_len;
2197:   mumps->id.isol_loc    = NULL; // an init state
2198:   mumps->id.sol_loc     = NULL;
2199:   mumps->id.sol_loc_len = 0;

2201:   lsol_loc = mumps->id.lsol_loc;
2202:   PetscCall(PetscIntMultError(nrhs, lsol_loc, &nlsol_loc)); /* length of sol_loc */
2203:   PetscCall(PetscMalloc2(nlsol_loc, &sol_loc, lsol_loc, &isol_loc));
2204:   PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_FALSE, nlsol_loc, sol_loc, mumps->id.precision, &mumps->id.sol_loc_len, &mumps->id.sol_loc));
2205:   mumps->id.isol_loc = isol_loc;

2207:   PetscCall(VecCreateSeqWithArray(PETSC_COMM_SELF, 1, nlsol_loc, (PetscScalar *)sol_loc, &msol_loc));

2209:   if (denseB) {
2210:     PetscCall(MatGetLocalSize(B, &m, NULL));
2211:     PetscCall(MatDenseGetArrayRead(B, &barray));
2212:     if (ldb != m && m) {
2213:       PetscCall(PetscMalloc1((size_t)nrhs * m, &rhsalloc));
2214:       for (j = 0; j < nrhs; ++j) PetscCall(PetscArraycpy(rhsalloc + j * m, barray + (size_t)j * ldb, m));
2215:     }
2216:     rhsarray = rhsalloc ? rhsalloc : barray;
2217:     if (mumps->ICNTL20 == 10) {
2218:       mumps->id.ICNTL(20) = 10; /* dense distributed RHS */
2219:       PetscCall(MatMumpsSetUpDistRHSInfo(A, nrhs, rhsarray));
2220:       // the solution will be scattered to v_mpi, which wraps X
2221:       PetscCall(VecCreateMPIWithArray(PetscObjectComm((PetscObject)B), 1, nrhs * m, nrhsM, NULL, &v_mpi));
2222:     } else {
2223:       mumps->id.ICNTL(20) = 0; /* dense centralized RHS */
2224:       /* TODO: Because of non-contiguous indices, the created vecscatter scat_rhs is not done in MPI_Gather, resulting in
2225:         very inefficient communication. An optimization is to use VecScatterCreateToZero to gather B to rank 0. Then on rank
2226:         0, re-arrange B into desired order, which is a local operation.
2227:       */

2229:       /* scatter v_mpi to b_seq because MUMPS before 5.3.0 only supports centralized rhs */
2230:       /* wrap dense rhs matrix B into a vector v_mpi */
2231:       PetscCall(VecCreateMPIWithArray(PetscObjectComm((PetscObject)B), 1, nrhs * m, nrhsM, rhsarray, &v_mpi));

2233:       /* scatter v_mpi to b_seq in proc[0]. With ICNTL(20) = 0, MUMPS requires rhs to be centralized on the host! */
2234:       if (!mumps->myid) {
2235:         PetscInt *idx;
2236:         /* idx: maps from k-th index of v_mpi to (i,j)-th global entry of B */
2237:         PetscCall(PetscMalloc1(nrhsM, &idx));
2238:         PetscCall(MatGetOwnershipRanges(B, &rstart));
2239:         for (proc = 0, k = 0; proc < mumps->petsc_size; proc++) {
2240:           for (j = 0; j < nrhs; j++) {
2241:             for (i = rstart[proc]; i < rstart[proc + 1]; i++) idx[k++] = j * M + i;
2242:           }
2243:         }

2245:         PetscCall(VecCreateSeq(PETSC_COMM_SELF, nrhsM, &b_seq));
2246:         PetscCall(ISCreateGeneral(PETSC_COMM_SELF, nrhsM, idx, PETSC_OWN_POINTER, &is_to));
2247:         PetscCall(ISCreateStride(PETSC_COMM_SELF, nrhsM, 0, 1, &is_from));
2248:       } else {
2249:         PetscCall(VecCreateSeq(PETSC_COMM_SELF, 0, &b_seq));
2250:         PetscCall(ISCreateStride(PETSC_COMM_SELF, 0, 0, 1, &is_to));
2251:         PetscCall(ISCreateStride(PETSC_COMM_SELF, 0, 0, 1, &is_from));
2252:       }

2254:       PetscCall(VecScatterCreate(v_mpi, is_from, b_seq, is_to, &scat_rhs));
2255:       PetscCall(VecScatterBegin(scat_rhs, v_mpi, b_seq, INSERT_VALUES, SCATTER_FORWARD));
2256:       PetscCall(ISDestroy(&is_to));
2257:       PetscCall(ISDestroy(&is_from));
2258:       PetscCall(VecScatterEnd(scat_rhs, v_mpi, b_seq, INSERT_VALUES, SCATTER_FORWARD));

2260:       if (!mumps->myid) { /* define rhs on the host */
2261:         PetscCall(VecGetArrayRead(b_seq, &rhsarray));
2262:         PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, nrhsM, rhsarray, mumps->id.precision, &mumps->id.rhs_len, &mumps->id.rhs));
2263:         PetscCall(VecRestoreArrayRead(b_seq, &rhsarray));
2264:       }
2265:     }
2266:   } else { /* sparse B */
2267:     b = (Mat_MPIAIJ *)Bt->data;

2269:     /* wrap dense X into a vector v_mpi */
2270:     PetscCall(MatGetLocalSize(X, &m, NULL));
2271:     PetscCall(MatDenseGetArrayRead(X, &barray));
2272:     PetscCall(VecCreateMPIWithArray(PetscObjectComm((PetscObject)X), 1, nrhs * m, nrhsM, barray, &v_mpi));
2273:     PetscCall(MatDenseRestoreArrayRead(X, &barray));

2275:     if (!mumps->myid) {
2276:       PetscCall(MatSeqAIJGetArray(b->A, &aa));
2277:       PetscCall(MatGetRowIJ(b->A, 1, PETSC_FALSE, PETSC_FALSE, &spnr, (const PetscInt **)&ia, (const PetscInt **)&ja, &flg));
2278:       PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot get IJ structure");
2279:       PetscCall(PetscMUMPSIntCSRCast(mumps, spnr, ia, ja, &mumps->id.irhs_ptr, &mumps->id.irhs_sparse, &mumps->id.nz_rhs));
2280:       PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, ((Mat_SeqAIJ *)b->A->data)->nz, aa, mumps->id.precision, &mumps->id.rhs_sparse_len, &mumps->id.rhs_sparse));
2281:     } else {
2282:       mumps->id.irhs_ptr    = NULL;
2283:       mumps->id.irhs_sparse = NULL;
2284:       mumps->id.nz_rhs      = 0;
2285:       if (mumps->id.rhs_sparse_len) {
2286:         PetscCall(PetscFree(mumps->id.rhs_sparse));
2287:         mumps->id.rhs_sparse_len = 0;
2288:       }
2289:     }
2290:   }

2292:   /* solve phase */
2293:   mumps->id.job = JOB_SOLVE;
2294:   PetscMUMPS_c(mumps);
2295:   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));

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

2299:   /* scatter mumps distributed solution to PETSc vector v_mpi, which shares local arrays with solution matrix X */
2300:   PetscCall(MatDenseGetArray(X, &array));
2301:   PetscCall(MatGetLocalSize(X, &m, NULL));
2302:   if (ldx != m && m) PetscCall(PetscMalloc1((size_t)nrhs * m, &solalloc));
2303:   PetscCall(VecPlaceArray(v_mpi, solalloc ? solalloc : array));

2305:   /* create scatter scat_sol */
2306:   PetscCall(MatGetOwnershipRanges(X, &rstart));
2307:   /* iidx: index for scatter mumps solution to PETSc X */

2309:   PetscCall(ISCreateStride(PETSC_COMM_SELF, nlsol_loc, 0, 1, &is_from));
2310:   PetscCall(PetscMalloc1(nlsol_loc, &idxx));
2311:   for (i = 0; i < lsol_loc; i++) {
2312:     isol_loc[i] -= 1; /* change Fortran style to C style. isol_loc[i+j*lsol_loc] contains x[isol_loc[i]] in j-th vector */

2314:     for (proc = 0; proc < mumps->petsc_size; proc++) {
2315:       if (isol_loc[i] >= rstart[proc] && isol_loc[i] < rstart[proc + 1]) {
2316:         myrstart = rstart[proc];
2317:         k        = isol_loc[i] - myrstart;          /* local index on 1st column of PETSc vector X */
2318:         iidx     = k + myrstart * nrhs;             /* maps mumps isol_loc[i] to PETSc index in X */
2319:         m        = rstart[proc + 1] - rstart[proc]; /* rows of X for this proc */
2320:         break;
2321:       }
2322:     }

2324:     for (j = 0; j < nrhs; j++) idxx[i + j * lsol_loc] = iidx + j * m;
2325:   }
2326:   PetscCall(ISCreateGeneral(PETSC_COMM_SELF, nlsol_loc, idxx, PETSC_COPY_VALUES, &is_to));
2327:   PetscCall(MatMumpsCastMumpsScalarArray(nlsol_loc, mumps->id.precision, mumps->id.sol_loc, sol_loc)); // Vec msol_loc is created with sol_loc[]
2328:   PetscCall(VecScatterCreate(msol_loc, is_from, v_mpi, is_to, &scat_sol));
2329:   PetscCall(VecScatterBegin(scat_sol, msol_loc, v_mpi, INSERT_VALUES, SCATTER_FORWARD));
2330:   PetscCall(ISDestroy(&is_from));
2331:   PetscCall(ISDestroy(&is_to));
2332:   PetscCall(VecScatterEnd(scat_sol, msol_loc, v_mpi, INSERT_VALUES, SCATTER_FORWARD));
2333:   if (solalloc) {
2334:     PetscCall(MatGetLocalSize(X, &m, NULL));
2335:     for (j = 0; j < nrhs; ++j) PetscCall(PetscArraycpy(array + (size_t)j * ldx, solalloc + j * m, m));
2336:   }
2337:   PetscCall(MatDenseRestoreArray(X, &array));

2339:   if (mumps->id.sol_loc_len) { // in case we allocated intermediate buffers
2340:     mumps->id.sol_loc_len = 0;
2341:     PetscCall(PetscFree(mumps->id.sol_loc));
2342:   }

2344:   // restore old values
2345:   mumps->id.sol_loc     = sol_loc_save;
2346:   mumps->id.sol_loc_len = sol_loc_len_save;
2347:   mumps->id.isol_loc    = isol_loc_save;

2349:   PetscCall(PetscFree2(sol_loc, isol_loc));
2350:   PetscCall(PetscFree(idxx));
2351:   PetscCall(VecDestroy(&msol_loc));
2352:   PetscCall(VecDestroy(&v_mpi));
2353:   if (!denseB) {
2354:     if (!mumps->myid) {
2355:       b = (Mat_MPIAIJ *)Bt->data;
2356:       PetscCall(MatSeqAIJRestoreArray(b->A, &aa));
2357:       PetscCall(MatRestoreRowIJ(b->A, 1, PETSC_FALSE, PETSC_FALSE, &spnr, (const PetscInt **)&ia, (const PetscInt **)&ja, &flg));
2358:       PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot restore IJ structure");
2359:     }
2360:   } else {
2361:     if (mumps->ICNTL20 == 0) {
2362:       PetscCall(VecDestroy(&b_seq));
2363:       PetscCall(VecScatterDestroy(&scat_rhs));
2364:     }
2365:   }
2366:   PetscCall(VecScatterDestroy(&scat_sol));
2367:   PetscCall(PetscFree(rhsalloc));
2368:   PetscCall(PetscFree(solalloc));
2369:   if (!mumps->use_petsc_omp_support || mumps->is_omp_master)
2370:     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))));
2371:   PetscFunctionReturn(PETSC_SUCCESS);
2372: }

2374: static PetscErrorCode MatMatSolveTranspose_MUMPS(Mat A, Mat B, Mat X)
2375: {
2376:   Mat_MUMPS          *mumps = (Mat_MUMPS *)A->data;
2377:   const PetscMUMPSInt value = mumps->id.ICNTL(9);

2379:   PetscFunctionBegin;
2380:   mumps->id.ICNTL(9) = 0;
2381:   PetscCall(MatMatSolve_MUMPS(A, B, X));
2382:   mumps->id.ICNTL(9) = value;
2383:   PetscFunctionReturn(PETSC_SUCCESS);
2384: }

2386: static PetscErrorCode MatMatTransposeSolve_MUMPS(Mat A, Mat Bt, Mat X)
2387: {
2388:   PetscBool flg;
2389:   Mat       B;

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

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

2398:   PetscCall(MatMatSolve_MUMPS(A, B, X));
2399:   PetscCall(MatDestroy(&B));
2400:   PetscFunctionReturn(PETSC_SUCCESS);
2401: }

2403: #if !PetscDefined(USE_COMPLEX)
2404: /*
2405:   input:
2406:    F:        numeric factor
2407:   output:
2408:    nneg:     total number of negative pivots
2409:    nzero:    total number of zero pivots
2410:    npos:     (global dimension of F) - nneg - nzero
2411: */
2412: static PetscErrorCode MatGetInertia_SBAIJMUMPS(Mat F, PetscInt *nneg, PetscInt *nzero, PetscInt *npos)
2413: {
2414:   Mat_MUMPS  *mumps = (Mat_MUMPS *)F->data;
2415:   PetscMPIInt size;

2417:   PetscFunctionBegin;
2418:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)F), &size));
2419:   /* 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 */
2420:   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));

2422:   if (nneg) *nneg = mumps->id.INFOG(12);
2423:   if (nzero || npos) {
2424:     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");
2425:     if (nzero) *nzero = mumps->id.INFOG(28);
2426:     if (npos) *npos = F->rmap->N - (mumps->id.INFOG(12) + mumps->id.INFOG(28));
2427:   }
2428:   PetscFunctionReturn(PETSC_SUCCESS);
2429: }
2430: #endif

2432: static PetscErrorCode MatMumpsGatherNonzerosOnMaster(MatReuse reuse, Mat_MUMPS *mumps)
2433: {
2434:   PetscMPIInt    nreqs;
2435:   PetscMUMPSInt *irn, *jcn;
2436:   PetscMPIInt    count;
2437:   PetscCount     totnnz, remain;
2438:   const PetscInt osize = mumps->omp_comm_size;
2439:   PetscScalar   *val;

2441:   PetscFunctionBegin;
2442:   if (osize > 1) {
2443:     if (reuse == MAT_INITIAL_MATRIX) {
2444:       /* master first gathers counts of nonzeros to receive */
2445:       if (mumps->is_omp_master) PetscCall(PetscMalloc1(osize, &mumps->recvcount));
2446:       PetscCallMPI(MPI_Gather(&mumps->nnz, 1, MPIU_INT64, mumps->recvcount, 1, MPIU_INT64, 0 /*master*/, mumps->omp_comm));

2448:       /* Then each computes number of send/recvs */
2449:       if (mumps->is_omp_master) {
2450:         /* Start from 1 since self communication is not done in MPI */
2451:         nreqs = 0;
2452:         for (PetscMPIInt i = 1; i < osize; i++) nreqs += (mumps->recvcount[i] + PETSC_MPI_INT_MAX - 1) / PETSC_MPI_INT_MAX;
2453:       } else {
2454:         nreqs = (PetscMPIInt)((mumps->nnz + PETSC_MPI_INT_MAX - 1) / PETSC_MPI_INT_MAX);
2455:       }
2456:       PetscCall(PetscMalloc1(nreqs * 3, &mumps->reqs)); /* Triple the requests since we send irn, jcn and val separately */

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

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

2471:         /* Self communication */
2472:         PetscCall(PetscArraycpy(irn, mumps->irn, mumps->nnz));
2473:         PetscCall(PetscArraycpy(jcn, mumps->jcn, mumps->nnz));
2474:         PetscCall(PetscArraycpy(val, mumps->val, mumps->nnz));

2476:         /* Replace mumps->irn/jcn etc on master with the newly allocated bigger arrays */
2477:         PetscCall(PetscFree2(mumps->irn, mumps->jcn));
2478:         PetscCall(PetscFree(mumps->val_alloc));
2479:         mumps->nnz = totnnz;
2480:         mumps->irn = irn;
2481:         mumps->jcn = jcn;
2482:         mumps->val = mumps->val_alloc = val;

2484:         irn += mumps->recvcount[0]; /* recvcount[0] is old mumps->nnz on omp rank 0 */
2485:         jcn += mumps->recvcount[0];
2486:         val += mumps->recvcount[0];

2488:         /* Remote communication */
2489:         for (PetscMPIInt i = 1; i < osize; i++) {
2490:           count  = (PetscMPIInt)PetscMin(mumps->recvcount[i], (PetscMPIInt)PETSC_MPI_INT_MAX);
2491:           remain = mumps->recvcount[i] - count;
2492:           while (count > 0) {
2493:             PetscCallMPI(MPIU_Irecv(irn, count, MPIU_MUMPSINT, i, mumps->tag, mumps->omp_comm, &mumps->reqs[nreqs++]));
2494:             PetscCallMPI(MPIU_Irecv(jcn, count, MPIU_MUMPSINT, i, mumps->tag, mumps->omp_comm, &mumps->reqs[nreqs++]));
2495:             PetscCallMPI(MPIU_Irecv(val, count, MPIU_SCALAR, i, mumps->tag, mumps->omp_comm, &mumps->reqs[nreqs++]));
2496:             irn += count;
2497:             jcn += count;
2498:             val += count;
2499:             count = (PetscMPIInt)PetscMin(remain, (PetscMPIInt)PETSC_MPI_INT_MAX);
2500:             remain -= count;
2501:           }
2502:         }
2503:       } else {
2504:         irn    = mumps->irn;
2505:         jcn    = mumps->jcn;
2506:         val    = mumps->val;
2507:         count  = (PetscMPIInt)PetscMin(mumps->nnz, (PetscMPIInt)PETSC_MPI_INT_MAX);
2508:         remain = mumps->nnz - count;
2509:         while (count > 0) {
2510:           PetscCallMPI(MPIU_Isend(irn, count, MPIU_MUMPSINT, 0, mumps->tag, mumps->omp_comm, &mumps->reqs[nreqs++]));
2511:           PetscCallMPI(MPIU_Isend(jcn, count, MPIU_MUMPSINT, 0, mumps->tag, mumps->omp_comm, &mumps->reqs[nreqs++]));
2512:           PetscCallMPI(MPIU_Isend(val, count, MPIU_SCALAR, 0, mumps->tag, mumps->omp_comm, &mumps->reqs[nreqs++]));
2513:           irn += count;
2514:           jcn += count;
2515:           val += count;
2516:           count = (PetscMPIInt)PetscMin(remain, (PetscMPIInt)PETSC_MPI_INT_MAX);
2517:           remain -= count;
2518:         }
2519:       }
2520:     } else {
2521:       nreqs = 0;
2522:       if (mumps->is_omp_master) {
2523:         val = mumps->val + mumps->recvcount[0];
2524:         for (PetscMPIInt i = 1; i < osize; i++) { /* Remote communication only since self data is already in place */
2525:           count  = (PetscMPIInt)PetscMin(mumps->recvcount[i], (PetscMPIInt)PETSC_MPI_INT_MAX);
2526:           remain = mumps->recvcount[i] - count;
2527:           while (count > 0) {
2528:             PetscCallMPI(MPIU_Irecv(val, count, MPIU_SCALAR, i, mumps->tag, mumps->omp_comm, &mumps->reqs[nreqs++]));
2529:             val += count;
2530:             count = (PetscMPIInt)PetscMin(remain, (PetscMPIInt)PETSC_MPI_INT_MAX);
2531:             remain -= count;
2532:           }
2533:         }
2534:       } else {
2535:         val    = mumps->val;
2536:         count  = (PetscMPIInt)PetscMin(mumps->nnz, (PetscMPIInt)PETSC_MPI_INT_MAX);
2537:         remain = mumps->nnz - count;
2538:         while (count > 0) {
2539:           PetscCallMPI(MPIU_Isend(val, count, MPIU_SCALAR, 0, mumps->tag, mumps->omp_comm, &mumps->reqs[nreqs++]));
2540:           val += count;
2541:           count = (PetscMPIInt)PetscMin(remain, (PetscMPIInt)PETSC_MPI_INT_MAX);
2542:           remain -= count;
2543:         }
2544:       }
2545:     }
2546:     PetscCallMPI(MPI_Waitall(nreqs, mumps->reqs, MPI_STATUSES_IGNORE));
2547:     mumps->tag++; /* It is totally fine for above send/recvs to share one mpi tag */
2548:   }
2549:   PetscFunctionReturn(PETSC_SUCCESS);
2550: }

2552: static PetscErrorCode MatFactorNumeric_MUMPS(Mat F, Mat A, PETSC_UNUSED const MatFactorInfo *info)
2553: {
2554:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

2556:   PetscFunctionBegin;
2557:   if (mumps->id.INFOG(1) < 0 && !(mumps->id.INFOG(1) == -16 && mumps->id.INFOG(1) == 0)) {
2558:     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)));
2559:     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)));
2560:     PetscFunctionReturn(PETSC_SUCCESS);
2561:   }

2563:   PetscCall((*mumps->ConvertToTriples)(A, 1, MAT_REUSE_MATRIX, mumps));
2564:   PetscCall(MatMumpsGatherNonzerosOnMaster(MAT_REUSE_MATRIX, mumps));
2565:   PetscCall(MatMumpsEnsureSchurArray_Private(F));

2567:   /* numerical factorization phase */
2568:   mumps->id.job = JOB_FACTNUMERIC;
2569:   if (!mumps->id.ICNTL(18)) { /* A is centralized */
2570:     if (!mumps->myid) PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, mumps->nnz, mumps->val, mumps->id.precision, &mumps->id.a_len, &mumps->id.a));
2571:   } else {
2572:     PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, mumps->nnz, mumps->val, mumps->id.precision, &mumps->id.a_loc_len, &mumps->id.a_loc));
2573:   }

2575:   if (mumps->id.ICNTL(22)) PetscCall(PetscStrncpy(mumps->id.ooc_prefix, ((PetscObject)F)->prefix, sizeof(((MUMPS_STRUC_C *)NULL)->ooc_prefix)));
2576:   if (A->rmap->N && A->cmap->N) PetscMUMPS_c(mumps);
2577:   if (mumps->id.INFOG(1) < 0) {
2578:     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));
2579:     if (mumps->id.INFOG(1) == -10) {
2580:       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)));
2581:       F->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
2582:     } else if (mumps->id.INFOG(1) == -13) {
2583:       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)));
2584:       F->factorerrortype = MAT_FACTOR_OUTMEMORY;
2585:     } else if (mumps->id.INFOG(1) == -8 || mumps->id.INFOG(1) == -9 || (-16 < mumps->id.INFOG(1) && mumps->id.INFOG(1) < -10)) {
2586:       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)));
2587:       F->factorerrortype = MAT_FACTOR_OUTMEMORY;
2588:     } else {
2589:       PetscCall(PetscInfo(F, "MUMPS error in numerical factorization: INFOG(1)=%d, INFO(2)=%d\n", mumps->id.INFOG(1), mumps->id.INFO(2)));
2590:       F->factorerrortype = MAT_FACTOR_OTHER;
2591:     }
2592:   }
2593:   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));

2595:   F->assembled = PETSC_TRUE;

2597:   if (F->schur) { /* reset Schur status to unfactored */
2598: #if PetscDefined(HAVE_CUDA)
2599:     F->schur->offloadmask = PETSC_OFFLOAD_CPU;
2600: #endif
2601:     PetscScalar *array;
2602:     PetscCall(MatDenseGetArray(F->schur, &array));
2603:     PetscCall(MatMumpsCastMumpsScalarArray(mumps->id.size_schur * mumps->id.size_schur, mumps->id.precision, mumps->id.schur, array));
2604:     PetscCall(MatDenseRestoreArray(F->schur, &array));
2605:     if (mumps->id.ICNTL(19) == 1) { /* stored by rows */
2606:       mumps->id.ICNTL(19) = 2;
2607:       PetscCall(MatTranspose(F->schur, MAT_INPLACE_MATRIX, &F->schur));
2608:     }
2609:     PetscCall(MatFactorRestoreSchurComplement(F, NULL, MAT_FACTOR_SCHUR_UNFACTORED));
2610:   }

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

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

2627:     /* distributed solution; Create x_seq=sol_loc for repeated use */
2628:     if (mumps->x_seq) {
2629:       PetscCall(VecScatterDestroy(&mumps->scat_sol));
2630:       PetscCall(PetscFree(mumps->id.isol_loc));
2631:       PetscCall(VecDestroy(&mumps->x_seq));
2632:     }
2633:     lsol_loc = mumps->id.INFO(23); /* length of sol_loc */
2634:     PetscCall(PetscMalloc1(lsol_loc, &mumps->id.isol_loc));
2635:     PetscCall(VecCreateSeq(PETSC_COMM_SELF, lsol_loc, &mumps->x_seq));
2636:     PetscCall(VecGetArray(mumps->x_seq, &array));
2637:     PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_FALSE, lsol_loc, array, mumps->id.precision, &mumps->id.sol_loc_len, &mumps->id.sol_loc));
2638:     PetscCall(VecRestoreArray(mumps->x_seq, &array));
2639:     mumps->id.lsol_loc = (PetscMUMPSInt)lsol_loc;
2640:   }
2641:   PetscCall(PetscLogFlops((double)ID_RINFO_GET(mumps->id, 2)));
2642:   PetscFunctionReturn(PETSC_SUCCESS);
2643: }

2645: /* Sets MUMPS options from the options database */
2646: static PetscErrorCode MatSetFromOptions_MUMPS(Mat F, Mat A)
2647: {
2648:   Mat_MUMPS    *mumps = (Mat_MUMPS *)F->data;
2649:   PetscReal     cntl;
2650:   PetscMUMPSInt icntl = 0, size, *listvar_schur;
2651:   PetscInt      info[80], i, ninfo = 80, rbs, cbs;
2652:   PetscBool     flg   = PETSC_FALSE;
2653:   PetscBool     schur = mumps->id.icntl ? (PetscBool)(mumps->id.ICNTL(26) == -1) : (PetscBool)(mumps->ICNTL26 == -1);
2654:   void         *arr;

2656:   PetscFunctionBegin;
2657:   PetscOptionsBegin(PetscObjectComm((PetscObject)F), ((PetscObject)F)->prefix, "MUMPS Options", "Mat");
2658:   if (mumps->id.job == JOB_NULL) { /* MatSetFromOptions_MUMPS() has never been called before */
2659:     PetscPrecision precision  = PetscDefined(USE_REAL_SINGLE) ? PETSC_PRECISION_SINGLE : PETSC_PRECISION_DOUBLE;
2660:     PetscInt       nthreads   = 0;
2661:     PetscInt       nCNTL_pre  = mumps->CNTL_pre ? mumps->CNTL_pre[0] : 0;
2662:     PetscInt       nICNTL_pre = mumps->ICNTL_pre ? mumps->ICNTL_pre[0] : 0;
2663:     PetscMUMPSInt  nblk, *blkvar, *blkptr;

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

2669:     PetscCall(PetscOptionsName("-mat_mumps_use_omp_threads", "Convert MPI processes into OpenMP threads", "None", &mumps->use_petsc_omp_support));
2670:     if (mumps->use_petsc_omp_support) nthreads = -1; /* -1 will let PetscOmpCtrlCreate() guess a proper value when user did not supply one */
2671:     /* do not use PetscOptionsInt() so that the option -mat_mumps_use_omp_threads is not displayed twice in the help */
2672:     PetscCall(PetscOptionsGetInt(NULL, ((PetscObject)F)->prefix, "-mat_mumps_use_omp_threads", &nthreads, NULL));
2673:     if (mumps->use_petsc_omp_support) {
2674:       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 : "");
2675: #if PetscDefined(HAVE_OPENMP_SUPPORT)
2676:       PetscCall(PetscOmpCtrlCreate(mumps->petsc_comm, nthreads, &mumps->omp_ctrl));
2677:       PetscCall(PetscOmpCtrlGetOmpComms(mumps->omp_ctrl, &mumps->omp_comm, &mumps->mumps_comm, &mumps->is_omp_master));
2678: #else
2679:       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",
2680:               ((PetscObject)F)->prefix ? ((PetscObject)F)->prefix : "");
2681: #endif
2682:     } else {
2683:       mumps->omp_comm      = PETSC_COMM_SELF;
2684:       mumps->mumps_comm    = mumps->petsc_comm;
2685:       mumps->is_omp_master = PETSC_TRUE;
2686:     }
2687:     PetscCallMPI(MPI_Comm_size(mumps->omp_comm, &mumps->omp_comm_size));
2688:     mumps->reqs = NULL;
2689:     mumps->tag  = 0;

2691:     if (mumps->mumps_comm != MPI_COMM_NULL) {
2692:       if (PetscDefined(HAVE_OPENMP_SUPPORT) && mumps->use_petsc_omp_support) {
2693:         /* It looks like MUMPS does not dup the input comm. Dup a new comm for MUMPS to avoid any tag mismatches. */
2694:         MPI_Comm comm;
2695:         PetscCallMPI(MPI_Comm_dup(mumps->mumps_comm, &comm));
2696:         mumps->mumps_comm = comm;
2697:       } else PetscCall(PetscCommGetComm(mumps->petsc_comm, &mumps->mumps_comm));
2698:     }

2700:     mumps->id.comm_fortran = MPI_Comm_c2f(mumps->mumps_comm);
2701:     mumps->id.job          = JOB_INIT;
2702:     mumps->id.par          = 1; /* host participates factorizaton and solve */
2703:     mumps->id.sym          = mumps->sym;

2705:     size          = mumps->id.size_schur;
2706:     arr           = mumps->id.schur;
2707:     listvar_schur = mumps->id.listvar_schur;
2708:     nblk          = mumps->id.nblk;
2709:     blkvar        = mumps->id.blkvar;
2710:     blkptr        = mumps->id.blkptr;
2711:     if (PetscDefined(USE_DEBUG)) {
2712:       for (PetscInt i = 0; i < size; i++)
2713:         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,
2714:                    A->rmap->N);
2715:     }

2717:     PetscCall(PetscOptionsEnum("-pc_precision", "Precision used by MUMPS", "MATSOLVERMUMPS", PetscPrecisionTypes, (PetscEnum)precision, (PetscEnum *)&precision, NULL));
2718:     PetscCheck(precision == PETSC_PRECISION_SINGLE || precision == PETSC_PRECISION_DOUBLE, PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "MUMPS does not support %s precision", PetscPrecisionTypes[precision]);
2719:     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");
2720:     PetscCall(MatMumpsAllocateInternalID(&mumps->id, precision));

2722:     PetscMUMPS_c(mumps);
2723:     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));

2725:     /* set PETSc-MUMPS default options - override MUMPS default */
2726:     mumps->id.ICNTL(3) = 0;
2727:     mumps->id.ICNTL(4) = 0;
2728:     if (mumps->petsc_size == 1) {
2729:       mumps->id.ICNTL(18) = 0; /* centralized assembled matrix input */
2730:       mumps->id.ICNTL(7)  = 7; /* automatic choice of ordering done by the package */
2731:     } else {
2732:       mumps->id.ICNTL(18) = 3; /* distributed assembled matrix input */
2733:       mumps->id.ICNTL(21) = 1; /* distributed solution */
2734:     }
2735:     if (nblk && blkptr) {
2736:       mumps->id.ICNTL(15) = 1;
2737:       mumps->id.nblk      = nblk;
2738:       mumps->id.blkvar    = blkvar;
2739:       mumps->id.blkptr    = blkptr;
2740:     } else mumps->id.ICNTL(15) = 0;

2742:     /* restore cached ICNTL and CNTL values */
2743:     for (icntl = 0; icntl < nICNTL_pre; ++icntl) mumps->id.ICNTL(mumps->ICNTL_pre[1 + 2 * icntl]) = mumps->ICNTL_pre[2 + 2 * icntl];
2744:     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]);

2746:     PetscCall(PetscFree(mumps->ICNTL_pre));
2747:     PetscCall(PetscFree(mumps->CNTL_pre));

2749:     if (schur) {
2750:       mumps->id.size_schur    = size;
2751:       mumps->id.schur_lld     = size;
2752:       mumps->id.schur         = arr;
2753:       mumps->id.listvar_schur = listvar_schur;
2754:       if (mumps->petsc_size > 1) {
2755:         PetscBool gs; /* gs is false if any rank other than root has non-empty IS */

2757:         mumps->id.ICNTL(19) = 1;                                                                            /* MUMPS returns Schur centralized on the host */
2758:         gs                  = mumps->myid ? (mumps->id.size_schur ? PETSC_FALSE : PETSC_TRUE) : PETSC_TRUE; /* always true on root; false on others if their size != 0 */
2759:         PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &gs, 1, MPI_C_BOOL, MPI_LAND, mumps->petsc_comm));
2760:         PetscCheck(gs, PETSC_COMM_SELF, PETSC_ERR_SUP, "MUMPS distributed parallel Schur complements not yet supported from PETSc");
2761:       } else {
2762:         if (F->factortype == MAT_FACTOR_LU) {
2763:           mumps->id.ICNTL(19) = 3; /* MUMPS returns full matrix */
2764:         } else {
2765:           mumps->id.ICNTL(19) = 2; /* MUMPS returns lower triangular part */
2766:         }
2767:       }
2768:       mumps->id.ICNTL(26) = -1;
2769:     }

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

2777:     mumps->scat_rhs = NULL;
2778:     mumps->scat_sol = NULL;
2779:   }
2780:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_1", "ICNTL(1): output stream for error messages", "None", mumps->id.ICNTL(1), &icntl, &flg));
2781:   if (flg) mumps->id.ICNTL(1) = icntl;
2782:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_2", "ICNTL(2): output stream for diagnostic printing, statistics, and warning", "None", mumps->id.ICNTL(2), &icntl, &flg));
2783:   if (flg) mumps->id.ICNTL(2) = icntl;
2784:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_3", "ICNTL(3): output stream for global information, collected on the host", "None", mumps->id.ICNTL(3), &icntl, &flg));
2785:   if (flg) mumps->id.ICNTL(3) = icntl;

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

2791:   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));
2792:   if (flg) mumps->id.ICNTL(6) = icntl;

2794:   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));
2795:   if (flg) {
2796:     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");
2797:     mumps->id.ICNTL(7) = icntl;
2798:   }

2800:   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));
2801:   /* 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() */
2802:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_10", "ICNTL(10): max num of refinements", "None", mumps->id.ICNTL(10), &mumps->id.ICNTL(10), NULL));
2803:   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));
2804:   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));
2805:   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));
2806:   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));
2807:   PetscCall(MatGetBlockSizes(A, &rbs, &cbs));
2808:   if (rbs == cbs && rbs > 1) mumps->id.ICNTL(15) = (PetscMUMPSInt)-rbs;
2809:   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));
2810:   if (flg) {
2811:     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");
2812:     else if (mumps->id.ICNTL(15) > 0) {
2813:       const PetscInt *bsizes;
2814:       PetscInt        nblocks, p, *blkptr = NULL;
2815:       PetscMPIInt    *recvcounts, *displs, n;
2816:       PetscMPIInt     rank, size = 0;

2818:       PetscCall(MatGetVariableBlockSizes(A, &nblocks, &bsizes));
2819:       flg = PETSC_TRUE;
2820:       for (p = 0; p < nblocks; ++p) {
2821:         if (bsizes[p] > 1) break;
2822:       }
2823:       if (p == nblocks) flg = PETSC_FALSE;
2824:       PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &flg, 1, MPI_C_BOOL, MPI_LOR, PetscObjectComm((PetscObject)A)));
2825:       if (flg) { // if at least one process supplies variable block sizes and they are not all set to 1
2826:         PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank));
2827:         if (rank == 0) PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
2828:         PetscCall(PetscCalloc2(size, &recvcounts, size + 1, &displs));
2829:         PetscCall(PetscMPIIntCast(nblocks, &n));
2830:         PetscCallMPI(MPI_Gather(&n, 1, MPI_INT, recvcounts, 1, MPI_INT, 0, PetscObjectComm((PetscObject)A)));
2831:         for (PetscInt p = 0; p < size; ++p) displs[p + 1] = displs[p] + recvcounts[p];
2832:         PetscCall(PetscMalloc1(displs[size] + 1, &blkptr));
2833:         PetscCallMPI(MPI_Bcast(displs + size, 1, MPIU_INT, 0, PetscObjectComm((PetscObject)A)));
2834:         PetscCallMPI(MPI_Gatherv(bsizes, n, MPIU_INT, blkptr + 1, recvcounts, displs, MPIU_INT, 0, PetscObjectComm((PetscObject)A)));
2835:         if (rank == 0) {
2836:           blkptr[0] = 1;
2837:           for (PetscInt p = 0; p < n; ++p) blkptr[p + 1] += blkptr[p];
2838:           PetscCall(MatMumpsSetBlk(F, displs[size], NULL, blkptr));
2839:         }
2840:         PetscCall(PetscFree2(recvcounts, displs));
2841:         PetscCall(PetscFree(blkptr));
2842:       }
2843:     }
2844:   }
2845:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_19", "ICNTL(19): computes the Schur complement", "None", mumps->id.ICNTL(19), &mumps->id.ICNTL(19), NULL));
2846:   if (mumps->id.ICNTL(19) <= 0 || mumps->id.ICNTL(19) > 3) { /* reset any Schur data (if any) */
2847:     PetscCall(MatMumpsResetSchur_Private(F));
2848:   }

2850:   /* Two MPICH Fortran MPI_IN_PLACE binding bugs prevented the use of 'mpich + mumps'. One happened with "mpi4py + mpich + mumps",
2851:      and was reported by Firedrake. See https://bitbucket.org/mpi4py/mpi4py/issues/162/mpi4py-initialization-breaks-fortran
2852:      and a petsc-maint mailing list thread with subject 'MUMPS segfaults in parallel because of ...'
2853:      This bug was fixed by https://github.com/pmodels/mpich/pull/4149. But the fix brought a new bug,
2854:      see https://github.com/pmodels/mpich/issues/5589. This bug was fixed by https://github.com/pmodels/mpich/pull/5590.
2855:      In short, we could not use distributed RHS until with MPICH v4.0b1 or we enabled a workaround in mumps-5.6.2+
2856:    */
2857:   mumps->ICNTL20 = 10; /* Distributed dense RHS, by default */
2858: #if PETSC_PKG_MUMPS_VERSION_LT(5, 3, 0) || (PetscDefined(HAVE_MPICH) && MPICH_NUMVERSION < 40000101) || PetscDefined(HAVE_MSMPI)
2859:   mumps->ICNTL20 = 0; /* Centralized dense RHS, if need be */
2860: #endif
2861:   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));
2862:   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);
2863: #if PETSC_PKG_MUMPS_VERSION_LT(5, 3, 0)
2864:   PetscCheck(!flg || mumps->ICNTL20 != 10, PETSC_COMM_SELF, PETSC_ERR_SUP, "ICNTL(20)=10 is not supported before MUMPS-5.3.0");
2865: #endif
2866:   /* 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 */

2868:   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));
2869:   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))'
2870:   if (mumps->id.ICNTL(22)) {
2871:     // MUMPS will use the /tmp directory if -mat_mumps_ooc_tmpdir is not set by user.
2872:     // 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().
2873:     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));
2874:   }
2875:   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));
2876:   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));
2877:   if (mumps->id.ICNTL(24)) mumps->id.ICNTL(13) = 1; /* turn-off ScaLAPACK to help with the correct detection of null pivots */

2879:   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));
2880:   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));
2881:   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));
2882:   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));
2883:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_29", "ICNTL(29): parallel ordering 1 = PTScotch, 2 = ParMETIS", "None", mumps->id.ICNTL(29), &mumps->id.ICNTL(29), NULL));
2884:   /* 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 */
2885:   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));
2886:   /* 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 */
2887:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_33", "ICNTL(33): compute determinant", "None", mumps->id.ICNTL(33), &mumps->id.ICNTL(33), NULL));
2888:   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));
2889:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_36", "ICNTL(36): choice of BLR factorization variant", "None", mumps->id.ICNTL(36), &mumps->id.ICNTL(36), NULL));
2890:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_37", "ICNTL(37): compression of the contribution blocks (CB)", "None", mumps->id.ICNTL(37), &mumps->id.ICNTL(37), NULL));
2891:   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));
2892:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_40", "ICNTL(40): adaptive BLR precision feature", "None", mumps->id.ICNTL(40), &mumps->id.ICNTL(40), NULL));
2893:   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));
2894:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_48", "ICNTL(48): multithreading with tree parallelism", "None", mumps->id.ICNTL(48), &mumps->id.ICNTL(48), NULL));
2895:   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));
2896:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_56", "ICNTL(56): postponing and rank-revealing factorization", "None", mumps->id.ICNTL(56), &mumps->id.ICNTL(56), NULL));
2897:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_58", "ICNTL(58): defines options for symbolic factorization", "None", mumps->id.ICNTL(58), &mumps->id.ICNTL(58), NULL));

2899:   PetscCall(PetscOptionsReal("-mat_mumps_cntl_1", "CNTL(1): relative pivoting threshold", "None", (PetscReal)ID_CNTL_GET(mumps->id, 1), &cntl, &flg));
2900:   if (flg) ID_CNTL_SET(mumps->id, 1, cntl);
2901:   PetscCall(PetscOptionsReal("-mat_mumps_cntl_2", "CNTL(2): stopping criterion of refinement", "None", (PetscReal)ID_CNTL_GET(mumps->id, 2), &cntl, &flg));
2902:   if (flg) ID_CNTL_SET(mumps->id, 2, cntl);
2903:   PetscCall(PetscOptionsReal("-mat_mumps_cntl_3", "CNTL(3): absolute pivoting threshold", "None", (PetscReal)ID_CNTL_GET(mumps->id, 3), &cntl, &flg));
2904:   if (flg) ID_CNTL_SET(mumps->id, 3, cntl);
2905:   PetscCall(PetscOptionsReal("-mat_mumps_cntl_4", "CNTL(4): value for static pivoting", "None", (PetscReal)ID_CNTL_GET(mumps->id, 4), &cntl, &flg));
2906:   if (flg) ID_CNTL_SET(mumps->id, 4, cntl);
2907:   PetscCall(PetscOptionsReal("-mat_mumps_cntl_5", "CNTL(5): fixation for null pivots", "None", (PetscReal)ID_CNTL_GET(mumps->id, 5), &cntl, &flg));
2908:   if (flg) ID_CNTL_SET(mumps->id, 5, cntl);
2909:   PetscCall(PetscOptionsReal("-mat_mumps_cntl_7", "CNTL(7): dropping parameter used during BLR", "None", (PetscReal)ID_CNTL_GET(mumps->id, 7), &cntl, &flg));
2910:   if (flg) ID_CNTL_SET(mumps->id, 7, cntl);

2912:   PetscCall(PetscOptionsIntArray("-mat_mumps_view_info", "request INFO local to each processor", "", info, &ninfo, NULL));
2913:   if (ninfo) {
2914:     PetscCheck(ninfo <= 80, PETSC_COMM_SELF, PETSC_ERR_USER, "number of INFO %" PetscInt_FMT " must <= 80", ninfo);
2915:     PetscCall(PetscMalloc1(ninfo, &mumps->info));
2916:     mumps->ninfo = ninfo;
2917:     for (i = 0; i < ninfo; i++) {
2918:       PetscCheck(info[i] >= 0 && info[i] <= 80, PETSC_COMM_SELF, PETSC_ERR_USER, "index of INFO %" PetscInt_FMT " must between 1 and 80", ninfo);
2919:       mumps->info[i] = info[i];
2920:     }
2921:   }
2922:   PetscOptionsEnd();
2923:   PetscFunctionReturn(PETSC_SUCCESS);
2924: }

2926: static PetscErrorCode MatFactorSymbolic_MUMPS_ReportIfError(Mat F, Mat A, PETSC_UNUSED const MatFactorInfo *info, Mat_MUMPS *mumps)
2927: {
2928:   PetscFunctionBegin;
2929:   if (mumps->id.INFOG(1) < 0) {
2930:     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));
2931:     if (mumps->id.INFOG(1) == -6) {
2932:       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)));
2933:       F->factorerrortype = MAT_FACTOR_STRUCT_ZEROPIVOT;
2934:     } else if (mumps->id.INFOG(1) == -5 || mumps->id.INFOG(1) == -7) {
2935:       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)));
2936:       F->factorerrortype = MAT_FACTOR_OUTMEMORY;
2937:     } else {
2938:       PetscCall(PetscInfo(F, "MUMPS error in analysis: INFOG(1)=%d, INFO(2)=%d " MUMPS_MANUALS "\n", mumps->id.INFOG(1), mumps->id.INFO(2)));
2939:       F->factorerrortype = MAT_FACTOR_OTHER;
2940:     }
2941:   }
2942:   if (!mumps->id.n) F->factorerrortype = MAT_FACTOR_NOERROR;
2943:   PetscFunctionReturn(PETSC_SUCCESS);
2944: }

2946: static PetscErrorCode MatLUFactorSymbolic_AIJMUMPS(Mat F, Mat A, IS r, PETSC_UNUSED IS c, const MatFactorInfo *info)
2947: {
2948:   Mat_MUMPS     *mumps = (Mat_MUMPS *)F->data;
2949:   Vec            b;
2950:   const PetscInt M = A->rmap->N;

2952:   PetscFunctionBegin;
2953:   if (mumps->matstruc == SAME_NONZERO_PATTERN) {
2954:     /* F is assembled by a previous call of MatLUFactorSymbolic_AIJMUMPS() */
2955:     PetscFunctionReturn(PETSC_SUCCESS);
2956:   }

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

2961:   PetscCall((*mumps->ConvertToTriples)(A, 1, MAT_INITIAL_MATRIX, mumps));
2962:   PetscCall(MatMumpsGatherNonzerosOnMaster(MAT_INITIAL_MATRIX, mumps));
2963:   PetscCall(MatMumpsEnsureSchurArray_Private(F));

2965:   /* analysis phase */
2966:   mumps->id.job = JOB_FACTSYMBOLIC;
2967:   PetscCall(PetscMUMPSIntCast(M, &mumps->id.n));
2968:   switch (mumps->id.ICNTL(18)) {
2969:   case 0: /* centralized assembled matrix input */
2970:     if (!mumps->myid) {
2971:       mumps->id.nnz = mumps->nnz;
2972:       mumps->id.irn = mumps->irn;
2973:       mumps->id.jcn = mumps->jcn;
2974:       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));
2975:       if (r && mumps->id.ICNTL(7) == 7 && !F->schur) {
2976:         mumps->id.ICNTL(7) = 1;
2977:         if (!mumps->myid) {
2978:           const PetscInt *idx;

2980:           PetscCall(PetscMalloc1(M, &mumps->id.perm_in));
2981:           PetscCall(ISGetIndices(r, &idx));
2982:           for (PetscInt i = 0; i < M; i++) PetscCall(PetscMUMPSIntCast(idx[i] + 1, &mumps->id.perm_in[i])); /* perm_in[]: start from 1, not 0! */
2983:           PetscCall(ISRestoreIndices(r, &idx));
2984:         }
2985:       }
2986:     }
2987:     break;
2988:   case 3: /* distributed assembled matrix input (size>1) */
2989:     mumps->id.nnz_loc = mumps->nnz;
2990:     mumps->id.irn_loc = mumps->irn;
2991:     mumps->id.jcn_loc = mumps->jcn;
2992:     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));
2993:     if (mumps->ICNTL20 == 0) { /* Centralized rhs. Create scatter scat_rhs for repeated use in MatSolve() */
2994:       PetscCall(MatCreateVecs(A, NULL, &b));
2995:       PetscCall(VecScatterCreateToZero(b, &mumps->scat_rhs, &mumps->b_seq));
2996:       PetscCall(VecDestroy(&b));
2997:     }
2998:     break;
2999:   }
3000:   if (A->rmap->N && A->cmap->N) {
3001:     PetscMUMPS_c(mumps);
3002:     PetscCall(MatFactorSymbolic_MUMPS_ReportIfError(F, A, info, mumps));
3003:   }
3004:   F->ops->lufactornumeric   = MatFactorNumeric_MUMPS;
3005:   F->ops->solve             = MatSolve_MUMPS;
3006:   F->ops->solvetranspose    = MatSolveTranspose_MUMPS;
3007:   F->ops->matsolve          = MatMatSolve_MUMPS;
3008:   F->ops->mattransposesolve = MatMatTransposeSolve_MUMPS;
3009:   F->ops->matsolvetranspose = MatMatSolveTranspose_MUMPS;

3011:   mumps->matstruc = SAME_NONZERO_PATTERN;
3012:   PetscFunctionReturn(PETSC_SUCCESS);
3013: }

3015: /* Note the PETSc r and c permutations are ignored */
3016: static PetscErrorCode MatLUFactorSymbolic_BAIJMUMPS(Mat F, Mat A, PETSC_UNUSED IS r, PETSC_UNUSED IS c, const MatFactorInfo *info)
3017: {
3018:   Mat_MUMPS     *mumps = (Mat_MUMPS *)F->data;
3019:   Vec            b;
3020:   const PetscInt M = A->rmap->N;

3022:   PetscFunctionBegin;
3023:   if (mumps->matstruc == SAME_NONZERO_PATTERN) {
3024:     /* F is assembled by a previous call of MatLUFactorSymbolic_BAIJMUMPS() */
3025:     PetscFunctionReturn(PETSC_SUCCESS);
3026:   }

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

3031:   PetscCall((*mumps->ConvertToTriples)(A, 1, MAT_INITIAL_MATRIX, mumps));
3032:   PetscCall(MatMumpsGatherNonzerosOnMaster(MAT_INITIAL_MATRIX, mumps));
3033:   PetscCall(MatMumpsEnsureSchurArray_Private(F));

3035:   /* analysis phase */
3036:   mumps->id.job = JOB_FACTSYMBOLIC;
3037:   PetscCall(PetscMUMPSIntCast(M, &mumps->id.n));
3038:   switch (mumps->id.ICNTL(18)) {
3039:   case 0: /* centralized assembled matrix input */
3040:     if (!mumps->myid) {
3041:       mumps->id.nnz = mumps->nnz;
3042:       mumps->id.irn = mumps->irn;
3043:       mumps->id.jcn = mumps->jcn;
3044:       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));
3045:     }
3046:     break;
3047:   case 3: /* distributed assembled matrix input (size>1) */
3048:     mumps->id.nnz_loc = mumps->nnz;
3049:     mumps->id.irn_loc = mumps->irn;
3050:     mumps->id.jcn_loc = mumps->jcn;
3051:     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));
3052:     if (mumps->ICNTL20 == 0) { /* Centralized rhs. Create scatter scat_rhs for repeated use in MatSolve() */
3053:       PetscCall(MatCreateVecs(A, NULL, &b));
3054:       PetscCall(VecScatterCreateToZero(b, &mumps->scat_rhs, &mumps->b_seq));
3055:       PetscCall(VecDestroy(&b));
3056:     }
3057:     break;
3058:   }
3059:   if (A->rmap->N && A->cmap->N) {
3060:     PetscMUMPS_c(mumps);
3061:     PetscCall(MatFactorSymbolic_MUMPS_ReportIfError(F, A, info, mumps));
3062:   }
3063:   F->ops->lufactornumeric   = MatFactorNumeric_MUMPS;
3064:   F->ops->solve             = MatSolve_MUMPS;
3065:   F->ops->solvetranspose    = MatSolveTranspose_MUMPS;
3066:   F->ops->matsolve          = MatMatSolve_MUMPS;
3067:   F->ops->mattransposesolve = MatMatTransposeSolve_MUMPS;
3068:   F->ops->matsolvetranspose = MatMatSolveTranspose_MUMPS;

3070:   mumps->matstruc = SAME_NONZERO_PATTERN;
3071:   PetscFunctionReturn(PETSC_SUCCESS);
3072: }

3074: /* Note the PETSc r permutation and factor info are ignored */
3075: static PetscErrorCode MatCholeskyFactorSymbolic_MUMPS(Mat F, Mat A, PETSC_UNUSED IS r, const MatFactorInfo *info)
3076: {
3077:   Mat_MUMPS     *mumps = (Mat_MUMPS *)F->data;
3078:   Vec            b;
3079:   const PetscInt M = A->rmap->N;

3081:   PetscFunctionBegin;
3082:   if (mumps->matstruc == SAME_NONZERO_PATTERN) {
3083:     /* F is assembled by a previous call of MatCholeskyFactorSymbolic_MUMPS() */
3084:     PetscFunctionReturn(PETSC_SUCCESS);
3085:   }

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

3090:   PetscCall((*mumps->ConvertToTriples)(A, 1, MAT_INITIAL_MATRIX, mumps));
3091:   PetscCall(MatMumpsGatherNonzerosOnMaster(MAT_INITIAL_MATRIX, mumps));
3092:   PetscCall(MatMumpsEnsureSchurArray_Private(F));

3094:   /* analysis phase */
3095:   mumps->id.job = JOB_FACTSYMBOLIC;
3096:   PetscCall(PetscMUMPSIntCast(M, &mumps->id.n));
3097:   switch (mumps->id.ICNTL(18)) {
3098:   case 0: /* centralized assembled matrix input */
3099:     if (!mumps->myid) {
3100:       mumps->id.nnz = mumps->nnz;
3101:       mumps->id.irn = mumps->irn;
3102:       mumps->id.jcn = mumps->jcn;
3103:       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));
3104:     }
3105:     break;
3106:   case 3: /* distributed assembled matrix input (size>1) */
3107:     mumps->id.nnz_loc = mumps->nnz;
3108:     mumps->id.irn_loc = mumps->irn;
3109:     mumps->id.jcn_loc = mumps->jcn;
3110:     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));
3111:     if (mumps->ICNTL20 == 0) { /* Centralized rhs. Create scatter scat_rhs for repeated use in MatSolve() */
3112:       PetscCall(MatCreateVecs(A, NULL, &b));
3113:       PetscCall(VecScatterCreateToZero(b, &mumps->scat_rhs, &mumps->b_seq));
3114:       PetscCall(VecDestroy(&b));
3115:     }
3116:     break;
3117:   }
3118:   if (A->rmap->N && A->cmap->N) {
3119:     PetscMUMPS_c(mumps);
3120:     PetscCall(MatFactorSymbolic_MUMPS_ReportIfError(F, A, info, mumps));
3121:   }
3122:   F->ops->choleskyfactornumeric = MatFactorNumeric_MUMPS;
3123:   F->ops->solve                 = MatSolve_MUMPS;
3124:   F->ops->solvetranspose        = MatSolve_MUMPS;
3125:   F->ops->matsolve              = MatMatSolve_MUMPS;
3126:   F->ops->mattransposesolve     = MatMatTransposeSolve_MUMPS;
3127:   F->ops->matsolvetranspose     = MatMatSolveTranspose_MUMPS;
3128: #if PetscDefined(USE_COMPLEX)
3129:   F->ops->getinertia = NULL;
3130: #else
3131:   F->ops->getinertia = MatGetInertia_SBAIJMUMPS;
3132: #endif

3134:   mumps->matstruc = SAME_NONZERO_PATTERN;
3135:   PetscFunctionReturn(PETSC_SUCCESS);
3136: }

3138: static PetscErrorCode MatView_MUMPS(Mat A, PetscViewer viewer)
3139: {
3140:   PetscBool         isascii;
3141:   PetscViewerFormat format;
3142:   Mat_MUMPS        *mumps = (Mat_MUMPS *)A->data;

3144:   PetscFunctionBegin;
3145:   /* check if matrix is mumps type */
3146:   if (A->ops->solve != MatSolve_MUMPS) PetscFunctionReturn(PETSC_SUCCESS);

3148:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
3149:   if (isascii) {
3150:     PetscCall(PetscViewerGetFormat(viewer, &format));
3151:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
3152:       PetscCall(PetscViewerASCIIPrintf(viewer, "MUMPS run parameters:\n"));
3153:       PetscCall(PetscViewerASCIIPrintf(viewer, "  precision:                           %s\n", PetscPrecisionTypes[mumps->id.precision]));
3154:       if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
3155:         PetscCall(PetscViewerASCIIPrintf(viewer, "  SYM (matrix type):                   %d\n", mumps->id.sym));
3156:         PetscCall(PetscViewerASCIIPrintf(viewer, "  PAR (host participation):            %d\n", mumps->id.par));
3157:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(1) (output for error):         %d\n", mumps->id.ICNTL(1)));
3158:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(2) (output of diagnostic msg): %d\n", mumps->id.ICNTL(2)));
3159:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(3) (output for global info):   %d\n", mumps->id.ICNTL(3)));
3160:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(4) (level of printing):        %d\n", mumps->id.ICNTL(4)));
3161:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(5) (input mat struct):         %d\n", mumps->id.ICNTL(5)));
3162:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(6) (matrix prescaling):        %d\n", mumps->id.ICNTL(6)));
3163:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(7) (sequential matrix ordering):%d\n", mumps->id.ICNTL(7)));
3164:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(8) (scaling strategy):         %d\n", mumps->id.ICNTL(8)));
3165:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(10) (max num of refinements):  %d\n", mumps->id.ICNTL(10)));
3166:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(11) (error analysis):          %d\n", mumps->id.ICNTL(11)));
3167:         if (mumps->id.ICNTL(11) > 0) {
3168:           PetscCall(PetscViewerASCIIPrintf(viewer, "    RINFOG(4) (inf norm of input mat):        %g\n", (double)ID_RINFOG_GET(mumps->id, 4)));
3169:           PetscCall(PetscViewerASCIIPrintf(viewer, "    RINFOG(5) (inf norm of solution):         %g\n", (double)ID_RINFOG_GET(mumps->id, 5)));
3170:           PetscCall(PetscViewerASCIIPrintf(viewer, "    RINFOG(6) (inf norm of residual):         %g\n", (double)ID_RINFOG_GET(mumps->id, 6)));
3171:           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)));
3172:           PetscCall(PetscViewerASCIIPrintf(viewer, "    RINFOG(9) (error estimate):               %g\n", (double)ID_RINFOG_GET(mumps->id, 9)));
3173:           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)));
3174:         }
3175:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(12) (efficiency control):                         %d\n", mumps->id.ICNTL(12)));
3176:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(13) (sequential factorization of the root node):  %d\n", mumps->id.ICNTL(13)));
3177:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(14) (percentage of estimated workspace increase): %d\n", mumps->id.ICNTL(14)));
3178:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(15) (compression of the input matrix):            %d\n", mumps->id.ICNTL(15)));
3179:         /* ICNTL(15-17) not used */
3180:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(18) (input mat struct):                           %d\n", mumps->id.ICNTL(18)));
3181:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(19) (Schur complement info):                      %d\n", mumps->id.ICNTL(19)));
3182:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(20) (RHS sparse pattern):                         %d\n", mumps->id.ICNTL(20)));
3183:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(21) (solution struct):                            %d\n", mumps->id.ICNTL(21)));
3184:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(22) (in-core/out-of-core facility):               %d\n", mumps->id.ICNTL(22)));
3185:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(23) (max size of memory allocated locally):       %d\n", mumps->id.ICNTL(23)));

3187:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(24) (detection of null pivot rows):               %d\n", mumps->id.ICNTL(24)));
3188:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(25) (computation of a null space basis):          %d\n", mumps->id.ICNTL(25)));
3189:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(26) (Schur options for RHS or solution):          %d\n", mumps->id.ICNTL(26)));
3190:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(27) (blocking size for multiple RHS):             %d\n", mumps->id.ICNTL(27)));
3191:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(28) (use parallel or sequential ordering):        %d\n", mumps->id.ICNTL(28)));
3192:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(29) (parallel ordering):                          %d\n", mumps->id.ICNTL(29)));

3194:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(30) (user-specified set of entries in inv(A)):    %d\n", mumps->id.ICNTL(30)));
3195:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(31) (factors is discarded in the solve phase):    %d\n", mumps->id.ICNTL(31)));
3196:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(33) (compute determinant):                        %d\n", mumps->id.ICNTL(33)));
3197:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(35) (activate BLR based factorization):           %d\n", mumps->id.ICNTL(35)));
3198:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(36) (choice of BLR factorization variant):        %d\n", mumps->id.ICNTL(36)));
3199:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(37) (compression of the contribution blocks):     %d\n", mumps->id.ICNTL(37)));
3200:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(38) (estimated compression rate of LU factors):   %d\n", mumps->id.ICNTL(38)));
3201:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(40) (adaptive BLR precision feature):             %d\n", mumps->id.ICNTL(40)));
3202:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(47) (single precision factorization in a double precision instance): %d\n", mumps->id.ICNTL(47)));
3203:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(48) (multithreading with tree parallelism):       %d\n", mumps->id.ICNTL(48)));
3204:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(49) (compact workarray at the end of factorization phase):%d\n", mumps->id.ICNTL(49)));
3205:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(56) (postponing and rank-revealing factorization):%d\n", mumps->id.ICNTL(56)));
3206:         PetscCall(PetscViewerASCIIPrintf(viewer, "  ICNTL(58) (options for symbolic factorization):         %d\n", mumps->id.ICNTL(58)));

3208:         PetscCall(PetscViewerASCIIPrintf(viewer, "  CNTL(1) (relative pivoting threshold):      %g\n", (double)ID_CNTL_GET(mumps->id, 1)));
3209:         PetscCall(PetscViewerASCIIPrintf(viewer, "  CNTL(2) (stopping criterion of refinement): %g\n", (double)ID_CNTL_GET(mumps->id, 2)));
3210:         PetscCall(PetscViewerASCIIPrintf(viewer, "  CNTL(3) (absolute pivoting threshold):      %g\n", (double)ID_CNTL_GET(mumps->id, 3)));
3211:         PetscCall(PetscViewerASCIIPrintf(viewer, "  CNTL(4) (value of static pivoting):         %g\n", (double)ID_CNTL_GET(mumps->id, 4)));
3212:         PetscCall(PetscViewerASCIIPrintf(viewer, "  CNTL(5) (fixation for null pivots):         %g\n", (double)ID_CNTL_GET(mumps->id, 5)));
3213:         PetscCall(PetscViewerASCIIPrintf(viewer, "  CNTL(7) (dropping parameter for BLR):       %g\n", (double)ID_CNTL_GET(mumps->id, 7)));

3215:         /* information local to each processor */
3216:         PetscCall(PetscViewerASCIIPrintf(viewer, "  RINFO(1) (local estimated flops for the elimination after analysis):\n"));
3217:         PetscCall(PetscViewerASCIIPushSynchronized(viewer));
3218:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "    [%d] %g\n", mumps->myid, (double)ID_RINFO_GET(mumps->id, 1)));
3219:         PetscCall(PetscViewerFlush(viewer));
3220:         PetscCall(PetscViewerASCIIPrintf(viewer, "  RINFO(2) (local estimated flops for the assembly after factorization):\n"));
3221:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "    [%d] %g\n", mumps->myid, (double)ID_RINFO_GET(mumps->id, 2)));
3222:         PetscCall(PetscViewerFlush(viewer));
3223:         PetscCall(PetscViewerASCIIPrintf(viewer, "  RINFO(3) (local estimated flops for the elimination after factorization):\n"));
3224:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "    [%d] %g\n", mumps->myid, (double)ID_RINFO_GET(mumps->id, 3)));
3225:         PetscCall(PetscViewerFlush(viewer));

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

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

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

3239:         if (mumps->ninfo && mumps->ninfo <= 80) {
3240:           for (PetscInt i = 0; i < mumps->ninfo; i++) {
3241:             PetscCall(PetscViewerASCIIPrintf(viewer, "  INFO(%" PetscInt_FMT "):\n", mumps->info[i]));
3242:             PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "    [%d] %d\n", mumps->myid, mumps->id.INFO(mumps->info[i])));
3243:             PetscCall(PetscViewerFlush(viewer));
3244:           }
3245:         }
3246:         PetscCall(PetscViewerASCIIPopSynchronized(viewer));
3247:       } else PetscCall(PetscViewerASCIIPrintf(viewer, "  Use -%sksp_view ::ascii_info_detail to display information for all processes\n", ((PetscObject)A)->prefix ? ((PetscObject)A)->prefix : ""));

3249:       if (mumps->myid == 0) { /* information from the host */
3250:         PetscCall(PetscViewerASCIIPrintf(viewer, "  RINFOG(1) (global estimated flops for the elimination after analysis): %g\n", (double)ID_RINFOG_GET(mumps->id, 1)));
3251:         PetscCall(PetscViewerASCIIPrintf(viewer, "  RINFOG(2) (global estimated flops for the assembly after factorization): %g\n", (double)ID_RINFOG_GET(mumps->id, 2)));
3252:         PetscCall(PetscViewerASCIIPrintf(viewer, "  RINFOG(3) (global estimated flops for the elimination after factorization): %g\n", (double)ID_RINFOG_GET(mumps->id, 3)));
3253:         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)));

3255:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(3) (estimated real workspace for factors on all processors after analysis): %d\n", mumps->id.INFOG(3)));
3256:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(4) (estimated integer workspace for factors on all processors after analysis): %d\n", mumps->id.INFOG(4)));
3257:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(5) (estimated maximum front size in the complete tree): %d\n", mumps->id.INFOG(5)));
3258:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(6) (number of nodes in the complete tree): %d\n", mumps->id.INFOG(6)));
3259:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(7) (ordering option effectively used after analysis): %d\n", mumps->id.INFOG(7)));
3260:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(8) (structural symmetry in percent of the permuted matrix after analysis): %d\n", mumps->id.INFOG(8)));
3261:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(9) (total real/complex workspace to store the matrix factors after factorization): %d\n", mumps->id.INFOG(9)));
3262:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(10) (total integer space store the matrix factors after factorization): %d\n", mumps->id.INFOG(10)));
3263:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(11) (order of largest frontal matrix after factorization): %d\n", mumps->id.INFOG(11)));
3264:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(12) (number of off-diagonal pivots): %d\n", mumps->id.INFOG(12)));
3265:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(13) (number of delayed pivots after factorization): %d\n", mumps->id.INFOG(13)));
3266:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(14) (number of memory compress after factorization): %d\n", mumps->id.INFOG(14)));
3267:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(15) (number of steps of iterative refinement after solution): %d\n", mumps->id.INFOG(15)));
3268:         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)));
3269:         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)));
3270:         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)));
3271:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(19) (size of all MUMPS internal data allocated during factorization: sum over all processors): %d\n", mumps->id.INFOG(19)));
3272:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(20) (estimated number of entries in the factors): %d\n", mumps->id.INFOG(20)));
3273:         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)));
3274:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(22) (size in MB of memory effectively used during factorization - sum over all processors): %d\n", mumps->id.INFOG(22)));
3275:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(23) (after analysis: value of ICNTL(6) effectively used): %d\n", mumps->id.INFOG(23)));
3276:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(24) (after analysis: value of ICNTL(12) effectively used): %d\n", mumps->id.INFOG(24)));
3277:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(25) (after factorization: number of pivots modified by static pivoting): %d\n", mumps->id.INFOG(25)));
3278:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(28) (after factorization: number of null pivots encountered): %d\n", mumps->id.INFOG(28)));
3279:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(29) (after factorization: effective number of entries in the factors (sum over all processors)): %d\n", mumps->id.INFOG(29)));
3280:         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)));
3281:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(32) (after analysis: type of analysis done): %d\n", mumps->id.INFOG(32)));
3282:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(33) (value used for ICNTL(8)): %d\n", mumps->id.INFOG(33)));
3283:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(34) (exponent of the determinant if determinant is requested): %d\n", mumps->id.INFOG(34)));
3284:         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)));
3285:         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)));
3286:         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)));
3287:         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)));
3288:         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)));
3289:       }
3290:     }
3291:   }
3292:   PetscFunctionReturn(PETSC_SUCCESS);
3293: }

3295: static PetscErrorCode MatGetInfo_MUMPS(Mat A, PETSC_UNUSED MatInfoType flag, MatInfo *info)
3296: {
3297:   Mat_MUMPS *mumps = (Mat_MUMPS *)A->data;

3299:   PetscFunctionBegin;
3300:   info->block_size        = 1.0;
3301:   info->nz_allocated      = mumps->id.INFOG(20) >= 0 ? mumps->id.INFOG(20) : -1.0e6 * mumps->id.INFOG(20);
3302:   info->nz_used           = mumps->id.INFOG(20) >= 0 ? mumps->id.INFOG(20) : -1.0e6 * mumps->id.INFOG(20);
3303:   info->nz_unneeded       = 0.0;
3304:   info->assemblies        = 0.0;
3305:   info->mallocs           = 0.0;
3306:   info->memory            = 0.0;
3307:   info->fill_ratio_given  = 0;
3308:   info->fill_ratio_needed = 0;
3309:   info->factor_mallocs    = 0;
3310:   PetscFunctionReturn(PETSC_SUCCESS);
3311: }

3313: static PetscErrorCode MatFactorSetSchurIS_MUMPS(Mat F, IS is)
3314: {
3315:   Mat_MUMPS      *mumps = (Mat_MUMPS *)F->data;
3316:   const PetscInt *idxs;
3317:   PetscInt        size, i;

3319:   PetscFunctionBegin;
3320:   PetscCall(MatMumpsResetSchur_Private(F));
3321:   if (!is) PetscFunctionReturn(PETSC_SUCCESS);
3322:   /* Schur complement matrix */
3323:   PetscCall(ISGetLocalSize(is, &size));
3324:   PetscCall(MatCreateSeqDense(PETSC_COMM_SELF, size, size, NULL, &F->schur));
3325:   // don't allocate mumps->id.schur[] now as its precision is yet to be known
3326:   PetscCall(PetscMUMPSIntCast(size, &mumps->id.size_schur));
3327:   PetscCall(PetscMUMPSIntCast(size, &mumps->id.schur_lld));
3328:   if (mumps->sym == 1) PetscCall(MatSetOption(F->schur, MAT_SPD, PETSC_TRUE));

3330:   /* MUMPS expects Fortran style indices */
3331:   PetscCall(PetscMalloc1(size, &mumps->id.listvar_schur));
3332:   PetscCall(ISGetIndices(is, &idxs));
3333:   for (i = 0; i < size; i++) PetscCall(PetscMUMPSIntCast(idxs[i] + 1, &mumps->id.listvar_schur[i]));
3334:   PetscCall(ISRestoreIndices(is, &idxs));
3335:   /* set a special value of ICNTL (not handled my MUMPS) to be used in the solve phase by PETSc */
3336:   if (mumps->id.icntl) mumps->id.ICNTL(26) = -1;
3337:   else mumps->ICNTL26 = -1;
3338:   PetscFunctionReturn(PETSC_SUCCESS);
3339: }

3341: static PetscErrorCode MatFactorCreateSchurComplement_MUMPS(Mat F, Mat *S)
3342: {
3343:   Mat          St;
3344:   Mat_MUMPS   *mumps = (Mat_MUMPS *)F->data;
3345:   PetscScalar *array;
3346:   PetscInt     i, j, N = mumps->id.size_schur;

3348:   PetscFunctionBegin;
3349:   PetscCheck(mumps->id.ICNTL(19), PetscObjectComm((PetscObject)F), PETSC_ERR_ORDER, "Schur complement mode not selected! Call MatFactorSetSchurIS() to enable it");
3350:   PetscCall(MatCreate(PETSC_COMM_SELF, &St));
3351:   PetscCall(MatSetSizes(St, PETSC_DECIDE, PETSC_DECIDE, mumps->id.size_schur, mumps->id.size_schur));
3352:   PetscCall(MatSetType(St, MATDENSE));
3353:   PetscCall(MatSetUp(St));
3354:   PetscCall(MatDenseGetArray(St, &array));
3355:   PetscCall(MatMumpsEnsureSchurArray_Private(F));
3356:   if (!mumps->sym) {                /* MUMPS always returns a full matrix */
3357:     if (mumps->id.ICNTL(19) == 1) { /* stored by rows */
3358:       for (i = 0; i < N; i++) {
3359:         for (j = 0; j < N; j++) array[j * N + i] = ID_FIELD_GET(mumps->id, schur, i * N + j);
3360:       }
3361:     } else { /* stored by columns */
3362:       PetscCall(MatMumpsCastMumpsScalarArray(N * N, mumps->id.precision, mumps->id.schur, array));
3363:     }
3364:   } else {                          /* either full or lower-triangular (not packed) */
3365:     if (mumps->id.ICNTL(19) == 2) { /* lower triangular stored by columns */
3366:       for (i = 0; i < N; i++) {
3367:         for (j = i; j < N; j++) array[i * N + j] = array[j * N + i] = ID_FIELD_GET(mumps->id, schur, i * N + j);
3368:       }
3369:     } else if (mumps->id.ICNTL(19) == 3) { /* full matrix */
3370:       PetscCall(MatMumpsCastMumpsScalarArray(N * N, mumps->id.precision, mumps->id.schur, array));
3371:     } else { /* ICNTL(19) == 1 lower triangular stored by rows */
3372:       for (i = 0; i < N; i++) {
3373:         for (j = 0; j < i + 1; j++) array[i * N + j] = array[j * N + i] = ID_FIELD_GET(mumps->id, schur, i * N + j);
3374:       }
3375:     }
3376:   }
3377:   PetscCall(MatDenseRestoreArray(St, &array));
3378:   *S = St;
3379:   PetscFunctionReturn(PETSC_SUCCESS);
3380: }

3382: static PetscErrorCode MatMumpsSetIcntl_MUMPS(Mat F, PetscInt icntl, PetscInt ival)
3383: {
3384:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3386:   PetscFunctionBegin;
3387:   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);
3388:   if (mumps->id.job == JOB_NULL) {                                            /* need to cache icntl and ival since PetscMUMPS_c() has never been called */
3389:     PetscMUMPSInt i, nICNTL_pre = mumps->ICNTL_pre ? mumps->ICNTL_pre[0] : 0; /* number of already cached ICNTL */
3390:     for (i = 0; i < nICNTL_pre; ++i)
3391:       if (mumps->ICNTL_pre[1 + 2 * i] == icntl) break; /* is this ICNTL already cached? */
3392:     if (i == nICNTL_pre) {                             /* not already cached */
3393:       if (i > 0) PetscCall(PetscRealloc(sizeof(PetscMUMPSInt) * (2 * nICNTL_pre + 3), &mumps->ICNTL_pre));
3394:       else PetscCall(PetscCalloc(sizeof(PetscMUMPSInt) * 3, &mumps->ICNTL_pre));
3395:       mumps->ICNTL_pre[0]++;
3396:     }
3397:     mumps->ICNTL_pre[1 + 2 * i] = (PetscMUMPSInt)icntl;
3398:     PetscCall(PetscMUMPSIntCast(ival, mumps->ICNTL_pre + 2 + 2 * i));
3399:   } else PetscCall(PetscMUMPSIntCast(ival, &mumps->id.ICNTL(icntl)));
3400:   PetscFunctionReturn(PETSC_SUCCESS);
3401: }

3403: static PetscErrorCode MatMumpsGetIcntl_MUMPS(Mat F, PetscInt icntl, PetscInt *ival)
3404: {
3405:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3407:   PetscFunctionBegin;
3408:   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);
3409:   if (mumps->id.job == JOB_NULL) {
3410:     PetscInt i, nICNTL_pre = mumps->ICNTL_pre ? mumps->ICNTL_pre[0] : 0;
3411:     *ival = 0;
3412:     for (i = 0; i < nICNTL_pre; ++i) {
3413:       if (mumps->ICNTL_pre[1 + 2 * i] == icntl) *ival = mumps->ICNTL_pre[2 + 2 * i];
3414:     }
3415:   } else *ival = mumps->id.ICNTL(icntl);
3416:   PetscFunctionReturn(PETSC_SUCCESS);
3417: }

3419: static PetscErrorCode MatMumpsSetCntl_MUMPS(Mat F, PetscInt icntl, PetscReal val)
3420: {
3421:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3423:   PetscFunctionBegin;
3424:   PetscCheck(icntl >= 1 && icntl <= 7, PetscObjectComm((PetscObject)F), PETSC_ERR_ARG_WRONG, "Unsupported CNTL value %" PetscInt_FMT, icntl);
3425:   if (mumps->id.job == JOB_NULL) {
3426:     PetscInt i, nCNTL_pre = mumps->CNTL_pre ? mumps->CNTL_pre[0] : 0;
3427:     for (i = 0; i < nCNTL_pre; ++i)
3428:       if (mumps->CNTL_pre[1 + 2 * i] == icntl) break;
3429:     if (i == nCNTL_pre) {
3430:       if (i > 0) PetscCall(PetscRealloc(sizeof(PetscReal) * (2 * nCNTL_pre + 3), &mumps->CNTL_pre));
3431:       else PetscCall(PetscCalloc(sizeof(PetscReal) * 3, &mumps->CNTL_pre));
3432:       mumps->CNTL_pre[0]++;
3433:     }
3434:     mumps->CNTL_pre[1 + 2 * i] = icntl;
3435:     mumps->CNTL_pre[2 + 2 * i] = val;
3436:   } else ID_CNTL_SET(mumps->id, icntl, val);
3437:   PetscFunctionReturn(PETSC_SUCCESS);
3438: }

3440: static PetscErrorCode MatMumpsGetCntl_MUMPS(Mat F, PetscInt icntl, PetscReal *val)
3441: {
3442:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3444:   PetscFunctionBegin;
3445:   PetscCheck(icntl >= 1 && icntl <= 7, PetscObjectComm((PetscObject)F), PETSC_ERR_ARG_WRONG, "Unsupported CNTL value %" PetscInt_FMT, icntl);
3446:   if (mumps->id.job == JOB_NULL) {
3447:     PetscInt i, nCNTL_pre = mumps->CNTL_pre ? mumps->CNTL_pre[0] : 0;
3448:     *val = 0.0;
3449:     for (i = 0; i < nCNTL_pre; ++i) {
3450:       if (mumps->CNTL_pre[1 + 2 * i] == icntl) *val = mumps->CNTL_pre[2 + 2 * i];
3451:     }
3452:   } else *val = ID_CNTL_GET(mumps->id, icntl);
3453:   PetscFunctionReturn(PETSC_SUCCESS);
3454: }

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

3459:   Logically Collective

3461:   Input Parameters:
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`.
3463: - tmpdir - temporary directory for out-of-core facility.

3465:   Level: beginner

3467:   Note:
3468:   To make it effective, this routine must be called before the numeric factorization, i.e., `PCSetUp()`.
3469:   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.

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

3477:   PetscFunctionBegin;
3480:   PetscCall(PetscStrncpy(mumps->id.ooc_tmpdir, tmpdir, sizeof(((MUMPS_STRUC_C *)NULL)->ooc_tmpdir)));
3481:   PetscFunctionReturn(PETSC_SUCCESS);
3482: }

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

3487:   Logically Collective

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

3492:   Output Parameter:
3493: . tmpdir - temporary directory for out-of-core facility.

3495:   Level: beginner

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

3500: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatMumpsSetOocTmpDir`, `MatMumpsSetIcntl()`, `MatMumpsGetIcntl()`, `MatMumpsSetCntl()`, `MatMumpsGetInfo()`, `MatMumpsGetInfog()`, `MatMumpsGetRinfo()`, `MatMumpsGetRinfog()`
3501: @*/
3502: PetscErrorCode MatMumpsGetOocTmpDir(Mat F, const char *tmpdir[])
3503: {
3504:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3506:   PetscFunctionBegin;
3509:   if (tmpdir) *tmpdir = mumps->id.ooc_tmpdir;
3510:   PetscFunctionReturn(PETSC_SUCCESS);
3511: }

3513: static PetscErrorCode MatMumpsGetInfo_MUMPS(Mat F, PetscInt icntl, PetscInt *info)
3514: {
3515:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3517:   PetscFunctionBegin;
3518:   *info = mumps->id.INFO(icntl);
3519:   PetscFunctionReturn(PETSC_SUCCESS);
3520: }

3522: static PetscErrorCode MatMumpsGetInfog_MUMPS(Mat F, PetscInt icntl, PetscInt *infog)
3523: {
3524:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3526:   PetscFunctionBegin;
3527:   *infog = mumps->id.INFOG(icntl);
3528:   PetscFunctionReturn(PETSC_SUCCESS);
3529: }

3531: static PetscErrorCode MatMumpsGetRinfo_MUMPS(Mat F, PetscInt icntl, PetscReal *rinfo)
3532: {
3533:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3535:   PetscFunctionBegin;
3536:   *rinfo = ID_RINFO_GET(mumps->id, icntl);
3537:   PetscFunctionReturn(PETSC_SUCCESS);
3538: }

3540: static PetscErrorCode MatMumpsGetRinfog_MUMPS(Mat F, PetscInt icntl, PetscReal *rinfog)
3541: {
3542:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3544:   PetscFunctionBegin;
3545:   *rinfog = ID_RINFOG_GET(mumps->id, icntl);
3546:   PetscFunctionReturn(PETSC_SUCCESS);
3547: }

3549: static PetscErrorCode MatMumpsGetNullPivots_MUMPS(Mat F, PetscInt *size, PetscInt **array)
3550: {
3551:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3553:   PetscFunctionBegin;
3554:   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");
3555:   *size  = 0;
3556:   *array = NULL;
3557:   if (!mumps->myid) {
3558:     *size = mumps->id.INFOG(28);
3559:     PetscCall(PetscMalloc1(*size, array));
3560:     for (int i = 0; i < *size; i++) (*array)[i] = mumps->id.pivnul_list[i] - 1;
3561:   }
3562:   PetscFunctionReturn(PETSC_SUCCESS);
3563: }

3565: static PetscErrorCode MatMumpsGetInverse_MUMPS(Mat F, Mat spRHS)
3566: {
3567:   Mat          Bt = NULL, Btseq = NULL;
3568:   PetscBool    flg;
3569:   Mat_MUMPS   *mumps = (Mat_MUMPS *)F->data;
3570:   PetscScalar *aa;
3571:   PetscInt     spnr, *ia, *ja, M, nrhs;

3573:   PetscFunctionBegin;
3574:   PetscAssertPointer(spRHS, 2);
3575:   PetscCall(PetscObjectTypeCompare((PetscObject)spRHS, MATTRANSPOSEVIRTUAL, &flg));
3576:   PetscCheck(flg, PetscObjectComm((PetscObject)spRHS), PETSC_ERR_ARG_WRONG, "Matrix spRHS must be type MATTRANSPOSEVIRTUAL matrix");
3577:   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));
3578:   PetscCall(MatTransposeGetMat(spRHS, &Bt));

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

3582:   if (mumps->petsc_size > 1) {
3583:     Mat_MPIAIJ *b = (Mat_MPIAIJ *)Bt->data;
3584:     Btseq         = b->A;
3585:   } else {
3586:     Btseq = Bt;
3587:   }

3589:   PetscCall(MatGetSize(spRHS, &M, &nrhs));
3590:   mumps->id.nrhs = (PetscMUMPSInt)nrhs;
3591:   PetscCall(PetscMUMPSIntCast(M, &mumps->id.lrhs));
3592:   mumps->id.rhs = NULL;

3594:   if (!mumps->myid) {
3595:     PetscCall(MatSeqAIJGetArray(Btseq, &aa));
3596:     PetscCall(MatGetRowIJ(Btseq, 1, PETSC_FALSE, PETSC_FALSE, &spnr, (const PetscInt **)&ia, (const PetscInt **)&ja, &flg));
3597:     PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot get IJ structure");
3598:     PetscCall(PetscMUMPSIntCSRCast(mumps, spnr, ia, ja, &mumps->id.irhs_ptr, &mumps->id.irhs_sparse, &mumps->id.nz_rhs));
3599:     PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, ((Mat_SeqAIJ *)Btseq->data)->nz, aa, mumps->id.precision, &mumps->id.rhs_sparse_len, &mumps->id.rhs_sparse));
3600:   } else {
3601:     mumps->id.irhs_ptr    = NULL;
3602:     mumps->id.irhs_sparse = NULL;
3603:     mumps->id.nz_rhs      = 0;
3604:     if (mumps->id.rhs_sparse_len) {
3605:       PetscCall(PetscFree(mumps->id.rhs_sparse));
3606:       mumps->id.rhs_sparse_len = 0;
3607:     }
3608:   }
3609:   mumps->id.ICNTL(20) = 1; /* rhs is sparse */
3610:   mumps->id.ICNTL(21) = 0; /* solution is in assembled centralized format */

3612:   /* solve phase */
3613:   mumps->id.job = JOB_SOLVE;
3614:   PetscMUMPS_c(mumps);
3615:   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));

3617:   if (!mumps->myid) {
3618:     PetscCall(MatSeqAIJRestoreArray(Btseq, &aa));
3619:     PetscCall(MatRestoreRowIJ(Btseq, 1, PETSC_FALSE, PETSC_FALSE, &spnr, (const PetscInt **)&ia, (const PetscInt **)&ja, &flg));
3620:     PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot restore IJ structure");
3621:   }
3622:   PetscFunctionReturn(PETSC_SUCCESS);
3623: }

3625: static PetscErrorCode MatMumpsGetInverseTranspose_MUMPS(Mat F, Mat spRHST)
3626: {
3627:   Mat spRHS;

3629:   PetscFunctionBegin;
3630:   PetscCall(MatCreateTranspose(spRHST, &spRHS));
3631:   PetscCall(MatMumpsGetInverse_MUMPS(F, spRHS));
3632:   PetscCall(MatDestroy(&spRHS));
3633:   PetscFunctionReturn(PETSC_SUCCESS);
3634: }

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

3640:   PetscFunctionBegin;
3641:   if (nblk) {
3642:     PetscAssertPointer(blkptr, 4);
3643:     PetscCall(PetscMUMPSIntCast(nblk, &mumps->id.nblk));
3644:     PetscCall(PetscFree(mumps->id.blkptr));
3645:     PetscCall(PetscMalloc1(nblk + 1, &mumps->id.blkptr));
3646:     for (PetscInt i = 0; i < nblk + 1; ++i) PetscCall(PetscMUMPSIntCast(blkptr[i], mumps->id.blkptr + i));
3647:     // mumps->id.icntl[] might have not been allocated, which is done in MatSetFromOptions_MUMPS(). So we don't assign ICNTL(15).
3648:     // We use id.nblk and id.blkptr to know what values to set to ICNTL(15) in MatSetFromOptions_MUMPS().
3649:     // mumps->id.ICNTL(15) = 1;
3650:     if (blkvar) {
3651:       PetscCall(PetscFree(mumps->id.blkvar));
3652:       PetscCall(PetscMalloc1(F->rmap->N, &mumps->id.blkvar));
3653:       for (PetscInt i = 0; i < F->rmap->N; ++i) PetscCall(PetscMUMPSIntCast(blkvar[i], mumps->id.blkvar + i));
3654:     }
3655:   } else {
3656:     PetscCall(PetscFree(mumps->id.blkptr));
3657:     PetscCall(PetscFree(mumps->id.blkvar));
3658:     // mumps->id.ICNTL(15) = 0;
3659:     mumps->id.nblk = 0;
3660:   }
3661:   PetscFunctionReturn(PETSC_SUCCESS);
3662: }

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

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

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

3672:   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.
3673:   See details below.

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

3677:   Options Database Keys:
3678: +  -mat_mumps_icntl_1           - ICNTL(1): output stream for error messages
3679: .  -mat_mumps_icntl_2           - ICNTL(2): output stream for diagnostic printing, statistics, and warning
3680: .  -mat_mumps_icntl_3           - ICNTL(3): output stream for global information, collected on the host
3681: .  -mat_mumps_icntl_4           - ICNTL(4): level of printing (0 to 4)
3682: .  -mat_mumps_icntl_6           - ICNTL(6): permutes to a zero-free diagonal and/or scale the matrix (0 to 7)
3683: .  -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
3684:                                   Use -pc_factor_mat_ordering_type type to have PETSc perform the ordering (sequential only)
3685: .  -mat_mumps_icntl_8           - ICNTL(8): scaling strategy (-2 to 8 or 77)
3686: .  -mat_mumps_icntl_10          - ICNTL(10): max num of refinements
3687: .  -mat_mumps_icntl_11          - ICNTL(11): statistics related to an error analysis (via -ksp_view)
3688: .  -mat_mumps_icntl_12          - ICNTL(12): an ordering strategy for symmetric matrices (0 to 3)
3689: .  -mat_mumps_icntl_13          - ICNTL(13): parallelism of the root node (enable ScaLAPACK) and its splitting
3690: .  -mat_mumps_icntl_14          - ICNTL(14): percentage increase in the estimated working space
3691: .  -mat_mumps_icntl_15          - ICNTL(15): compression of the input matrix resulting from a block format
3692: .  -mat_mumps_icntl_19          - ICNTL(19): computes the Schur complement
3693: .  -mat_mumps_icntl_20          - ICNTL(20): give MUMPS centralized (0) or distributed (10) dense RHS
3694: .  -mat_mumps_icntl_22          - ICNTL(22): in-core/out-of-core factorization and solve (0 or 1)
3695: .  -mat_mumps_icntl_23          - ICNTL(23): max size of the working memory (MB) that can allocate per processor
3696: .  -mat_mumps_icntl_24          - ICNTL(24): detection of null pivot rows (0 or 1)
3697: .  -mat_mumps_icntl_25          - ICNTL(25): compute a solution of a deficient matrix and a null space basis
3698: .  -mat_mumps_icntl_26          - ICNTL(26): drives the solution phase if a Schur complement matrix
3699: .  -mat_mumps_icntl_28          - ICNTL(28): use 1 for sequential analysis and ICNTL(7) ordering, or 2 for parallel analysis and ICNTL(29) ordering
3700: .  -mat_mumps_icntl_29          - ICNTL(29): parallel ordering 1 = PTScotch, 2 = ParMETIS
3701: .  -mat_mumps_icntl_30          - ICNTL(30): compute user-specified set of entries in inv(A)
3702: .  -mat_mumps_icntl_31          - ICNTL(31): indicates which factors may be discarded during factorization
3703: .  -mat_mumps_icntl_33          - ICNTL(33): compute determinant
3704: .  -mat_mumps_icntl_35          - ICNTL(35): level of activation of BLR (Block Low-Rank) feature
3705: .  -mat_mumps_icntl_36          - ICNTL(36): controls the choice of BLR factorization variant
3706: .  -mat_mumps_icntl_37          - ICNTL(37): compression of the contribution blocks (CB)
3707: .  -mat_mumps_icntl_38          - ICNTL(38): sets the estimated compression rate of LU factors with BLR
3708: .  -mat_mumps_icntl_40          - ICNTL(40): adaptive BLR precision feature
3709: .  -mat_mumps_icntl_47          - ICNTL(47): single precision factorization in a double precision instance
3710: .  -mat_mumps_icntl_48          - ICNTL(48): multithreading with tree parallelism
3711: .  -mat_mumps_icntl_49          - ICNTL(49): compact workarray at the end of factorization phase
3712: .  -mat_mumps_icntl_58          - ICNTL(58): options for symbolic factorization
3713: .  -mat_mumps_cntl_1            - CNTL(1): relative pivoting threshold
3714: .  -mat_mumps_cntl_2            - CNTL(2): stopping criterion of refinement
3715: .  -mat_mumps_cntl_3            - CNTL(3): absolute pivoting threshold
3716: .  -mat_mumps_cntl_4            - CNTL(4): value for static pivoting
3717: .  -mat_mumps_cntl_5            - CNTL(5): fixation for null pivots
3718: .  -mat_mumps_cntl_7            - CNTL(7): precision of the dropping parameter used during BLR factorization
3719: -  -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.
3720:                                   Default might be the number of cores per CPU package (socket) as reported by hwloc and suggested by the MUMPS manual.

3722:   Level: beginner

3724:   Notes:
3725:   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
3726:   error if the matrix is Hermitian.

3728:   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
3729:   `MatSetOptionsPrefixFactor()` on the matrix from which the factor was obtained or `MatSetOptionsPrefix()` on the factor matrix.

3731:   When a MUMPS factorization fails inside a KSP solve, for example with a `KSP_DIVERGED_PC_FAILED`, one can find the MUMPS information about
3732:   the failure with
3733: .vb
3734:           KSPGetPC(ksp,&pc);
3735:           PCFactorGetMatrix(pc,&mat);
3736:           MatMumpsGetInfo(mat,....);
3737:           MatMumpsGetInfog(mat,....); etc.
3738: .ve
3739:   Or run with `-ksp_error_if_not_converged` and the program will be stopped and the information printed in the error message.

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

3745:   selective 64-bit: with the default MUMPS build, 64-bit integers have been introduced where needed. In compressed sparse row (CSR) storage of matrices,
3746:   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
3747:   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
3748:   integer) build of all dependent libraries MPI, ScaLAPACK, LAPACK and BLAS.

3750:   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.

3752:   Two modes to run MUMPS/PETSc with OpenMP
3753: .vb
3754:    Set `OMP_NUM_THREADS` and run with fewer MPI ranks than cores. For example, if you want to have 16 OpenMP
3755:    threads per rank, then you may use "export `OMP_NUM_THREADS` = 16 && mpiexec -n 4 ./test".
3756: .ve

3758: .vb
3759:    `-mat_mumps_use_omp_threads` [m] and run your code with as many MPI ranks as the number of cores. For example,
3760:    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"
3761: .ve

3763:    To run MUMPS in MPI+OpenMP hybrid mode (i.e., enable multithreading in MUMPS), but still run the non-MUMPS part
3764:    (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`
3765:    (or `--with-hwloc`), and have an MPI that supports MPI-3.0's process shared memory (which is usually available). Since MUMPS calls BLAS
3766:    libraries, to really get performance, you should have multithreaded BLAS libraries such as Intel MKL, AMD ACML, Cray libSci or OpenBLAS
3767:    (PETSc will automatically try to utilized a threaded BLAS if `--with-openmp` is provided).

3769:    If you run your code through a job submission system, there are caveats in MPI rank mapping. We use MPI_Comm_split_type() to obtain MPI
3770:    processes on each compute node. Listing the processes in rank ascending order, we split processes on a node into consecutive groups of
3771:    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
3772:    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
3773:    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.
3774:    In a multi-socket compute node, MPI rank mapping is an issue. Still use the above example and suppose your compute node has two sockets,
3775:    if you interleave MPI ranks on the two sockets, in other words, even ranks are placed on socket 0, and odd ranks are on socket 1, and bind
3776:    MPI ranks 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
3777:    cores in socket 1, that definitely hurts locality. On the other hand, if you map MPI ranks consecutively on the two sockets, then the
3778:    problem will not happen. Therefore, when you use `-mat_mumps_use_omp_threads`, you need to keep an eye on your MPI rank mapping and CPU binding.
3779:    For example, with the Slurm job scheduler, one can use srun `--cpu-bind`=verbose -m block:block to map consecutive MPI ranks to sockets and
3780:    examine the mapping result.

3782:    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,
3783:    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
3784:    calls `omp_set_num_threads`(m) internally before calling MUMPS.

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

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

3791: static PetscErrorCode MatFactorGetSolverType_mumps(PETSC_UNUSED Mat A, MatSolverType *type)
3792: {
3793:   PetscFunctionBegin;
3794:   *type = MATSOLVERMUMPS;
3795:   PetscFunctionReturn(PETSC_SUCCESS);
3796: }

3798: /* MatGetFactor for Seq and MPI AIJ matrices */
3799: static PetscErrorCode MatGetFactor_aij_mumps(Mat A, MatFactorType ftype, Mat *F)
3800: {
3801:   Mat         B;
3802:   Mat_MUMPS  *mumps;
3803:   PetscBool   isSeqAIJ, isDiag, isDense;
3804:   PetscMPIInt size;

3806:   PetscFunctionBegin;
3807:   if (PetscDefined(USE_COMPLEX) && ftype == MAT_FACTOR_CHOLESKY && A->hermitian == PETSC_BOOL3_TRUE && A->symmetric != PETSC_BOOL3_TRUE) {
3808:     PetscCall(PetscInfo(A, "Hermitian MAT_FACTOR_CHOLESKY is not supported. Use MAT_FACTOR_LU instead.\n"));
3809:     *F = NULL;
3810:     PetscFunctionReturn(PETSC_SUCCESS);
3811:   }
3812:   /* Create the factorization matrix */
3813:   PetscCall(PetscObjectBaseTypeCompare((PetscObject)A, MATSEQAIJ, &isSeqAIJ));
3814:   PetscCall(PetscObjectBaseTypeCompare((PetscObject)A, MATDIAGONAL, &isDiag));
3815:   PetscCall(PetscObjectTypeCompareAny((PetscObject)A, &isDense, MATSEQDENSE, MATMPIDENSE, NULL));
3816:   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &B));
3817:   PetscCall(MatSetSizes(B, A->rmap->n, A->cmap->n, A->rmap->N, A->cmap->N));
3818:   PetscCall(PetscStrallocpy(MATSOLVERMUMPS, &((PetscObject)B)->type_name));
3819:   PetscCall(MatSetUp(B));

3821:   PetscCall(PetscNew(&mumps));

3823:   B->ops->view    = MatView_MUMPS;
3824:   B->ops->getinfo = MatGetInfo_MUMPS;

3826:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorGetSolverType_C", MatFactorGetSolverType_mumps));
3827:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorSetSchurIS_C", MatFactorSetSchurIS_MUMPS));
3828:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorCreateSchurComplement_C", MatFactorCreateSchurComplement_MUMPS));
3829:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetIcntl_C", MatMumpsSetIcntl_MUMPS));
3830:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetIcntl_C", MatMumpsGetIcntl_MUMPS));
3831:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetCntl_C", MatMumpsSetCntl_MUMPS));
3832:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetCntl_C", MatMumpsGetCntl_MUMPS));
3833:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInfo_C", MatMumpsGetInfo_MUMPS));
3834:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInfog_C", MatMumpsGetInfog_MUMPS));
3835:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetRinfo_C", MatMumpsGetRinfo_MUMPS));
3836:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetRinfog_C", MatMumpsGetRinfog_MUMPS));
3837:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetNullPivots_C", MatMumpsGetNullPivots_MUMPS));
3838:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInverse_C", MatMumpsGetInverse_MUMPS));
3839:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInverseTranspose_C", MatMumpsGetInverseTranspose_MUMPS));
3840:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetBlk_C", MatMumpsSetBlk_MUMPS));

3842:   if (ftype == MAT_FACTOR_LU) {
3843:     B->ops->lufactorsymbolic = MatLUFactorSymbolic_AIJMUMPS;
3844:     B->factortype            = MAT_FACTOR_LU;
3845:     if (isSeqAIJ) mumps->ConvertToTriples = MatConvertToTriples_seqaij_seqaij;
3846:     else if (isDiag) mumps->ConvertToTriples = MatConvertToTriples_diagonal_xaij;
3847:     else if (isDense) mumps->ConvertToTriples = MatConvertToTriples_dense_xaij;
3848:     else mumps->ConvertToTriples = MatConvertToTriples_mpiaij_mpiaij;
3849:     PetscCall(PetscStrallocpy(MATORDERINGEXTERNAL, (char **)&B->preferredordering[MAT_FACTOR_LU]));
3850:     mumps->sym = 0;
3851:   } else {
3852:     B->ops->choleskyfactorsymbolic = MatCholeskyFactorSymbolic_MUMPS;
3853:     B->factortype                  = MAT_FACTOR_CHOLESKY;
3854:     if (isSeqAIJ) mumps->ConvertToTriples = MatConvertToTriples_seqaij_seqsbaij;
3855:     else if (isDiag) mumps->ConvertToTriples = MatConvertToTriples_diagonal_xaij;
3856:     else if (isDense) mumps->ConvertToTriples = MatConvertToTriples_dense_xaij;
3857:     else mumps->ConvertToTriples = MatConvertToTriples_mpiaij_mpisbaij;
3858:     PetscCall(PetscStrallocpy(MATORDERINGEXTERNAL, (char **)&B->preferredordering[MAT_FACTOR_CHOLESKY]));
3859:     if (PetscDefined(USE_COMPLEX)) mumps->sym = 2;
3860:     else if (A->spd == PETSC_BOOL3_TRUE) mumps->sym = 1;
3861:     else mumps->sym = 2;
3862:   }

3864:   /* set solvertype */
3865:   PetscCall(PetscFree(B->solvertype));
3866:   PetscCall(PetscStrallocpy(MATSOLVERMUMPS, &B->solvertype));
3867:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
3868:   if (size == 1) {
3869:     /* MUMPS option -mat_mumps_icntl_7 1 is automatically set if PETSc ordering is passed into symbolic factorization */
3870:     B->canuseordering = PETSC_TRUE;
3871:   }
3872:   B->ops->destroy = MatDestroy_MUMPS;
3873:   B->data         = (void *)mumps;

3875:   *F               = B;
3876:   mumps->id.job    = JOB_NULL;
3877:   mumps->ICNTL_pre = NULL;
3878:   mumps->CNTL_pre  = NULL;
3879:   mumps->matstruc  = DIFFERENT_NONZERO_PATTERN;
3880:   PetscFunctionReturn(PETSC_SUCCESS);
3881: }

3883: /* MatGetFactor for Seq and MPI SBAIJ matrices */
3884: static PetscErrorCode MatGetFactor_sbaij_mumps(Mat A, PETSC_UNUSED MatFactorType ftype, Mat *F)
3885: {
3886:   Mat         B;
3887:   Mat_MUMPS  *mumps;
3888:   PetscBool   isSeqSBAIJ;
3889:   PetscMPIInt size;

3891:   PetscFunctionBegin;
3892:   if (PetscDefined(USE_COMPLEX) && ftype == MAT_FACTOR_CHOLESKY && A->hermitian == PETSC_BOOL3_TRUE && A->symmetric != PETSC_BOOL3_TRUE) {
3893:     PetscCall(PetscInfo(A, "Hermitian MAT_FACTOR_CHOLESKY is not supported. Use MAT_FACTOR_LU instead.\n"));
3894:     *F = NULL;
3895:     PetscFunctionReturn(PETSC_SUCCESS);
3896:   }
3897:   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &B));
3898:   PetscCall(MatSetSizes(B, A->rmap->n, A->cmap->n, A->rmap->N, A->cmap->N));
3899:   PetscCall(PetscStrallocpy(MATSOLVERMUMPS, &((PetscObject)B)->type_name));
3900:   PetscCall(MatSetUp(B));

3902:   PetscCall(PetscNew(&mumps));
3903:   PetscCall(PetscObjectTypeCompare((PetscObject)A, MATSEQSBAIJ, &isSeqSBAIJ));
3904:   if (isSeqSBAIJ) {
3905:     mumps->ConvertToTriples = MatConvertToTriples_seqsbaij_seqsbaij;
3906:   } else {
3907:     mumps->ConvertToTriples = MatConvertToTriples_mpisbaij_mpisbaij;
3908:   }

3910:   B->ops->choleskyfactorsymbolic = MatCholeskyFactorSymbolic_MUMPS;
3911:   B->ops->view                   = MatView_MUMPS;
3912:   B->ops->getinfo                = MatGetInfo_MUMPS;

3914:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorGetSolverType_C", MatFactorGetSolverType_mumps));
3915:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorSetSchurIS_C", MatFactorSetSchurIS_MUMPS));
3916:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorCreateSchurComplement_C", MatFactorCreateSchurComplement_MUMPS));
3917:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetIcntl_C", MatMumpsSetIcntl_MUMPS));
3918:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetIcntl_C", MatMumpsGetIcntl_MUMPS));
3919:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetCntl_C", MatMumpsSetCntl_MUMPS));
3920:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetCntl_C", MatMumpsGetCntl_MUMPS));
3921:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInfo_C", MatMumpsGetInfo_MUMPS));
3922:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInfog_C", MatMumpsGetInfog_MUMPS));
3923:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetRinfo_C", MatMumpsGetRinfo_MUMPS));
3924:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetRinfog_C", MatMumpsGetRinfog_MUMPS));
3925:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetNullPivots_C", MatMumpsGetNullPivots_MUMPS));
3926:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInverse_C", MatMumpsGetInverse_MUMPS));
3927:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInverseTranspose_C", MatMumpsGetInverseTranspose_MUMPS));
3928:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetBlk_C", MatMumpsSetBlk_MUMPS));

3930:   B->factortype = MAT_FACTOR_CHOLESKY;
3931:   if (PetscDefined(USE_COMPLEX)) mumps->sym = 2;
3932:   else if (A->spd == PETSC_BOOL3_TRUE) mumps->sym = 1;
3933:   else mumps->sym = 2;

3935:   /* set solvertype */
3936:   PetscCall(PetscFree(B->solvertype));
3937:   PetscCall(PetscStrallocpy(MATSOLVERMUMPS, &B->solvertype));
3938:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
3939:   if (size == 1) {
3940:     /* MUMPS option -mat_mumps_icntl_7 1 is automatically set if PETSc ordering is passed into symbolic factorization */
3941:     B->canuseordering = PETSC_TRUE;
3942:   }
3943:   PetscCall(PetscStrallocpy(MATORDERINGEXTERNAL, (char **)&B->preferredordering[MAT_FACTOR_CHOLESKY]));
3944:   B->ops->destroy = MatDestroy_MUMPS;
3945:   B->data         = (void *)mumps;

3947:   *F               = B;
3948:   mumps->id.job    = JOB_NULL;
3949:   mumps->ICNTL_pre = NULL;
3950:   mumps->CNTL_pre  = NULL;
3951:   mumps->matstruc  = DIFFERENT_NONZERO_PATTERN;
3952:   PetscFunctionReturn(PETSC_SUCCESS);
3953: }

3955: static PetscErrorCode MatGetFactor_baij_mumps(Mat A, MatFactorType ftype, Mat *F)
3956: {
3957:   Mat         B;
3958:   Mat_MUMPS  *mumps;
3959:   PetscBool   isSeqBAIJ;
3960:   PetscMPIInt size;

3962:   PetscFunctionBegin;
3963:   /* Create the factorization matrix */
3964:   PetscCall(PetscObjectTypeCompare((PetscObject)A, MATSEQBAIJ, &isSeqBAIJ));
3965:   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &B));
3966:   PetscCall(MatSetSizes(B, A->rmap->n, A->cmap->n, A->rmap->N, A->cmap->N));
3967:   PetscCall(PetscStrallocpy(MATSOLVERMUMPS, &((PetscObject)B)->type_name));
3968:   PetscCall(MatSetUp(B));

3970:   PetscCall(PetscNew(&mumps));
3971:   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");
3972:   B->ops->lufactorsymbolic = MatLUFactorSymbolic_BAIJMUMPS;
3973:   B->factortype            = MAT_FACTOR_LU;
3974:   if (isSeqBAIJ) mumps->ConvertToTriples = MatConvertToTriples_seqbaij_seqaij;
3975:   else mumps->ConvertToTriples = MatConvertToTriples_mpibaij_mpiaij;
3976:   mumps->sym = 0;
3977:   PetscCall(PetscStrallocpy(MATORDERINGEXTERNAL, (char **)&B->preferredordering[MAT_FACTOR_LU]));

3979:   B->ops->view    = MatView_MUMPS;
3980:   B->ops->getinfo = MatGetInfo_MUMPS;

3982:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorGetSolverType_C", MatFactorGetSolverType_mumps));
3983:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorSetSchurIS_C", MatFactorSetSchurIS_MUMPS));
3984:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorCreateSchurComplement_C", MatFactorCreateSchurComplement_MUMPS));
3985:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetIcntl_C", MatMumpsSetIcntl_MUMPS));
3986:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetIcntl_C", MatMumpsGetIcntl_MUMPS));
3987:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetCntl_C", MatMumpsSetCntl_MUMPS));
3988:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetCntl_C", MatMumpsGetCntl_MUMPS));
3989:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInfo_C", MatMumpsGetInfo_MUMPS));
3990:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInfog_C", MatMumpsGetInfog_MUMPS));
3991:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetRinfo_C", MatMumpsGetRinfo_MUMPS));
3992:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetRinfog_C", MatMumpsGetRinfog_MUMPS));
3993:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetNullPivots_C", MatMumpsGetNullPivots_MUMPS));
3994:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInverse_C", MatMumpsGetInverse_MUMPS));
3995:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInverseTranspose_C", MatMumpsGetInverseTranspose_MUMPS));
3996:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetBlk_C", MatMumpsSetBlk_MUMPS));

3998:   /* set solvertype */
3999:   PetscCall(PetscFree(B->solvertype));
4000:   PetscCall(PetscStrallocpy(MATSOLVERMUMPS, &B->solvertype));
4001:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
4002:   if (size == 1) {
4003:     /* MUMPS option -mat_mumps_icntl_7 1 is automatically set if PETSc ordering is passed into symbolic factorization */
4004:     B->canuseordering = PETSC_TRUE;
4005:   }
4006:   B->ops->destroy = MatDestroy_MUMPS;
4007:   B->data         = (void *)mumps;

4009:   *F               = B;
4010:   mumps->id.job    = JOB_NULL;
4011:   mumps->ICNTL_pre = NULL;
4012:   mumps->CNTL_pre  = NULL;
4013:   mumps->matstruc  = DIFFERENT_NONZERO_PATTERN;
4014:   PetscFunctionReturn(PETSC_SUCCESS);
4015: }

4017: /* MatGetFactor for Seq and MPI SELL matrices */
4018: static PetscErrorCode MatGetFactor_sell_mumps(Mat A, MatFactorType ftype, Mat *F)
4019: {
4020:   Mat         B;
4021:   Mat_MUMPS  *mumps;
4022:   PetscBool   isSeqSELL;
4023:   PetscMPIInt size;

4025:   PetscFunctionBegin;
4026:   /* Create the factorization matrix */
4027:   PetscCall(PetscObjectTypeCompare((PetscObject)A, MATSEQSELL, &isSeqSELL));
4028:   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &B));
4029:   PetscCall(MatSetSizes(B, A->rmap->n, A->cmap->n, A->rmap->N, A->cmap->N));
4030:   PetscCall(PetscStrallocpy(MATSOLVERMUMPS, &((PetscObject)B)->type_name));
4031:   PetscCall(MatSetUp(B));

4033:   PetscCall(PetscNew(&mumps));

4035:   B->ops->view    = MatView_MUMPS;
4036:   B->ops->getinfo = MatGetInfo_MUMPS;

4038:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorGetSolverType_C", MatFactorGetSolverType_mumps));
4039:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorSetSchurIS_C", MatFactorSetSchurIS_MUMPS));
4040:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorCreateSchurComplement_C", MatFactorCreateSchurComplement_MUMPS));
4041:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetIcntl_C", MatMumpsSetIcntl_MUMPS));
4042:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetIcntl_C", MatMumpsGetIcntl_MUMPS));
4043:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetCntl_C", MatMumpsSetCntl_MUMPS));
4044:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetCntl_C", MatMumpsGetCntl_MUMPS));
4045:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInfo_C", MatMumpsGetInfo_MUMPS));
4046:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInfog_C", MatMumpsGetInfog_MUMPS));
4047:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetRinfo_C", MatMumpsGetRinfo_MUMPS));
4048:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetRinfog_C", MatMumpsGetRinfog_MUMPS));
4049:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetNullPivots_C", MatMumpsGetNullPivots_MUMPS));

4051:   PetscCheck(ftype == MAT_FACTOR_LU, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "To be implemented");
4052:   B->ops->lufactorsymbolic = MatLUFactorSymbolic_AIJMUMPS;
4053:   B->factortype            = MAT_FACTOR_LU;
4054:   PetscCheck(isSeqSELL, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "To be implemented");
4055:   mumps->ConvertToTriples = MatConvertToTriples_seqsell_seqaij;
4056:   mumps->sym              = 0;
4057:   PetscCall(PetscStrallocpy(MATORDERINGEXTERNAL, (char **)&B->preferredordering[MAT_FACTOR_LU]));

4059:   /* set solvertype */
4060:   PetscCall(PetscFree(B->solvertype));
4061:   PetscCall(PetscStrallocpy(MATSOLVERMUMPS, &B->solvertype));
4062:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
4063:   if (size == 1) {
4064:     /* MUMPS option -mat_mumps_icntl_7 1 is automatically set if PETSc ordering is passed into symbolic factorization  */
4065:     B->canuseordering = PETSC_TRUE;
4066:   }
4067:   B->ops->destroy = MatDestroy_MUMPS;
4068:   B->data         = (void *)mumps;

4070:   *F               = B;
4071:   mumps->id.job    = JOB_NULL;
4072:   mumps->ICNTL_pre = NULL;
4073:   mumps->CNTL_pre  = NULL;
4074:   mumps->matstruc  = DIFFERENT_NONZERO_PATTERN;
4075:   PetscFunctionReturn(PETSC_SUCCESS);
4076: }

4078: /* MatGetFactor for MATNEST matrices */
4079: static PetscErrorCode MatGetFactor_nest_mumps(Mat A, MatFactorType ftype, Mat *F)
4080: {
4081:   Mat         B, **mats;
4082:   Mat_MUMPS  *mumps;
4083:   PetscInt    nr, nc;
4084:   PetscMPIInt size;
4085:   PetscBool   flg = PETSC_TRUE;

4087:   PetscFunctionBegin;
4088:   if (PetscDefined(USE_COMPLEX) && ftype == MAT_FACTOR_CHOLESKY && A->hermitian == PETSC_BOOL3_TRUE && A->symmetric != PETSC_BOOL3_TRUE) {
4089:     PetscCall(PetscInfo(A, "Hermitian MAT_FACTOR_CHOLESKY is not supported. Use MAT_FACTOR_LU instead.\n"));
4090:     *F = NULL;
4091:     PetscFunctionReturn(PETSC_SUCCESS);
4092:   }

4094:   /* Return if some condition is not satisfied */
4095:   *F = NULL;
4096:   PetscCall(MatNestGetSubMats(A, &nr, &nc, &mats));
4097:   if (ftype == MAT_FACTOR_CHOLESKY) {
4098:     IS       *rows, *cols;
4099:     PetscInt *m, *M;

4101:     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);
4102:     PetscCall(PetscMalloc2(nr, &rows, nc, &cols));
4103:     PetscCall(MatNestGetISs(A, rows, cols));
4104:     for (PetscInt r = 0; flg && r < nr; r++) PetscCall(ISEqualUnsorted(rows[r], cols[r], &flg));
4105:     if (!flg) {
4106:       PetscCall(PetscFree2(rows, cols));
4107:       PetscCall(PetscInfo(A, "MAT_FACTOR_CHOLESKY not supported for unequal row and column maps. Use MAT_FACTOR_LU.\n"));
4108:       PetscFunctionReturn(PETSC_SUCCESS);
4109:     }
4110:     PetscCall(PetscMalloc2(nr, &m, nr, &M));
4111:     for (PetscInt r = 0; r < nr; r++) PetscCall(ISGetMinMax(rows[r], &m[r], &M[r]));
4112:     for (PetscInt r = 0; flg && r < nr; r++)
4113:       for (PetscInt k = r + 1; flg && k < nr; k++)
4114:         if ((m[k] <= m[r] && m[r] <= M[k]) || (m[k] <= M[r] && M[r] <= M[k])) flg = PETSC_FALSE;
4115:     PetscCall(PetscFree2(m, M));
4116:     PetscCall(PetscFree2(rows, cols));
4117:     if (!flg) {
4118:       PetscCall(PetscInfo(A, "MAT_FACTOR_CHOLESKY not supported for intersecting row maps. Use MAT_FACTOR_LU.\n"));
4119:       PetscFunctionReturn(PETSC_SUCCESS);
4120:     }
4121:   }

4123:   for (PetscInt r = 0; r < nr; r++) {
4124:     for (PetscInt c = 0; c < nc; c++) {
4125:       Mat       sub = mats[r][c];
4126:       PetscBool isSeqAIJ, isMPIAIJ, isSeqBAIJ, isMPIBAIJ, isSeqSBAIJ, isMPISBAIJ, isDiag, isDense;

4128:       if (!sub || (ftype == MAT_FACTOR_CHOLESKY && c < r)) continue;
4129:       PetscCall(MatGetTranspose_TransposeVirtual(&sub, NULL, NULL, NULL, NULL));
4130:       PetscCall(PetscObjectBaseTypeCompare((PetscObject)sub, MATSEQAIJ, &isSeqAIJ));
4131:       PetscCall(PetscObjectBaseTypeCompare((PetscObject)sub, MATMPIAIJ, &isMPIAIJ));
4132:       PetscCall(PetscObjectBaseTypeCompare((PetscObject)sub, MATSEQBAIJ, &isSeqBAIJ));
4133:       PetscCall(PetscObjectBaseTypeCompare((PetscObject)sub, MATMPIBAIJ, &isMPIBAIJ));
4134:       PetscCall(PetscObjectBaseTypeCompare((PetscObject)sub, MATSEQSBAIJ, &isSeqSBAIJ));
4135:       PetscCall(PetscObjectBaseTypeCompare((PetscObject)sub, MATMPISBAIJ, &isMPISBAIJ));
4136:       PetscCall(PetscObjectTypeCompare((PetscObject)sub, MATDIAGONAL, &isDiag));
4137:       PetscCall(PetscObjectTypeCompareAny((PetscObject)sub, &isDense, MATSEQDENSE, MATMPIDENSE, NULL));
4138:       if (ftype == MAT_FACTOR_CHOLESKY) {
4139:         if (r == c) {
4140:           if (!isSeqAIJ && !isMPIAIJ && !isSeqBAIJ && !isMPIBAIJ && !isSeqSBAIJ && !isMPISBAIJ && !isDiag && !isDense) {
4141:             PetscCall(PetscInfo(sub, "MAT_FACTOR_CHOLESKY not supported for diagonal block of type %s.\n", ((PetscObject)sub)->type_name));
4142:             flg = PETSC_FALSE;
4143:           }
4144:         } else if (!isSeqAIJ && !isMPIAIJ && !isSeqBAIJ && !isMPIBAIJ && !isDiag && !isDense) {
4145:           PetscCall(PetscInfo(sub, "MAT_FACTOR_CHOLESKY not supported for off-diagonal block of type %s.\n", ((PetscObject)sub)->type_name));
4146:           flg = PETSC_FALSE;
4147:         }
4148:       } else if (!isSeqAIJ && !isMPIAIJ && !isSeqBAIJ && !isMPIBAIJ && !isDiag && !isDense) {
4149:         PetscCall(PetscInfo(sub, "MAT_FACTOR_LU not supported for block of type %s.\n", ((PetscObject)sub)->type_name));
4150:         flg = PETSC_FALSE;
4151:       }
4152:     }
4153:   }
4154:   if (!flg) PetscFunctionReturn(PETSC_SUCCESS);

4156:   /* Create the factorization matrix */
4157:   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &B));
4158:   PetscCall(MatSetSizes(B, A->rmap->n, A->cmap->n, A->rmap->N, A->cmap->N));
4159:   PetscCall(PetscStrallocpy(MATSOLVERMUMPS, &((PetscObject)B)->type_name));
4160:   PetscCall(MatSetUp(B));

4162:   PetscCall(PetscNew(&mumps));

4164:   B->ops->view    = MatView_MUMPS;
4165:   B->ops->getinfo = MatGetInfo_MUMPS;

4167:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorGetSolverType_C", MatFactorGetSolverType_mumps));
4168:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorSetSchurIS_C", MatFactorSetSchurIS_MUMPS));
4169:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatFactorCreateSchurComplement_C", MatFactorCreateSchurComplement_MUMPS));
4170:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetIcntl_C", MatMumpsSetIcntl_MUMPS));
4171:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetIcntl_C", MatMumpsGetIcntl_MUMPS));
4172:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetCntl_C", MatMumpsSetCntl_MUMPS));
4173:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetCntl_C", MatMumpsGetCntl_MUMPS));
4174:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInfo_C", MatMumpsGetInfo_MUMPS));
4175:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInfog_C", MatMumpsGetInfog_MUMPS));
4176:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetRinfo_C", MatMumpsGetRinfo_MUMPS));
4177:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetRinfog_C", MatMumpsGetRinfog_MUMPS));
4178:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetNullPivots_C", MatMumpsGetNullPivots_MUMPS));
4179:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInverse_C", MatMumpsGetInverse_MUMPS));
4180:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsGetInverseTranspose_C", MatMumpsGetInverseTranspose_MUMPS));
4181:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMumpsSetBlk_C", MatMumpsSetBlk_MUMPS));

4183:   if (ftype == MAT_FACTOR_LU) {
4184:     B->ops->lufactorsymbolic = MatLUFactorSymbolic_AIJMUMPS;
4185:     B->factortype            = MAT_FACTOR_LU;
4186:     mumps->sym               = 0;
4187:   } else {
4188:     B->ops->choleskyfactorsymbolic = MatCholeskyFactorSymbolic_MUMPS;
4189:     B->factortype                  = MAT_FACTOR_CHOLESKY;
4190:     if (PetscDefined(USE_COMPLEX)) mumps->sym = 2;
4191:     else if (A->spd == PETSC_BOOL3_TRUE) mumps->sym = 1;
4192:     else mumps->sym = 2;
4193:   }
4194:   mumps->ConvertToTriples = MatConvertToTriples_nest_xaij;
4195:   PetscCall(PetscStrallocpy(MATORDERINGEXTERNAL, (char **)&B->preferredordering[ftype]));

4197:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
4198:   if (size == 1) {
4199:     /* MUMPS option -mat_mumps_icntl_7 1 is automatically set if PETSc ordering is passed into symbolic factorization */
4200:     B->canuseordering = PETSC_TRUE;
4201:   }

4203:   /* set solvertype */
4204:   PetscCall(PetscFree(B->solvertype));
4205:   PetscCall(PetscStrallocpy(MATSOLVERMUMPS, &B->solvertype));
4206:   B->ops->destroy = MatDestroy_MUMPS;
4207:   B->data         = (void *)mumps;

4209:   *F               = B;
4210:   mumps->id.job    = JOB_NULL;
4211:   mumps->ICNTL_pre = NULL;
4212:   mumps->CNTL_pre  = NULL;
4213:   mumps->matstruc  = DIFFERENT_NONZERO_PATTERN;
4214:   PetscFunctionReturn(PETSC_SUCCESS);
4215: }

4217: PETSC_INTERN PetscErrorCode MatSolverTypeRegister_MUMPS(void)
4218: {
4219:   PetscFunctionBegin;
4220:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATMPIAIJ, MAT_FACTOR_LU, MatGetFactor_aij_mumps));
4221:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATMPIAIJ, MAT_FACTOR_CHOLESKY, MatGetFactor_aij_mumps));
4222:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATMPIBAIJ, MAT_FACTOR_LU, MatGetFactor_baij_mumps));
4223:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATMPIBAIJ, MAT_FACTOR_CHOLESKY, MatGetFactor_baij_mumps));
4224:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATMPISBAIJ, MAT_FACTOR_CHOLESKY, MatGetFactor_sbaij_mumps));
4225:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATSEQAIJ, MAT_FACTOR_LU, MatGetFactor_aij_mumps));
4226:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATSEQAIJ, MAT_FACTOR_CHOLESKY, MatGetFactor_aij_mumps));
4227:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATSEQBAIJ, MAT_FACTOR_LU, MatGetFactor_baij_mumps));
4228:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATSEQBAIJ, MAT_FACTOR_CHOLESKY, MatGetFactor_baij_mumps));
4229:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATSEQSBAIJ, MAT_FACTOR_CHOLESKY, MatGetFactor_sbaij_mumps));
4230:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATSEQSELL, MAT_FACTOR_LU, MatGetFactor_sell_mumps));
4231:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATDIAGONAL, MAT_FACTOR_LU, MatGetFactor_aij_mumps));
4232:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATDIAGONAL, MAT_FACTOR_CHOLESKY, MatGetFactor_aij_mumps));
4233:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATSEQDENSE, MAT_FACTOR_LU, MatGetFactor_aij_mumps));
4234:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATSEQDENSE, MAT_FACTOR_CHOLESKY, MatGetFactor_aij_mumps));
4235:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATMPIDENSE, MAT_FACTOR_LU, MatGetFactor_aij_mumps));
4236:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATMPIDENSE, MAT_FACTOR_CHOLESKY, MatGetFactor_aij_mumps));
4237:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATNEST, MAT_FACTOR_LU, MatGetFactor_nest_mumps));
4238:   PetscCall(MatSolverTypeRegister(MATSOLVERMUMPS, MATNEST, MAT_FACTOR_CHOLESKY, MatGetFactor_nest_mumps));
4239:   PetscFunctionReturn(PETSC_SUCCESS);
4240: }