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 defined(PETSC_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 defined(PETSC_USE_COMPLEX)
 21:     #if defined(PETSC_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 defined(PETSC_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 defined(PETSC_USE_COMPLEX)
 43:   #if defined(PETSC_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 defined(PETSC_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: #if PetscDefined(USE_64BIT_INDICES)
 89:   PetscAssert(a <= PETSC_MUMPS_INT_MAX && a >= PETSC_MUMPS_INT_MIN, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "PetscInt too long for PetscMUMPSInt");
 90: #endif
 91:   *b = (PetscMUMPSInt)a;
 92:   PetscFunctionReturn(PETSC_SUCCESS);
 93: }

 95: /* Put these utility routines here since they are only used in this file */
 96: 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)
 97: {
 98:   PetscInt  myval;
 99:   PetscBool myset;

101:   PetscFunctionBegin;
102:   /* PetscInt's size should be always >= PetscMUMPSInt's. It is safe to call PetscOptionsInt_Private to read a PetscMUMPSInt */
103:   PetscCall(PetscOptionsInt_Private(PetscOptionsObject, opt, text, man, (PetscInt)currentvalue, &myval, &myset, lb, ub));
104:   if (myset) PetscCall(PetscMUMPSIntCast(myval, value));
105:   if (set) *set = myset;
106:   PetscFunctionReturn(PETSC_SUCCESS);
107: }
108: #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)

