Actual source code: matimpl.h

  1: #pragma once

  3: #include <petscmat.h>
  4: #include <petscmatcoarsen.h>
  5: #include <petsc/private/petscimpl.h>

  7: PETSC_EXTERN PetscBool      MatRegisterAllCalled;
  8: PETSC_EXTERN PetscBool      MatSeqAIJRegisterAllCalled;
  9: PETSC_EXTERN PetscBool      MatOrderingRegisterAllCalled;
 10: PETSC_EXTERN PetscBool      MatColoringRegisterAllCalled;
 11: PETSC_EXTERN PetscBool      MatPartitioningRegisterAllCalled;
 12: PETSC_EXTERN PetscBool      MatMeshToCellGraphRegisterAllCalled;
 13: PETSC_EXTERN PetscBool      MatCoarsenRegisterAllCalled;
 14: PETSC_EXTERN PetscErrorCode MatRegisterAll(void);
 15: PETSC_EXTERN PetscErrorCode MatOrderingRegisterAll(void);
 16: PETSC_EXTERN PetscErrorCode MatColoringRegisterAll(void);
 17: PETSC_EXTERN PetscErrorCode MatPartitioningRegisterAll(void);
 18: PETSC_EXTERN PetscErrorCode MatMeshToCellGraphRegisterAll(void);
 19: PETSC_EXTERN PetscErrorCode MatCoarsenRegisterAll(void);
 20: PETSC_EXTERN PetscErrorCode MatSeqAIJRegisterAll(void);

 22: /* Gets the root type of the input matrix's type (e.g., MATAIJ for MATSEQAIJ) */
 23: PETSC_EXTERN PetscErrorCode MatGetRootType_Private(Mat, MatType *);

 25: /* Gets the MPI type corresponding to the input matrix's type (e.g., MATMPIAIJ for MATSEQAIJ) */
 26: PETSC_INTERN PetscErrorCode MatGetMPIMatType_Private(Mat, MatType *);

 28: /*
 29:   This file defines the parts of the matrix data structure that are
 30:   shared by all matrix types.
 31: */

 33: /*
 34:     If you add entries here also add them to the MATOP enum
 35:     in include/petscmat.h
 36: */
 37: typedef struct _MatOps *MatOps;
 38: struct _MatOps {
 39:   /* 0*/
 40:   PetscErrorCode (*setvalues)(Mat, PetscInt, const PetscInt[], PetscInt, const PetscInt[], const PetscScalar[], InsertMode);
 41:   PetscErrorCode (*getrow)(Mat, PetscInt, PetscInt *, PetscInt *[], PetscScalar *[]);
 42:   PetscErrorCode (*restorerow)(Mat, PetscInt, PetscInt *, PetscInt *[], PetscScalar *[]);
 43:   PetscErrorCode (*mult)(Mat, Vec, Vec);
 44:   PetscErrorCode (*multadd)(Mat, Vec, Vec, Vec);
 45:   /* 5*/
 46:   PetscErrorCode (*multtranspose)(Mat, Vec, Vec);
 47:   PetscErrorCode (*multtransposeadd)(Mat, Vec, Vec, Vec);
 48:   PetscErrorCode (*solve)(Mat, Vec, Vec);
 49:   PetscErrorCode (*solveadd)(Mat, Vec, Vec, Vec);
 50:   PetscErrorCode (*solvetranspose)(Mat, Vec, Vec);
 51:   /*10*/
 52:   PetscErrorCode (*solvetransposeadd)(Mat, Vec, Vec, Vec);
 53:   PetscErrorCode (*lufactor)(Mat, IS, IS, const MatFactorInfo *);
 54:   PetscErrorCode (*choleskyfactor)(Mat, IS, const MatFactorInfo *);
 55:   PetscErrorCode (*sor)(Mat, Vec, PetscReal, MatSORType, PetscReal, PetscInt, PetscInt, Vec);
 56:   PetscErrorCode (*transpose)(Mat, MatReuse, Mat *);
 57:   /*15*/
 58:   PetscErrorCode (*getinfo)(Mat, MatInfoType, MatInfo *);
 59:   PetscErrorCode (*equal)(Mat, Mat, PetscBool *);
 60:   PetscErrorCode (*getdiagonal)(Mat, Vec);
 61:   PetscErrorCode (*diagonalscale)(Mat, Vec, Vec);
 62:   PetscErrorCode (*norm)(Mat, NormType, PetscReal *);
 63:   /*20*/
 64:   PetscErrorCode (*assemblybegin)(Mat, MatAssemblyType);
 65:   PetscErrorCode (*assemblyend)(Mat, MatAssemblyType);
 66:   PetscErrorCode (*setoption)(Mat, MatOption, PetscBool);
 67:   PetscErrorCode (*zeroentries)(Mat);
 68:   /*24*/
 69:   PetscErrorCode (*zerorows)(Mat, PetscInt, const PetscInt[], PetscScalar, Vec, Vec);
 70:   PetscErrorCode (*lufactorsymbolic)(Mat, Mat, IS, IS, const MatFactorInfo *);
 71:   PetscErrorCode (*lufactornumeric)(Mat, Mat, const MatFactorInfo *);
 72:   PetscErrorCode (*choleskyfactorsymbolic)(Mat, Mat, IS, const MatFactorInfo *);
 73:   PetscErrorCode (*choleskyfactornumeric)(Mat, Mat, const MatFactorInfo *);
 74:   /*29*/
 75:   PetscErrorCode (*setup)(Mat);
 76:   PetscErrorCode (*ilufactorsymbolic)(Mat, Mat, IS, IS, const MatFactorInfo *);
 77:   PetscErrorCode (*iccfactorsymbolic)(Mat, Mat, IS, const MatFactorInfo *);
 78:   PetscErrorCode (*getdiagonalblock)(Mat, Mat *);
 79:   PetscErrorCode (*setinf)(Mat);
 80:   /*34*/
 81:   PetscErrorCode (*duplicate)(Mat, MatDuplicateOption, Mat *);
 82:   PetscErrorCode (*forwardsolve)(Mat, Vec, Vec);
 83:   PetscErrorCode (*backwardsolve)(Mat, Vec, Vec);
 84:   PetscErrorCode (*ilufactor)(Mat, IS, IS, const MatFactorInfo *);
 85:   PetscErrorCode (*iccfactor)(Mat, IS, const MatFactorInfo *);
 86:   /*39*/
 87:   PetscErrorCode (*axpy)(Mat, PetscScalar, Mat, MatStructure);
 88:   PetscErrorCode (*createsubmatrices)(Mat, PetscInt, const IS[], const IS[], MatReuse, Mat *[]);
 89:   PetscErrorCode (*increaseoverlap)(Mat, PetscInt, IS[], PetscInt);
 90:   PetscErrorCode (*getvalues)(Mat, PetscInt, const PetscInt[], PetscInt, const PetscInt[], PetscScalar[]);
 91:   PetscErrorCode (*copy)(Mat, Mat, MatStructure);
 92:   /*44*/
 93:   PetscErrorCode (*getrowmax)(Mat, Vec, PetscInt[]);
 94:   PetscErrorCode (*scale)(Mat, PetscScalar);
 95:   PetscErrorCode (*shift)(Mat, PetscScalar);
 96:   PetscErrorCode (*diagonalset)(Mat, Vec, InsertMode);
 97:   PetscErrorCode (*zerorowscolumns)(Mat, PetscInt, const PetscInt[], PetscScalar, Vec, Vec);
 98:   /*49*/
 99:   PetscErrorCode (*setrandom)(Mat, PetscRandom);
100:   PetscErrorCode (*getrowij)(Mat, PetscInt, PetscBool, PetscBool, PetscInt *, const PetscInt *[], const PetscInt *[], PetscBool *);
101:   PetscErrorCode (*restorerowij)(Mat, PetscInt, PetscBool, PetscBool, PetscInt *, const PetscInt *[], const PetscInt *[], PetscBool *);
102:   PetscErrorCode (*getcolumnij)(Mat, PetscInt, PetscBool, PetscBool, PetscInt *, const PetscInt *[], const PetscInt *[], PetscBool *);
103:   PetscErrorCode (*restorecolumnij)(Mat, PetscInt, PetscBool, PetscBool, PetscInt *, const PetscInt *[], const PetscInt *[], PetscBool *);
104:   /*54*/
105:   PetscErrorCode (*fdcoloringcreate)(Mat, ISColoring, MatFDColoring);
106:   PetscErrorCode (*coloringpatch)(Mat, PetscInt, PetscInt, ISColoringValue[], ISColoring *);
107:   PetscErrorCode (*setunfactored)(Mat);
108:   PetscErrorCode (*permute)(Mat, IS, IS, Mat *);
109:   PetscErrorCode (*setvaluesblocked)(Mat, PetscInt, const PetscInt[], PetscInt, const PetscInt[], const PetscScalar[], InsertMode);
110:   /*59*/
111:   PetscErrorCode (*createsubmatrix)(Mat, IS, IS, MatReuse, Mat *);
112:   PetscErrorCode (*destroy)(Mat);
113:   PetscErrorCode (*view)(Mat, PetscViewer);
114:   PetscErrorCode (*convertfrom)(Mat, MatType, MatReuse, Mat *);
115:   PetscErrorCode (*matmatmultsymbolic)(Mat, Mat, Mat, PetscReal, Mat);
116:   /*64*/
117:   PetscErrorCode (*matmatmultnumeric)(Mat, Mat, Mat, Mat);
118:   PetscErrorCode (*setlocaltoglobalmapping)(Mat, ISLocalToGlobalMapping, ISLocalToGlobalMapping);
119:   PetscErrorCode (*setvalueslocal)(Mat, PetscInt, const PetscInt[], PetscInt, const PetscInt[], const PetscScalar[], InsertMode);
120:   PetscErrorCode (*zerorowslocal)(Mat, PetscInt, const PetscInt[], PetscScalar, Vec, Vec);
121:   PetscErrorCode (*getrowmaxabs)(Mat, Vec, PetscInt[]);
122:   /*69*/
123:   PetscErrorCode (*getrowminabs)(Mat, Vec, PetscInt[]);
124:   PetscErrorCode (*convert)(Mat, MatType, MatReuse, Mat *);
125:   PetscErrorCode (*hasoperation)(Mat, MatOperation, PetscBool *);
126:   PetscErrorCode (*fdcoloringapply)(Mat, MatFDColoring, Vec, void *);
127:   PetscErrorCode (*setfromoptions)(Mat, PetscOptionItems);
128:   /*74*/
129:   PetscErrorCode (*findzerodiagonals)(Mat, IS *);
130:   PetscErrorCode (*mults)(Mat, Vecs, Vecs);
131:   PetscErrorCode (*solves)(Mat, Vecs, Vecs);
132:   PetscErrorCode (*getinertia)(Mat, PetscInt *, PetscInt *, PetscInt *);
133:   PetscErrorCode (*load)(Mat, PetscViewer);
134:   /*79*/
135:   PetscErrorCode (*issymmetric)(Mat, PetscReal, PetscBool *);
136:   PetscErrorCode (*ishermitian)(Mat, PetscReal, PetscBool *);
137:   PetscErrorCode (*isstructurallysymmetric)(Mat, PetscBool *);
138:   PetscErrorCode (*setvaluesblockedlocal)(Mat, PetscInt, const PetscInt[], PetscInt, const PetscInt[], const PetscScalar[], InsertMode);
139:   PetscErrorCode (*getvecs)(Mat, Vec *, Vec *);
140:   /*84*/
141:   PetscErrorCode (*matmultsymbolic)(Mat, Mat, PetscReal, Mat);
142:   PetscErrorCode (*matmultnumeric)(Mat, Mat, Mat);
143:   PetscErrorCode (*ptapnumeric)(Mat, Mat, Mat); /* double dispatch wrapper routine */
144:   PetscErrorCode (*mattransposemultsymbolic)(Mat, Mat, PetscReal, Mat);
145:   PetscErrorCode (*mattransposemultnumeric)(Mat, Mat, Mat);
146:   /*89*/
147:   PetscErrorCode (*bindtocpu)(Mat, PetscBool);
148:   PetscErrorCode (*productsetfromoptions)(Mat);
149:   PetscErrorCode (*productsymbolic)(Mat);
150:   PetscErrorCode (*productnumeric)(Mat);
151:   PetscErrorCode (*conjugate)(Mat); /* complex conjugate */
152:   /*94*/
153:   PetscErrorCode (*viewnative)(Mat, PetscViewer);
154:   PetscErrorCode (*setvaluesrow)(Mat, PetscInt, const PetscScalar[]);
155:   PetscErrorCode (*realpart)(Mat);
156:   PetscErrorCode (*imaginarypart)(Mat);
157:   PetscErrorCode (*getrowuppertriangular)(Mat);
158:   /*99*/
159:   PetscErrorCode (*restorerowuppertriangular)(Mat);
160:   PetscErrorCode (*matsolve)(Mat, Mat, Mat);
161:   PetscErrorCode (*matsolvetranspose)(Mat, Mat, Mat);
162:   PetscErrorCode (*getrowmin)(Mat, Vec, PetscInt[]);
163:   PetscErrorCode (*getcolumnvector)(Mat, Vec, PetscInt);
164:   /*104*/
165:   PetscErrorCode (*getseqnonzerostructure)(Mat, Mat *);
166:   PetscErrorCode (*create)(Mat);
167:   PetscErrorCode (*getghosts)(Mat, PetscInt *, const PetscInt *[]);
168:   PetscErrorCode (*getlocalsubmatrix)(Mat, IS, IS, Mat *);
169:   PetscErrorCode (*restorelocalsubmatrix)(Mat, IS, IS, Mat *);
170:   /*109*/
171:   PetscErrorCode (*multdiagonalblock)(Mat, Vec, Vec);
172:   PetscErrorCode (*hermitiantranspose)(Mat, MatReuse, Mat *);
173:   PetscErrorCode (*multhermitiantranspose)(Mat, Vec, Vec);
174:   PetscErrorCode (*multhermitiantransposeadd)(Mat, Vec, Vec, Vec);
175:   PetscErrorCode (*getmultiprocblock)(Mat, MPI_Comm, MatReuse, Mat *);
176:   /*114*/
177:   PetscErrorCode (*findnonzerorows)(Mat, IS *);
178:   PetscErrorCode (*getcolumnreductions)(Mat, PetscInt, PetscReal *);
179:   PetscErrorCode (*invertblockdiagonal)(Mat, const PetscScalar **);
180:   PetscErrorCode (*invertvariableblockdiagonal)(Mat, PetscInt, const PetscInt *, PetscScalar *);
181:   PetscErrorCode (*createsubmatricesmpi)(Mat, PetscInt, const IS[], const IS[], MatReuse, Mat **);
182:   /*119*/
183:   PetscErrorCode (*transposematmultsymbolic)(Mat, Mat, PetscReal, Mat);
184:   PetscErrorCode (*transposematmultnumeric)(Mat, Mat, Mat);
185:   PetscErrorCode (*transposecoloringcreate)(Mat, ISColoring, MatTransposeColoring);
186:   PetscErrorCode (*transcoloringapplysptoden)(MatTransposeColoring, Mat, Mat);
187:   PetscErrorCode (*transcoloringapplydentosp)(MatTransposeColoring, Mat, Mat);
188:   /*124*/
189:   PetscErrorCode (*rartnumeric)(Mat, Mat, Mat); /* double dispatch wrapper routine */
190:   PetscErrorCode (*setblocksizes)(Mat, PetscInt, PetscInt);
191:   PetscErrorCode (*residual)(Mat, Vec, Vec, Vec);
192:   PetscErrorCode (*fdcoloringsetup)(Mat, ISColoring, MatFDColoring);
193:   PetscErrorCode (*findoffblockdiagonalentries)(Mat, IS *);
194:   /*129*/
195:   PetscErrorCode (*creatempimatconcatenateseqmat)(MPI_Comm, Mat, PetscInt, MatReuse, Mat *);
196:   PetscErrorCode (*destroysubmatrices)(PetscInt, Mat *[]);
197:   PetscErrorCode (*mattransposesolve)(Mat, Mat, Mat);
198:   PetscErrorCode (*getvalueslocal)(Mat, PetscInt, const PetscInt[], PetscInt, const PetscInt[], PetscScalar[]);
199:   PetscErrorCode (*creategraph)(Mat, PetscBool, PetscBool, PetscReal, PetscInt, PetscInt[], Mat *);
200:   /*134*/
201:   PetscErrorCode (*transposesymbolic)(Mat, Mat *);
202:   PetscErrorCode (*eliminatezeros)(Mat, PetscBool);
203:   PetscErrorCode (*getrowsumabs)(Mat, Vec);
204:   PetscErrorCode (*getfactor)(Mat, MatSolverType, MatFactorType, Mat *);
205:   PetscErrorCode (*getblockdiagonal)(Mat, Mat *); // NOTE: the caller of get{block, vblock}diagonal owns the returned matrix;
206:   /*139*/
207:   PetscErrorCode (*getvblockdiagonal)(Mat, Mat *); // they must destroy it after use
208:   PetscErrorCode (*copyhashtoxaij)(Mat, Mat);
209:   PetscErrorCode (*getcurrentmemtype)(Mat, PetscMemType *);
210:   PetscErrorCode (*zerorowscolumnslocal)(Mat, PetscInt, const PetscInt[], PetscScalar, Vec, Vec);
211:   PetscErrorCode (*adot)(Mat, Vec, Vec, PetscScalar *); /* induced vector inner product */
212:   /*144*/
213:   PetscErrorCode (*anorm)(Mat, Vec, PetscReal *); /* induced vector norm */
214:   PetscErrorCode (*adot_local)(Mat, Vec, Vec, PetscScalar *);
215:   PetscErrorCode (*anorm_local)(Mat, Vec, PetscReal *);
216:   PetscErrorCode (*getordering)(Mat, MatOrderingType, IS *, IS *);
217: };
218: /*
219:     If you add MatOps entries above also add them to the MATOP enum
220:     in include/petscmat.h
221: */