110: // An abstract type for specific MUMPS types {S,D,C,Z}MUMPS_STRUC_C.
111: //
112: // 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.
113: // 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
114: // arrays within the types are directly linked. At the end, we only need to copy ~20 integers/pointers, which is doable. See PreMumpsCall()/PostMumpsCall().
115: //
116: // Not all fields in the specific types are exposed in the abstract type. We only need those used by the PETSc/MUMPS interface.
117: // 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.
118: // Also note that we added some *_len fields not in specific types to track sizes of those MumpsScalar buffers.
119: typedef struct {
120:   PetscPrecision precision;   // precision used by MUMPS
121:   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

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

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

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

145:   /* Matrix by blocks */
146:   MUMPS_INT *blkptr;
147:   MUMPS_INT *blkvar;

149:   /* Ordering, if given by user */
150:   MUMPS_INT *perm_in;

152:   /* RHS, solution, ouptput data and statistics */
153:   void      *rhs, *redrhs, *rhs_sparse, *sol_loc, *rhs_loc;                 // MumpsScalar buffers
154:   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

156:   MUMPS_INT *irhs_sparse, *irhs_ptr, *isol_loc, *irhs_loc;
157:   MUMPS_INT  nrhs, lrhs, lredrhs, nz_rhs, lsol_loc, nloc_rhs, lrhs_loc;
158:   // 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)
159:   MUMPS_INT  schur_lld;
160:   MUMPS_INT *info, *infog;   // fixed size array
161:   void      *rinfo, *rinfog; // MumpsReal, fixed size array

163:   /* Null space */
164:   MUMPS_INT *pivnul_list; // allocated by MUMPS!
165:   MUMPS_INT *mapping;     // allocated by MUMPS!

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

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

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

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

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

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

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

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

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

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

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

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

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

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

509: // 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!
510: #if defined(PETSC_USE_COMPLEX)
511:   #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)
512: #else
513:   #define ID_FIELD_GET(ID, F, I) ((ID).precision == PETSC_PRECISION_SINGLE ? ((float *)(ID).F)[I] : ((double *)(ID).F)[I])
514: #endif

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

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

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

566: typedef struct Mat_MUMPS Mat_MUMPS;
567: struct Mat_MUMPS {
568:   XMUMPS_STRUC_C id;

570:   MatStructure   matstruc;
571:   PetscMPIInt    myid, petsc_size;
572:   PetscMUMPSInt *irn, *jcn;       /* the (i,j,v) triplets passed to mumps. */
573:   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. */
574:   PetscCount     nnz;             /* number of nonzeros. The type is called selective 64-bit in mumps */
575:   PetscMUMPSInt  sym;
576:   MPI_Comm       mumps_comm;
577:   PetscMUMPSInt *ICNTL_pre;
578:   PetscReal     *CNTL_pre;
579:   PetscMUMPSInt  ICNTL9_pre;         /* check if ICNTL(9) is changed from previous MatSolve */
580:   VecScatter     scat_rhs, scat_sol; /* used by MatSolve() */
581:   PetscMUMPSInt  ICNTL20;            /* use centralized (0) or distributed (10) dense RHS */
582:   PetscMUMPSInt  ICNTL26;
583:   PetscMUMPSInt  lrhs_loc, nloc_rhs, *irhs_loc;
584: #if defined(PETSC_HAVE_OPENMP_SUPPORT)
585:   PetscInt    *rhs_nrow, max_nrhs;
586:   PetscMPIInt *rhs_recvcounts, *rhs_disps;
587:   PetscScalar *rhs_loc, *rhs_recvbuf;
588: #endif
589:   Vec            b_seq, x_seq;
590:   PetscInt       ninfo, *info; /* which INFO to display */
591:   PetscInt       sizeredrhs;
592:   PetscScalar   *schur_sol;
593:   PetscInt       schur_sizesol;
594:   PetscScalar   *redrhs;              // buffer in PetscScalar in case MumpsScalar is in a different precision
595:   PetscMUMPSInt *ia_alloc, *ja_alloc; /* work arrays used for the CSR struct for sparse rhs */
596:   PetscCount     cur_ilen, cur_jlen;  /* current len of ia_alloc[], ja_alloc[] */
597:   PetscErrorCode (*ConvertToTriples)(Mat, PetscInt, MatReuse, Mat_MUMPS *);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

818:  */

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

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

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

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

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

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

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

927:   PetscFunctionBegin;
928: #if defined(PETSC_USE_COMPLEX)
929:   PetscCall(MatIsHermitianKnown(A, &isset, &hermitian));
930:   PetscCheck(!isset || !hermitian, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MUMPS does not support Hermitian symmetric matrices for Choleksy");
931: #endif
932:   ai = aa->i;
933:   aj = aa->j;
934:   PetscCall(MatGetBlockSize(A, &bs));
935:   if (reuse == MAT_INITIAL_MATRIX) {
936:     const PetscCount alloc_size = aa->nz * bs2;

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

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

990: static PetscErrorCode MatConvertToTriples_seqaij_seqsbaij(Mat A, PetscInt shift, MatReuse reuse, Mat_MUMPS *mumps)
991: {
992:   const PetscInt    *ai, *aj, *ajj, *adiag, M = A->rmap->n;
993:   PetscCount         nz, rnz, i, j;
994:   const PetscScalar *av, *v1;
995:   PetscScalar       *val;
996:   PetscMUMPSInt     *row, *col;
997:   Mat_SeqAIJ        *aa = (Mat_SeqAIJ *)A->data;
998:   PetscBool          diagDense;
999: #if defined(PETSC_USE_COMPLEX)
1000:   PetscBool hermitian, isset;
1001: #endif

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

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

1098: static PetscErrorCode MatConvertToTriples_mpisbaij_mpisbaij(Mat A, PetscInt shift, MatReuse reuse, Mat_MUMPS *mumps)
1099: {
1100:   const PetscInt    *ai, *aj, *bi, *bj, *garray, *ajj, *bjj;
1101:   PetscInt           bs;
1102:   PetscCount         rstart, nz, i, j, k, m, jj, irow, countA, countB;
1103:   PetscMUMPSInt     *row, *col;
1104:   const PetscScalar *av, *bv, *v1, *v2;
1105:   PetscScalar       *val;
1106:   Mat_MPISBAIJ      *mat = (Mat_MPISBAIJ *)A->data;
1107:   Mat_SeqSBAIJ      *aa  = (Mat_SeqSBAIJ *)mat->A->data;
1108:   Mat_SeqBAIJ       *bb  = (Mat_SeqBAIJ *)mat->B->data;
1109:   const PetscInt     bs2 = aa->bs2, mbs = aa->mbs;
1110: #if defined(PETSC_USE_COMPLEX)
1111:   PetscBool hermitian, isset;
1112: #endif

1114:   PetscFunctionBegin;
1115: #if defined(PETSC_USE_COMPLEX)
1116:   PetscCall(MatIsHermitianKnown(A, &isset, &hermitian));
1117:   PetscCheck(!isset || !hermitian, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MUMPS does not support Hermitian symmetric matrices for Choleksy");
1118: #endif
1119:   PetscCall(MatGetBlockSize(A, &bs));
1120:   rstart = A->rmap->rstart;
1121:   ai     = aa->i;
1122:   aj     = aa->j;
1123:   bi     = bb->i;
1124:   bj     = bb->j;
1125:   av     = aa->a;
1126:   bv     = bb->a;

1128:   garray = mat->garray;

1130:   if (reuse == MAT_INITIAL_MATRIX) {
1131:     nz = (aa->nz + bb->nz) * bs2; /* just a conservative estimate */
1132:     PetscCall(PetscMalloc2(nz, &row, nz, &col));
1133:     PetscCall(PetscMalloc1(nz, &val));
1134:     /* can not decide the exact mumps->nnz now because of the SBAIJ */
1135:     mumps->irn = row;
1136:     mumps->jcn = col;
1137:     mumps->val = mumps->val_alloc = val;
1138:   } else {
1139:     val = mumps->val;
1140:   }

1142:   jj   = 0;
1143:   irow = rstart;
1144:   for (i = 0; i < mbs; i++) {
1145:     ajj    = aj + ai[i]; /* ptr to the beginning of this row */
1146:     countA = ai[i + 1] - ai[i];
1147:     countB = bi[i + 1] - bi[i];
1148:     bjj    = bj + bi[i];
1149:     v1     = av + ai[i] * bs2;
1150:     v2     = bv + bi[i] * bs2;

1152:     if (bs > 1) {
1153:       /* A-part */
1154:       for (j = 0; j < countA; j++) {
1155:         for (k = 0; k < bs; k++) {
1156:           for (m = 0; m < bs; m++) {
1157:             if (rstart + ajj[j] * bs > irow || k >= m) {
1158:               if (reuse == MAT_INITIAL_MATRIX) {
1159:                 PetscCall(PetscMUMPSIntCast(irow + m + shift, &row[jj]));
1160:                 PetscCall(PetscMUMPSIntCast(rstart + ajj[j] * bs + k + shift, &col[jj]));
1161:               }
1162:               val[jj++] = v1[j * bs2 + m + k * bs];
1163:             }
1164:           }
1165:         }
1166:       }

1168:       /* B-part */
1169:       for (j = 0; j < countB; j++) {
1170:         for (k = 0; k < bs; k++) {
1171:           for (m = 0; m < bs; m++) {
1172:             if (reuse == MAT_INITIAL_MATRIX) {
1173:               PetscCall(PetscMUMPSIntCast(irow + m + shift, &row[jj]));
1174:               PetscCall(PetscMUMPSIntCast(garray[bjj[j]] * bs + k + shift, &col[jj]));
1175:             }
1176:             val[jj++] = v2[j * bs2 + m + k * bs];
1177:           }
1178:         }
1179:       }
1180:     } else {
1181:       /* A-part */
1182:       for (j = 0; j < countA; j++) {
1183:         if (reuse == MAT_INITIAL_MATRIX) {
1184:           PetscCall(PetscMUMPSIntCast(irow + shift, &row[jj]));
1185:           PetscCall(PetscMUMPSIntCast(rstart + ajj[j] + shift, &col[jj]));
1186:         }
1187:         val[jj++] = v1[j];
1188:       }

1190:       /* B-part */
1191:       for (j = 0; j < countB; j++) {
1192:         if (reuse == MAT_INITIAL_MATRIX) {
1193:           PetscCall(PetscMUMPSIntCast(irow + shift, &row[jj]));
1194:           PetscCall(PetscMUMPSIntCast(garray[bjj[j]] + shift, &col[jj]));
1195:         }
1196:         val[jj++] = v2[j];
1197:       }
1198:     }
1199:     irow += bs;
1200:   }
1201:   if (reuse == MAT_INITIAL_MATRIX) mumps->nnz = jj;
1202:   PetscFunctionReturn(PETSC_SUCCESS);
1203: }

1205: static PetscErrorCode MatConvertToTriples_mpiaij_mpiaij(Mat A, PetscInt shift, MatReuse reuse, Mat_MUMPS *mumps)
1206: {
1207:   const PetscInt    *ai, *aj, *bi, *bj, *garray, m = A->rmap->n, *ajj, *bjj;
1208:   PetscCount         rstart, cstart, nz, i, j, jj, irow, countA, countB;
1209:   PetscMUMPSInt     *row, *col;
1210:   const PetscScalar *av, *bv, *v1, *v2;
1211:   PetscScalar       *val;
1212:   Mat                Ad, Ao;
1213:   Mat_SeqAIJ        *aa;
1214:   Mat_SeqAIJ        *bb;

1216:   PetscFunctionBegin;
1217:   PetscCall(MatMPIAIJGetSeqAIJ(A, &Ad, &Ao, &garray));
1218:   PetscCall(MatSeqAIJGetArrayRead(Ad, &av));
1219:   PetscCall(MatSeqAIJGetArrayRead(Ao, &bv));

1221:   aa = (Mat_SeqAIJ *)Ad->data;
1222:   bb = (Mat_SeqAIJ *)Ao->data;
1223:   ai = aa->i;
1224:   aj = aa->j;
1225:   bi = bb->i;
1226:   bj = bb->j;

1228:   rstart = A->rmap->rstart;
1229:   cstart = A->cmap->rstart;

1231:   if (reuse == MAT_INITIAL_MATRIX) {
1232:     nz = (PetscCount)aa->nz + bb->nz; /* make sure the sum won't overflow PetscInt */
1233:     PetscCall(PetscMalloc2(nz, &row, nz, &col));
1234:     PetscCall(PetscMalloc1(nz, &val));
1235:     mumps->nnz = nz;
1236:     mumps->irn = row;
1237:     mumps->jcn = col;
1238:     mumps->val = mumps->val_alloc = val;
1239:   } else {
1240:     val = mumps->val;
1241:   }

1243:   jj   = 0;
1244:   irow = rstart;
1245:   for (i = 0; i < m; i++) {
1246:     ajj    = aj + ai[i]; /* ptr to the beginning of this row */
1247:     countA = ai[i + 1] - ai[i];
1248:     countB = bi[i + 1] - bi[i];
1249:     bjj    = bj + bi[i];
1250:     v1     = av + ai[i];
1251:     v2     = bv + bi[i];

1253:     /* A-part */
1254:     for (j = 0; j < countA; j++) {
1255:       if (reuse == MAT_INITIAL_MATRIX) {
1256:         PetscCall(PetscMUMPSIntCast(irow + shift, &row[jj]));
1257:         PetscCall(PetscMUMPSIntCast(cstart + ajj[j] + shift, &col[jj]));
1258:       }
1259:       val[jj++] = v1[j];
1260:     }

1262:     /* B-part */
1263:     for (j = 0; j < countB; j++) {
1264:       if (reuse == MAT_INITIAL_MATRIX) {
1265:         PetscCall(PetscMUMPSIntCast(irow + shift, &row[jj]));
1266:         PetscCall(PetscMUMPSIntCast(garray[bjj[j]] + shift, &col[jj]));
1267:       }
1268:       val[jj++] = v2[j];
1269:     }
1270:     irow++;
1271:   }
1272:   PetscCall(MatSeqAIJRestoreArrayRead(Ad, &av));
1273:   PetscCall(MatSeqAIJRestoreArrayRead(Ao, &bv));
1274:   PetscFunctionReturn(PETSC_SUCCESS);
1275: }

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

1291:   PetscFunctionBegin;
1292:   PetscCall(MatGetBlockSize(A, &bs));
1293:   if (reuse == MAT_INITIAL_MATRIX) {
1294:     nz = bs2 * (aa->nz + bb->nz);
1295:     PetscCall(PetscMalloc2(nz, &row, nz, &col));
1296:     PetscCall(PetscMalloc1(nz, &val));
1297:     mumps->nnz = nz;
1298:     mumps->irn = row;
1299:     mumps->jcn = col;
1300:     mumps->val = mumps->val_alloc = val;
1301:   } else {
1302:     val = mumps->val;
1303:   }

1305:   jj   = 0;
1306:   irow = rstart;
1307:   for (i = 0; i < mbs; i++) {
1308:     countA = ai[i + 1] - ai[i];
1309:     countB = bi[i + 1] - bi[i];
1310:     ajj    = aj + ai[i];
1311:     bjj    = bj + bi[i];
1312:     v1     = av + bs2 * ai[i];
1313:     v2     = bv + bs2 * bi[i];

1315:     idx = 0;
1316:     /* A-part */
1317:     for (k = 0; k < countA; k++) {
1318:       for (j = 0; j < bs; j++) {
1319:         for (n = 0; n < bs; n++) {
1320:           if (reuse == MAT_INITIAL_MATRIX) {
1321:             PetscCall(PetscMUMPSIntCast(irow + n + shift, &row[jj]));
1322:             PetscCall(PetscMUMPSIntCast(cstart + bs * ajj[k] + j + shift, &col[jj]));
1323:           }
1324:           val[jj++] = v1[idx++];
1325:         }
1326:       }
1327:     }

1329:     idx = 0;
1330:     /* B-part */
1331:     for (k = 0; k < countB; k++) {
1332:       for (j = 0; j < bs; j++) {
1333:         for (n = 0; n < bs; n++) {
1334:           if (reuse == MAT_INITIAL_MATRIX) {
1335:             PetscCall(PetscMUMPSIntCast(irow + n + shift, &row[jj]));
1336:             PetscCall(PetscMUMPSIntCast(bs * garray[bjj[k]] + j + shift, &col[jj]));
1337:           }
1338:           val[jj++] = v2[idx++];
1339:         }
1340:       }
1341:     }
1342:     irow += bs;
1343:   }
1344:   PetscFunctionReturn(PETSC_SUCCESS);
1345: }

1347: static PetscErrorCode MatConvertToTriples_mpiaij_mpisbaij(Mat A, PetscInt shift, MatReuse reuse, Mat_MUMPS *mumps)
1348: {
1349:   const PetscInt    *ai, *aj, *adiag, *bi, *bj, *garray, m = A->rmap->n, *ajj, *bjj;
1350:   PetscCount         rstart, nz, nza, nzb, i, j, jj, irow, countA, countB;
1351:   PetscMUMPSInt     *row, *col;
1352:   const PetscScalar *av, *bv, *v1, *v2;
1353:   PetscScalar       *val;
1354:   Mat                Ad, Ao;
1355:   Mat_SeqAIJ        *aa;
1356:   Mat_SeqAIJ        *bb;
1357: #if defined(PETSC_USE_COMPLEX)
1358:   PetscBool hermitian, isset;
1359: #endif

1361:   PetscFunctionBegin;
1362: #if defined(PETSC_USE_COMPLEX)
1363:   PetscCall(MatIsHermitianKnown(A, &isset, &hermitian));
1364:   PetscCheck(!isset || !hermitian, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MUMPS does not support Hermitian symmetric matrices for Choleksy");
1365: #endif
1366:   PetscCall(MatMPIAIJGetSeqAIJ(A, &Ad, &Ao, &garray));
1367:   PetscCall(MatSeqAIJGetArrayRead(Ad, &av));
1368:   PetscCall(MatSeqAIJGetArrayRead(Ao, &bv));

1370:   aa = (Mat_SeqAIJ *)Ad->data;
1371:   bb = (Mat_SeqAIJ *)Ao->data;
1372:   ai = aa->i;
1373:   aj = aa->j;
1374:   bi = bb->i;
1375:   bj = bb->j;
1376:   PetscCall(MatGetDiagonalMarkers_SeqAIJ(Ad, &adiag, NULL));
1377:   rstart = A->rmap->rstart;

1379:   if (reuse == MAT_INITIAL_MATRIX) {
1380:     nza = 0; /* num of upper triangular entries in mat->A, including diagonals */
1381:     nzb = 0; /* num of upper triangular entries in mat->B */
1382:     for (i = 0; i < m; i++) {
1383:       nza += (ai[i + 1] - adiag[i]);
1384:       countB = bi[i + 1] - bi[i];
1385:       bjj    = bj + bi[i];
1386:       for (j = 0; j < countB; j++) {
1387:         if (garray[bjj[j]] > rstart) nzb++;
1388:       }
1389:     }

1391:     nz = nza + nzb; /* total nz of upper triangular part of mat */
1392:     PetscCall(PetscMalloc2(nz, &row, nz, &col));
1393:     PetscCall(PetscMalloc1(nz, &val));
1394:     mumps->nnz = nz;
1395:     mumps->irn = row;
1396:     mumps->jcn = col;
1397:     mumps->val = mumps->val_alloc = val;
1398:   } else {
1399:     val = mumps->val;
1400:   }

1402:   jj   = 0;
1403:   irow = rstart;
1404:   for (i = 0; i < m; i++) {
1405:     ajj    = aj + adiag[i]; /* ptr to the beginning of the diagonal of this row */
1406:     v1     = av + adiag[i];
1407:     countA = ai[i + 1] - adiag[i];
1408:     countB = bi[i + 1] - bi[i];
1409:     bjj    = bj + bi[i];
1410:     v2     = bv + bi[i];

1412:     /* A-part */
1413:     for (j = 0; j < countA; j++) {
1414:       if (reuse == MAT_INITIAL_MATRIX) {
1415:         PetscCall(PetscMUMPSIntCast(irow + shift, &row[jj]));
1416:         PetscCall(PetscMUMPSIntCast(rstart + ajj[j] + shift, &col[jj]));
1417:       }
1418:       val[jj++] = v1[j];
1419:     }

1421:     /* B-part */
1422:     for (j = 0; j < countB; j++) {
1423:       if (garray[bjj[j]] > rstart) {
1424:         if (reuse == MAT_INITIAL_MATRIX) {
1425:           PetscCall(PetscMUMPSIntCast(irow + shift, &row[jj]));
1426:           PetscCall(PetscMUMPSIntCast(garray[bjj[j]] + shift, &col[jj]));
1427:         }
1428:         val[jj++] = v2[j];
1429:       }
1430:     }
1431:     irow++;
1432:   }
1433:   PetscCall(MatSeqAIJRestoreArrayRead(Ad, &av));
1434:   PetscCall(MatSeqAIJRestoreArrayRead(Ao, &bv));
1435:   PetscFunctionReturn(PETSC_SUCCESS);
1436: }

1438: static PetscErrorCode MatConvertToTriples_diagonal_xaij(Mat A, PETSC_UNUSED PetscInt shift, MatReuse reuse, Mat_MUMPS *mumps)
1439: {
1440:   const PetscScalar *av;
1441:   const PetscInt     M = A->rmap->n;
1442:   PetscCount         i;
1443:   PetscMUMPSInt     *row, *col;
1444:   Vec                v;

1446:   PetscFunctionBegin;
1447:   PetscCall(MatDiagonalGetDiagonal(A, &v));
1448:   PetscCall(VecGetArrayRead(v, &av));
1449:   if (reuse == MAT_INITIAL_MATRIX) {
1450:     PetscCall(PetscMalloc2(M, &row, M, &col));
1451:     for (i = 0; i < M; i++) {
1452:       PetscCall(PetscMUMPSIntCast(i + A->rmap->rstart, &row[i]));
1453:       col[i] = row[i];
1454:     }
1455:     mumps->val = (PetscScalar *)av;
1456:     mumps->irn = row;
1457:     mumps->jcn = col;
1458:     mumps->nnz = M;
1459:   } 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 */
1460:   else mumps->val = (PetscScalar *)av;                                      /* in the default case, mumps->val is never allocated, one just needs to update the mumps->val pointer */
1461:   PetscCall(VecRestoreArrayRead(v, &av));
1462:   PetscFunctionReturn(PETSC_SUCCESS);
1463: }

1465: static PetscErrorCode MatConvertToTriples_dense_xaij(Mat A, PETSC_UNUSED PetscInt shift, MatReuse reuse, Mat_MUMPS *mumps)
1466: {
1467:   PetscScalar   *v;
1468:   const PetscInt m = A->rmap->n, N = A->cmap->N;
1469:   PetscInt       lda;
1470:   PetscCount     i, j;
1471:   PetscMUMPSInt *row, *col;

1473:   PetscFunctionBegin;
1474:   PetscCall(MatDenseGetArray(A, &v));
1475:   PetscCall(MatDenseGetLDA(A, &lda));
1476:   if (reuse == MAT_INITIAL_MATRIX) {
1477:     PetscCall(PetscMalloc2(m * N, &row, m * N, &col));
1478:     for (i = 0; i < m; i++) {
1479:       col[i] = 0;
1480:       PetscCall(PetscMUMPSIntCast(i + A->rmap->rstart, &row[i]));
1481:     }
1482:     for (j = 1; j < N; j++) {
1483:       for (i = 0; i < m; i++) PetscCall(PetscMUMPSIntCast(j, col + i + m * j));
1484:       PetscCall(PetscArraycpy(row + m * j, row + m * (j - 1), m));
1485:     }
1486:     if (lda == m) mumps->val = v;
1487:     else {
1488:       PetscCall(PetscMalloc1(m * N, &mumps->val));
1489:       mumps->val_alloc = mumps->val;
1490:       for (j = 0; j < N; j++) PetscCall(PetscArraycpy(mumps->val + m * j, v + lda * j, m));
1491:     }
1492:     mumps->irn = row;
1493:     mumps->jcn = col;
1494:     mumps->nnz = m * N;
1495:   } else {
1496:     if (lda == m && !mumps->nest_vals) mumps->val = v;
1497:     else {
1498:       for (j = 0; j < N; j++) PetscCall(PetscArraycpy(mumps->val + m * j, v + lda * j, m));
1499:     }
1500:   }
1501:   PetscCall(MatDenseRestoreArray(A, &v));
1502:   PetscFunctionReturn(PETSC_SUCCESS);
1503: }

1505: // If the input Mat (sub) is either MATTRANSPOSEVIRTUAL or MATHERMITIANTRANSPOSEVIRTUAL, this function gets the parent Mat until it is not a
1506: // MATTRANSPOSEVIRTUAL or MATHERMITIANTRANSPOSEVIRTUAL itself and returns the appropriate shift, scaling, and whether the parent Mat should be conjugated
1507: // and its rows and columns permuted
1508: // TODO FIXME: this should not be in this file and should instead be refactored where the same logic applies, e.g., MatAXPY_Dense_Nest()
1509: static PetscErrorCode MatGetTranspose_TransposeVirtual(Mat *sub, PetscBool *conjugate, PetscScalar *vshift, PetscScalar *vscale, PetscBool *swap)
1510: {
1511:   Mat         A;
1512:   PetscScalar s[2];
1513:   PetscBool   isTrans, isHTrans, compare;

1515:   PetscFunctionBegin;
1516:   do {
1517:     PetscCall(PetscObjectTypeCompare((PetscObject)*sub, MATTRANSPOSEVIRTUAL, &isTrans));
1518:     if (isTrans) {
1519:       PetscCall(MatTransposeGetMat(*sub, &A));
1520:       isHTrans = PETSC_FALSE;
1521:     } else {
1522:       PetscCall(PetscObjectTypeCompare((PetscObject)*sub, MATHERMITIANTRANSPOSEVIRTUAL, &isHTrans));
1523:       if (isHTrans) PetscCall(MatHermitianTransposeGetMat(*sub, &A));
1524:     }
1525:     compare = (PetscBool)(isTrans || isHTrans);
1526:     if (compare) {
1527:       if (vshift && vscale) {
1528:         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));
1529:         if (!*conjugate) {
1530:           *vshift += s[0] * *vscale;
1531:           *vscale *= s[1];
1532:         } else {
1533:           *vshift += PetscConj(s[0]) * *vscale;
1534:           *vscale *= PetscConj(s[1]);
1535:         }
1536:       }
1537:       if (swap) *swap = (PetscBool)!*swap;
1538:       if (isHTrans && conjugate) *conjugate = (PetscBool)!*conjugate;
1539:       *sub = A;
1540:     }
1541:   } while (compare);
1542:   PetscFunctionReturn(PETSC_SUCCESS);
1543: }

1545: static PetscErrorCode MatConvertToTriples_nest_xaij(Mat A, PetscInt shift, MatReuse reuse, Mat_MUMPS *mumps)
1546: {
1547:   Mat     **mats;
1548:   PetscInt  nr, nc;
1549:   PetscBool chol = mumps->sym ? PETSC_TRUE : PETSC_FALSE;

1551:   PetscFunctionBegin;
1552:   PetscCall(MatNestGetSubMats(A, &nr, &nc, &mats));
1553:   if (reuse == MAT_INITIAL_MATRIX) {
1554:     PetscMUMPSInt *irns, *jcns;
1555:     PetscScalar   *vals;
1556:     PetscCount     totnnz, cumnnz, maxnnz;
1557:     PetscInt      *pjcns_w, Mbs = 0;
1558:     IS            *rows, *cols;
1559:     PetscInt     **rows_idx, **cols_idx;

1561:     cumnnz = 0;
1562:     maxnnz = 0;
1563:     PetscCall(PetscMalloc2(nr * nc + 1, &mumps->nest_vals_start, nr * nc, &mumps->nest_convert_to_triples));
1564:     for (PetscInt r = 0; r < nr; r++) {
1565:       for (PetscInt c = 0; c < nc; c++) {
1566:         Mat sub = mats[r][c];

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

1575:           PetscCall(MatGetTranspose_TransposeVirtual(&sub, NULL, NULL, NULL, NULL));
1576:           PetscCall(PetscObjectBaseTypeCompare((PetscObject)sub, MATSEQAIJ, &isSeqAIJ));
1577:           PetscCall(PetscObjectBaseTypeCompare((PetscObject)sub, MATMPIAIJ, &isMPIAIJ));
1578:           PetscCall(PetscObjectBaseTypeCompare((PetscObject)sub, MATSEQBAIJ, &isSeqBAIJ));
1579:           PetscCall(PetscObjectBaseTypeCompare((PetscObject)sub, MATMPIBAIJ, &isMPIBAIJ));
1580:           PetscCall(PetscObjectBaseTypeCompare((PetscObject)sub, MATSEQSBAIJ, &isSeqSBAIJ));
1581:           PetscCall(PetscObjectBaseTypeCompare((PetscObject)sub, MATMPISBAIJ, &isMPISBAIJ));
1582:           PetscCall(PetscObjectTypeCompare((PetscObject)sub, MATDIAGONAL, &isDiag));
1583:           PetscCall(PetscObjectTypeCompareAny((PetscObject)sub, &isDense, MATSEQDENSE, MATMPIDENSE, NULL));

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

1618:     /* Allocate total COO */
1619:     totnnz = cumnnz;
1620:     PetscCall(PetscMalloc2(totnnz, &irns, totnnz, &jcns));
1621:     PetscCall(PetscMalloc1(totnnz, &vals));

1623:     /* Handle rows and column maps
1624:        We directly map rows and use an SF for the columns */
1625:     PetscCall(PetscMalloc4(nr, &rows, nc, &cols, nr, &rows_idx, nc, &cols_idx));
1626:     PetscCall(MatNestGetISs(A, rows, cols));
1627:     for (PetscInt r = 0; r < nr; r++) PetscCall(ISGetIndices(rows[r], (const PetscInt **)&rows_idx[r]));
1628:     for (PetscInt c = 0; c < nc; c++) PetscCall(ISGetIndices(cols[c], (const PetscInt **)&cols_idx[c]));
1629:     if (PetscDefined(USE_64BIT_INDICES)) PetscCall(PetscMalloc1(maxnnz, &pjcns_w));
1630:     else (void)maxnnz;

1632:     cumnnz = 0;
1633:     for (PetscInt r = 0; r < nr; r++) {
1634:       for (PetscInt c = 0; c < nc; c++) {
1635:         Mat             sub    = mats[r][c];
1636:         const PetscInt *ridx   = rows_idx[r];
1637:         const PetscInt *cidx   = cols_idx[c];
1638:         PetscScalar     vscale = 1.0, vshift = 0.0;
1639:         PetscInt        rst, size, bs;
1640:         PetscSF         csf;
1641:         PetscBool       conjugate = PETSC_FALSE, swap = PETSC_FALSE;
1642:         PetscLayout     cmap;
1643:         PetscInt        innz;

1645:         mumps->nest_vals_start[r * nc + c] = cumnnz;
1646:         if (c == r) {
1647:           PetscCall(ISGetSize(rows[r], &size));
1648:           if (!mumps->nest_convert_to_triples[r * nc + c]) {
1649:             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
1650:           }
1651:           PetscCall(MatGetBlockSize(sub, &bs));
1652:           Mbs += size / bs;
1653:         }
1654:         if (!mumps->nest_convert_to_triples[r * nc + c]) continue;

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

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

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

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

1669:         /* Swap the role of rows and columns indices for transposed blocks
1670:            since we need values with global final ordering */
1671:         if (swap) {
1672:           cidx = rows_idx[r];
1673:           ridx = cols_idx[c];
1674:         }

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

1689:         /* Import indices: use direct map for rows and mapped indices for columns */
1690:         if (swap) {
1691:           for (PetscInt k = 0; k < mumps->nnz; k++) {
1692:             PetscCall(PetscMUMPSIntCast(ridx[mumps->irn[k] - rst] + shift, &jcns[cumnnz + k]));
1693:             PetscCall(PetscMUMPSIntCast(pjcns_w[k] + shift, &irns[cumnnz + k]));
1694:           }
1695:         } else {
1696:           for (PetscInt k = 0; k < mumps->nnz; k++) {
1697:             PetscCall(PetscMUMPSIntCast(ridx[mumps->irn[k] - rst] + shift, &irns[cumnnz + k]));
1698:             PetscCall(PetscMUMPSIntCast(pjcns_w[k] + shift, &jcns[cumnnz + k]));
1699:           }
1700:         }

1702:         /* Import values to full COO */
1703:         if (conjugate) { /* conjugate the entries */
1704:           PetscScalar *v = vals + cumnnz;
1705:           for (PetscInt k = 0; k < mumps->nnz; k++) v[k] = vscale * PetscConj(mumps->val[k]);
1706:         } else if (vscale != 1.0) {
1707:           PetscScalar *v = vals + cumnnz;
1708:           for (PetscInt k = 0; k < mumps->nnz; k++) v[k] = vscale * mumps->val[k];
1709:         } else PetscCall(PetscArraycpy(vals + cumnnz, mumps->val, mumps->nnz));

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

1715:         /* Free scratch memory */
1716:         PetscCall(PetscFree2(mumps->irn, mumps->jcn));
1717:         PetscCall(PetscFree(mumps->val_alloc));
1718:         mumps->val = NULL;
1719:         mumps->nnz = 0;
1720:       }
1721:     }
1722:     if (mumps->id.ICNTL(15) == 1) {
1723:       if (Mbs != A->rmap->N) {
1724:         PetscMPIInt rank, size;

1726:         PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank));
1727:         PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
1728:         if (rank == 0) {
1729:           PetscInt shift = 0;

1731:           PetscCall(PetscMUMPSIntCast(Mbs, &mumps->id.nblk));
1732:           PetscCall(PetscFree(mumps->id.blkptr));
1733:           PetscCall(PetscMalloc1(Mbs + 1, &mumps->id.blkptr));
1734:           mumps->id.blkptr[0] = 1;
1735:           for (PetscInt i = 0; i < size; ++i) {
1736:             for (PetscInt r = 0; r < nr; r++) {
1737:               Mat             sub = mats[r][r];
1738:               const PetscInt *ranges;
1739:               PetscInt        bs;

1741:               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
1742:               PetscCall(MatGetOwnershipRanges(sub, &ranges));
1743:               PetscCall(MatGetBlockSize(sub, &bs));
1744:               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));
1745:               shift += (ranges[i + 1] - ranges[i]) / bs;
1746:             }
1747:           }
1748:         }
1749:       } else mumps->id.ICNTL(15) = 0;
1750:     }
1751:     if (PetscDefined(USE_64BIT_INDICES)) PetscCall(PetscFree(pjcns_w));
1752:     for (PetscInt r = 0; r < nr; r++) PetscCall(ISRestoreIndices(rows[r], (const PetscInt **)&rows_idx[r]));
1753:     for (PetscInt c = 0; c < nc; c++) PetscCall(ISRestoreIndices(cols[c], (const PetscInt **)&cols_idx[c]));
1754:     PetscCall(PetscFree4(rows, cols, rows_idx, cols_idx));
1755:     if (!chol) PetscCheck(cumnnz == totnnz, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Different number of nonzeros %" PetscCount_FMT " != %" PetscCount_FMT, cumnnz, totnnz);
1756:     mumps->nest_vals_start[nr * nc] = cumnnz;

1758:     /* Set pointers for final MUMPS data structure */
1759:     mumps->nest_vals = vals;
1760:     mumps->val_alloc = NULL; /* do not use val_alloc since it may be reallocated with the OMP callpath */
1761:     mumps->val       = vals;
1762:     mumps->irn       = irns;
1763:     mumps->jcn       = jcns;
1764:     mumps->nnz       = cumnnz;
1765:   } else {
1766:     PetscScalar *oval = mumps->nest_vals;
1767:     for (PetscInt r = 0; r < nr; r++) {
1768:       for (PetscInt c = 0; c < nc; c++) {
1769:         PetscBool   conjugate = PETSC_FALSE;
1770:         Mat         sub       = mats[r][c];
1771:         PetscScalar vscale = 1.0, vshift = 0.0;
1772:         PetscInt    midx = r * nc + c;

1774:         if (!mumps->nest_convert_to_triples[midx]) continue;
1775:         PetscCall(MatGetTranspose_TransposeVirtual(&sub, &conjugate, &vshift, &vscale, NULL));
1776:         PetscCheck(vshift == 0.0, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Nonzero shift in parent MatShell");
1777:         mumps->val = oval + mumps->nest_vals_start[midx];
1778:         PetscCall((*mumps->nest_convert_to_triples[midx])(sub, shift, MAT_REUSE_MATRIX, mumps));
1779:         if (conjugate) {
1780:           PetscCount nnz = mumps->nest_vals_start[midx + 1] - mumps->nest_vals_start[midx];
1781:           for (PetscCount k = 0; k < nnz; k++) mumps->val[k] = vscale * PetscConj(mumps->val[k]);
1782:         } else if (vscale != 1.0) {
1783:           PetscCount nnz = mumps->nest_vals_start[midx + 1] - mumps->nest_vals_start[midx];
1784:           for (PetscCount k = 0; k < nnz; k++) mumps->val[k] *= vscale;
1785:         }
1786:       }
1787:     }
1788:     mumps->val = oval;
1789:   }
1790:   PetscFunctionReturn(PETSC_SUCCESS);
1791: }

1793: static PetscErrorCode MatDestroy_MUMPS(Mat F)
1794: {
1795:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

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

1838:   /* clear composed functions */
1839:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatFactorGetSolverType_C", NULL));
1840:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatFactorSetSchurIS_C", NULL));
1841:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatFactorCreateSchurComplement_C", NULL));
1842:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatMumpsSetIcntl_C", NULL));
1843:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatMumpsGetIcntl_C", NULL));
1844:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatMumpsSetCntl_C", NULL));
1845:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatMumpsGetCntl_C", NULL));
1846:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatMumpsGetInfo_C", NULL));
1847:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatMumpsGetInfog_C", NULL));
1848:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatMumpsGetRinfo_C", NULL));
1849:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatMumpsGetRinfog_C", NULL));
1850:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatMumpsGetNullPivots_C", NULL));
1851:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatMumpsGetInverse_C", NULL));
1852:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatMumpsGetInverseTranspose_C", NULL));
1853:   PetscCall(PetscObjectComposeFunction((PetscObject)F, "MatMumpsSetBlk_C", NULL));
1854:   PetscFunctionReturn(PETSC_SUCCESS);
1855: }

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

1864:   PetscFunctionBegin;
1865:   PetscCall(MatGetSize(A, &M, NULL));
1866:   PetscCall(MatGetLocalSize(A, &m, NULL));
1867:   PetscCheck(M <= PETSC_MUMPS_INT_MAX, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "PetscInt too long for PetscMUMPSInt");
1868:   if (ompsize == 1) {
1869:     if (!mumps->irhs_loc) {
1870:       mumps->nloc_rhs = (PetscMUMPSInt)m;
1871:       PetscCall(PetscMalloc1(m, &mumps->irhs_loc));
1872:       PetscCall(MatGetOwnershipRange(A, &rstart, NULL));
1873:       for (i = 0; i < m; i++) PetscCall(PetscMUMPSIntCast(rstart + i + 1, &mumps->irhs_loc[i])); /* use 1-based indices */
1874:     }
1875:     PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, m * nrhs, array, mumps->id.precision, &mumps->id.rhs_loc_len, &mumps->id.rhs_loc));
1876:   } else {
1877: #if defined(PETSC_HAVE_OPENMP_SUPPORT)
1878:     const PetscInt *ranges;
1879:     PetscMPIInt     j, k, sendcount, *petsc_ranks, *omp_ranks;
1880:     MPI_Group       petsc_group, omp_group;
1881:     PetscScalar    *recvbuf = NULL;

1883:     if (mumps->is_omp_master) {
1884:       /* Lazily initialize the omp stuff for distributed rhs */
1885:       if (!mumps->irhs_loc) {
1886:         PetscCall(PetscMalloc2(ompsize, &omp_ranks, ompsize, &petsc_ranks));
1887:         PetscCall(PetscMalloc3(ompsize, &mumps->rhs_nrow, ompsize, &mumps->rhs_recvcounts, ompsize, &mumps->rhs_disps));
1888:         PetscCallMPI(MPI_Comm_group(mumps->petsc_comm, &petsc_group));
1889:         PetscCallMPI(MPI_Comm_group(mumps->omp_comm, &omp_group));
1890:         for (j = 0; j < ompsize; j++) omp_ranks[j] = j;
1891:         PetscCallMPI(MPI_Group_translate_ranks(omp_group, ompsize, omp_ranks, petsc_group, petsc_ranks));

1893:         /* Populate mumps->irhs_loc[], rhs_nrow[] */
1894:         mumps->nloc_rhs = 0;
1895:         PetscCall(MatGetOwnershipRanges(A, &ranges));
1896:         for (j = 0; j < ompsize; j++) {
1897:           mumps->rhs_nrow[j] = ranges[petsc_ranks[j] + 1] - ranges[petsc_ranks[j]];
1898:           mumps->nloc_rhs += mumps->rhs_nrow[j];
1899:         }
1900:         PetscCall(PetscMalloc1(mumps->nloc_rhs, &mumps->irhs_loc));
1901:         for (j = k = 0; j < ompsize; j++) {
1902:           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 */
1903:         }

1905:         PetscCall(PetscFree2(omp_ranks, petsc_ranks));
1906:         PetscCallMPI(MPI_Group_free(&petsc_group));
1907:         PetscCallMPI(MPI_Group_free(&omp_group));
1908:       }

1910:       /* Realloc buffers when current nrhs is bigger than what we have met */
1911:       if (nrhs > mumps->max_nrhs) {
1912:         PetscCall(PetscFree2(mumps->rhs_loc, mumps->rhs_recvbuf));
1913:         PetscCall(PetscMalloc2(mumps->nloc_rhs * nrhs, &mumps->rhs_loc, mumps->nloc_rhs * nrhs, &mumps->rhs_recvbuf));
1914:         mumps->max_nrhs = nrhs;
1915:       }

1917:       /* Setup recvcounts[], disps[], recvbuf on omp rank 0 for the upcoming MPI_Gatherv */
1918:       for (j = 0; j < ompsize; j++) PetscCall(PetscMPIIntCast(mumps->rhs_nrow[j] * nrhs, &mumps->rhs_recvcounts[j]));
1919:       mumps->rhs_disps[0] = 0;
1920:       for (j = 1; j < ompsize; j++) {
1921:         mumps->rhs_disps[j] = mumps->rhs_disps[j - 1] + mumps->rhs_recvcounts[j - 1];
1922:         PetscCheck(mumps->rhs_disps[j] >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "PetscMPIInt overflow!");
1923:       }
1924:       recvbuf = (nrhs == 1) ? mumps->rhs_loc : mumps->rhs_recvbuf; /* Directly use rhs_loc[] as recvbuf. Single rhs is common in Ax=b */
1925:     }

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

1930:     if (mumps->is_omp_master) {
1931:       if (nrhs > 1) { /* Copy & re-arrange data from rhs_recvbuf[] to mumps->rhs_loc[] only when there are multiple rhs */
1932:         PetscScalar *dst, *dstbase = mumps->rhs_loc;
1933:         for (j = 0; j < ompsize; j++) {
1934:           const PetscScalar *src = mumps->rhs_recvbuf + mumps->rhs_disps[j];
1935:           dst                    = dstbase;
1936:           for (i = 0; i < nrhs; i++) {
1937:             PetscCall(PetscArraycpy(dst, src, mumps->rhs_nrow[j]));
1938:             src += mumps->rhs_nrow[j];
1939:             dst += mumps->nloc_rhs;
1940:           }
1941:           dstbase += mumps->rhs_nrow[j];
1942:         }
1943:       }
1944:       PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, mumps->nloc_rhs * nrhs, mumps->rhs_loc, mumps->id.precision, &mumps->id.rhs_loc_len, &mumps->id.rhs_loc));
1945:     }
1946: #endif /* PETSC_HAVE_OPENMP_SUPPORT */
1947:   }
1948:   mumps->id.nrhs     = (PetscMUMPSInt)nrhs;
1949:   mumps->id.nloc_rhs = (PetscMUMPSInt)mumps->nloc_rhs;
1950:   mumps->id.lrhs_loc = mumps->nloc_rhs;
1951:   mumps->id.irhs_loc = mumps->irhs_loc;
1952:   PetscFunctionReturn(PETSC_SUCCESS);
1953: }

1955: static PetscErrorCode MatSolve_MUMPS(Mat A, Vec b, Vec x)
1956: {
1957:   Mat_MUMPS         *mumps  = (Mat_MUMPS *)A->data;
1958:   const PetscScalar *barray = NULL;
1959:   PetscScalar       *array;
1960:   IS                 is_iden, is_petsc;
1961:   PetscBool          second_solve = PETSC_FALSE;
1962:   static PetscBool   cite1 = PETSC_FALSE, cite2 = PETSC_FALSE;

1964:   PetscFunctionBegin;
1965:   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 "
1966:                                    "Journal on Matrix Analysis and Applications},\n  volume = {23},\n  number = {1},\n  pages = {15--41},\n  year = {2001}\n}\n",
1967:                                    &cite1));
1968:   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 "
1969:                                    "Computing},\n  volume = {32},\n  number = {2},\n  pages = {136--156},\n  year = {2006}\n}\n",
1970:                                    &cite2));

1972:   PetscCall(VecFlag(x, A->factorerrortype));
1973:   if (A->factorerrortype) {
1974:     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)));
1975:     PetscFunctionReturn(PETSC_SUCCESS);
1976:   }

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

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

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

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

2027:   if (mumps->petsc_size > 1) { /* convert mumps distributed solution to PETSc mpi x */
2028:     if (mumps->scat_sol && mumps->ICNTL9_pre != mumps->id.ICNTL(9)) {
2029:       /* when id.ICNTL(9) changes, the contents of ilsol_loc may change (not its size, lsol_loc), recreates scat_sol */
2030:       PetscCall(VecScatterDestroy(&mumps->scat_sol));
2031:     }
2032:     if (!mumps->scat_sol) { /* create scatter scat_sol */
2033:       PetscInt *isol2_loc = NULL;
2034:       PetscCall(ISCreateStride(PETSC_COMM_SELF, mumps->id.lsol_loc, 0, 1, &is_iden)); /* from */
2035:       PetscCall(PetscMalloc1(mumps->id.lsol_loc, &isol2_loc));
2036:       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 */
2037:       PetscCall(ISCreateGeneral(PETSC_COMM_SELF, mumps->id.lsol_loc, isol2_loc, PETSC_OWN_POINTER, &is_petsc)); /* to */
2038:       PetscCall(VecScatterCreate(mumps->x_seq, is_iden, x, is_petsc, &mumps->scat_sol));
2039:       PetscCall(ISDestroy(&is_iden));
2040:       PetscCall(ISDestroy(&is_petsc));
2041:       mumps->ICNTL9_pre = mumps->id.ICNTL(9); /* save current value of id.ICNTL(9) */
2042:     }

2044:     PetscScalar *xarray;
2045:     PetscCall(VecGetArray(mumps->x_seq, &xarray));
2046:     PetscCall(MatMumpsCastMumpsScalarArray(mumps->id.lsol_loc, mumps->id.precision, mumps->id.sol_loc, xarray));
2047:     PetscCall(VecRestoreArray(mumps->x_seq, &xarray));
2048:     PetscCall(VecScatterBegin(mumps->scat_sol, mumps->x_seq, x, INSERT_VALUES, SCATTER_FORWARD));
2049:     PetscCall(VecScatterEnd(mumps->scat_sol, mumps->x_seq, x, INSERT_VALUES, SCATTER_FORWARD));

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

2062:   PetscCall(PetscLogFlops(2.0 * PetscMax(0, (mumps->id.INFO(28) >= 0 ? mumps->id.INFO(28) : -1000000 * mumps->id.INFO(28)) - A->cmap->n)));
2063:   PetscFunctionReturn(PETSC_SUCCESS);
2064: }