223: typedef struct _n_MatRootName *MatRootName;
224: struct _n_MatRootName {
225:   char       *rname, *sname, *mname;
226:   MatRootName next;
227: };

229: PETSC_EXTERN MatRootName MatRootNameList;

231: /*
232:    Utility private matrix routines used outside Mat
233: */
234: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatFindNonzeroRowsOrCols_Basic(Mat, PetscBool, PetscReal, IS *);
235: PETSC_EXTERN PetscErrorCode                MatShellGetScalingShifts(Mat, PetscScalar *, PetscScalar *, Vec *, Vec *, Vec *, Mat *, IS *, IS *);

237: #define MAT_SHELL_NOT_ALLOWED (void *)-1

239: /*
240:    Utility private matrix routines
241: */
242: PETSC_INTERN PetscErrorCode MatConvert_Basic(Mat, MatType, MatReuse, Mat *);
243: PETSC_INTERN PetscErrorCode MatConvert_Shell(Mat, MatType, MatReuse, Mat *);
244: PETSC_INTERN PetscErrorCode MatConvertFrom_Shell(Mat, MatType, MatReuse, Mat *);
245: PETSC_INTERN PetscErrorCode MatShellSetContext_Immutable(Mat, void *);
246: PETSC_INTERN PetscErrorCode MatShellSetContextDestroy_Immutable(Mat, PetscCtxDestroyFn *);
247: PETSC_INTERN PetscErrorCode MatShellSetManageScalingShifts_Immutable(Mat);
248: PETSC_INTERN PetscErrorCode MatCopy_Basic(Mat, Mat, MatStructure);
249: PETSC_INTERN PetscErrorCode MatDiagonalSet_Default(Mat, Vec, InsertMode);
250: #if PetscDefined(HAVE_SCALAPACK) && (PetscDefined(USE_REAL_SINGLE) || PetscDefined(USE_REAL_DOUBLE))
251: PETSC_INTERN PetscErrorCode MatConvert_Dense_ScaLAPACK(Mat, MatType, MatReuse, Mat *);
252: #endif
253: PETSC_INTERN PetscErrorCode MatSetPreallocationCOO_Basic(Mat, PetscCount, PetscInt[], PetscInt[]);
254: PETSC_INTERN PetscErrorCode MatSetValuesCOO_Basic(Mat, const PetscScalar[], InsertMode);