2066: static PetscErrorCode MatSolveTranspose_MUMPS(Mat A, Vec b, Vec x)
2067: {
2068:   Mat_MUMPS          *mumps = (Mat_MUMPS *)A->data;
2069:   const PetscMUMPSInt value = mumps->id.ICNTL(9);

2071:   PetscFunctionBegin;
2072:   mumps->id.ICNTL(9) = 0;
2073:   PetscCall(MatSolve_MUMPS(A, b, x));
2074:   mumps->id.ICNTL(9) = value;
2075:   PetscFunctionReturn(PETSC_SUCCESS);
2076: }

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

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

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

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

2122:   PetscCall(MatGetSize(B, &M, &nrhs));
2123:   PetscCall(PetscIntMultError(nrhs, M, &nrhsM));
2124:   mumps->id.nrhs = (PetscMUMPSInt)nrhs;
2125:   mumps->id.lrhs = (PetscMUMPSInt)M;

2127:   if (mumps->petsc_size == 1) { // handle this easy case specially and return early
2128:     PetscScalar *aa;
2129:     PetscInt     spnr, *ia, *ja;
2130:     PetscBool    second_solve = PETSC_FALSE;

2132:     PetscCall(MatDenseGetArray(X, &array));
2133:     if (denseB) {
2134:       /* copy B to X */
2135:       PetscCall(MatDenseGetArrayRead(B, &barray));
2136:       PetscCall(PetscArraycpy(array, barray, nrhsM));
2137:       PetscCall(MatDenseRestoreArrayRead(B, &barray));
2138:     } else { /* sparse B */
2139:       PetscCall(MatSeqAIJGetArray(Bt, &aa));
2140:       PetscCall(MatGetRowIJ(Bt, 1, PETSC_FALSE, PETSC_FALSE, &spnr, (const PetscInt **)&ia, (const PetscInt **)&ja, &flg));
2141:       PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot get IJ structure");
2142:       PetscCall(PetscMUMPSIntCSRCast(mumps, spnr, ia, ja, &mumps->id.irhs_ptr, &mumps->id.irhs_sparse, &mumps->id.nz_rhs));
2143:       PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, mumps->id.nz_rhs, aa, mumps->id.precision, &mumps->id.rhs_sparse_len, &mumps->id.rhs_sparse));
2144:     }
2145:     PetscCall(MatMumpsMakeMumpsScalarArray(denseB, nrhsM, array, mumps->id.precision, &mumps->id.rhs_len, &mumps->id.rhs));

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

2156:     mumps->id.job = JOB_SOLVE;
2157:     PetscMUMPS_c(mumps);
2158:     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));

2160:     /* handle expansion step of Schur complement (if any) */
2161:     if (second_solve) PetscCall(MatMumpsHandleSchur_Private(A, PETSC_TRUE));
2162:     else if (mumps->id.ICNTL(26) == 1) { // condense the right hand side
2163:       PetscCall(MatMumpsSolveSchur_Private(A));
2164:       for (j = 0; j < nrhs; ++j)
2165:         for (i = 0; i < mumps->id.size_schur; ++i) array[mumps->id.listvar_schur[i] - 1 + j * M] = ID_FIELD_GET(mumps->id, redrhs, i + j * mumps->id.lredrhs);
2166:     }

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

2174:     // no matter dense B or sparse B, solution is in id.rhs; convert it to array of X.
2175:     PetscCall(MatMumpsCastMumpsScalarArray(nrhsM, mumps->id.precision, mumps->id.rhs, array));
2176:     PetscCall(MatDenseRestoreArray(X, &array));
2177:     PetscFunctionReturn(PETSC_SUCCESS);
2178:   }

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

2183:   /* create msol_loc to hold mumps local solution */
2184:   isol_loc_save         = mumps->id.isol_loc; /* save these, as we want to reuse them in MatSolve() */
2185:   sol_loc_save          = mumps->id.sol_loc;
2186:   sol_loc_len_save      = mumps->id.sol_loc_len;
2187:   mumps->id.isol_loc    = NULL; // an init state
2188:   mumps->id.sol_loc     = NULL;
2189:   mumps->id.sol_loc_len = 0;

2191:   lsol_loc = mumps->id.lsol_loc;
2192:   PetscCall(PetscIntMultError(nrhs, lsol_loc, &nlsol_loc)); /* length of sol_loc */
2193:   PetscCall(PetscMalloc2(nlsol_loc, &sol_loc, lsol_loc, &isol_loc));
2194:   PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_FALSE, nlsol_loc, sol_loc, mumps->id.precision, &mumps->id.sol_loc_len, &mumps->id.sol_loc));
2195:   mumps->id.isol_loc = isol_loc;

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

2199:   if (denseB) {
2200:     if (mumps->ICNTL20 == 10) {
2201:       mumps->id.ICNTL(20) = 10; /* dense distributed RHS */
2202:       PetscCall(MatDenseGetArrayRead(B, &barray));
2203:       PetscCall(MatMumpsSetUpDistRHSInfo(A, nrhs, barray)); // put barray to rhs_loc
2204:       PetscCall(MatDenseRestoreArrayRead(B, &barray));
2205:       PetscCall(MatGetLocalSize(B, &m, NULL));
2206:       PetscCall(VecCreateMPIWithArray(PetscObjectComm((PetscObject)B), 1, nrhs * m, nrhsM, NULL, &v_mpi)); // will scatter the solution to v_mpi, which wraps X
2207:     } else {
2208:       mumps->id.ICNTL(20) = 0; /* dense centralized RHS */
2209:       /* TODO: Because of non-contiguous indices, the created vecscatter scat_rhs is not done in MPI_Gather, resulting in
2210:         very inefficient communication. An optimization is to use VecScatterCreateToZero to gather B to rank 0. Then on rank
2211:         0, re-arrange B into desired order, which is a local operation.
2212:       */

2214:       /* scatter v_mpi to b_seq because MUMPS before 5.3.0 only supports centralized rhs */
2215:       /* wrap dense rhs matrix B into a vector v_mpi */
2216:       PetscCall(MatGetLocalSize(B, &m, NULL));
2217:       PetscCall(MatDenseGetArrayRead(B, &barray));
2218:       PetscCall(VecCreateMPIWithArray(PetscObjectComm((PetscObject)B), 1, nrhs * m, nrhsM, barray, &v_mpi));
2219:       PetscCall(MatDenseRestoreArrayRead(B, &barray));

2221:       /* scatter v_mpi to b_seq in proc[0]. With ICNTL(20) = 0, MUMPS requires rhs to be centralized on the host! */
2222:       if (!mumps->myid) {
2223:         PetscInt *idx;
2224:         /* idx: maps from k-th index of v_mpi to (i,j)-th global entry of B */
2225:         PetscCall(PetscMalloc1(nrhsM, &idx));
2226:         PetscCall(MatGetOwnershipRanges(B, &rstart));
2227:         for (proc = 0, k = 0; proc < mumps->petsc_size; proc++) {
2228:           for (j = 0; j < nrhs; j++) {
2229:             for (i = rstart[proc]; i < rstart[proc + 1]; i++) idx[k++] = j * M + i;
2230:           }
2231:         }

2233:         PetscCall(VecCreateSeq(PETSC_COMM_SELF, nrhsM, &b_seq));
2234:         PetscCall(ISCreateGeneral(PETSC_COMM_SELF, nrhsM, idx, PETSC_OWN_POINTER, &is_to));
2235:         PetscCall(ISCreateStride(PETSC_COMM_SELF, nrhsM, 0, 1, &is_from));
2236:       } else {
2237:         PetscCall(VecCreateSeq(PETSC_COMM_SELF, 0, &b_seq));
2238:         PetscCall(ISCreateStride(PETSC_COMM_SELF, 0, 0, 1, &is_to));
2239:         PetscCall(ISCreateStride(PETSC_COMM_SELF, 0, 0, 1, &is_from));
2240:       }

2242:       PetscCall(VecScatterCreate(v_mpi, is_from, b_seq, is_to, &scat_rhs));
2243:       PetscCall(VecScatterBegin(scat_rhs, v_mpi, b_seq, INSERT_VALUES, SCATTER_FORWARD));
2244:       PetscCall(ISDestroy(&is_to));
2245:       PetscCall(ISDestroy(&is_from));
2246:       PetscCall(VecScatterEnd(scat_rhs, v_mpi, b_seq, INSERT_VALUES, SCATTER_FORWARD));

2248:       if (!mumps->myid) { /* define rhs on the host */
2249:         PetscCall(VecGetArrayRead(b_seq, &barray));
2250:         PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, nrhsM, barray, mumps->id.precision, &mumps->id.rhs_len, &mumps->id.rhs));
2251:         PetscCall(VecRestoreArrayRead(b_seq, &barray));
2252:       }
2253:     }
2254:   } else { /* sparse B */
2255:     b = (Mat_MPIAIJ *)Bt->data;

2257:     /* wrap dense X into a vector v_mpi */
2258:     PetscCall(MatGetLocalSize(X, &m, NULL));
2259:     PetscCall(MatDenseGetArrayRead(X, &barray));
2260:     PetscCall(VecCreateMPIWithArray(PetscObjectComm((PetscObject)X), 1, nrhs * m, nrhsM, barray, &v_mpi));
2261:     PetscCall(MatDenseRestoreArrayRead(X, &barray));

2263:     if (!mumps->myid) {
2264:       PetscCall(MatSeqAIJGetArray(b->A, &aa));
2265:       PetscCall(MatGetRowIJ(b->A, 1, PETSC_FALSE, PETSC_FALSE, &spnr, (const PetscInt **)&ia, (const PetscInt **)&ja, &flg));
2266:       PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot get IJ structure");
2267:       PetscCall(PetscMUMPSIntCSRCast(mumps, spnr, ia, ja, &mumps->id.irhs_ptr, &mumps->id.irhs_sparse, &mumps->id.nz_rhs));
2268:       PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_TRUE, ((Mat_SeqAIJ *)b->A->data)->nz, aa, mumps->id.precision, &mumps->id.rhs_sparse_len, &mumps->id.rhs_sparse));
2269:     } else {
2270:       mumps->id.irhs_ptr    = NULL;
2271:       mumps->id.irhs_sparse = NULL;
2272:       mumps->id.nz_rhs      = 0;
2273:       if (mumps->id.rhs_sparse_len) {
2274:         PetscCall(PetscFree(mumps->id.rhs_sparse));
2275:         mumps->id.rhs_sparse_len = 0;
2276:       }
2277:     }
2278:   }

2280:   /* solve phase */
2281:   mumps->id.job = JOB_SOLVE;
2282:   PetscMUMPS_c(mumps);
2283:   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));

2285:   /* scatter mumps distributed solution to PETSc vector v_mpi, which shares local arrays with solution matrix X */
2286:   PetscCall(MatDenseGetArray(X, &array));
2287:   PetscCall(VecPlaceArray(v_mpi, array));

2289:   /* create scatter scat_sol */
2290:   PetscCall(MatGetOwnershipRanges(X, &rstart));
2291:   /* iidx: index for scatter mumps solution to PETSc X */

2293:   PetscCall(ISCreateStride(PETSC_COMM_SELF, nlsol_loc, 0, 1, &is_from));
2294:   PetscCall(PetscMalloc1(nlsol_loc, &idxx));
2295:   for (i = 0; i < lsol_loc; i++) {
2296:     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 */

2298:     for (proc = 0; proc < mumps->petsc_size; proc++) {
2299:       if (isol_loc[i] >= rstart[proc] && isol_loc[i] < rstart[proc + 1]) {
2300:         myrstart = rstart[proc];
2301:         k        = isol_loc[i] - myrstart;          /* local index on 1st column of PETSc vector X */
2302:         iidx     = k + myrstart * nrhs;             /* maps mumps isol_loc[i] to PETSc index in X */
2303:         m        = rstart[proc + 1] - rstart[proc]; /* rows of X for this proc */
2304:         break;
2305:       }
2306:     }

2308:     for (j = 0; j < nrhs; j++) idxx[i + j * lsol_loc] = iidx + j * m;
2309:   }
2310:   PetscCall(ISCreateGeneral(PETSC_COMM_SELF, nlsol_loc, idxx, PETSC_COPY_VALUES, &is_to));
2311:   PetscCall(MatMumpsCastMumpsScalarArray(nlsol_loc, mumps->id.precision, mumps->id.sol_loc, sol_loc)); // Vec msol_loc is created with sol_loc[]
2312:   PetscCall(VecScatterCreate(msol_loc, is_from, v_mpi, is_to, &scat_sol));
2313:   PetscCall(VecScatterBegin(scat_sol, msol_loc, v_mpi, INSERT_VALUES, SCATTER_FORWARD));
2314:   PetscCall(ISDestroy(&is_from));
2315:   PetscCall(ISDestroy(&is_to));
2316:   PetscCall(VecScatterEnd(scat_sol, msol_loc, v_mpi, INSERT_VALUES, SCATTER_FORWARD));
2317:   PetscCall(MatDenseRestoreArray(X, &array));

2319:   if (mumps->id.sol_loc_len) { // in case we allocated intermediate buffers
2320:     mumps->id.sol_loc_len = 0;
2321:     PetscCall(PetscFree(mumps->id.sol_loc));
2322:   }

2324:   // restore old values
2325:   mumps->id.sol_loc     = sol_loc_save;
2326:   mumps->id.sol_loc_len = sol_loc_len_save;
2327:   mumps->id.isol_loc    = isol_loc_save;

2329:   PetscCall(PetscFree2(sol_loc, isol_loc));
2330:   PetscCall(PetscFree(idxx));
2331:   PetscCall(VecDestroy(&msol_loc));
2332:   PetscCall(VecDestroy(&v_mpi));
2333:   if (!denseB) {
2334:     if (!mumps->myid) {
2335:       b = (Mat_MPIAIJ *)Bt->data;
2336:       PetscCall(MatSeqAIJRestoreArray(b->A, &aa));
2337:       PetscCall(MatRestoreRowIJ(b->A, 1, PETSC_FALSE, PETSC_FALSE, &spnr, (const PetscInt **)&ia, (const PetscInt **)&ja, &flg));
2338:       PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot restore IJ structure");
2339:     }
2340:   } else {
2341:     if (mumps->ICNTL20 == 0) {
2342:       PetscCall(VecDestroy(&b_seq));
2343:       PetscCall(VecScatterDestroy(&scat_rhs));
2344:     }
2345:   }
2346:   PetscCall(VecScatterDestroy(&scat_sol));
2347:   PetscCall(PetscLogFlops(nrhs * PetscMax(0, 2.0 * (mumps->id.INFO(28) >= 0 ? mumps->id.INFO(28) : -1000000 * mumps->id.INFO(28)) - A->cmap->n)));
2348:   PetscFunctionReturn(PETSC_SUCCESS);
2349: }

2351: static PetscErrorCode MatMatSolveTranspose_MUMPS(Mat A, Mat B, Mat X)
2352: {
2353:   Mat_MUMPS          *mumps = (Mat_MUMPS *)A->data;
2354:   const PetscMUMPSInt value = mumps->id.ICNTL(9);

2356:   PetscFunctionBegin;
2357:   mumps->id.ICNTL(9) = 0;
2358:   PetscCall(MatMatSolve_MUMPS(A, B, X));
2359:   mumps->id.ICNTL(9) = value;
2360:   PetscFunctionReturn(PETSC_SUCCESS);
2361: }

2363: static PetscErrorCode MatMatTransposeSolve_MUMPS(Mat A, Mat Bt, Mat X)
2364: {
2365:   PetscBool flg;
2366:   Mat       B;

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

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

2375:   PetscCall(MatMatSolve_MUMPS(A, B, X));
2376:   PetscCall(MatDestroy(&B));
2377:   PetscFunctionReturn(PETSC_SUCCESS);
2378: }

2380: #if !defined(PETSC_USE_COMPLEX)
2381: /*
2382:   input:
2383:    F:        numeric factor
2384:   output:
2385:    nneg:     total number of negative pivots
2386:    nzero:    total number of zero pivots
2387:    npos:     (global dimension of F) - nneg - nzero
2388: */
2389: static PetscErrorCode MatGetInertia_SBAIJMUMPS(Mat F, PetscInt *nneg, PetscInt *nzero, PetscInt *npos)
2390: {
2391:   Mat_MUMPS  *mumps = (Mat_MUMPS *)F->data;
2392:   PetscMPIInt size;

2394:   PetscFunctionBegin;
2395:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)F), &size));
2396:   /* 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 */
2397:   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));

2399:   if (nneg) *nneg = mumps->id.INFOG(12);
2400:   if (nzero || npos) {
2401:     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");
2402:     if (nzero) *nzero = mumps->id.INFOG(28);
2403:     if (npos) *npos = F->rmap->N - (mumps->id.INFOG(12) + mumps->id.INFOG(28));
2404:   }
2405:   PetscFunctionReturn(PETSC_SUCCESS);
2406: }
2407: #endif

2409: static PetscErrorCode MatMumpsGatherNonzerosOnMaster(MatReuse reuse, Mat_MUMPS *mumps)
2410: {
2411:   PetscMPIInt    nreqs;
2412:   PetscMUMPSInt *irn, *jcn;
2413:   PetscMPIInt    count;
2414:   PetscCount     totnnz, remain;
2415:   const PetscInt osize = mumps->omp_comm_size;
2416:   PetscScalar   *val;

2418:   PetscFunctionBegin;
2419:   if (osize > 1) {
2420:     if (reuse == MAT_INITIAL_MATRIX) {
2421:       /* master first gathers counts of nonzeros to receive */
2422:       if (mumps->is_omp_master) PetscCall(PetscMalloc1(osize, &mumps->recvcount));
2423:       PetscCallMPI(MPI_Gather(&mumps->nnz, 1, MPIU_INT64, mumps->recvcount, 1, MPIU_INT64, 0 /*master*/, mumps->omp_comm));

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

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

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

2448:         /* Self communication */
2449:         PetscCall(PetscArraycpy(irn, mumps->irn, mumps->nnz));
2450:         PetscCall(PetscArraycpy(jcn, mumps->jcn, mumps->nnz));
2451:         PetscCall(PetscArraycpy(val, mumps->val, mumps->nnz));

2453:         /* Replace mumps->irn/jcn etc on master with the newly allocated bigger arrays */
2454:         PetscCall(PetscFree2(mumps->irn, mumps->jcn));
2455:         PetscCall(PetscFree(mumps->val_alloc));
2456:         mumps->nnz = totnnz;
2457:         mumps->irn = irn;
2458:         mumps->jcn = jcn;
2459:         mumps->val = mumps->val_alloc = val;

2461:         irn += mumps->recvcount[0]; /* recvcount[0] is old mumps->nnz on omp rank 0 */
2462:         jcn += mumps->recvcount[0];
2463:         val += mumps->recvcount[0];

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

2529: static PetscErrorCode MatFactorNumeric_MUMPS(Mat F, Mat A, PETSC_UNUSED const MatFactorInfo *info)
2530: {
2531:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

2533:   PetscFunctionBegin;
2534:   if (mumps->id.INFOG(1) < 0 && !(mumps->id.INFOG(1) == -16 && mumps->id.INFOG(1) == 0)) {
2535:     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)));
2536:     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)));
2537:     PetscFunctionReturn(PETSC_SUCCESS);
2538:   }

2540:   PetscCall((*mumps->ConvertToTriples)(A, 1, MAT_REUSE_MATRIX, mumps));
2541:   PetscCall(MatMumpsGatherNonzerosOnMaster(MAT_REUSE_MATRIX, mumps));
2542:   PetscCall(MatMumpsEnsureSchurArray_Private(F));

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