256: /*
257:    Index translation for the local submatrices of MATLOCALREF and MATIS, which both forward their local
258:    insertions to another matrix. These need to be macros because they use sizeof
259: */
260: #define MatIndexSpaceGet_Private(buf, nrow, ncol, irowm, icolm) \
261:   do { \
262:     if ((nrow) + (ncol) > (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) { \
263:       PetscCall(PetscMalloc2(nrow, &(irowm), ncol, &(icolm))); \
264:     } else { \
265:       irowm = &(buf)[0]; \
266:       icolm = &(buf)[nrow]; \
267:     } \
268:   } while (0)

270: #define MatIndexSpaceRestore_Private(buf, nrow, ncol, irowm, icolm) \
271:   do { \
272:     if ((nrow) + (ncol) > (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) PetscCall(PetscFree2(irowm, icolm)); \
273:   } while (0)

275: /* Turn n block indices into the n * bs scalar indices they stand for */
276: static inline void MatBlockIndicesExpand_Private(PetscInt n, const PetscInt idx[], PetscInt bs, PetscInt idxm[])
277: {
278:   for (PetscInt i = 0; i < n; i++) {
279:     for (PetscInt j = 0; j < bs; j++) idxm[i * bs + j] = idx[i] * bs + j;
280:   }
281: }

283: PETSC_INTERN PetscErrorCode MatDenseSetUpProduct_Private(Mat, PetscLayout, PetscLayout, Mat, MatType);

285: /* Scattering of dense matrices with strided PetscSF */
286: PETSC_EXTERN PetscErrorCode MatDenseScatter_Private(PetscSF, Mat, Mat, InsertMode, ScatterMode);
287: PETSC_INTERN PetscErrorCode MatDenseScatterWithSF_Private(PetscSF, Mat, Mat, MPI_Op, ScatterMode, PetscBool);
288: PETSC_INTERN PetscErrorCode MatDenseDuplicateLocalWithLDA_Private(Mat, PetscInt, Mat *);

290: /* This can be moved to the public header after implementing some missing MatProducts */
291: PETSC_INTERN PetscErrorCode MatCreateFromISLocalToGlobalMapping(ISLocalToGlobalMapping, Mat, PetscBool, PetscBool, MatType, Mat *);

293: /* these callbacks rely on the old matrix function pointers for
294:    matmat operations. They are unsafe, and should be removed.
295:    However, the amount of work needed to clean up all the
296:    implementations is not negligible */
297: PETSC_INTERN PetscErrorCode MatProductSymbolic_AB(Mat);
298: PETSC_INTERN PetscErrorCode MatProductNumeric_AB(Mat);
299: PETSC_INTERN PetscErrorCode MatProductSymbolic_AtB(Mat);
300: PETSC_INTERN PetscErrorCode MatProductNumeric_AtB(Mat);
301: PETSC_INTERN PetscErrorCode MatProductSymbolic_ABt(Mat);
302: PETSC_INTERN PetscErrorCode MatProductNumeric_ABt(Mat);
303: PETSC_INTERN PetscErrorCode MatProductNumeric_PtAP(Mat);
304: PETSC_INTERN PetscErrorCode MatProductNumeric_RARt(Mat);
305: PETSC_INTERN PetscErrorCode MatProductSymbolic_ABC(Mat);
306: PETSC_INTERN PetscErrorCode MatProductNumeric_ABC(Mat);

308: PETSC_INTERN PetscErrorCode MatProductCreate_Private(Mat, Mat, Mat, Mat);
309: /* this callback handles all the different triple products and
310:    does not rely on the function pointers; used by cuSPARSE/hipSPARSE and KOKKOS-KERNELS */
311: PETSC_INTERN PetscErrorCode MatProductSymbolic_ABC_Basic(Mat);

313: /* CreateGraph is common to AIJ seq and mpi */
314: PETSC_INTERN PetscErrorCode MatCreateGraph_Simple_AIJ(Mat, PetscBool, PetscBool, PetscReal, PetscInt, PetscInt[], Mat *);

316: #if PetscDefined(CLANG_STATIC_ANALYZER)
317: template <typename Tm>
318: extern void MatCheckPreallocated(Tm, int);
319: template <typename Tm>
320: extern void MatCheckProduct(Tm, int);
321: #else /* PETSC_CLANG_STATIC_ANALYZER */
322:   #define MatCheckPreallocated(A, arg) \
323:     do { \
324:       if (!(A)->preallocated) PetscCall(MatSetUp(A)); \
325:     } while (0)

327:   #if PetscDefined(USE_DEBUG)
328:     #define MatCheckProduct(A, arg) \
329:       do { \
330:         PetscCheck((A)->product, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Argument %d \"%s\" is not a matrix obtained from MatProductCreate()", arg, #A); \
331:       } while (0)
332:   #else
333:     #define MatCheckProduct(A, arg) \
334:       do { \
335:       } while (0)
336:   #endif
337: #endif /* PETSC_CLANG_STATIC_ANALYZER */

339: /*
340:   The stash is used to temporarily store inserted matrix values that
341:   belong to another processor. During the assembly phase the stashed
342:   values are moved to the correct processor and
343: */

345: typedef struct _MatStashSpace *PetscMatStashSpace;

347: struct _MatStashSpace {
348:   PetscMatStashSpace next;
349:   PetscScalar       *space_head, *val;
350:   PetscInt          *idx, *idy;
351:   PetscInt           total_space_size;
352:   PetscInt           local_used;
353:   PetscInt           local_remaining;
354: };

356: PETSC_EXTERN PetscErrorCode PetscMatStashSpaceGet(PetscInt, PetscInt, PetscMatStashSpace *);
357: PETSC_EXTERN PetscErrorCode PetscMatStashSpaceContiguous(PetscInt, PetscMatStashSpace *, PetscScalar *, PetscInt *, PetscInt *);
358: PETSC_EXTERN PetscErrorCode PetscMatStashSpaceDestroy(PetscMatStashSpace *);

360: typedef struct {
361:   PetscInt count;
362: } MatStashHeader;

364: typedef struct {
365:   void    *buffer; /* Of type blocktype, dynamically constructed  */
366:   PetscInt count;
367:   char     pending;
368: } MatStashFrame;

370: typedef struct _MatStash MatStash;
371: struct _MatStash {
372:   PetscInt           nmax;              /* maximum stash size */
373:   PetscInt           umax;              /* user specified max-size */
374:   PetscInt           oldnmax;           /* the nmax value used previously */
375:   PetscInt           n;                 /* stash size */
376:   PetscInt           bs;                /* block size of the stash */
377:   PetscInt           reallocs;          /* preserve the no of mallocs invoked */
378:   PetscMatStashSpace space_head, space; /* linked list to hold stashed global row/column numbers and matrix values */

380:   PetscErrorCode (*ScatterBegin)(Mat, MatStash *, PetscInt *);
381:   PetscErrorCode (*ScatterGetMesg)(MatStash *, PetscMPIInt *, PetscInt **, PetscInt **, PetscScalar **, PetscInt *);
382:   PetscErrorCode (*ScatterEnd)(MatStash *);
383:   PetscErrorCode (*ScatterDestroy)(MatStash *);

385:   /* The following variables are used for communication */
386:   MPI_Comm      comm;
387:   PetscMPIInt   size, rank;
388:   PetscMPIInt   tag1, tag2;
389:   MPI_Request  *send_waits;     /* array of send requests */
390:   MPI_Request  *recv_waits;     /* array of receive requests */
391:   MPI_Status   *send_status;    /* array of send status */
392:   PetscMPIInt   nsends, nrecvs; /* numbers of sends and receives */
393:   PetscScalar  *svalues;        /* sending data */
394:   PetscInt     *sindices;
395:   PetscScalar **rvalues;    /* receiving data (values) */
396:   PetscInt    **rindices;   /* receiving data (indices) */
397:   PetscMPIInt   nprocessed; /* number of messages already processed */
398:   PetscMPIInt  *flg_v;      /* indicates what messages have arrived so far and from whom */
399:   PetscBool     reproduce;
400:   PetscMPIInt   reproduce_count;

402:   /* The following variables are used for BTS communication */
403:   PetscBool       first_assembly_done; /* Is the first time matrix assembly done? */
404:   PetscBool       use_status;          /* Use MPI_Status to determine number of items in each message */
405:   PetscMPIInt     nsendranks;
406:   PetscMPIInt     nrecvranks;
407:   PetscMPIInt    *sendranks;
408:   PetscMPIInt    *recvranks;
409:   MatStashHeader *sendhdr, *recvhdr;
410:   MatStashFrame  *sendframes; /* pointers to the main messages */
411:   MatStashFrame  *recvframes;
412:   MatStashFrame  *recvframe_active;
413:   PetscInt        recvframe_i;     /* index of block within active frame */
414:   PetscInt        recvframe_count; /* Count actually sent for current frame */
415:   PetscMPIInt     recvcount;       /* Number of receives processed so far */
416:   PetscMPIInt    *some_indices;    /* From last call to MPI_Waitsome */
417:   MPI_Status     *some_statuses;   /* Statuses from last call to MPI_Waitsome */
418:   PetscMPIInt     some_count;      /* Number of requests completed in last call to MPI_Waitsome */
419:   PetscMPIInt     some_i;          /* Index of request currently being processed */
420:   MPI_Request    *sendreqs;
421:   MPI_Request    *recvreqs;
422:   PetscSegBuffer  segsendblocks;
423:   PetscSegBuffer  segrecvframe;
424:   PetscSegBuffer  segrecvblocks;
425:   MPI_Datatype    blocktype;
426:   size_t          blocktype_size;
427:   InsertMode     *insertmode; /* Pointer to check mat->insertmode and set upon message arrival in case no local values have been set. */
428: };

430: #if !PetscDefined(HAVE_MPIUNI)
431: PETSC_INTERN PetscErrorCode MatStashScatterDestroy_BTS(MatStash *);
432: #endif
433: PETSC_INTERN PetscErrorCode MatStashCreate_Private(MPI_Comm, PetscInt, MatStash *);
434: PETSC_INTERN PetscErrorCode MatStashDestroy_Private(MatStash *);
435: PETSC_INTERN PetscErrorCode MatStashScatterEnd_Private(MatStash *);
436: PETSC_INTERN PetscErrorCode MatStashSetInitialSize_Private(MatStash *, PetscInt);
437: PETSC_INTERN PetscErrorCode MatStashGetInfo_Private(MatStash *, PetscInt *, PetscInt *);
438: PETSC_INTERN PetscErrorCode MatStashValuesRow_Private(MatStash *, PetscInt, PetscInt, const PetscInt[], const PetscScalar[], PetscBool);
439: PETSC_INTERN PetscErrorCode MatStashValuesCol_Private(MatStash *, PetscInt, PetscInt, const PetscInt[], const PetscScalar[], PetscInt, PetscBool);
440: PETSC_INTERN PetscErrorCode MatStashValuesRowBlocked_Private(MatStash *, PetscInt, PetscInt, const PetscInt[], const PetscScalar[], PetscInt, PetscInt, PetscInt);
441: PETSC_INTERN PetscErrorCode MatStashValuesColBlocked_Private(MatStash *, PetscInt, PetscInt, const PetscInt[], const PetscScalar[], PetscInt, PetscInt, PetscInt);
442: PETSC_INTERN PetscErrorCode MatStashScatterBegin_Private(Mat, MatStash *, PetscInt *);
443: PETSC_INTERN PetscErrorCode MatStashScatterGetMesg_Private(MatStash *, PetscMPIInt *, PetscInt **, PetscInt **, PetscScalar **, PetscInt *);
444: PETSC_INTERN PetscErrorCode MatGetInfo_External(Mat, MatInfoType, MatInfo *);

446: typedef struct {
447:   PetscInt  dim;
448:   PetscInt  dims[4];
449:   PetscInt  starts[4];
450:   PetscBool noc; /* this is a single component problem, hence user will not set MatStencil.c */
451: } MatStencilInfo;

453: /* Info about using compressed row format */
454: typedef struct {
455:   PetscBool use;    /* indicates compressed rows have been checked and will be used */
456:   PetscInt  nrows;  /* number of non-zero rows */
457:   PetscInt *i;      /* compressed row pointer  */
458:   PetscInt *rindex; /* compressed row index               */
459: } Mat_CompressedRow;
460: PETSC_EXTERN PetscErrorCode MatCheckCompressedRow(Mat, PetscInt, Mat_CompressedRow *, PetscInt *, PetscInt, PetscReal);

462: typedef struct { /* used by MatCreateRedundantMatrix() for reusing matredundant */
463:   PetscInt     nzlocal, nsends, nrecvs;
464:   PetscMPIInt *send_rank, *recv_rank;
465:   PetscInt    *sbuf_nz, *rbuf_nz, *sbuf_j, **rbuf_j;
466:   PetscScalar *sbuf_a, **rbuf_a;
467:   MPI_Comm     subcomm; /* when user does not provide a subcomm */
468:   IS           isrow, iscol;
469:   Mat         *matseq;
470: } Mat_Redundant;

472: typedef struct { /* used by MatProduct() */
473:   MatProductType type;
474:   char          *alg;
475:   Mat            A, B, C, Dwork;
476:   PetscBool      symbolic_used_the_fact_A_is_symmetric; /* Symbolic phase took advantage of the fact that A is symmetric, and optimized e.g. AtB as AB. Then, .. */
477:   PetscBool      symbolic_used_the_fact_B_is_symmetric; /* .. in the numeric phase, if a new A is not symmetric (but has the same sparsity as the old A therefore .. */
478:   PetscBool      symbolic_used_the_fact_C_is_symmetric; /* MatMatMult(A,B,MAT_REUSE_MATRIX,..&C) is still legitimate), we need to redo symbolic! */
479:   PetscObjectParameterDeclare(PetscReal, fill);
480:   PetscBool api_user; /* used to distinguish command line options and to indicate the matrix values are ready to be consumed at symbolic phase if needed */
481:   PetscBool setfromoptionscalled;

483:   /* Some products may display the information on the algorithm used */
484:   PetscErrorCode (*view)(Mat, PetscViewer);

486:   /* nonzero state of A at the last symbolic phase, used by MatProductComputeWithMat_Private() to run that phase again when the nonzero pattern of A changes */
487:   PetscObjectState Anonzerostate;

489:   /* many products have intermediate data structures, each specific to Mat types and product type */
490:   PetscBool          clear;   /* whether or not to clear the data structures after MatProductNumeric has been called */
491:   void              *data;    /* where to stash those structures */
492:   PetscCtxDestroyFn *destroy; /* freeing data */
493: } Mat_Product;

495: struct _p_Mat {
496:   PETSCHEADER(struct _MatOps);
497:   PetscLayout      rmap, cmap;
498:   void            *data;                                    /* implementation-specific data */
499:   MatFactorType    factortype;                              /* MAT_FACTOR_LU, ILU, CHOLESKY or ICC */
500:   PetscBool        trivialsymbolic;                         /* indicates the symbolic factorization doesn't actually do a symbolic factorization, it is delayed to the numeric factorization */
501:   PetscBool        canuseordering;                          /* factorization can use ordering provide to routine (most PETSc implementations) */
502:   MatOrderingType  preferredordering[MAT_FACTOR_NUM_TYPES]; /* what is the preferred (or default) ordering for the matrix solver type */
503:   PetscBool        assembled;                               /* is the matrix assembled? */
504:   PetscBool        was_assembled;                           /* new values inserted into assembled mat */
505:   PetscInt         num_ass;                                 /* number of times matrix has been assembled */
506:   PetscObjectState nonzerostate;                            /* each time new nonzeros locations are introduced into the matrix this is updated */
507:   PetscObjectState ass_nonzerostate;                        /* nonzero state at last assembly */
508:   MatInfo          info;                                    /* matrix information */
509:   InsertMode       insertmode;                              /* have values been inserted in matrix or added? */
510:   MatStash         stash, bstash;                           /* used for assembling off-proc mat emements */
511:   MatNullSpace     nullsp;                                  /* null space (operator is singular) */
512:   MatNullSpace     transnullsp;                             /* null space of transpose of operator */
513:   MatNullSpace     nearnullsp;                              /* near null space to be used by multigrid methods */
514:   PetscInt         congruentlayouts;                        /* are the rows and columns layouts congruent? */
515:   PetscBool        preallocated;
516:   MatStencilInfo   stencil; /* information for structured grid */
517:   PetscBool3       symmetric, hermitian, structurally_symmetric, spd;
518:   PetscBool        symmetry_eternal, structural_symmetry_eternal, spd_eternal;
519:   PetscBool        nooffprocentries, nooffproczerorows;
520:   PetscBool        assembly_subset; /* set by MAT_SUBSET_OFF_PROC_ENTRIES */
521:   PetscBool        submat_singleis; /* for efficient PCSetUp_ASM() */
522:   PetscBool        structure_only;
523:   PetscBool        sortedfull;      /* full, sorted rows are inserted */
524:   PetscBool        force_diagonals; /* set by MAT_FORCE_DIAGONAL_ENTRIES */
525: #if PetscDefined(HAVE_DEVICE)
526:   PetscOffloadMask offloadmask; /* a mask which indicates where the valid matrix data is (GPU, CPU or both) */
527:   PetscBool        boundtocpu;
528:   PetscBool        bindingpropagates;
529: #endif
530:   char                *defaultrandtype;
531:   void                *spptr; /* pointer for special library like SuperLU */
532:   char                *solvertype;
533:   PetscBool            checksymmetryonassembly, checknullspaceonassembly;
534:   PetscReal            checksymmetrytol;
535:   Mat                  schur;                            /* Schur complement matrix */
536:   MatFactorSchurStatus schur_status;                     /* status of the Schur complement matrix */
537:   Mat_Redundant       *redundant;                        /* used by MatCreateRedundantMatrix() */
538:   PetscBool            erroriffailure;                   /* Generate an error if detected (for example a zero pivot) instead of returning */
539:   MatFactorError       factorerrortype;                  /* type of error in factorization */
540:   PetscReal            factorerror_zeropivot_value;      /* If numerical zero pivot was detected this is the computed value */
541:   PetscInt             factorerror_zeropivot_row;        /* Row where zero pivot was detected */
542:   PetscInt             nblocks, *bsizes;                 /* support for MatSetVariableBlockSizes() */
543:   PetscInt             p_cstart, p_rank, p_cend, n_rank; /* Information from parallel MatComputeVariableBlockEnvelope() */
544:   PetscBool            p_parallel;
545:   char                *defaultvectype;
546:   Mat_Product         *product;
547:   PetscBool            form_explicit_transpose; /* hint to generate an explicit mat tranpsose for operations like MatMultTranspose() */
548:   PetscBool            transupdated;            /* whether or not the explicitly generated transpose is up-to-date */
549:   char                *factorprefix;            /* the prefix to use with factored matrix that is created */
550:   PetscBool            hash_active;             /* indicates MatSetValues() is being handled by hashing */
551:   Vec                  dot_vec;                 /* work vector used by MatADot_Default() */
552: };

554: PETSC_INTERN PetscErrorCode MatAXPY_Basic(Mat, PetscScalar, Mat, MatStructure);
555: PETSC_INTERN PetscErrorCode MatAXPY_BasicWithPreallocation(Mat, Mat, PetscScalar, Mat, MatStructure);
556: PETSC_INTERN PetscErrorCode MatAXPY_Basic_Preallocate(Mat, Mat, Mat *);
557: PETSC_INTERN PetscErrorCode MatAXPY_Dense_Nest(Mat, PetscScalar, Mat);

559: /*
560:     Utility for MatZeroRows
561: */
562: PETSC_INTERN PetscErrorCode MatZeroRowsMapLocal_Private(Mat, PetscInt, const PetscInt *, PetscInt *, PetscInt **);

564: /*
565:     Utility for MatView/MatLoad
566: */
567: PETSC_INTERN PetscErrorCode MatView_Binary_BlockSizes(Mat, PetscViewer);
568: PETSC_INTERN PetscErrorCode MatLoad_Binary_BlockSizes(Mat, PetscViewer);

570: /*
571:     Object for partitioning graphs
572: */

574: typedef struct _MatPartitioningOps *MatPartitioningOps;
575: struct _MatPartitioningOps {
576:   PetscErrorCode (*apply)(MatPartitioning, IS *);
577:   PetscErrorCode (*applynd)(MatPartitioning, IS *);
578:   PetscErrorCode (*setfromoptions)(MatPartitioning, PetscOptionItems);
579:   PetscErrorCode (*destroy)(MatPartitioning);
580:   PetscErrorCode (*view)(MatPartitioning, PetscViewer);
581:   PetscErrorCode (*improve)(MatPartitioning, IS *);
582: };

584: struct _p_MatPartitioning {
585:   PETSCHEADER(struct _MatPartitioningOps);
586:   Mat        adj;
587:   PetscInt  *vertex_weights;
588:   PetscReal *part_weights;
589:   PetscInt   n;    /* number of partitions */
590:   PetscInt   ncon; /* number of vertex weights per vertex */
591:   void      *data;
592:   PetscBool  use_edge_weights; /* A flag indicates whether or not to use edge weights */
593: };

595: /* needed for parallel nested dissection by ParMETIS */
596: PETSC_INTERN PetscErrorCode MatPartitioningSizesToSep_Private(PetscInt, PetscInt[], PetscInt[], PetscInt[]);

598: /* shared by the MatPartitioning and PetscPartitioner bindings to PT-SCOTCH */
599: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode PetscPTSCOTCHPartitionGraph_Private(MPI_Comm, const PetscInt[], PetscInt[], PetscInt[], PetscInt[], PetscInt[], PetscBool, PetscInt, PetscInt[], PetscInt, double, PetscInt[]);

601: /*
602:     Object for coarsen graphs
603: */
604: typedef struct _MatCoarsenOps *MatCoarsenOps;
605: struct _MatCoarsenOps {
606:   PetscErrorCode (*apply)(MatCoarsen);
607:   PetscErrorCode (*setfromoptions)(MatCoarsen, PetscOptionItems);
608:   PetscErrorCode (*destroy)(MatCoarsen);
609:   PetscErrorCode (*view)(MatCoarsen, PetscViewer);
610: };

612: #define MAT_COARSEN_STRENGTH_INDEX_SIZE 3
613: struct _p_MatCoarsen {
614:   PETSCHEADER(struct _MatCoarsenOps);
615:   Mat   graph;
616:   void *subctx;
617:   /* */
618:   PetscBool         strict_aggs;
619:   IS                perm;
620:   PetscCoarsenData *agg_lists;
621:   PetscInt          max_it;    /* number of iterations in HEM */
622:   PetscReal         threshold; /* HEM can filter interim graphs */
623:   PetscInt          strength_index_size;
624:   PetscInt          strength_index[MAT_COARSEN_STRENGTH_INDEX_SIZE];
625: };

627: PETSC_EXTERN PetscErrorCode MatCoarsenMISKSetDistance(MatCoarsen, PetscInt);
628: PETSC_EXTERN PetscErrorCode MatCoarsenMISKGetDistance(MatCoarsen, PetscInt *);

630: /*
631:     Used in aijdevice.h
632: */
633: typedef struct {
634:   PetscInt    *i;
635:   PetscInt    *j;
636:   PetscScalar *a;
637:   PetscInt     n;
638:   PetscInt     ignorezeroentries;
639: } PetscCSRDataStructure;

641: /*
642:     MatFDColoring is used to compute Jacobian matrices efficiently
643:   via coloring. The data structure is explained below in an example.

645:    Color =   0    1     0    2   |   2      3       0
646:    ---------------------------------------------------
647:             00   01              |          05
648:             10   11              |   14     15               Processor  0
649:                        22    23  |          25
650:                        32    33  |
651:    ===================================================
652:                                  |   44     45     46
653:             50                   |          55               Processor 1
654:                                  |   64            66
655:    ---------------------------------------------------

657:     ncolors = 4;

659:     ncolumns      = {2,1,1,0}
660:     columns       = {{0,2},{1},{3},{}}
661:     nrows         = {4,2,3,3}
662:     rows          = {{0,1,2,3},{0,1},{1,2,3},{0,1,2}}
663:     vwscale       = {dx(0),dx(1),dx(2),dx(3)}               MPI Vec
664:     vscale        = {dx(0),dx(1),dx(2),dx(3),dx(4),dx(5)}   Seq Vec

666:     ncolumns      = {1,0,1,1}
667:     columns       = {{6},{},{4},{5}}
668:     nrows         = {3,0,2,2}
669:     rows          = {{0,1,2},{},{1,2},{1,2}}
670:     vwscale       = {dx(4),dx(5),dx(6)}              MPI Vec
671:     vscale        = {dx(0),dx(4),dx(5),dx(6)}        Seq Vec

673:     See the routine MatFDColoringApply() for how this data is used
674:     to compute the Jacobian.

676: */
677: typedef struct {
678:   PetscInt     row;
679:   PetscInt     col;
680:   PetscScalar *valaddr; /* address of value */
681: } MatEntry;

683: typedef struct {
684:   PetscInt     row;
685:   PetscScalar *valaddr; /* address of value */
686: } MatEntry2;

688: struct _p_MatFDColoring {
689:   PETSCHEADER(int);
690:   PetscInt                M, N, m;          /* total rows, columns; local rows */
691:   PetscInt                rstart;           /* first row owned by local processor */
692:   PetscInt                ncolors;          /* number of colors */
693:   PetscInt               *ncolumns;         /* number of local columns for a color */
694:   PetscInt              **columns;          /* lists the local columns of each color (using global column numbering) */
695:   IS                     *isa;              /* these are the IS that contain the column values given in columns */
696:   PetscInt               *nrows;            /* number of local rows for each color */
697:   MatEntry               *matentry;         /* holds (row, column, address of value) for Jacobian matrix entry */
698:   MatEntry2              *matentry2;        /* holds (row, address of value) for Jacobian matrix entry */
699:   PetscScalar            *dy;               /* store a block of F(x+dx)-F(x) when J is in BAIJ format */
700:   PetscReal               error_rel;        /* square root of relative error in computing function */
701:   PetscReal               umin;             /* minimum allowable u'dx value */
702:   Vec                     w1, w2, w3;       /* work vectors used in computing Jacobian */
703:   PetscBool               fset;             /* indicates that the initial function value F(X) is set */
704:   MatFDColoringFn        *f;                /* function that defines Jacobian */
705:   void                   *fctx;             /* optional user-defined context for use by the function f */
706:   Vec                     vscale;           /* holds FD scaling, i.e. 1/dx for each perturbed column */
707:   PetscInt                currentcolor;     /* color for which function evaluation is being done now */
708:   const char             *htype;            /* "wp" or "ds" */
709:   ISColoringType          ctype;            /* IS_COLORING_GLOBAL or IS_COLORING_LOCAL */
710:   PetscInt                brows, bcols;     /* number of block rows or columns for speedup inserting the dense matrix into sparse Jacobian */
711:   PetscBool               setupcalled;      /* true if setup has been called */
712:   PetscBool               viewed;           /* true if the -mat_fd_coloring_view has been triggered already */
713:   PetscFortranCallbackFn *ftn_func_pointer; /* serve the same purpose as *fortran_func_pointers in PETSc objects */
714:   void                   *ftn_func_cntx;
715:   PetscObjectId           matid; /* matrix this object was created with, must always be the same */
716: };

718: typedef struct _MatColoringOps *MatColoringOps;
719: struct _MatColoringOps {
720:   PetscErrorCode (*destroy)(MatColoring);
721:   PetscErrorCode (*setfromoptions)(MatColoring, PetscOptionItems);
722:   PetscErrorCode (*view)(MatColoring, PetscViewer);
723:   PetscErrorCode (*apply)(MatColoring, ISColoring *);
724:   PetscErrorCode (*weights)(MatColoring, PetscReal **, PetscInt **);
725: };

727: struct _p_MatColoring {
728:   PETSCHEADER(struct _MatColoringOps);
729:   Mat                   mat;
730:   PetscInt              dist;         /* distance of the coloring */
731:   PetscInt              maxcolors;    /* the maximum number of colors returned, maxcolors=1 for MIS */
732:   void                 *data;         /* inner context */
733:   PetscBool             valid;        /* check to see if what is produced is a valid coloring */
734:   MatColoringWeightType weight_type;  /* type of weight computation to be performed */
735:   PetscReal            *user_weights; /* custom weights and permutation */
736:   PetscInt             *user_lperm;
737:   PetscBool             valid_iscoloring; /* check to see if matcoloring is produced a valid iscoloring */
738: };

740: struct _p_MatTransposeColoring {
741:   PETSCHEADER(int);
742:   PetscInt       M, N, m;      /* total rows, columns; local rows */
743:   PetscInt       rstart;       /* first row owned by local processor */
744:   PetscInt       ncolors;      /* number of colors */
745:   PetscInt      *ncolumns;     /* number of local columns for a color */
746:   PetscInt      *nrows;        /* number of local rows for each color */
747:   PetscInt       currentcolor; /* color for which function evaluation is being done now */
748:   ISColoringType ctype;        /* IS_COLORING_GLOBAL or IS_COLORING_LOCAL */

750:   PetscInt *colorforrow, *colorforcol; /* pointer to rows and columns */
751:   PetscInt *rows;                      /* lists the local rows for each color (using the local row numbering) */
752:   PetscInt *den2sp;                    /* maps (row,color) in the dense matrix to index of sparse matrix array a->a */
753:   PetscInt *columns;                   /* lists the local columns of each color (using global column numbering) */
754:   PetscInt  brows;                     /* number of rows for efficient implementation of MatTransColoringApplyDenToSp() */
755:   PetscInt *lstart;                    /* array used for loop over row blocks of Csparse */
756: };

758: /*
759:    Null space context for preconditioner/operators
760: */
761: struct _p_MatNullSpace {
762:   PETSCHEADER(int);
763:   PetscBool             has_cnst;
764:   PetscInt              n;
765:   Vec                  *vecs;
766:   PetscScalar          *alpha;  /* for projections */
767:   MatNullSpaceRemoveFn *remove; /* for user provided removal function */
768:   void                 *rmctx;  /* context for remove() function */
769: };

771: /*
772:    Internal data structure for MATMPIDENSE
773: */
774: typedef struct {
775:   Mat A; /* local submatrix */

777:   /* The following variables are used for matrix assembly */
778:   PetscBool    donotstash;        /* Flag indicating if values should be stashed */
779:   MPI_Request *send_waits;        /* array of send requests */
780:   MPI_Request *recv_waits;        /* array of receive requests */
781:   PetscInt     nsends, nrecvs;    /* numbers of sends and receives */
782:   PetscScalar *svalues, *rvalues; /* sending and receiving data */
783:   PetscInt     rmax;              /* maximum message length */

785:   /* The following variables are used for matrix-vector products */
786:   Vec       lvec;        /* local vector */
787:   PetscSF   Mvctx;       /* for mat-mult communications */
788:   PetscBool roworiented; /* if true, row-oriented input (default) */

790:   /* Support for MatDenseGetColumnVec and MatDenseGetSubMatrix */
791:   Mat                cmat;     /* matrix representation of a given subset of columns */
792:   Vec                cvec;     /* vector representation of a given column */
793:   const PetscScalar *ptrinuse; /* holds array to be restored (just a placeholder) */
794:   PetscInt           vecinuse; /* if cvec is in use (col = vecinuse-1) */
795:   PetscInt           matinuse; /* if cmat is in use (cbegin = matinuse-1) */
796:   /* if this is from MatDenseGetSubMatrix, which columns and rows does it correspond to? */
797:   PetscInt sub_rbegin;
798:   PetscInt sub_rend;
799:   PetscInt sub_cbegin;
800:   PetscInt sub_cend;
801: } Mat_MPIDense;

803: /*
804:    Checking zero pivot for LU, ILU preconditioners.
805: */
806: typedef struct {
807:   PetscInt    nshift, nshift_max;
808:   PetscReal   shift_amount, shift_lo, shift_hi, shift_top, shift_fraction;
809:   PetscBool   newshift;
810:   PetscReal   rs; /* active row sum of abs(off-diagonals) */
811:   PetscScalar pv; /* pivot of the active row */
812: } FactorShiftCtx;

814: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatTransposeCheckNonzeroState_Private(Mat, Mat);

816: PETSC_EXTERN PetscErrorCode MatFactorDumpMatrix(Mat);
817: PETSC_INTERN PetscErrorCode MatSetBlockSizes_Default(Mat, PetscInt, PetscInt);

819: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatShift_Basic(Mat, PetscScalar);
820: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatProductComputeWithMat_Private(Mat, Mat, MatProductType, Mat);

822: static inline PetscErrorCode MatPivotCheck_nz(PETSC_UNUSED Mat mat, const MatFactorInfo *info, FactorShiftCtx *sctx, PETSC_UNUSED PetscInt row)
823: {
824:   PetscReal _rs   = sctx->rs;
825:   PetscReal _zero = info->zeropivot * _rs;

827:   PetscFunctionBegin;
828:   if (PetscAbsScalar(sctx->pv) <= _zero && !PetscIsNanScalar(sctx->pv)) {
829:     /* force |diag| > zeropivot*rs */
830:     if (!sctx->nshift) sctx->shift_amount = info->shiftamount;
831:     else sctx->shift_amount *= 2.0;
832:     sctx->newshift = PETSC_TRUE;
833:     sctx->nshift++;
834:   } else {
835:     sctx->newshift = PETSC_FALSE;
836:   }
837:   PetscFunctionReturn(PETSC_SUCCESS);
838: }

840: static inline PetscErrorCode MatPivotCheck_pd(PETSC_UNUSED Mat mat, const MatFactorInfo *info, FactorShiftCtx *sctx, PETSC_UNUSED PetscInt row)
841: {
842:   PetscReal _rs   = sctx->rs;
843:   PetscReal _zero = info->zeropivot * _rs;

845:   PetscFunctionBegin;
846:   if (PetscRealPart(sctx->pv) <= _zero && !PetscIsNanScalar(sctx->pv)) {
847:     /* force matfactor to be diagonally dominant */
848:     if (sctx->nshift == sctx->nshift_max) {
849:       sctx->shift_fraction = sctx->shift_hi;
850:     } else {
851:       sctx->shift_lo       = sctx->shift_fraction;
852:       sctx->shift_fraction = (sctx->shift_hi + sctx->shift_lo) / (PetscReal)2.;
853:     }
854:     sctx->shift_amount = sctx->shift_fraction * sctx->shift_top;
855:     sctx->nshift++;
856:     sctx->newshift = PETSC_TRUE;
857:   } else {
858:     sctx->newshift = PETSC_FALSE;
859:   }
860:   PetscFunctionReturn(PETSC_SUCCESS);
861: }

863: static inline PetscErrorCode MatPivotCheck_inblocks(PETSC_UNUSED Mat mat, const MatFactorInfo *info, FactorShiftCtx *sctx, PETSC_UNUSED PetscInt row)
864: {
865:   PetscReal _zero = info->zeropivot;

867:   PetscFunctionBegin;
868:   if (PetscAbsScalar(sctx->pv) <= _zero && !PetscIsNanScalar(sctx->pv)) {
869:     sctx->pv += info->shiftamount;
870:     sctx->shift_amount = 0.0;
871:     sctx->nshift++;
872:   }
873:   sctx->newshift = PETSC_FALSE;
874:   PetscFunctionReturn(PETSC_SUCCESS);
875: }

877: static inline PetscErrorCode MatPivotCheck_none(Mat fact, Mat mat, const MatFactorInfo *info, FactorShiftCtx *sctx, PetscInt row)
878: {
879:   PetscReal _zero = info->zeropivot;

881:   PetscFunctionBegin;
882:   sctx->newshift = PETSC_FALSE;
883:   if (PetscAbsScalar(sctx->pv) <= _zero && !PetscIsNanScalar(sctx->pv)) {
884:     PetscCheck(!mat->erroriffailure, PETSC_COMM_SELF, PETSC_ERR_MAT_LU_ZRPVT, "Zero pivot row %" PetscInt_FMT " value %g tolerance %g", row, (double)PetscAbsScalar(sctx->pv), (double)_zero);
885:     PetscCall(PetscInfo(mat, "Detected zero pivot in factorization in row %" PetscInt_FMT " value %g tolerance %g\n", row, (double)PetscAbsScalar(sctx->pv), (double)_zero));
886:     fact->factorerrortype             = MAT_FACTOR_NUMERIC_ZEROPIVOT;
887:     fact->factorerror_zeropivot_value = PetscAbsScalar(sctx->pv);
888:     fact->factorerror_zeropivot_row   = row;
889:   }
890:   PetscFunctionReturn(PETSC_SUCCESS);
891: }

893: static inline PetscErrorCode MatPivotCheck(Mat fact, Mat mat, const MatFactorInfo *info, FactorShiftCtx *sctx, PetscInt row)
894: {
895:   PetscFunctionBegin;
896:   if (info->shifttype == (PetscReal)MAT_SHIFT_NONZERO) PetscCall(MatPivotCheck_nz(mat, info, sctx, row));
897:   else if (info->shifttype == (PetscReal)MAT_SHIFT_POSITIVE_DEFINITE) PetscCall(MatPivotCheck_pd(mat, info, sctx, row));
898:   else if (info->shifttype == (PetscReal)MAT_SHIFT_INBLOCKS) PetscCall(MatPivotCheck_inblocks(mat, info, sctx, row));
899:   else PetscCall(MatPivotCheck_none(fact, mat, info, sctx, row));
900:   PetscFunctionReturn(PETSC_SUCCESS);
901: }

903: /*
904:   Create and initialize a linked list
905:   Input Parameters:
906:     idx_start - starting index of the list
907:     lnk_max   - max value of lnk indicating the end of the list
908:     nlnk      - max length of the list
909:   Output Parameters:
910:     lnk       - list initialized
911:     bt        - PetscBT (bitarray) with all bits set to false
912:     lnk_empty - flg indicating the list is empty
913: */
914: #define PetscLLCreate(idx_start, lnk_max, nlnk, lnk, bt) ((PetscErrorCode)(PetscMalloc1(nlnk, &(lnk)) || PetscBTCreate(nlnk, &(bt)) || ((lnk)[idx_start] = lnk_max, PETSC_SUCCESS)))

916: #define PetscLLCreate_new(idx_start, lnk_max, nlnk, lnk, bt, lnk_empty) ((PetscErrorCode)(PetscMalloc1(nlnk, &(lnk)) || PetscBTCreate(nlnk, &(bt)) || (lnk_empty = PETSC_TRUE, 0) || ((lnk)[idx_start] = lnk_max, PETSC_SUCCESS)))

918: static inline PetscErrorCode PetscLLInsertLocation_Private(PetscBool assume_sorted, PetscInt k, PetscInt idx_start, PetscInt entry, PetscInt *PETSC_RESTRICT nlnk, PetscInt *PETSC_RESTRICT lnkdata, PetscInt *PETSC_RESTRICT lnk)
919: {
920:   PetscInt location;

922:   PetscFunctionBegin;
923:   /* start from the beginning if entry < previous entry */
924:   if (!assume_sorted && k && entry < *lnkdata) *lnkdata = idx_start;
925:   /* search for insertion location */
926:   do {
927:     location = *lnkdata;
928:     *lnkdata = lnk[location];
929:   } while (entry > *lnkdata);
930:   /* insertion location is found, add entry into lnk */
931:   lnk[location] = entry;
932:   lnk[entry]    = *lnkdata;
933:   ++(*nlnk);
934:   *lnkdata = entry; /* next search starts from here if next_entry > entry */
935:   PetscFunctionReturn(PETSC_SUCCESS);
936: }

938: static inline PetscErrorCode PetscLLAdd_Private(PetscInt nidx, const PetscInt *PETSC_RESTRICT indices, PetscInt idx_start, PetscInt *PETSC_RESTRICT nlnk, PetscInt *PETSC_RESTRICT lnk, PetscBT bt, PetscBool assume_sorted)
939: {
940:   PetscFunctionBegin;
941:   *nlnk = 0;
942:   for (PetscInt k = 0, lnkdata = idx_start; k < nidx; ++k) {
943:     const PetscInt entry = indices[k];

945:     if (!PetscBTLookupSet(bt, entry)) PetscCall(PetscLLInsertLocation_Private(assume_sorted, k, idx_start, entry, nlnk, &lnkdata, lnk));
946:   }
947:   PetscFunctionReturn(PETSC_SUCCESS);
948: }

950: /*
951:   Add an index set into a sorted linked list
952:   Input Parameters:
953:     nidx      - number of input indices
954:     indices   - integer array
955:     idx_start - starting index of the list
956:     lnk       - linked list(an integer array) that is created
957:     bt        - PetscBT (bitarray), bt[idx]=true marks idx is in lnk
958:   output Parameters:
959:     nlnk      - number of newly added indices
960:     lnk       - the sorted(increasing order) linked list containing new and non-redundate entries from indices
961:     bt        - updated PetscBT (bitarray)
962: */
963: static inline PetscErrorCode PetscLLAdd(PetscInt nidx, const PetscInt *PETSC_RESTRICT indices, PetscInt idx_start, PetscInt *PETSC_RESTRICT nlnk, PetscInt *PETSC_RESTRICT lnk, PetscBT bt)
964: {
965:   PetscFunctionBegin;
966:   PetscCall(PetscLLAdd_Private(nidx, indices, idx_start, nlnk, lnk, bt, PETSC_FALSE));
967:   PetscFunctionReturn(PETSC_SUCCESS);
968: }

970: /*
971:   Add a SORTED ascending index set into a sorted linked list - same as PetscLLAdd() bus skip 'if (_k && _entry < _lnkdata) _lnkdata  = idx_start;'
972:   Input Parameters:
973:     nidx      - number of input indices
974:     indices   - sorted integer array
975:     idx_start - starting index of the list
976:     lnk       - linked list(an integer array) that is created
977:     bt        - PetscBT (bitarray), bt[idx]=true marks idx is in lnk
978:   output Parameters:
979:     nlnk      - number of newly added indices
980:     lnk       - the sorted(increasing order) linked list containing new and non-redundate entries from indices
981:     bt        - updated PetscBT (bitarray)
982: */
983: static inline PetscErrorCode PetscLLAddSorted(PetscInt nidx, const PetscInt *PETSC_RESTRICT indices, PetscInt idx_start, PetscInt *PETSC_RESTRICT nlnk, PetscInt *PETSC_RESTRICT lnk, PetscBT bt)
984: {
985:   PetscFunctionBegin;
986:   PetscCall(PetscLLAdd_Private(nidx, indices, idx_start, nlnk, lnk, bt, PETSC_TRUE));
987:   PetscFunctionReturn(PETSC_SUCCESS);
988: }

990: /*
991:   Add a permuted index set into a sorted linked list
992:   Input Parameters:
993:     nidx      - number of input indices
994:     indices   - integer array
995:     perm      - permutation of indices
996:     idx_start - starting index of the list
997:     lnk       - linked list(an integer array) that is created
998:     bt        - PetscBT (bitarray), bt[idx]=true marks idx is in lnk
999:   output Parameters:
1000:     nlnk      - number of newly added indices
1001:     lnk       - the sorted(increasing order) linked list containing new and non-redundate entries from indices
1002:     bt        - updated PetscBT (bitarray)
1003: */
1004: static inline PetscErrorCode PetscLLAddPerm(PetscInt nidx, const PetscInt *PETSC_RESTRICT indices, const PetscInt *PETSC_RESTRICT perm, PetscInt idx_start, PetscInt *PETSC_RESTRICT nlnk, PetscInt *PETSC_RESTRICT lnk, PetscBT bt)
1005: {
1006:   PetscFunctionBegin;
1007:   *nlnk = 0;
1008:   for (PetscInt k = 0, lnkdata = idx_start; k < nidx; ++k) {
1009:     const PetscInt entry = perm[indices[k]];

1011:     if (!PetscBTLookupSet(bt, entry)) PetscCall(PetscLLInsertLocation_Private(PETSC_FALSE, k, idx_start, entry, nlnk, &lnkdata, lnk));
1012:   }
1013:   PetscFunctionReturn(PETSC_SUCCESS);
1014: }

1016: #if 0
1017: /* this appears to be unused? */
1018: static inline PetscErrorCode PetscLLAddSorted_new(PetscInt nidx, PetscInt *indices, PetscInt idx_start, PetscBool *lnk_empty, PetscInt *nlnk, PetscInt *lnk, PetscBT bt)
1019: {
1020:   PetscInt lnkdata = idx_start;

1022:   PetscFunctionBegin;
1023:   if (*lnk_empty) {
1024:     for (PetscInt k = 0; k < nidx; ++k) {
1025:       const PetscInt entry = indices[k], location = lnkdata;

1027:       PetscCall(PetscBTSet(bt,entry)); /* mark the new entry */
1028:       lnkdata       = lnk[location];
1029:       /* insertion location is found, add entry into lnk */
1030:       lnk[location] = entry;
1031:       lnk[entry]    = lnkdata;
1032:       lnkdata       = entry; /* next search starts from here */
1033:     }
1034:     /* lnk[indices[nidx-1]] = lnk[idx_start];
1035:        lnk[idx_start]       = indices[0];
1036:        PetscCall(PetscBTSet(bt,indices[0]));
1037:        for (_k=1; _k<nidx; _k++) {
1038:        PetscCall(PetscBTSet(bt,indices[_k]));
1039:        lnk[indices[_k-1]] = indices[_k];
1040:        }
1041:     */
1042:     *nlnk      = nidx;
1043:     *lnk_empty = PETSC_FALSE;
1044:   } else {
1045:     *nlnk = 0;
1046:     for (PetscInt k = 0; k < nidx; ++k) {
1047:       const PetscInt entry = indices[k];

1049:       if (!PetscBTLookupSet(bt,entry)) PetscCall(PetscLLInsertLocation_Private(PETSC_TRUE,k,idx_start,entry,nlnk,&lnkdata,lnk));
1050:     }
1051:   }
1052:   PetscFunctionReturn(PETSC_SUCCESS);
1053: }
1054: #endif

1056: /*
1057:   Add a SORTED index set into a sorted linked list used for LUFactorSymbolic()
1058:   Same as PetscLLAddSorted() with an additional operation:
1059:        count the number of input indices that are no larger than 'diag'
1060:   Input Parameters:
1061:     indices   - sorted integer array
1062:     idx_start - starting index of the list, index of pivot row
1063:     lnk       - linked list(an integer array) that is created
1064:     bt        - PetscBT (bitarray), bt[idx]=true marks idx is in lnk
1065:     diag      - index of the active row in LUFactorSymbolic
1066:     nzbd      - number of input indices with indices <= idx_start
1067:     im        - im[idx_start] is initialized as num of nonzero entries in row=idx_start
1068:   output Parameters:
1069:     nlnk      - number of newly added indices
1070:     lnk       - the sorted(increasing order) linked list containing new and non-redundate entries from indices
1071:     bt        - updated PetscBT (bitarray)
1072:     im        - im[idx_start]: unchanged if diag is not an entry
1073:                              : num of entries with indices <= diag if diag is an entry
1074: */
1075: static inline PetscErrorCode PetscLLAddSortedLU(const PetscInt *PETSC_RESTRICT indices, PetscInt idx_start, PetscInt *PETSC_RESTRICT nlnk, PetscInt *PETSC_RESTRICT lnk, PetscBT bt, PetscInt diag, PetscInt nzbd, PetscInt *PETSC_RESTRICT im)
1076: {
1077:   const PetscInt nidx = im[idx_start] - nzbd; /* num of entries with idx_start < index <= diag */

1079:   PetscFunctionBegin;
1080:   *nlnk = 0;
1081:   for (PetscInt k = 0, lnkdata = idx_start; k < nidx; ++k) {
1082:     const PetscInt entry = indices[k];

1084:     ++nzbd;
1085:     if (entry == diag) im[idx_start] = nzbd;
1086:     if (!PetscBTLookupSet(bt, entry)) PetscCall(PetscLLInsertLocation_Private(PETSC_TRUE, k, idx_start, entry, nlnk, &lnkdata, lnk));
1087:   }
1088:   PetscFunctionReturn(PETSC_SUCCESS);
1089: }

1091: /*
1092:   Copy data on the list into an array, then initialize the list
1093:   Input Parameters:
1094:     idx_start - starting index of the list
1095:     lnk_max   - max value of lnk indicating the end of the list
1096:     nlnk      - number of data on the list to be copied
1097:     lnk       - linked list
1098:     bt        - PetscBT (bitarray), bt[idx]=true marks idx is in lnk
1099:   output Parameters:
1100:     indices   - array that contains the copied data
1101:     lnk       - linked list that is cleaned and initialize
1102:     bt        - PetscBT (bitarray) with all bits set to false
1103: */
1104: static inline PetscErrorCode PetscLLClean(PetscInt idx_start, PetscInt lnk_max, PetscInt nlnk, PetscInt *PETSC_RESTRICT lnk, PetscInt *PETSC_RESTRICT indices, PetscBT bt)
1105: {
1106:   PetscFunctionBegin;
1107:   for (PetscInt j = 0, idx = idx_start; j < nlnk; ++j) {
1108:     idx        = lnk[idx];
1109:     indices[j] = idx;
1110:     PetscCall(PetscBTClear(bt, idx));
1111:   }
1112:   lnk[idx_start] = lnk_max;
1113:   PetscFunctionReturn(PETSC_SUCCESS);
1114: }

1116: /*
1117:   Free memories used by the list
1118: */
1119: #define PetscLLDestroy(lnk, bt) ((PetscErrorCode)(PetscFree(lnk) || PetscBTDestroy(&(bt))))

1121: /* Routines below are used for incomplete matrix factorization */
1122: /*
1123:   Create and initialize a linked list and its levels
1124:   Input Parameters:
1125:     idx_start - starting index of the list
1126:     lnk_max   - max value of lnk indicating the end of the list
1127:     nlnk      - max length of the list
1128:   Output Parameters:
1129:     lnk       - list initialized
1130:     lnk_lvl   - array of size nlnk for storing levels of lnk
1131:     bt        - PetscBT (bitarray) with all bits set to false
1132: */
1133: #define PetscIncompleteLLCreate(idx_start, lnk_max, nlnk, lnk, lnk_lvl, bt) \
1134:   ((PetscErrorCode)(PetscIntMultError(2, nlnk, NULL) || PetscMalloc1(2 * (nlnk), &(lnk)) || PetscBTCreate(nlnk, &(bt)) || ((lnk)[idx_start] = lnk_max, lnk_lvl = (lnk) + (nlnk), PETSC_SUCCESS)))

1136: static inline PetscErrorCode PetscIncompleteLLInsertLocation_Private(PetscBool assume_sorted, PetscInt k, PetscInt idx_start, PetscInt entry, PetscInt *PETSC_RESTRICT nlnk, PetscInt *PETSC_RESTRICT lnkdata, PetscInt *PETSC_RESTRICT lnk, PetscInt *PETSC_RESTRICT lnklvl, PetscInt newval)
1137: {
1138:   PetscFunctionBegin;
1139:   PetscCall(PetscLLInsertLocation_Private(assume_sorted, k, idx_start, entry, nlnk, lnkdata, lnk));
1140:   lnklvl[entry] = newval;
1141:   PetscFunctionReturn(PETSC_SUCCESS);
1142: }

1144: /*
1145:   Initialize a sorted linked list used for ILU and ICC
1146:   Input Parameters:
1147:     nidx      - number of input idx
1148:     idx       - integer array used for storing column indices
1149:     idx_start - starting index of the list
1150:     perm      - indices of an IS
1151:     lnk       - linked list(an integer array) that is created
1152:     lnklvl    - levels of lnk
1153:     bt        - PetscBT (bitarray), bt[idx]=true marks idx is in lnk
1154:   output Parameters:
1155:     nlnk     - number of newly added idx
1156:     lnk      - the sorted(increasing order) linked list containing new and non-redundate entries from idx
1157:     lnklvl   - levels of lnk
1158:     bt       - updated PetscBT (bitarray)
1159: */
1160: static inline PetscErrorCode PetscIncompleteLLInit(PetscInt nidx, const PetscInt *PETSC_RESTRICT idx, PetscInt idx_start, const PetscInt *PETSC_RESTRICT perm, PetscInt *PETSC_RESTRICT nlnk, PetscInt *PETSC_RESTRICT lnk, PetscInt *PETSC_RESTRICT lnklvl, PetscBT bt)
1161: {
1162:   PetscFunctionBegin;
1163:   *nlnk = 0;
1164:   for (PetscInt k = 0, lnkdata = idx_start; k < nidx; ++k) {
1165:     const PetscInt entry = perm[idx[k]];

1167:     if (!PetscBTLookupSet(bt, entry)) PetscCall(PetscIncompleteLLInsertLocation_Private(PETSC_FALSE, k, idx_start, entry, nlnk, &lnkdata, lnk, lnklvl, 0));
1168:   }
1169:   PetscFunctionReturn(PETSC_SUCCESS);
1170: }

1172: static inline PetscErrorCode PetscIncompleteLLAdd_Private(PetscInt nidx, const PetscInt *PETSC_RESTRICT idx, PetscInt level, const PetscInt *PETSC_RESTRICT idxlvl, PetscInt idx_start, PetscInt *PETSC_RESTRICT nlnk, PetscInt *PETSC_RESTRICT lnk, PetscInt *PETSC_RESTRICT lnklvl, PetscBT bt, PetscInt prow_offset, PetscBool assume_sorted)
1173: {
1174:   PetscFunctionBegin;
1175:   *nlnk = 0;
1176:   for (PetscInt k = 0, lnkdata = idx_start; k < nidx; ++k) {
1177:     const PetscInt incrlev = idxlvl[k] + prow_offset + 1;

1179:     if (incrlev <= level) {
1180:       const PetscInt entry = idx[k];

1182:       if (!PetscBTLookupSet(bt, entry)) PetscCall(PetscIncompleteLLInsertLocation_Private(assume_sorted, k, idx_start, entry, nlnk, &lnkdata, lnk, lnklvl, incrlev));
1183:       else if (lnklvl[entry] > incrlev) lnklvl[entry] = incrlev; /* existing entry */
1184:     }
1185:   }
1186:   PetscFunctionReturn(PETSC_SUCCESS);
1187: }

1189: /*
1190:   Add a SORTED index set into a sorted linked list for ICC
1191:   Input Parameters:
1192:     nidx      - number of input indices
1193:     idx       - sorted integer array used for storing column indices
1194:     level     - level of fill, e.g., ICC(level)
1195:     idxlvl    - level of idx
1196:     idx_start - starting index of the list
1197:     lnk       - linked list(an integer array) that is created
1198:     lnklvl    - levels of lnk
1199:     bt        - PetscBT (bitarray), bt[idx]=true marks idx is in lnk
1200:     idxlvl_prow - idxlvl[prow], where prow is the row number of the idx
1201:   output Parameters:
1202:     nlnk   - number of newly added indices
1203:     lnk    - the sorted(increasing order) linked list containing new and non-redundate entries from idx
1204:     lnklvl - levels of lnk
1205:     bt     - updated PetscBT (bitarray)
1206:   Note: the level of U(i,j) is set as lvl(i,j) = min{ lvl(i,j), lvl(prow,i)+lvl(prow,j)+1)
1207:         where idx = non-zero columns of U(prow,prow+1:n-1), prow<i
1208: */
1209: static inline PetscErrorCode PetscICCLLAddSorted(PetscInt nidx, const PetscInt *PETSC_RESTRICT idx, PetscInt level, const PetscInt *PETSC_RESTRICT idxlvl, PetscInt idx_start, PetscInt *PETSC_RESTRICT nlnk, PetscInt *PETSC_RESTRICT lnk, PetscInt *PETSC_RESTRICT lnklvl, PetscBT bt, PetscInt idxlvl_prow)
1210: {
1211:   PetscFunctionBegin;
1212:   PetscCall(PetscIncompleteLLAdd_Private(nidx, idx, level, idxlvl, idx_start, nlnk, lnk, lnklvl, bt, idxlvl_prow, PETSC_TRUE));
1213:   PetscFunctionReturn(PETSC_SUCCESS);
1214: }

1216: /*
1217:   Add a SORTED index set into a sorted linked list for ILU
1218:   Input Parameters:
1219:     nidx      - number of input indices
1220:     idx       - sorted integer array used for storing column indices
1221:     level     - level of fill, e.g., ICC(level)
1222:     idxlvl    - level of idx
1223:     idx_start - starting index of the list
1224:     lnk       - linked list(an integer array) that is created
1225:     lnklvl    - levels of lnk
1226:     bt        - PetscBT (bitarray), bt[idx]=true marks idx is in lnk
1227:     prow      - the row number of idx
1228:   output Parameters:
1229:     nlnk     - number of newly added idx
1230:     lnk      - the sorted(increasing order) linked list containing new and non-redundate entries from idx
1231:     lnklvl   - levels of lnk
1232:     bt       - updated PetscBT (bitarray)

1234:   Note: the level of factor(i,j) is set as lvl(i,j) = min{ lvl(i,j), lvl(i,prow)+lvl(prow,j)+1)
1235:         where idx = non-zero columns of U(prow,prow+1:n-1), prow<i
1236: */
1237: static inline PetscErrorCode PetscILULLAddSorted(PetscInt nidx, const PetscInt *PETSC_RESTRICT idx, PetscInt level, const PetscInt *PETSC_RESTRICT idxlvl, PetscInt idx_start, PetscInt *PETSC_RESTRICT nlnk, PetscInt *PETSC_RESTRICT lnk, PetscInt *PETSC_RESTRICT lnklvl, PetscBT bt, PetscInt prow)
1238: {
1239:   PetscFunctionBegin;
1240:   PetscCall(PetscIncompleteLLAdd_Private(nidx, idx, level, idxlvl, idx_start, nlnk, lnk, lnklvl, bt, lnklvl[prow], PETSC_TRUE));
1241:   PetscFunctionReturn(PETSC_SUCCESS);
1242: }

1244: /*
1245:   Add a index set into a sorted linked list
1246:   Input Parameters:
1247:     nidx      - number of input idx
1248:     idx   - integer array used for storing column indices
1249:     level     - level of fill, e.g., ICC(level)
1250:     idxlvl - level of idx
1251:     idx_start - starting index of the list
1252:     lnk       - linked list(an integer array) that is created
1253:     lnklvl   - levels of lnk
1254:     bt        - PetscBT (bitarray), bt[idx]=true marks idx is in lnk
1255:   output Parameters:
1256:     nlnk      - number of newly added idx
1257:     lnk       - the sorted(increasing order) linked list containing new and non-redundate entries from idx
1258:     lnklvl   - levels of lnk
1259:     bt        - updated PetscBT (bitarray)
1260: */
1261: static inline PetscErrorCode PetscIncompleteLLAdd(PetscInt nidx, const PetscInt *PETSC_RESTRICT idx, PetscInt level, const PetscInt *PETSC_RESTRICT idxlvl, PetscInt idx_start, PetscInt *PETSC_RESTRICT nlnk, PetscInt *PETSC_RESTRICT lnk, PetscInt *PETSC_RESTRICT lnklvl, PetscBT bt)
1262: {
1263:   PetscFunctionBegin;
1264:   PetscCall(PetscIncompleteLLAdd_Private(nidx, idx, level, idxlvl, idx_start, nlnk, lnk, lnklvl, bt, 0, PETSC_FALSE));
1265:   PetscFunctionReturn(PETSC_SUCCESS);
1266: }

1268: /*
1269:   Add a SORTED index set into a sorted linked list
1270:   Input Parameters:
1271:     nidx      - number of input indices
1272:     idx   - sorted integer array used for storing column indices
1273:     level     - level of fill, e.g., ICC(level)
1274:     idxlvl - level of idx
1275:     idx_start - starting index of the list
1276:     lnk       - linked list(an integer array) that is created
1277:     lnklvl    - levels of lnk
1278:     bt        - PetscBT (bitarray), bt[idx]=true marks idx is in lnk
1279:   output Parameters:
1280:     nlnk      - number of newly added idx
1281:     lnk       - the sorted(increasing order) linked list containing new and non-redundate entries from idx
1282:     lnklvl    - levels of lnk
1283:     bt        - updated PetscBT (bitarray)
1284: */
1285: static inline PetscErrorCode PetscIncompleteLLAddSorted(PetscInt nidx, const PetscInt *PETSC_RESTRICT idx, PetscInt level, const PetscInt *PETSC_RESTRICT idxlvl, PetscInt idx_start, PetscInt *PETSC_RESTRICT nlnk, PetscInt *PETSC_RESTRICT lnk, PetscInt *PETSC_RESTRICT lnklvl, PetscBT bt)
1286: {
1287:   PetscFunctionBegin;
1288:   PetscCall(PetscIncompleteLLAdd_Private(nidx, idx, level, idxlvl, idx_start, nlnk, lnk, lnklvl, bt, 0, PETSC_TRUE));
1289:   PetscFunctionReturn(PETSC_SUCCESS);
1290: }

1292: /*
1293:   Copy data on the list into an array, then initialize the list
1294:   Input Parameters:
1295:     idx_start - starting index of the list
1296:     lnk_max   - max value of lnk indicating the end of the list
1297:     nlnk      - number of data on the list to be copied
1298:     lnk       - linked list
1299:     lnklvl    - level of lnk
1300:     bt        - PetscBT (bitarray), bt[idx]=true marks idx is in lnk
1301:   output Parameters:
1302:     indices - array that contains the copied data
1303:     lnk     - linked list that is cleaned and initialize
1304:     lnklvl  - level of lnk that is reinitialized
1305:     bt      - PetscBT (bitarray) with all bits set to false
1306: */
1307: static inline PetscErrorCode PetscIncompleteLLClean(PetscInt idx_start, PetscInt lnk_max, PetscInt nlnk, PetscInt *PETSC_RESTRICT lnk, PetscInt *PETSC_RESTRICT lnklvl, PetscInt *PETSC_RESTRICT indices, PetscInt *PETSC_RESTRICT indiceslvl, PetscBT bt)
1308: {
1309:   PetscFunctionBegin;
1310:   for (PetscInt j = 0, idx = idx_start; j < nlnk; ++j) {
1311:     idx           = lnk[idx];
1312:     indices[j]    = idx;
1313:     indiceslvl[j] = lnklvl[idx];
1314:     lnklvl[idx]   = -1;
1315:     PetscCall(PetscBTClear(bt, idx));
1316:   }
1317:   lnk[idx_start] = lnk_max;
1318:   PetscFunctionReturn(PETSC_SUCCESS);
1319: }

1321: /*
1322:   Free memories used by the list
1323: */
1324: #define PetscIncompleteLLDestroy(lnk, bt) ((PetscErrorCode)(PetscFree(lnk) || PetscBTDestroy(&(bt))))

1326: #if !PetscDefined(CLANG_STATIC_ANALYZER)
1327:   #define MatCheckSameLocalSize(A, ar1, B, ar2) \
1328:     do { \
1329:       PetscCheckSameComm(A, ar1, B, ar2); \
1330:       PetscCheck(((A)->rmap->n == (B)->rmap->n) && ((A)->cmap->n == (B)->cmap->n), PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Incompatible matrix local sizes: parameter # %d (%" PetscInt_FMT " x %" PetscInt_FMT ") != parameter # %d (%" PetscInt_FMT " x %" PetscInt_FMT ")", ar1, \
1331:                  (A)->rmap->n, (A)->cmap->n, ar2, (B)->rmap->n, (B)->cmap->n); \
1332:     } while (0)
1333:   #define MatCheckSameSize(A, ar1, B, ar2) \
1334:     do { \
1335:       PetscCheck(((A)->rmap->N == (B)->rmap->N) && ((A)->cmap->N == (B)->cmap->N), PetscObjectComm((PetscObject)(A)), PETSC_ERR_ARG_INCOMP, "Incompatible matrix global sizes: parameter # %d (%" PetscInt_FMT " x %" PetscInt_FMT ") != parameter # %d (%" PetscInt_FMT " x %" PetscInt_FMT ")", ar1, \
1336:                  (A)->rmap->N, (A)->cmap->N, ar2, (B)->rmap->N, (B)->cmap->N); \
1337:       MatCheckSameLocalSize(A, ar1, B, ar2); \
1338:     } while (0)
1339: #else
1340: template <typename Tm>
1341: extern void MatCheckSameLocalSize(Tm, int, Tm, int);
1342: template <typename Tm>
1343: extern void MatCheckSameSize(Tm, int, Tm, int);
1344: #endif

1346: #define VecCheckMatCompatible(M, x, ar1, b, ar2) \
1347:   do { \
1348:     PetscCheck((M)->cmap->N == (x)->map->N, PetscObjectComm((PetscObject)(M)), PETSC_ERR_ARG_SIZ, "Vector global length incompatible with matrix: parameter # %d global size %" PetscInt_FMT " != matrix column global size %" PetscInt_FMT, ar1, (x)->map->N, \
1349:                (M)->cmap->N); \
1350:     PetscCheck((M)->rmap->N == (b)->map->N, PetscObjectComm((PetscObject)(M)), PETSC_ERR_ARG_SIZ, "Vector global length incompatible with matrix: parameter # %d global size %" PetscInt_FMT " != matrix row global size %" PetscInt_FMT, ar2, (b)->map->N, \
1351:                (M)->rmap->N); \
1352:   } while (0)

1354: /*
1355:   Create and initialize a condensed linked list -
1356:     same as PetscLLCreate(), but uses a scalable array 'lnk' with size of max number of entries, not O(N).
1357:     Barry suggested this approach (Dec. 6, 2011):
1358:       I've thought of an alternative way of representing a linked list that is efficient but doesn't have the O(N) scaling issue
1359:       (it may be faster than the O(N) even sequentially due to less crazy memory access).

1361:       Instead of having some like  a  2  -> 4 -> 11 ->  22  list that uses slot 2  4 11 and 22 in a big array use a small array with two slots
1362:       for each entry for example  [ 2 1 | 4 3 | 22 -1 | 11 2]   so the first number (of the pair) is the value while the second tells you where
1363:       in the list the next entry is. Inserting a new link means just append another pair at the end. For example say we want to insert 13 into the
1364:       list it would then become [2 1 | 4 3 | 22 -1 | 11 4 | 13 2 ] you just add a pair at the end and fix the point for the one that points to it.
1365:       That is 11 use to point to the 2 slot, after the change 11 points to the 4th slot which has the value 13. Note that values are always next
1366:       to each other so memory access is much better than using the big array.

1368:   Example:
1369:      nlnk_max=5, lnk_max=36:
1370:      Initial list: [0, 0 | 36, 2 | 0, 0 | 0, 0 | 0, 0 | 0, 0 | 0, 0]
1371:      here, head_node has index 2 with value lnk[2]=lnk_max=36,
1372:            0-th entry is used to store the number of entries in the list,
1373:      The initial lnk represents head -> tail(marked by 36) with number of entries = lnk[0]=0.

1375:      Now adding a sorted set {2,4}, the list becomes
1376:      [2, 0 | 36, 4 |2, 6 | 4, 2 | 0, 0 | 0, 0 | 0, 0 ]
1377:      represents head -> 2 -> 4 -> tail with number of entries = lnk[0]=2.

1379:      Then adding a sorted set {0,3,35}, the list
1380:      [5, 0 | 36, 8 | 2, 10 | 4, 12 | 0, 4 | 3, 6 | 35, 2 ]
1381:      represents head -> 0 -> 2 -> 3 -> 4 -> 35 -> tail with number of entries = lnk[0]=5.

1383:   Input Parameters:
1384:     nlnk_max  - max length of the list
1385:     lnk_max   - max value of the entries
1386:   Output Parameters:
1387:     lnk       - list created and initialized
1388:     bt        - PetscBT (bitarray) with all bits set to false. Note: bt has size lnk_max, not nln_max!
1389: */
1390: static inline PetscErrorCode PetscLLCondensedCreate(PetscInt nlnk_max, PetscInt lnk_max, PetscInt **lnk, PetscBT *bt)
1391: {
1392:   PetscInt *llnk, lsize = 0;

1394:   PetscFunctionBegin;
1395:   PetscCall(PetscIntMultError(2, nlnk_max + 2, &lsize));
1396:   PetscCall(PetscMalloc1(lsize, lnk));
1397:   PetscCall(PetscBTCreate(lnk_max, bt));
1398:   llnk    = *lnk;
1399:   llnk[0] = 0;       /* number of entries on the list */
1400:   llnk[2] = lnk_max; /* value in the head node */
1401:   llnk[3] = 2;       /* next for the head node */
1402:   PetscFunctionReturn(PETSC_SUCCESS);
1403: }

1405: /*
1406:   Add a SORTED ascending index set into a sorted linked list. See PetscLLCondensedCreate() for detailed description.
1407:   Input Parameters:
1408:     nidx      - number of input indices
1409:     indices   - sorted integer array
1410:     lnk       - condensed linked list(an integer array) that is created
1411:     bt        - PetscBT (bitarray), bt[idx]=true marks idx is in lnk
1412:   output Parameters:
1413:     lnk       - the sorted(increasing order) linked list containing previous and newly added non-redundate indices
1414:     bt        - updated PetscBT (bitarray)
1415: */
1416: static inline PetscErrorCode PetscLLCondensedAddSorted(PetscInt nidx, const PetscInt indices[], PetscInt lnk[], PetscBT bt)
1417: {
1418:   PetscInt location = 2;      /* head */
1419:   PetscInt nlnk     = lnk[0]; /* num of entries on the input lnk */

1421:   PetscFunctionBegin;
1422:   for (PetscInt k = 0; k < nidx; k++) {
1423:     const PetscInt entry = indices[k];
1424:     if (!PetscBTLookupSet(bt, entry)) { /* new entry */
1425:       PetscInt next, lnkdata;

1427:       /* search for insertion location */
1428:       do {
1429:         next     = location + 1;  /* link from previous node to next node */
1430:         location = lnk[next];     /* idx of next node */
1431:         lnkdata  = lnk[location]; /* value of next node */
1432:       } while (entry > lnkdata);
1433:       /* insertion location is found, add entry into lnk */
1434:       const PetscInt newnode = 2 * (nlnk + 2); /* index for this new node */
1435:       lnk[next]              = newnode;        /* connect previous node to the new node */
1436:       lnk[newnode]           = entry;          /* set value of the new node */
1437:       lnk[newnode + 1]       = location;       /* connect new node to next node */
1438:       location               = newnode;        /* next search starts from the new node */
1439:       nlnk++;
1440:     }
1441:   }
1442:   lnk[0] = nlnk; /* number of entries in the list */
1443:   PetscFunctionReturn(PETSC_SUCCESS);
1444: }

1446: static inline PetscErrorCode PetscLLCondensedClean(PetscInt lnk_max, PETSC_UNUSED PetscInt nidx, PetscInt *indices, PetscInt lnk[], PetscBT bt)
1447: {
1448:   const PetscInt nlnk = lnk[0]; /* num of entries on the list */
1449:   PetscInt       next = lnk[3]; /* head node */

1451:   PetscFunctionBegin;
1452:   for (PetscInt k = 0; k < nlnk; k++) {
1453:     indices[k] = lnk[next];
1454:     next       = lnk[next + 1];
1455:     PetscCall(PetscBTClear(bt, indices[k]));
1456:   }
1457:   lnk[0] = 0;       /* num of entries on the list */
1458:   lnk[2] = lnk_max; /* initialize head node */
1459:   lnk[3] = 2;       /* head node */
1460:   PetscFunctionReturn(PETSC_SUCCESS);
1461: }

1463: static inline PetscErrorCode PetscLLCondensedView(PetscInt *lnk)
1464: {
1465:   PetscFunctionBegin;
1466:   PetscCall(PetscPrintf(PETSC_COMM_SELF, "LLCondensed of size %" PetscInt_FMT ", (val,  next)\n", lnk[0]));
1467:   for (PetscInt k = 2; k < lnk[0] + 2; ++k) PetscCall(PetscPrintf(PETSC_COMM_SELF, " %" PetscInt_FMT ": (%" PetscInt_FMT ", %" PetscInt_FMT ")\n", 2 * k, lnk[2 * k], lnk[2 * k + 1]));
1468:   PetscFunctionReturn(PETSC_SUCCESS);
1469: }

1471: /*
1472:   Free memories used by the list
1473: */
1474: static inline PetscErrorCode PetscLLCondensedDestroy(PetscInt *lnk, PetscBT bt)
1475: {
1476:   PetscFunctionBegin;
1477:   PetscCall(PetscFree(lnk));
1478:   PetscCall(PetscBTDestroy(&bt));
1479:   PetscFunctionReturn(PETSC_SUCCESS);
1480: }

1482: /*
1483:  Same as PetscLLCondensedCreate(), but does not use non-scalable O(lnk_max) bitarray
1484:   Input Parameters:
1485:     nlnk_max  - max length of the list
1486:   Output Parameters:
1487:     lnk       - list created and initialized
1488: */
1489: static inline PetscErrorCode PetscLLCondensedCreate_Scalable(PetscInt nlnk_max, PetscInt **lnk)
1490: {
1491:   PetscInt *llnk, lsize = 0;

1493:   PetscFunctionBegin;
1494:   PetscCall(PetscIntMultError(2, nlnk_max + 2, &lsize));
1495:   PetscCall(PetscMalloc1(lsize, lnk));
1496:   llnk    = *lnk;
1497:   llnk[0] = 0;             /* number of entries on the list */
1498:   llnk[2] = PETSC_INT_MAX; /* value in the head node */
1499:   llnk[3] = 2;             /* next for the head node */
1500:   PetscFunctionReturn(PETSC_SUCCESS);
1501: }

1503: static inline PetscErrorCode PetscLLCondensedExpand_Scalable(PetscInt nlnk_max, PetscInt **lnk)
1504: {
1505:   PetscInt lsize = 0;

1507:   PetscFunctionBegin;
1508:   PetscCall(PetscIntMultError(2, nlnk_max + 2, &lsize));
1509:   PetscCall(PetscRealloc((size_t)lsize * sizeof(PetscInt), lnk));
1510:   PetscFunctionReturn(PETSC_SUCCESS);
1511: }

1513: static inline PetscErrorCode PetscLLCondensedAddSorted_Scalable(PetscInt nidx, const PetscInt indices[], PetscInt lnk[])
1514: {
1515:   PetscInt location = 2;      /* head */
1516:   PetscInt nlnk     = lnk[0]; /* num of entries on the input lnk */

1518:   for (PetscInt k = 0; k < nidx; k++) {
1519:     const PetscInt entry = indices[k];
1520:     PetscInt       next, lnkdata;

1522:     /* search for insertion location */
1523:     do {
1524:       next     = location + 1;  /* link from previous node to next node */
1525:       location = lnk[next];     /* idx of next node */
1526:       lnkdata  = lnk[location]; /* value of next node */
1527:     } while (entry > lnkdata);
1528:     if (entry < lnkdata) {
1529:       /* insertion location is found, add entry into lnk */
1530:       const PetscInt newnode = 2 * (nlnk + 2); /* index for this new node */
1531:       lnk[next]              = newnode;        /* connect previous node to the new node */
1532:       lnk[newnode]           = entry;          /* set value of the new node */
1533:       lnk[newnode + 1]       = location;       /* connect new node to next node */
1534:       location               = newnode;        /* next search starts from the new node */
1535:       nlnk++;
1536:     }
1537:   }
1538:   lnk[0] = nlnk; /* number of entries in the list */
1539:   return PETSC_SUCCESS;
1540: }

1542: static inline PetscErrorCode PetscLLCondensedClean_Scalable(PETSC_UNUSED PetscInt nidx, PetscInt *indices, PetscInt *lnk)
1543: {
1544:   const PetscInt nlnk = lnk[0];
1545:   PetscInt       next = lnk[3]; /* head node */

1547:   for (PetscInt k = 0; k < nlnk; k++) {
1548:     indices[k] = lnk[next];
1549:     next       = lnk[next + 1];
1550:   }
1551:   lnk[0] = 0; /* num of entries on the list */
1552:   lnk[3] = 2; /* head node */
1553:   return PETSC_SUCCESS;
1554: }

1556: static inline PetscErrorCode PetscLLCondensedDestroy_Scalable(PetscInt *lnk)
1557: {
1558:   return PetscFree(lnk);
1559: }

1561: /*
1562:       lnk[0]   number of links
1563:       lnk[1]   number of entries
1564:       lnk[3n]  value
1565:       lnk[3n+1] len
1566:       lnk[3n+2] link to next value

1568:       The next three are always the first link

1570:       lnk[3]    PETSC_INT_MIN+1
1571:       lnk[4]    1
1572:       lnk[5]    link to first real entry

1574:       The next three are always the last link

1576:       lnk[6]    PETSC_INT_MAX - 1
1577:       lnk[7]    1
1578:       lnk[8]    next valid link (this is the same as lnk[0] but without the decreases)
1579: */

1581: static inline PetscErrorCode PetscLLCondensedCreate_fast(PetscInt nlnk_max, PetscInt **lnk)
1582: {
1583:   PetscInt *llnk;
1584:   PetscInt  lsize = 0;

1586:   PetscFunctionBegin;
1587:   PetscCall(PetscIntMultError(3, nlnk_max + 3, &lsize));
1588:   PetscCall(PetscMalloc1(lsize, lnk));
1589:   llnk    = *lnk;
1590:   llnk[0] = 0;                 /* nlnk: number of entries on the list */
1591:   llnk[1] = 0;                 /* number of integer entries represented in list */
1592:   llnk[3] = PETSC_INT_MIN + 1; /* value in the first node */
1593:   llnk[4] = 1;                 /* count for the first node */
1594:   llnk[5] = 6;                 /* next for the first node */
1595:   llnk[6] = PETSC_INT_MAX - 1; /* value in the last node */
1596:   llnk[7] = 1;                 /* count for the last node */
1597:   llnk[8] = 0;                 /* next valid node to be used */
1598:   PetscFunctionReturn(PETSC_SUCCESS);
1599: }

1601: static inline PetscErrorCode PetscLLCondensedAddSorted_fast(PetscInt nidx, const PetscInt indices[], PetscInt lnk[])
1602: {
1603:   for (PetscInt k = 0, prev = 3 /* first value */; k < nidx; k++) {
1604:     const PetscInt entry = indices[k];
1605:     PetscInt       next  = lnk[prev + 2];

1607:     /* search for insertion location */
1608:     while (entry >= lnk[next]) {
1609:       prev = next;
1610:       next = lnk[next + 2];
1611:     }
1612:     /* entry is in range of previous list */
1613:     if (entry < lnk[prev] + lnk[prev + 1]) continue;
1614:     lnk[1]++;
1615:     /* entry is right after previous list */
1616:     if (entry == lnk[prev] + lnk[prev + 1]) {
1617:       lnk[prev + 1]++;
1618:       if (lnk[next] == entry + 1) { /* combine two contiguous strings */
1619:         lnk[prev + 1] += lnk[next + 1];
1620:         lnk[prev + 2] = lnk[next + 2];
1621:         lnk[0]--;
1622:       }
1623:       continue;
1624:     }
1625:     /* entry is right before next list */
1626:     if (entry == lnk[next] - 1) {
1627:       lnk[next]--;
1628:       lnk[next + 1]++;
1629:       prev = next;
1630:       continue;
1631:     }
1632:     /*  add entry into lnk */
1633:     lnk[prev + 2] = 3 * ((lnk[8]++) + 3); /* connect previous node to the new node */
1634:     prev          = lnk[prev + 2];
1635:     lnk[prev]     = entry; /* set value of the new node */
1636:     lnk[prev + 1] = 1;     /* number of values in contiguous string is one to start */
1637:     lnk[prev + 2] = next;  /* connect new node to next node */
1638:     lnk[0]++;
1639:   }
1640:   return PETSC_SUCCESS;
1641: }

1643: static inline PetscErrorCode PetscLLCondensedClean_fast(PETSC_UNUSED PetscInt nidx, PetscInt *indices, PetscInt *lnk)
1644: {
1645:   const PetscInt nlnk = lnk[0];
1646:   PetscInt       next = lnk[5]; /* first node */

1648:   for (PetscInt k = 0, cnt = 0; k < nlnk; k++) {
1649:     for (PetscInt j = 0; j < lnk[next + 1]; j++) indices[cnt++] = lnk[next] + j;
1650:     next = lnk[next + 2];
1651:   }
1652:   lnk[0] = 0;                 /* nlnk: number of links */
1653:   lnk[1] = 0;                 /* number of integer entries represented in list */
1654:   lnk[3] = PETSC_INT_MIN + 1; /* value in the first node */
1655:   lnk[4] = 1;                 /* count for the first node */
1656:   lnk[5] = 6;                 /* next for the first node */
1657:   lnk[6] = PETSC_INT_MAX - 1; /* value in the last node */
1658:   lnk[7] = 1;                 /* count for the last node */
1659:   lnk[8] = 0;                 /* next valid location to make link */
1660:   return PETSC_SUCCESS;
1661: }

1663: static inline PetscErrorCode PetscLLCondensedView_fast(const PetscInt *lnk)
1664: {
1665:   const PetscInt nlnk = lnk[0];
1666:   PetscInt       next = lnk[5]; /* first node */

1668:   for (PetscInt k = 0; k < nlnk; k++) {
1669: #if 0 /* Debugging code */
1670:     printf("%d value %d len %d next %d\n", next, lnk[next], lnk[next + 1], lnk[next + 2]);
1671: #endif
1672:     next = lnk[next + 2];
1673:   }
1674:   return PETSC_SUCCESS;
1675: }

1677: static inline PetscErrorCode PetscLLCondensedDestroy_fast(PetscInt *lnk)
1678: {
1679:   return PetscFree(lnk);
1680: }

1682: PETSC_EXTERN PetscErrorCode PetscCDCreate(PetscInt, PetscCoarsenData **);
1683: PETSC_EXTERN PetscErrorCode PetscCDDestroy(PetscCoarsenData *);
1684: PETSC_EXTERN PetscErrorCode PetscCDIntNdSetID(PetscCDIntNd *, PetscInt);
1685: PETSC_EXTERN PetscErrorCode PetscCDIntNdGetID(const PetscCDIntNd *, PetscInt *);
1686: PETSC_EXTERN PetscErrorCode PetscCDAppendID(PetscCoarsenData *, PetscInt, PetscInt);
1687: PETSC_EXTERN PetscErrorCode PetscCDMoveAppend(PetscCoarsenData *, PetscInt, PetscInt);
1688: PETSC_EXTERN PetscErrorCode PetscCDAppendNode(PetscCoarsenData *, PetscInt, PetscCDIntNd *);
1689: PETSC_EXTERN PetscErrorCode PetscCDRemoveNextNode(PetscCoarsenData *, PetscInt, PetscCDIntNd *);
1690: PETSC_EXTERN PetscErrorCode PetscCDCountAt(const PetscCoarsenData *, PetscInt, PetscInt *);
1691: PETSC_EXTERN PetscErrorCode PetscCDIsEmptyAt(const PetscCoarsenData *, PetscInt, PetscBool *);
1692: PETSC_EXTERN PetscErrorCode PetscCDSetChunkSize(PetscCoarsenData *, PetscInt);
1693: PETSC_EXTERN PetscErrorCode PetscCDPrint(const PetscCoarsenData *, PetscInt, MPI_Comm);
1694: PETSC_EXTERN PetscErrorCode PetscCDGetNonemptyIS(PetscCoarsenData *, IS *);
1695: PETSC_EXTERN PetscErrorCode PetscCDGetMat(PetscCoarsenData *, Mat *);
1696: PETSC_EXTERN PetscErrorCode PetscCDSetMat(PetscCoarsenData *, Mat);
1697: PETSC_EXTERN PetscErrorCode PetscCDClearMat(PetscCoarsenData *);
1698: PETSC_EXTERN PetscErrorCode PetscCDRemoveAllAt(PetscCoarsenData *, PetscInt);
1699: PETSC_EXTERN PetscErrorCode PetscCDCount(const PetscCoarsenData *, PetscInt *_sz);

1701: PETSC_EXTERN PetscErrorCode PetscCDGetHeadPos(const PetscCoarsenData *, PetscInt, PetscCDIntNd **);
1702: PETSC_EXTERN PetscErrorCode PetscCDGetNextPos(const PetscCoarsenData *, PetscInt, PetscCDIntNd **);
1703: PETSC_EXTERN PetscErrorCode PetscCDGetASMBlocks(const PetscCoarsenData *, const PetscInt, PetscInt *, IS **);

1705: PETSC_SINGLE_LIBRARY_VISIBILITY_INTERNAL PetscErrorCode MatFDColoringApply_AIJ(Mat, MatFDColoring, Vec, void *);

1707: typedef struct {
1708:   Vec              diag;
1709:   PetscBool        diag_valid;
1710:   Vec              inv_diag;
1711:   PetscBool        inv_diag_valid;
1712:   PetscObjectState diag_state, inv_diag_state;
1713:   PetscInt        *col;
1714:   PetscScalar     *val;
1715: } Mat_Diagonal;

1717: #if PetscDefined(HAVE_CUDA)
1718: PETSC_INTERN PetscErrorCode MatADot_Diagonal_SeqCUDA(Mat, Vec, Vec, PetscScalar *);
1719: PETSC_INTERN PetscErrorCode MatANormSq_Diagonal_SeqCUDA(Mat, Vec, PetscReal *);
1720: #endif
1721: #if PetscDefined(HAVE_HIP)
1722: PETSC_INTERN PetscErrorCode MatADot_Diagonal_SeqHIP(Mat, Vec, Vec, PetscScalar *);
1723: PETSC_INTERN PetscErrorCode MatANormSq_Diagonal_SeqHIP(Mat, Vec, PetscReal *);
1724: #endif
1725: #if PetscDefined(HAVE_KOKKOS_KERNELS)
1726: PETSC_INTERN PetscErrorCode MatADot_Diagonal_SeqKokkos(Mat, Vec, Vec, PetscScalar *);
1727: PETSC_INTERN PetscErrorCode MatANormSq_Diagonal_SeqKokkos(Mat, Vec, PetscReal *);
1728: #endif

1730: PETSC_EXTERN PetscLogEvent MAT_Mult;
1731: PETSC_EXTERN PetscLogEvent MAT_MultAdd;
1732: PETSC_EXTERN PetscLogEvent MAT_MultTranspose;
1733: PETSC_EXTERN PetscLogEvent MAT_MultHermitianTranspose;
1734: PETSC_EXTERN PetscLogEvent MAT_MultTransposeAdd;
1735: PETSC_EXTERN PetscLogEvent MAT_MultHermitianTransposeAdd;
1736: PETSC_EXTERN PetscLogEvent MAT_ADot;
1737: PETSC_EXTERN PetscLogEvent MAT_ANorm;
1738: PETSC_EXTERN PetscLogEvent MAT_Solve;
1739: PETSC_EXTERN PetscLogEvent MAT_Solves;
1740: PETSC_EXTERN PetscLogEvent MAT_SolveAdd;
1741: PETSC_EXTERN PetscLogEvent MAT_SolveTranspose;
1742: PETSC_EXTERN PetscLogEvent MAT_SolveTransposeAdd;
1743: PETSC_EXTERN PetscLogEvent MAT_SOR;
1744: PETSC_EXTERN PetscLogEvent MAT_ForwardSolve;
1745: PETSC_EXTERN PetscLogEvent MAT_BackwardSolve;
1746: PETSC_EXTERN PetscLogEvent MAT_LUFactor;
1747: PETSC_EXTERN PetscLogEvent MAT_LUFactorSymbolic;
1748: PETSC_EXTERN PetscLogEvent MAT_LUFactorNumeric;
1749: PETSC_EXTERN PetscLogEvent MAT_QRFactor;
1750: PETSC_EXTERN PetscLogEvent MAT_QRFactorSymbolic;
1751: PETSC_EXTERN PetscLogEvent MAT_QRFactorNumeric;
1752: PETSC_EXTERN PetscLogEvent MAT_CholeskyFactor;
1753: PETSC_EXTERN PetscLogEvent MAT_CholeskyFactorSymbolic;
1754: PETSC_EXTERN PetscLogEvent MAT_CholeskyFactorNumeric;
1755: PETSC_EXTERN PetscLogEvent MAT_ILUFactor;
1756: PETSC_EXTERN PetscLogEvent MAT_ILUFactorSymbolic;
1757: PETSC_EXTERN PetscLogEvent MAT_ICCFactorSymbolic;
1758: PETSC_EXTERN PetscLogEvent MAT_Copy;
1759: PETSC_EXTERN PetscLogEvent MAT_Convert;
1760: PETSC_EXTERN PetscLogEvent MAT_Scale;
1761: PETSC_EXTERN PetscLogEvent MAT_AssemblyBegin;
1762: PETSC_EXTERN PetscLogEvent MAT_AssemblyEnd;
1763: PETSC_EXTERN PetscLogEvent MAT_SetValues;
1764: PETSC_EXTERN PetscLogEvent MAT_GetValues;
1765: PETSC_EXTERN PetscLogEvent MAT_GetRow;
1766: PETSC_EXTERN PetscLogEvent MAT_GetRowIJ;
1767: PETSC_EXTERN PetscLogEvent MAT_CreateSubMats;
1768: PETSC_EXTERN PetscLogEvent MAT_GetOrdering;
1769: PETSC_EXTERN PetscLogEvent MAT_RedundantMat;
1770: PETSC_EXTERN PetscLogEvent MAT_IncreaseOverlap;
1771: PETSC_EXTERN PetscLogEvent MAT_Partitioning;
1772: PETSC_EXTERN PetscLogEvent MAT_PartitioningND;
1773: PETSC_EXTERN PetscLogEvent MAT_Coarsen;
1774: PETSC_EXTERN PetscLogEvent MAT_ZeroEntries;
1775: PETSC_EXTERN PetscLogEvent MAT_Load;
1776: PETSC_EXTERN PetscLogEvent MAT_View;
1777: PETSC_EXTERN PetscLogEvent MAT_AXPY;
1778: PETSC_EXTERN PetscLogEvent MAT_FDColoringCreate;
1779: PETSC_EXTERN PetscLogEvent MAT_TransposeColoringCreate;
1780: PETSC_EXTERN PetscLogEvent MAT_FDColoringSetUp;
1781: PETSC_EXTERN PetscLogEvent MAT_FDColoringApply;
1782: PETSC_EXTERN PetscLogEvent MAT_Transpose;
1783: PETSC_EXTERN PetscLogEvent MAT_FDColoringFunction;
1784: PETSC_EXTERN PetscLogEvent MAT_CreateSubMat;
1785: PETSC_EXTERN PetscLogEvent MAT_MatSolve;
1786: PETSC_EXTERN PetscLogEvent MAT_MatTrSolve;
1787: PETSC_EXTERN PetscLogEvent MAT_MatMultSymbolic;
1788: PETSC_EXTERN PetscLogEvent MAT_MatMultNumeric;
1789: PETSC_EXTERN PetscLogEvent MAT_Getlocalmatcondensed;
1790: PETSC_EXTERN PetscLogEvent MAT_GetBrowsOfAcols;
1791: PETSC_EXTERN PetscLogEvent MAT_GetBrowsOfAocols;
1792: PETSC_EXTERN PetscLogEvent MAT_PtAPSymbolic;
1793: PETSC_EXTERN PetscLogEvent MAT_PtAPNumeric;
1794: PETSC_EXTERN PetscLogEvent MAT_Seqstompinum;
1795: PETSC_EXTERN PetscLogEvent MAT_Seqstompisym;
1796: PETSC_EXTERN PetscLogEvent MAT_Seqstompi;
1797: PETSC_EXTERN PetscLogEvent MAT_Getlocalmat;
1798: PETSC_EXTERN PetscLogEvent MAT_RARtSymbolic;
1799: PETSC_EXTERN PetscLogEvent MAT_RARtNumeric;
1800: PETSC_EXTERN PetscLogEvent MAT_MatTransposeMultSymbolic;
1801: PETSC_EXTERN PetscLogEvent MAT_MatTransposeMultNumeric;
1802: PETSC_EXTERN PetscLogEvent MAT_TransposeMatMultSymbolic;
1803: PETSC_EXTERN PetscLogEvent MAT_TransposeMatMultNumeric;
1804: PETSC_EXTERN PetscLogEvent MAT_MatMatMultSymbolic;
1805: PETSC_EXTERN PetscLogEvent MAT_MatMatMultNumeric;
1806: PETSC_EXTERN PetscLogEvent MAT_Getsymtransreduced;
1807: PETSC_EXTERN PetscLogEvent MAT_GetSeqNonzeroStructure;
1808: PETSC_EXTERN PetscLogEvent MATMFFD_Mult;
1809: PETSC_EXTERN PetscLogEvent MAT_GetMultiProcBlock;
1810: PETSC_EXTERN PetscLogEvent MAT_CUSPARSECopyToGPU;
1811: PETSC_EXTERN PetscLogEvent MAT_CUSPARSECopyFromGPU;
1812: PETSC_EXTERN PetscLogEvent MAT_CUSPARSEGenerateTranspose;
1813: PETSC_EXTERN PetscLogEvent MAT_CUSPARSESolveAnalysis;
1814: PETSC_EXTERN PetscLogEvent MAT_HIPSPARSECopyToGPU;
1815: PETSC_EXTERN PetscLogEvent MAT_HIPSPARSECopyFromGPU;
1816: PETSC_EXTERN PetscLogEvent MAT_HIPSPARSEGenerateTranspose;
1817: PETSC_EXTERN PetscLogEvent MAT_HIPSPARSESolveAnalysis;
1818: PETSC_EXTERN PetscLogEvent MAT_SetValuesBatch;
1819: PETSC_EXTERN PetscLogEvent MAT_CreateGraph;
1820: PETSC_EXTERN PetscLogEvent MAT_ViennaCLCopyToGPU;
1821: PETSC_EXTERN PetscLogEvent MAT_DenseCopyToGPU;
1822: PETSC_EXTERN PetscLogEvent MAT_DenseCopyFromGPU;
1823: PETSC_EXTERN PetscLogEvent MAT_Merge;
1824: PETSC_EXTERN PetscLogEvent MAT_Residual;
1825: PETSC_EXTERN PetscLogEvent MAT_SetRandom;
1826: PETSC_EXTERN PetscLogEvent MAT_FactorFactS;
1827: PETSC_EXTERN PetscLogEvent MAT_FactorInvS;
1828: PETSC_EXTERN PetscLogEvent MAT_PreallCOO;
1829: PETSC_EXTERN PetscLogEvent MAT_SetVCOO;
1830: PETSC_EXTERN PetscLogEvent MATCOLORING_Apply;
1831: PETSC_EXTERN PetscLogEvent MATCOLORING_Comm;
1832: PETSC_EXTERN PetscLogEvent MATCOLORING_Local;
1833: PETSC_EXTERN PetscLogEvent MATCOLORING_ISCreate;
1834: PETSC_EXTERN PetscLogEvent MATCOLORING_SetUp;
1835: PETSC_EXTERN PetscLogEvent MATCOLORING_Weights;
1836: PETSC_EXTERN PetscLogEvent MAT_H2Opus_Build;
1837: PETSC_EXTERN PetscLogEvent MAT_H2Opus_Compress;
1838: PETSC_EXTERN PetscLogEvent MAT_H2Opus_Orthog;
1839: PETSC_EXTERN PetscLogEvent MAT_H2Opus_LR;
1840: PETSC_EXTERN PetscLogEvent MAT_CUDACopyToGPU;
1841: PETSC_EXTERN PetscLogEvent MAT_HIPCopyToGPU;

1843: #if PetscDefined(CLANG_STATIC_ANALYZER)
1844:   #define MatGetDiagonalMarkers(SeqXXX, bs)
1845: #else
1846:   /*
1847:    Adds diagonal pointers to sparse matrix nonzero structure and determines if all diagonal entries are present

1849:    Rechecks the matrix data structure automatically if the nonzero structure of the matrix changed since the last call

1851:    Potential optimization: since the a->j[j] are sorted this could use bisection to find the diagonal

1853:    Developer Note:
1854:    Uses the C preprocessor as a template mechanism to produce MatGetDiagonal_Seq[SB]AIJ() to avoid duplicate code
1855: */
1856:   #define MatGetDiagonalMarkers(SeqXXX, bs) \
1857:     PetscErrorCode MatGetDiagonalMarkers_##SeqXXX(Mat A, const PetscInt *diag[], PetscBool *diagDense) \
1858:     { \
1859:       Mat_##SeqXXX *a = (Mat_##SeqXXX *)A->data; \
1860: \
1861:       PetscFunctionBegin; \
1862:       if (A->factortype != MAT_FACTOR_NONE) { \
1863:         if (diagDense) *diagDense = PETSC_TRUE; \
1864:         if (diag) *diag = a->diag; \
1865:         PetscFunctionReturn(PETSC_SUCCESS); \
1866:       } \
1867:       PetscCheck(diag != NULL || diagDense != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "At least one of diag or diagDense must be requested"); \
1868:       if (a->diagNonzeroState != A->nonzerostate || (diag != NULL && a->diag == NULL)) { \
1869:         const PetscInt m = A->rmap->n / (bs); \
1870: \
1871:         if (diag == NULL && a->diag == NULL) { \
1872:           a->diagDense = PETSC_TRUE; \
1873:           for (PetscInt i = 0; i < m; i++) { \
1874:             PetscBool found = PETSC_FALSE; \
1875: \
1876:             for (PetscInt j = a->i[i]; j < a->i[i + 1]; j++) { \
1877:               if (a->j[j] == i) { \
1878:                 found = PETSC_TRUE; \
1879:                 break; \
1880:               } \
1881:             } \
1882:             if (!found) { \
1883:               a->diagDense        = PETSC_FALSE; \
1884:               *diagDense          = a->diagDense; \
1885:               a->diagNonzeroState = A->nonzerostate; \
1886:               PetscFunctionReturn(PETSC_SUCCESS); \
1887:             } \
1888:           } \
1889:         } else { \
1890:           if (a->diag == NULL) PetscCall(PetscMalloc1(m, &a->diag)); \
1891:           a->diagDense = PETSC_TRUE; \
1892:           for (PetscInt i = 0; i < m; i++) { \
1893:             PetscBool found = PETSC_FALSE; \
1894: \
1895:             a->diag[i] = a->i[i + 1]; \
1896:             for (PetscInt j = a->i[i]; j < a->i[i + 1]; j++) { \
1897:               if (a->j[j] == i) { \
1898:                 a->diag[i] = j; \
1899:                 found      = PETSC_TRUE; \
1900:                 break; \
1901:               } \
1902:             } \
1903:             if (!found) a->diagDense = PETSC_FALSE; \
1904:           } \
1905:         } \
1906:         a->diagNonzeroState = A->nonzerostate; \
1907:       } \
1908:       if (diag) *diag = a->diag; \
1909:       if (diagDense) *diagDense = a->diagDense; \
1910:       PetscFunctionReturn(PETSC_SUCCESS); \
1911:     }
1912: #endif