2552:   if (mumps->id.ICNTL(22)) PetscCall(PetscStrncpy(mumps->id.ooc_prefix, ((PetscObject)F)->prefix, sizeof(((MUMPS_STRUC_C *)NULL)->ooc_prefix)));
2553:   if (A->rmap->N && A->cmap->N) PetscMUMPS_c(mumps);
2554:   if (mumps->id.INFOG(1) < 0) {
2555:     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));
2556:     if (mumps->id.INFOG(1) == -10) {
2557:       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)));
2558:       F->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
2559:     } else if (mumps->id.INFOG(1) == -13) {
2560:       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)));
2561:       F->factorerrortype = MAT_FACTOR_OUTMEMORY;
2562:     } else if (mumps->id.INFOG(1) == -8 || mumps->id.INFOG(1) == -9 || (-16 < mumps->id.INFOG(1) && mumps->id.INFOG(1) < -10)) {
2563:       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)));
2564:       F->factorerrortype = MAT_FACTOR_OUTMEMORY;
2565:     } else {
2566:       PetscCall(PetscInfo(F, "MUMPS error in numerical factorization: INFOG(1)=%d, INFO(2)=%d\n", mumps->id.INFOG(1), mumps->id.INFO(2)));
2567:       F->factorerrortype = MAT_FACTOR_OTHER;
2568:     }
2569:   }
2570:   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));

2572:   F->assembled = PETSC_TRUE;

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

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

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

2604:     /* distributed solution; Create x_seq=sol_loc for repeated use */
2605:     if (mumps->x_seq) {
2606:       PetscCall(VecScatterDestroy(&mumps->scat_sol));
2607:       PetscCall(PetscFree(mumps->id.isol_loc));
2608:       PetscCall(VecDestroy(&mumps->x_seq));
2609:     }
2610:     lsol_loc = mumps->id.INFO(23); /* length of sol_loc */
2611:     PetscCall(PetscMalloc1(lsol_loc, &mumps->id.isol_loc));
2612:     PetscCall(VecCreateSeq(PETSC_COMM_SELF, lsol_loc, &mumps->x_seq));
2613:     PetscCall(VecGetArray(mumps->x_seq, &array));
2614:     PetscCall(MatMumpsMakeMumpsScalarArray(PETSC_FALSE, lsol_loc, array, mumps->id.precision, &mumps->id.sol_loc_len, &mumps->id.sol_loc));
2615:     PetscCall(VecRestoreArray(mumps->x_seq, &array));
2616:     mumps->id.lsol_loc = (PetscMUMPSInt)lsol_loc;
2617:   }
2618:   PetscCall(PetscLogFlops((double)ID_RINFO_GET(mumps->id, 2)));
2619:   PetscFunctionReturn(PETSC_SUCCESS);
2620: }

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

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

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

2646:     PetscCall(PetscOptionsName("-mat_mumps_use_omp_threads", "Convert MPI processes into OpenMP threads", "None", &mumps->use_petsc_omp_support));
2647:     if (mumps->use_petsc_omp_support) nthreads = -1; /* -1 will let PetscOmpCtrlCreate() guess a proper value when user did not supply one */
2648:     /* do not use PetscOptionsInt() so that the option -mat_mumps_use_omp_threads is not displayed twice in the help */
2649:     PetscCall(PetscOptionsGetInt(NULL, ((PetscObject)F)->prefix, "-mat_mumps_use_omp_threads", &nthreads, NULL));
2650:     if (mumps->use_petsc_omp_support) {
2651:       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 : "");
2652: #if defined(PETSC_HAVE_OPENMP_SUPPORT)
2653:       PetscCall(PetscOmpCtrlCreate(mumps->petsc_comm, nthreads, &mumps->omp_ctrl));
2654:       PetscCall(PetscOmpCtrlGetOmpComms(mumps->omp_ctrl, &mumps->omp_comm, &mumps->mumps_comm, &mumps->is_omp_master));
2655: #else
2656:       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",
2657:               ((PetscObject)F)->prefix ? ((PetscObject)F)->prefix : "");
2658: #endif
2659:     } else {
2660:       mumps->omp_comm      = PETSC_COMM_SELF;
2661:       mumps->mumps_comm    = mumps->petsc_comm;
2662:       mumps->is_omp_master = PETSC_TRUE;
2663:     }
2664:     PetscCallMPI(MPI_Comm_size(mumps->omp_comm, &mumps->omp_comm_size));
2665:     mumps->reqs = NULL;
2666:     mumps->tag  = 0;

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

2677:     mumps->id.comm_fortran = MPI_Comm_c2f(mumps->mumps_comm);
2678:     mumps->id.job          = JOB_INIT;
2679:     mumps->id.par          = 1; /* host participates factorizaton and solve */
2680:     mumps->id.sym          = mumps->sym;

2682:     size          = mumps->id.size_schur;
2683:     arr           = mumps->id.schur;
2684:     listvar_schur = mumps->id.listvar_schur;
2685:     nblk          = mumps->id.nblk;
2686:     blkvar        = mumps->id.blkvar;
2687:     blkptr        = mumps->id.blkptr;
2688:     if (PetscDefined(USE_DEBUG)) {
2689:       for (PetscInt i = 0; i < size; i++)
2690:         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,
2691:                    A->rmap->N);
2692:     }

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

2699:     PetscMUMPS_c(mumps);
2700:     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));

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

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

2723:     PetscCall(PetscFree(mumps->ICNTL_pre));
2724:     PetscCall(PetscFree(mumps->CNTL_pre));

2726:     if (schur) {
2727:       mumps->id.size_schur    = size;
2728:       mumps->id.schur_lld     = size;
2729:       mumps->id.schur         = arr;
2730:       mumps->id.listvar_schur = listvar_schur;
2731:       if (mumps->petsc_size > 1) {
2732:         PetscBool gs; /* gs is false if any rank other than root has non-empty IS */

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

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

2754:     mumps->scat_rhs = NULL;
2755:     mumps->scat_sol = NULL;
2756:   }
2757:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_1", "ICNTL(1): output stream for error messages", "None", mumps->id.ICNTL(1), &icntl, &flg));
2758:   if (flg) mumps->id.ICNTL(1) = icntl;
2759:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_2", "ICNTL(2): output stream for diagnostic printing, statistics, and warning", "None", mumps->id.ICNTL(2), &icntl, &flg));
2760:   if (flg) mumps->id.ICNTL(2) = icntl;
2761:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_3", "ICNTL(3): output stream for global information, collected on the host", "None", mumps->id.ICNTL(3), &icntl, &flg));
2762:   if (flg) mumps->id.ICNTL(3) = icntl;

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

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

2771:   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));
2772:   if (flg) {
2773:     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");
2774:     mumps->id.ICNTL(7) = icntl;
2775:   }

2777:   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));
2778:   /* 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() */
2779:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_10", "ICNTL(10): max num of refinements", "None", mumps->id.ICNTL(10), &mumps->id.ICNTL(10), NULL));
2780:   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));
2781:   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));
2782:   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));
2783:   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));
2784:   PetscCall(MatGetBlockSizes(A, &rbs, &cbs));
2785:   if (rbs == cbs && rbs > 1) mumps->id.ICNTL(15) = (PetscMUMPSInt)-rbs;
2786:   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));
2787:   if (flg) {
2788:     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");
2789:     else if (mumps->id.ICNTL(15) > 0) {
2790:       const PetscInt *bsizes;
2791:       PetscInt        nblocks, p, *blkptr = NULL;
2792:       PetscMPIInt    *recvcounts, *displs, n;
2793:       PetscMPIInt     rank, size = 0;

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

2827:   /* Two MPICH Fortran MPI_IN_PLACE binding bugs prevented the use of 'mpich + mumps'. One happened with "mpi4py + mpich + mumps",
2828:      and was reported by Firedrake. See https://bitbucket.org/mpi4py/mpi4py/issues/162/mpi4py-initialization-breaks-fortran
2829:      and a petsc-maint mailing list thread with subject 'MUMPS segfaults in parallel because of ...'
2830:      This bug was fixed by https://github.com/pmodels/mpich/pull/4149. But the fix brought a new bug,
2831:      see https://github.com/pmodels/mpich/issues/5589. This bug was fixed by https://github.com/pmodels/mpich/pull/5590.
2832:      In short, we could not use distributed RHS until with MPICH v4.0b1 or we enabled a workaround in mumps-5.6.2+
2833:    */
2834:   mumps->ICNTL20 = 10; /* Distributed dense RHS, by default */
2835: #if PETSC_PKG_MUMPS_VERSION_LT(5, 3, 0) || (PetscDefined(HAVE_MPICH) && MPICH_NUMVERSION < 40000101) || PetscDefined(HAVE_MSMPI)
2836:   mumps->ICNTL20 = 0; /* Centralized dense RHS, if need be */
2837: #endif
2838:   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));
2839:   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);
2840: #if PETSC_PKG_MUMPS_VERSION_LT(5, 3, 0)
2841:   PetscCheck(!flg || mumps->ICNTL20 != 10, PETSC_COMM_SELF, PETSC_ERR_SUP, "ICNTL(20)=10 is not supported before MUMPS-5.3.0");
2842: #endif
2843:   /* 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 */

2845:   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));
2846:   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))'
2847:   if (mumps->id.ICNTL(22)) {
2848:     // MUMPS will use the /tmp directory if -mat_mumps_ooc_tmpdir is not set by user.
2849:     // 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().
2850:     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));
2851:   }
2852:   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));
2853:   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));
2854:   if (mumps->id.ICNTL(24)) mumps->id.ICNTL(13) = 1; /* turn-off ScaLAPACK to help with the correct detection of null pivots */

2856:   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));
2857:   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));
2858:   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));
2859:   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));
2860:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_29", "ICNTL(29): parallel ordering 1 = ptscotch, 2 = parmetis", "None", mumps->id.ICNTL(29), &mumps->id.ICNTL(29), NULL));
2861:   /* 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 */
2862:   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));
2863:   /* 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 */
2864:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_33", "ICNTL(33): compute determinant", "None", mumps->id.ICNTL(33), &mumps->id.ICNTL(33), NULL));
2865:   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));
2866:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_36", "ICNTL(36): choice of BLR factorization variant", "None", mumps->id.ICNTL(36), &mumps->id.ICNTL(36), NULL));
2867:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_37", "ICNTL(37): compression of the contribution blocks (CB)", "None", mumps->id.ICNTL(37), &mumps->id.ICNTL(37), NULL));
2868:   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));
2869:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_40", "ICNTL(40): adaptive BLR precision feature", "None", mumps->id.ICNTL(40), &mumps->id.ICNTL(40), NULL));
2870:   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));
2871:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_48", "ICNTL(48): multithreading with tree parallelism", "None", mumps->id.ICNTL(48), &mumps->id.ICNTL(48), NULL));
2872:   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));
2873:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_56", "ICNTL(56): postponing and rank-revealing factorization", "None", mumps->id.ICNTL(56), &mumps->id.ICNTL(56), NULL));
2874:   PetscCall(PetscOptionsMUMPSInt("-mat_mumps_icntl_58", "ICNTL(58): defines options for symbolic factorization", "None", mumps->id.ICNTL(58), &mumps->id.ICNTL(58), NULL));

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

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

2903: static PetscErrorCode MatFactorSymbolic_MUMPS_ReportIfError(Mat F, Mat A, PETSC_UNUSED const MatFactorInfo *info, Mat_MUMPS *mumps)
2904: {
2905:   PetscFunctionBegin;
2906:   if (mumps->id.INFOG(1) < 0) {
2907:     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));
2908:     if (mumps->id.INFOG(1) == -6) {
2909:       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)));
2910:       F->factorerrortype = MAT_FACTOR_STRUCT_ZEROPIVOT;
2911:     } else if (mumps->id.INFOG(1) == -5 || mumps->id.INFOG(1) == -7) {
2912:       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)));
2913:       F->factorerrortype = MAT_FACTOR_OUTMEMORY;
2914:     } else {
2915:       PetscCall(PetscInfo(F, "MUMPS error in analysis: INFOG(1)=%d, INFO(2)=%d " MUMPS_MANUALS "\n", mumps->id.INFOG(1), mumps->id.INFO(2)));
2916:       F->factorerrortype = MAT_FACTOR_OTHER;
2917:     }
2918:   }
2919:   if (!mumps->id.n) F->factorerrortype = MAT_FACTOR_NOERROR;
2920:   PetscFunctionReturn(PETSC_SUCCESS);
2921: }

2923: static PetscErrorCode MatLUFactorSymbolic_AIJMUMPS(Mat F, Mat A, IS r, PETSC_UNUSED IS c, const MatFactorInfo *info)
2924: {
2925:   Mat_MUMPS     *mumps = (Mat_MUMPS *)F->data;
2926:   Vec            b;
2927:   const PetscInt M = A->rmap->N;

2929:   PetscFunctionBegin;
2930:   if (mumps->matstruc == SAME_NONZERO_PATTERN) {
2931:     /* F is assembled by a previous call of MatLUFactorSymbolic_AIJMUMPS() */
2932:     PetscFunctionReturn(PETSC_SUCCESS);
2933:   }

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

2938:   PetscCall((*mumps->ConvertToTriples)(A, 1, MAT_INITIAL_MATRIX, mumps));
2939:   PetscCall(MatMumpsGatherNonzerosOnMaster(MAT_INITIAL_MATRIX, mumps));
2940:   PetscCall(MatMumpsEnsureSchurArray_Private(F));

2942:   /* analysis phase */
2943:   mumps->id.job = JOB_FACTSYMBOLIC;
2944:   PetscCall(PetscMUMPSIntCast(M, &mumps->id.n));
2945:   switch (mumps->id.ICNTL(18)) {
2946:   case 0: /* centralized assembled matrix input */
2947:     if (!mumps->myid) {
2948:       mumps->id.nnz = mumps->nnz;
2949:       mumps->id.irn = mumps->irn;
2950:       mumps->id.jcn = mumps->jcn;
2951:       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));
2952:       if (r && mumps->id.ICNTL(7) == 7 && !F->schur) {
2953:         mumps->id.ICNTL(7) = 1;
2954:         if (!mumps->myid) {
2955:           const PetscInt *idx;

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

2988:   mumps->matstruc = SAME_NONZERO_PATTERN;
2989:   PetscFunctionReturn(PETSC_SUCCESS);
2990: }

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

2999:   PetscFunctionBegin;
3000:   if (mumps->matstruc == SAME_NONZERO_PATTERN) {
3001:     /* F is assembled by a previous call of MatLUFactorSymbolic_BAIJMUMPS() */
3002:     PetscFunctionReturn(PETSC_SUCCESS);
3003:   }

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

3008:   PetscCall((*mumps->ConvertToTriples)(A, 1, MAT_INITIAL_MATRIX, mumps));
3009:   PetscCall(MatMumpsGatherNonzerosOnMaster(MAT_INITIAL_MATRIX, mumps));
3010:   PetscCall(MatMumpsEnsureSchurArray_Private(F));

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

3047:   mumps->matstruc = SAME_NONZERO_PATTERN;
3048:   PetscFunctionReturn(PETSC_SUCCESS);
3049: }

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

3058:   PetscFunctionBegin;
3059:   if (mumps->matstruc == SAME_NONZERO_PATTERN) {
3060:     /* F is assembled by a previous call of MatCholeskyFactorSymbolic_MUMPS() */
3061:     PetscFunctionReturn(PETSC_SUCCESS);
3062:   }

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

3067:   PetscCall((*mumps->ConvertToTriples)(A, 1, MAT_INITIAL_MATRIX, mumps));
3068:   PetscCall(MatMumpsGatherNonzerosOnMaster(MAT_INITIAL_MATRIX, mumps));
3069:   PetscCall(MatMumpsEnsureSchurArray_Private(F));

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

3111:   mumps->matstruc = SAME_NONZERO_PATTERN;
3112:   PetscFunctionReturn(PETSC_SUCCESS);
3113: }

3115: static PetscErrorCode MatView_MUMPS(Mat A, PetscViewer viewer)
3116: {
3117:   PetscBool         isascii;
3118:   PetscViewerFormat format;
3119:   Mat_MUMPS        *mumps = (Mat_MUMPS *)A->data;

3121:   PetscFunctionBegin;
3122:   /* check if matrix is mumps type */
3123:   if (A->ops->solve != MatSolve_MUMPS) PetscFunctionReturn(PETSC_SUCCESS);

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

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

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

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

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

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

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

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

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

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

3232:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(3) (estimated real workspace for factors on all processors after analysis): %d\n", mumps->id.INFOG(3)));
3233:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(4) (estimated integer workspace for factors on all processors after analysis): %d\n", mumps->id.INFOG(4)));
3234:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(5) (estimated maximum front size in the complete tree): %d\n", mumps->id.INFOG(5)));
3235:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(6) (number of nodes in the complete tree): %d\n", mumps->id.INFOG(6)));
3236:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(7) (ordering option effectively used after analysis): %d\n", mumps->id.INFOG(7)));
3237:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(8) (structural symmetry in percent of the permuted matrix after analysis): %d\n", mumps->id.INFOG(8)));
3238:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(9) (total real/complex workspace to store the matrix factors after factorization): %d\n", mumps->id.INFOG(9)));
3239:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(10) (total integer space store the matrix factors after factorization): %d\n", mumps->id.INFOG(10)));
3240:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(11) (order of largest frontal matrix after factorization): %d\n", mumps->id.INFOG(11)));
3241:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(12) (number of off-diagonal pivots): %d\n", mumps->id.INFOG(12)));
3242:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(13) (number of delayed pivots after factorization): %d\n", mumps->id.INFOG(13)));
3243:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(14) (number of memory compress after factorization): %d\n", mumps->id.INFOG(14)));
3244:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(15) (number of steps of iterative refinement after solution): %d\n", mumps->id.INFOG(15)));
3245:         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)));
3246:         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)));
3247:         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)));
3248:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(19) (size of all MUMPS internal data allocated during factorization: sum over all processors): %d\n", mumps->id.INFOG(19)));
3249:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(20) (estimated number of entries in the factors): %d\n", mumps->id.INFOG(20)));
3250:         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)));
3251:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(22) (size in MB of memory effectively used during factorization - sum over all processors): %d\n", mumps->id.INFOG(22)));
3252:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(23) (after analysis: value of ICNTL(6) effectively used): %d\n", mumps->id.INFOG(23)));
3253:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(24) (after analysis: value of ICNTL(12) effectively used): %d\n", mumps->id.INFOG(24)));
3254:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(25) (after factorization: number of pivots modified by static pivoting): %d\n", mumps->id.INFOG(25)));
3255:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(28) (after factorization: number of null pivots encountered): %d\n", mumps->id.INFOG(28)));
3256:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(29) (after factorization: effective number of entries in the factors (sum over all processors)): %d\n", mumps->id.INFOG(29)));
3257:         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)));
3258:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(32) (after analysis: type of analysis done): %d\n", mumps->id.INFOG(32)));
3259:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(33) (value used for ICNTL(8)): %d\n", mumps->id.INFOG(33)));
3260:         PetscCall(PetscViewerASCIIPrintf(viewer, "  INFOG(34) (exponent of the determinant if determinant is requested): %d\n", mumps->id.INFOG(34)));
3261:         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)));
3262:         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)));
3263:         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)));
3264:         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)));
3265:         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)));
3266:       }
3267:     }
3268:   }
3269:   PetscFunctionReturn(PETSC_SUCCESS);
3270: }

3272: static PetscErrorCode MatGetInfo_MUMPS(Mat A, PETSC_UNUSED MatInfoType flag, MatInfo *info)
3273: {
3274:   Mat_MUMPS *mumps = (Mat_MUMPS *)A->data;

3276:   PetscFunctionBegin;
3277:   info->block_size        = 1.0;
3278:   info->nz_allocated      = mumps->id.INFOG(20) >= 0 ? mumps->id.INFOG(20) : -1000000 * mumps->id.INFOG(20);
3279:   info->nz_used           = mumps->id.INFOG(20) >= 0 ? mumps->id.INFOG(20) : -1000000 * mumps->id.INFOG(20);
3280:   info->nz_unneeded       = 0.0;
3281:   info->assemblies        = 0.0;
3282:   info->mallocs           = 0.0;
3283:   info->memory            = 0.0;
3284:   info->fill_ratio_given  = 0;
3285:   info->fill_ratio_needed = 0;
3286:   info->factor_mallocs    = 0;
3287:   PetscFunctionReturn(PETSC_SUCCESS);
3288: }

3290: static PetscErrorCode MatFactorSetSchurIS_MUMPS(Mat F, IS is)
3291: {
3292:   Mat_MUMPS      *mumps = (Mat_MUMPS *)F->data;
3293:   const PetscInt *idxs;
3294:   PetscInt        size, i;

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

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

3318: static PetscErrorCode MatFactorCreateSchurComplement_MUMPS(Mat F, Mat *S)
3319: {
3320:   Mat          St;
3321:   Mat_MUMPS   *mumps = (Mat_MUMPS *)F->data;
3322:   PetscScalar *array;
3323:   PetscInt     i, j, N = mumps->id.size_schur;

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

3359: static PetscErrorCode MatMumpsSetIcntl_MUMPS(Mat F, PetscInt icntl, PetscInt ival)
3360: {
3361:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3363:   PetscFunctionBegin;
3364:   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);
3365:   if (mumps->id.job == JOB_NULL) {                                            /* need to cache icntl and ival since PetscMUMPS_c() has never been called */
3366:     PetscMUMPSInt i, nICNTL_pre = mumps->ICNTL_pre ? mumps->ICNTL_pre[0] : 0; /* number of already cached ICNTL */
3367:     for (i = 0; i < nICNTL_pre; ++i)
3368:       if (mumps->ICNTL_pre[1 + 2 * i] == icntl) break; /* is this ICNTL already cached? */
3369:     if (i == nICNTL_pre) {                             /* not already cached */
3370:       if (i > 0) PetscCall(PetscRealloc(sizeof(PetscMUMPSInt) * (2 * nICNTL_pre + 3), &mumps->ICNTL_pre));
3371:       else PetscCall(PetscCalloc(sizeof(PetscMUMPSInt) * 3, &mumps->ICNTL_pre));
3372:       mumps->ICNTL_pre[0]++;
3373:     }
3374:     mumps->ICNTL_pre[1 + 2 * i] = (PetscMUMPSInt)icntl;
3375:     PetscCall(PetscMUMPSIntCast(ival, mumps->ICNTL_pre + 2 + 2 * i));
3376:   } else PetscCall(PetscMUMPSIntCast(ival, &mumps->id.ICNTL(icntl)));
3377:   PetscFunctionReturn(PETSC_SUCCESS);
3378: }

3380: static PetscErrorCode MatMumpsGetIcntl_MUMPS(Mat F, PetscInt icntl, PetscInt *ival)
3381: {
3382:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3384:   PetscFunctionBegin;
3385:   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);
3386:   if (mumps->id.job == JOB_NULL) {
3387:     PetscInt i, nICNTL_pre = mumps->ICNTL_pre ? mumps->ICNTL_pre[0] : 0;
3388:     *ival = 0;
3389:     for (i = 0; i < nICNTL_pre; ++i) {
3390:       if (mumps->ICNTL_pre[1 + 2 * i] == icntl) *ival = mumps->ICNTL_pre[2 + 2 * i];
3391:     }
3392:   } else *ival = mumps->id.ICNTL(icntl);
3393:   PetscFunctionReturn(PETSC_SUCCESS);
3394: }

3396: static PetscErrorCode MatMumpsSetCntl_MUMPS(Mat F, PetscInt icntl, PetscReal val)
3397: {
3398:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

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

3417: static PetscErrorCode MatMumpsGetCntl_MUMPS(Mat F, PetscInt icntl, PetscReal *val)
3418: {
3419:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

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

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

3436:   Logically Collective

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

3442:   Level: beginner

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

3448: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatMumpsGetOocTmpDir`, `MatMumpsSetIcntl()`, `MatMumpsGetIcntl()`, `MatMumpsSetCntl()`, `MatMumpsGetInfo()`, `MatMumpsGetInfog()`, `MatMumpsGetRinfo()`, `MatMumpsGetRinfog()`
3449: @*/
3450: PetscErrorCode MatMumpsSetOocTmpDir(Mat F, const char *tmpdir)
3451: {
3452:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3454:   PetscFunctionBegin;
3457:   PetscCall(PetscStrncpy(mumps->id.ooc_tmpdir, tmpdir, sizeof(((MUMPS_STRUC_C *)NULL)->ooc_tmpdir)));
3458:   PetscFunctionReturn(PETSC_SUCCESS);
3459: }

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

3464:   Logically Collective

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

3469:   Output Parameter:
3470: . tmpdir - temporary directory for out-of-core facility.

3472:   Level: beginner

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

3477: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatMumpsSetOocTmpDir`, `MatMumpsSetIcntl()`, `MatMumpsGetIcntl()`, `MatMumpsSetCntl()`, `MatMumpsGetInfo()`, `MatMumpsGetInfog()`, `MatMumpsGetRinfo()`, `MatMumpsGetRinfog()`
3478: @*/
3479: PetscErrorCode MatMumpsGetOocTmpDir(Mat F, const char *tmpdir[])
3480: {
3481:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3483:   PetscFunctionBegin;
3486:   if (tmpdir) *tmpdir = mumps->id.ooc_tmpdir;
3487:   PetscFunctionReturn(PETSC_SUCCESS);
3488: }

3490: static PetscErrorCode MatMumpsGetInfo_MUMPS(Mat F, PetscInt icntl, PetscInt *info)
3491: {
3492:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3494:   PetscFunctionBegin;
3495:   *info = mumps->id.INFO(icntl);
3496:   PetscFunctionReturn(PETSC_SUCCESS);
3497: }

3499: static PetscErrorCode MatMumpsGetInfog_MUMPS(Mat F, PetscInt icntl, PetscInt *infog)
3500: {
3501:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3503:   PetscFunctionBegin;
3504:   *infog = mumps->id.INFOG(icntl);
3505:   PetscFunctionReturn(PETSC_SUCCESS);
3506: }

3508: static PetscErrorCode MatMumpsGetRinfo_MUMPS(Mat F, PetscInt icntl, PetscReal *rinfo)
3509: {
3510:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3512:   PetscFunctionBegin;
3513:   *rinfo = ID_RINFO_GET(mumps->id, icntl);
3514:   PetscFunctionReturn(PETSC_SUCCESS);
3515: }

3517: static PetscErrorCode MatMumpsGetRinfog_MUMPS(Mat F, PetscInt icntl, PetscReal *rinfog)
3518: {
3519:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3521:   PetscFunctionBegin;
3522:   *rinfog = ID_RINFOG_GET(mumps->id, icntl);
3523:   PetscFunctionReturn(PETSC_SUCCESS);
3524: }

3526: static PetscErrorCode MatMumpsGetNullPivots_MUMPS(Mat F, PetscInt *size, PetscInt **array)
3527: {
3528:   Mat_MUMPS *mumps = (Mat_MUMPS *)F->data;

3530:   PetscFunctionBegin;
3531:   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");
3532:   *size  = 0;
3533:   *array = NULL;
3534:   if (!mumps->myid) {
3535:     *size = mumps->id.INFOG(28);
3536:     PetscCall(PetscMalloc1(*size, array));
3537:     for (int i = 0; i < *size; i++) (*array)[i] = mumps->id.pivnul_list[i] - 1;
3538:   }
3539:   PetscFunctionReturn(PETSC_SUCCESS);
3540: }

3542: static PetscErrorCode MatMumpsGetInverse_MUMPS(Mat F, Mat spRHS)
3543: {
3544:   Mat          Bt = NULL, Btseq = NULL;
3545:   PetscBool    flg;
3546:   Mat_MUMPS   *mumps = (Mat_MUMPS *)F->data;
3547:   PetscScalar *aa;
3548:   PetscInt     spnr, *ia, *ja, M, nrhs;

3550:   PetscFunctionBegin;
3551:   PetscAssertPointer(spRHS, 2);
3552:   PetscCall(PetscObjectTypeCompare((PetscObject)spRHS, MATTRANSPOSEVIRTUAL, &flg));
3553:   PetscCheck(flg, PetscObjectComm((PetscObject)spRHS), PETSC_ERR_ARG_WRONG, "Matrix spRHS must be type MATTRANSPOSEVIRTUAL matrix");
3554:   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));
3555:   PetscCall(MatTransposeGetMat(spRHS, &Bt));

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

3559:   if (mumps->petsc_size > 1) {
3560:     Mat_MPIAIJ *b = (Mat_MPIAIJ *)Bt->data;
3561:     Btseq         = b->A;
3562:   } else {
3563:     Btseq = Bt;
3564:   }

3566:   PetscCall(MatGetSize(spRHS, &M, &nrhs));
3567:   mumps->id.nrhs = (PetscMUMPSInt)nrhs;
3568:   PetscCall(PetscMUMPSIntCast(M, &mumps->id.lrhs));
3569:   mumps->id.rhs = NULL;

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

3589:   /* solve phase */
3590:   mumps->id.job = JOB_SOLVE;
3591:   PetscMUMPS_c(mumps);
3592:   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));

3594:   if (!mumps->myid) {
3595:     PetscCall(MatSeqAIJRestoreArray(Btseq, &aa));
3596:     PetscCall(MatRestoreRowIJ(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 restore IJ structure");
3598:   }
3599:   PetscFunctionReturn(PETSC_SUCCESS);
3600: }

3602: static PetscErrorCode MatMumpsGetInverseTranspose_MUMPS(Mat F, Mat spRHST)
3603: {
3604:   Mat spRHS;

3606:   PetscFunctionBegin;
3607:   PetscCall(MatCreateTranspose(spRHST, &spRHS));
3608:   PetscCall(MatMumpsGetInverse_MUMPS(F, spRHS));
3609:   PetscCall(MatDestroy(&spRHS));
3610:   PetscFunctionReturn(PETSC_SUCCESS);
3611: }

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

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

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

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

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

3649:   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.
3650:   See details below.

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

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

3699:   Level: beginner

3701:   Notes:
3702:   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
3703:   error if the matrix is Hermitian.

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

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

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

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

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

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

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

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

3746:    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
3747:    processes on each compute node. Listing the processes in rank ascending order, we split processes on a node into consecutive groups of
3748:    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
3749:    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
3750:    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.
3751:    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,
3752:    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
3753:    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
3754:    cores in socket 1, that definitely hurts locality. On the other hand, if you map MPI ranks consecutively on the two sockets, then the
3755:    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.
3756:    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
3757:    examine the mapping result.

3759:    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,
3760:    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
3761:    calls `omp_set_num_threads`(m) internally before calling MUMPS.

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

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

3768: static PetscErrorCode MatFactorGetSolverType_mumps(PETSC_UNUSED Mat A, MatSolverType *type)
3769: {
3770:   PetscFunctionBegin;
3771:   *type = MATSOLVERMUMPS;
3772:   PetscFunctionReturn(PETSC_SUCCESS);
3773: }

3775: /* MatGetFactor for Seq and MPI AIJ matrices */
3776: static PetscErrorCode MatGetFactor_aij_mumps(Mat A, MatFactorType ftype, Mat *F)
3777: {
3778:   Mat         B;
3779:   Mat_MUMPS  *mumps;
3780:   PetscBool   isSeqAIJ, isDiag, isDense;
3781:   PetscMPIInt size;

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

3798:   PetscCall(PetscNew(&mumps));

3800:   B->ops->view    = MatView_MUMPS;
3801:   B->ops->getinfo = MatGetInfo_MUMPS;

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

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

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

3852:   *F               = B;
3853:   mumps->id.job    = JOB_NULL;
3854:   mumps->ICNTL_pre = NULL;
3855:   mumps->CNTL_pre  = NULL;
3856:   mumps->matstruc  = DIFFERENT_NONZERO_PATTERN;
3857:   PetscFunctionReturn(PETSC_SUCCESS);
3858: }

3860: /* MatGetFactor for Seq and MPI SBAIJ matrices */
3861: static PetscErrorCode MatGetFactor_sbaij_mumps(Mat A, PETSC_UNUSED MatFactorType ftype, Mat *F)
3862: {
3863:   Mat         B;
3864:   Mat_MUMPS  *mumps;
3865:   PetscBool   isSeqSBAIJ;
3866:   PetscMPIInt size;

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

3879:   PetscCall(PetscNew(&mumps));
3880:   PetscCall(PetscObjectTypeCompare((PetscObject)A, MATSEQSBAIJ, &isSeqSBAIJ));
3881:   if (isSeqSBAIJ) {
3882:     mumps->ConvertToTriples = MatConvertToTriples_seqsbaij_seqsbaij;
3883:   } else {
3884:     mumps->ConvertToTriples = MatConvertToTriples_mpisbaij_mpisbaij;
3885:   }

3887:   B->ops->choleskyfactorsymbolic = MatCholeskyFactorSymbolic_MUMPS;
3888:   B->ops->view                   = MatView_MUMPS;
3889:   B->ops->getinfo                = MatGetInfo_MUMPS;

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

3907:   B->factortype = MAT_FACTOR_CHOLESKY;
3908:   if (PetscDefined(USE_COMPLEX)) mumps->sym = 2;
3909:   else if (A->spd == PETSC_BOOL3_TRUE) mumps->sym = 1;
3910:   else mumps->sym = 2;

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

3924:   *F               = B;
3925:   mumps->id.job    = JOB_NULL;
3926:   mumps->ICNTL_pre = NULL;
3927:   mumps->CNTL_pre  = NULL;
3928:   mumps->matstruc  = DIFFERENT_NONZERO_PATTERN;
3929:   PetscFunctionReturn(PETSC_SUCCESS);
3930: }

3932: static PetscErrorCode MatGetFactor_baij_mumps(Mat A, MatFactorType ftype, Mat *F)
3933: {
3934:   Mat         B;
3935:   Mat_MUMPS  *mumps;
3936:   PetscBool   isSeqBAIJ;
3937:   PetscMPIInt size;

3939:   PetscFunctionBegin;
3940:   /* Create the factorization matrix */
3941:   PetscCall(PetscObjectTypeCompare((PetscObject)A, MATSEQBAIJ, &isSeqBAIJ));
3942:   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &B));
3943:   PetscCall(MatSetSizes(B, A->rmap->n, A->cmap->n, A->rmap->N, A->cmap->N));
3944:   PetscCall(PetscStrallocpy(MATSOLVERMUMPS, &((PetscObject)B)->type_name));
3945:   PetscCall(MatSetUp(B));

3947:   PetscCall(PetscNew(&mumps));
3948:   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");
3949:   B->ops->lufactorsymbolic = MatLUFactorSymbolic_BAIJMUMPS;
3950:   B->factortype            = MAT_FACTOR_LU;
3951:   if (isSeqBAIJ) mumps->ConvertToTriples = MatConvertToTriples_seqbaij_seqaij;
3952:   else mumps->ConvertToTriples = MatConvertToTriples_mpibaij_mpiaij;
3953:   mumps->sym = 0;
3954:   PetscCall(PetscStrallocpy(MATORDERINGEXTERNAL, (char **)&B->preferredordering[MAT_FACTOR_LU]));

3956:   B->ops->view    = MatView_MUMPS;
3957:   B->ops->getinfo = MatGetInfo_MUMPS;

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

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

3986:   *F               = B;
3987:   mumps->id.job    = JOB_NULL;
3988:   mumps->ICNTL_pre = NULL;
3989:   mumps->CNTL_pre  = NULL;
3990:   mumps->matstruc  = DIFFERENT_NONZERO_PATTERN;
3991:   PetscFunctionReturn(PETSC_SUCCESS);
3992: }

3994: /* MatGetFactor for Seq and MPI SELL matrices */
3995: static PetscErrorCode MatGetFactor_sell_mumps(Mat A, MatFactorType ftype, Mat *F)
3996: {
3997:   Mat         B;
3998:   Mat_MUMPS  *mumps;
3999:   PetscBool   isSeqSELL;
4000:   PetscMPIInt size;

4002:   PetscFunctionBegin;
4003:   /* Create the factorization matrix */
4004:   PetscCall(PetscObjectTypeCompare((PetscObject)A, MATSEQSELL, &isSeqSELL));
4005:   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &B));
4006:   PetscCall(MatSetSizes(B, A->rmap->n, A->cmap->n, A->rmap->N, A->cmap->N));
4007:   PetscCall(PetscStrallocpy(MATSOLVERMUMPS, &((PetscObject)B)->type_name));
4008:   PetscCall(MatSetUp(B));

4010:   PetscCall(PetscNew(&mumps));

4012:   B->ops->view    = MatView_MUMPS;
4013:   B->ops->getinfo = MatGetInfo_MUMPS;

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

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

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

4047:   *F               = B;
4048:   mumps->id.job    = JOB_NULL;
4049:   mumps->ICNTL_pre = NULL;
4050:   mumps->CNTL_pre  = NULL;
4051:   mumps->matstruc  = DIFFERENT_NONZERO_PATTERN;
4052:   PetscFunctionReturn(PETSC_SUCCESS);
4053: }

4055: /* MatGetFactor for MATNEST matrices */
4056: static PetscErrorCode MatGetFactor_nest_mumps(Mat A, MatFactorType ftype, Mat *F)
4057: {
4058:   Mat         B, **mats;
4059:   Mat_MUMPS  *mumps;
4060:   PetscInt    nr, nc;
4061:   PetscMPIInt size;
4062:   PetscBool   flg = PETSC_TRUE;

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

4071:   /* Return if some condition is not satisfied */
4072:   *F = NULL;
4073:   PetscCall(MatNestGetSubMats(A, &nr, &nc, &mats));
4074:   if (ftype == MAT_FACTOR_CHOLESKY) {
4075:     IS       *rows, *cols;
4076:     PetscInt *m, *M;

4078:     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);
4079:     PetscCall(PetscMalloc2(nr, &rows, nc, &cols));
4080:     PetscCall(MatNestGetISs(A, rows, cols));
4081:     for (PetscInt r = 0; flg && r < nr; r++) PetscCall(ISEqualUnsorted(rows[r], cols[r], &flg));
4082:     if (!flg) {
4083:       PetscCall(PetscFree2(rows, cols));
4084:       PetscCall(PetscInfo(A, "MAT_FACTOR_CHOLESKY not supported for unequal row and column maps. Use MAT_FACTOR_LU.\n"));
4085:       PetscFunctionReturn(PETSC_SUCCESS);
4086:     }
4087:     PetscCall(PetscMalloc2(nr, &m, nr, &M));
4088:     for (PetscInt r = 0; r < nr; r++) PetscCall(ISGetMinMax(rows[r], &m[r], &M[r]));
4089:     for (PetscInt r = 0; flg && r < nr; r++)
4090:       for (PetscInt k = r + 1; flg && k < nr; k++)
4091:         if ((m[k] <= m[r] && m[r] <= M[k]) || (m[k] <= M[r] && M[r] <= M[k])) flg = PETSC_FALSE;
4092:     PetscCall(PetscFree2(m, M));
4093:     PetscCall(PetscFree2(rows, cols));
4094:     if (!flg) {
4095:       PetscCall(PetscInfo(A, "MAT_FACTOR_CHOLESKY not supported for intersecting row maps. Use MAT_FACTOR_LU.\n"));
4096:       PetscFunctionReturn(PETSC_SUCCESS);
4097:     }
4098:   }

4100:   for (PetscInt r = 0; r < nr; r++) {
4101:     for (PetscInt c = 0; c < nc; c++) {
4102:       Mat       sub = mats[r][c];
4103:       PetscBool isSeqAIJ, isMPIAIJ, isSeqBAIJ, isMPIBAIJ, isSeqSBAIJ, isMPISBAIJ, isDiag, isDense;

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

4133:   /* Create the factorization matrix */
4134:   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &B));
4135:   PetscCall(MatSetSizes(B, A->rmap->n, A->cmap->n, A->rmap->N, A->cmap->N));
4136:   PetscCall(PetscStrallocpy(MATSOLVERMUMPS, &((PetscObject)B)->type_name));
4137:   PetscCall(MatSetUp(B));

4139:   PetscCall(PetscNew(&mumps));

4141:   B->ops->view    = MatView_MUMPS;
4142:   B->ops->getinfo = MatGetInfo_MUMPS;

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

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

4174:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
4175:   if (size == 1) {
4176:     /* MUMPS option -mat_mumps_icntl_7 1 is automatically set if PETSc ordering is passed into symbolic factorization */
4177:     B->canuseordering = PETSC_TRUE;
4178:   }

4180:   /* set solvertype */
4181:   PetscCall(PetscFree(B->solvertype));
4182:   PetscCall(PetscStrallocpy(MATSOLVERMUMPS, &B->solvertype));
4183:   B->ops->destroy = MatDestroy_MUMPS;
4184:   B->data         = (void *)mumps;

4186:   *F               = B;
4187:   mumps->id.job    = JOB_NULL;
4188:   mumps->ICNTL_pre = NULL;
4189:   mumps->CNTL_pre  = NULL;
4190:   mumps->matstruc  = DIFFERENT_NONZERO_PATTERN;
4191:   PetscFunctionReturn(PETSC_SUCCESS);
4192: }

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