17f296bb3SBarry Smith(ch_matrices)= 27f296bb3SBarry Smith 37f296bb3SBarry Smith# Matrices 47f296bb3SBarry Smith 57f296bb3SBarry SmithPETSc provides a variety of matrix implementations because no single 67f296bb3SBarry Smithmatrix format is appropriate for all problems. Currently, we support 77f296bb3SBarry Smithdense storage and compressed sparse row storage (both sequential and 87f296bb3SBarry Smithparallel versions) for CPU and GPU based matrices, as well as several specialized formats. Additional 97f296bb3SBarry Smithspecialized formats can be easily added. 107f296bb3SBarry Smith 117f296bb3SBarry SmithThis chapter describes the basics of using PETSc matrices in general 127f296bb3SBarry Smith(regardless of the particular format chosen) and discusses tips for 137f296bb3SBarry Smithefficient use of the several simple uniprocess and parallel matrix 147f296bb3SBarry Smithtypes. The use of PETSc matrices involves the following actions: create 157f296bb3SBarry Smitha particular type of matrix, insert values into it, process the matrix, 167f296bb3SBarry Smithuse the matrix for various computations, and finally destroy the matrix. 177f296bb3SBarry SmithThe application code does not need to know or care about the particular 187f296bb3SBarry Smithstorage formats of the matrices. 197f296bb3SBarry Smith 207f296bb3SBarry Smith(sec_matcreate)= 217f296bb3SBarry Smith 227f296bb3SBarry Smith## Creating matrices 237f296bb3SBarry Smith 247f296bb3SBarry SmithAs with vectors, PETSc has APIs that allow the user to specify the exact details of the matrix 257f296bb3SBarry Smithcreation process but also `DM` based creation routines that handle most of the details automatically 267f296bb3SBarry Smithfor specific families of applications. This is done with 277f296bb3SBarry Smith 287f296bb3SBarry Smith``` 297f296bb3SBarry SmithDMCreateMatrix(DM dm,Mat *A) 307f296bb3SBarry Smith``` 317f296bb3SBarry Smith 327f296bb3SBarry SmithThe type of matrix created can be controlled with either 337f296bb3SBarry Smith 347f296bb3SBarry Smith``` 357f296bb3SBarry SmithDMSetMatType(DM dm,MatType <MATAIJ or MATBAIJ or MATAIJCUSPARSE etc>) 367f296bb3SBarry Smith``` 377f296bb3SBarry Smith 387f296bb3SBarry Smithor with 397f296bb3SBarry Smith 407f296bb3SBarry Smith``` 417f296bb3SBarry SmithDMSetFromOptions(DM dm) 427f296bb3SBarry Smith``` 437f296bb3SBarry Smith 447f296bb3SBarry Smithand the options database option `-dm_mat_type <aij or baij or aijcusparse etc>` Matrices can be created for CPU usage, for GPU usage and for usage on 457f296bb3SBarry Smithboth the CPUs and GPUs. 467f296bb3SBarry Smith 477f296bb3SBarry SmithThe creation of `DM` objects is discussed in {any}`sec_struct`, {any}`sec_unstruct`, {any}`sec_network`. 487f296bb3SBarry Smith 497f296bb3SBarry Smith## Low-level matrix creation routines 507f296bb3SBarry Smith 517f296bb3SBarry SmithWhen using a `DM` is not practical for a particular application one can create matrices directly 527f296bb3SBarry Smithusing 537f296bb3SBarry Smith 547f296bb3SBarry Smith``` 557f296bb3SBarry SmithMatCreate(MPI_Comm comm,Mat *A) 567f296bb3SBarry SmithMatSetSizes(Mat A,PetscInt m,PetscInt n,PetscInt M,PetscInt N) 577f296bb3SBarry Smith``` 587f296bb3SBarry Smith 597f296bb3SBarry SmithThis routine generates a sequential matrix when running one process and 607f296bb3SBarry Smitha parallel matrix for two or more processes; the particular matrix 617f296bb3SBarry Smithformat is set by the user via options database commands. The user 627f296bb3SBarry Smithspecifies either the global matrix dimensions, given by `M` and `N` 637f296bb3SBarry Smithor the local dimensions, given by `m` and `n` while PETSc completely 647f296bb3SBarry Smithcontrols memory allocation. This routine facilitates switching among 657f296bb3SBarry Smithvarious matrix types, for example, to determine the format that is most 667f296bb3SBarry Smithefficient for a certain application. By default, `MatCreate()` employs 677f296bb3SBarry Smiththe sparse AIJ format, which is discussed in detail in 687f296bb3SBarry Smith{any}`sec_matsparse`. See the manual pages for further 697f296bb3SBarry Smithinformation about available matrix formats. 707f296bb3SBarry Smith 717f296bb3SBarry Smith## Assembling (putting values into) matrices 727f296bb3SBarry Smith 737f296bb3SBarry SmithTo insert or add entries to a matrix on CPUs, one can call a variant of 747f296bb3SBarry Smith`MatSetValues()`, either 757f296bb3SBarry Smith 767f296bb3SBarry Smith``` 777f296bb3SBarry SmithMatSetValues(Mat A,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar values[],INSERT_VALUES); 787f296bb3SBarry Smith``` 797f296bb3SBarry Smith 807f296bb3SBarry Smithor 817f296bb3SBarry Smith 827f296bb3SBarry Smith``` 837f296bb3SBarry SmithMatSetValues(Mat A,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar values[],ADD_VALUES); 847f296bb3SBarry Smith``` 857f296bb3SBarry Smith 867f296bb3SBarry SmithThis routine inserts or adds a logically dense subblock of dimension 877f296bb3SBarry Smith`m*n` into the matrix. The integer indices `idxm` and `idxn`, 887f296bb3SBarry Smithrespectively, indicate the global row and column numbers to be inserted. 897f296bb3SBarry Smith`MatSetValues()` uses the standard C convention, where the row and 907f296bb3SBarry Smithcolumn matrix indices begin with zero *regardless of the programming language 917f296bb3SBarry Smithemployed*. The array `values` is logically two-dimensional, containing 927f296bb3SBarry Smiththe values that are to be inserted. By default the values are given in 937f296bb3SBarry Smithrow major order, which is the opposite of the Fortran convention, 947f296bb3SBarry Smithmeaning that the value to be put in row `idxm[i]` and column 957f296bb3SBarry Smith`idxn[j]` is located in `values[i*n+j]`. To allow the insertion of 967f296bb3SBarry Smithvalues in column major order, one can call the command 977f296bb3SBarry Smith 987f296bb3SBarry Smith``` 997f296bb3SBarry SmithMatSetOption(Mat A,MAT_ROW_ORIENTED,PETSC_FALSE); 1007f296bb3SBarry Smith``` 1017f296bb3SBarry Smith 1027f296bb3SBarry Smith*Warning*: Several of the sparse implementations do *not* currently 1037f296bb3SBarry Smithsupport the column-oriented option. 1047f296bb3SBarry Smith 1057f296bb3SBarry SmithThis notation should not be a mystery to anyone. For example, to insert 1067f296bb3SBarry Smithone matrix into another when using MATLAB, one uses the command 1077f296bb3SBarry Smith`A(im,in) = B;` where `im` and `in` contain the indices for the 1087f296bb3SBarry Smithrows and columns. This action is identical to the calls above to 1097f296bb3SBarry Smith`MatSetValues()`. 1107f296bb3SBarry Smith 1117f296bb3SBarry SmithWhen using the block compressed sparse row matrix format (`MATSEQBAIJ` 1127f296bb3SBarry Smithor `MATMPIBAIJ`), one can insert elements more efficiently using the 1137f296bb3SBarry Smithblock variant, `MatSetValuesBlocked()` or 1147f296bb3SBarry Smith`MatSetValuesBlockedLocal()`. 1157f296bb3SBarry Smith 1167f296bb3SBarry SmithThe function `MatSetOption()` accepts several other inputs; see the 1177f296bb3SBarry Smithmanual page for details. 1187f296bb3SBarry Smith 1197f296bb3SBarry SmithAfter the matrix elements have been inserted or added into the matrix, 1207f296bb3SBarry Smiththey must be processed (also called “assembled”) before they can be 1217f296bb3SBarry Smithused. The routines for matrix processing are 1227f296bb3SBarry Smith 1237f296bb3SBarry Smith``` 1247f296bb3SBarry SmithMatAssemblyBegin(Mat A,MAT_FINAL_ASSEMBLY); 1257f296bb3SBarry SmithMatAssemblyEnd(Mat A,MAT_FINAL_ASSEMBLY); 1267f296bb3SBarry Smith``` 1277f296bb3SBarry Smith 1287f296bb3SBarry SmithBy placing other code between these two calls, the user can perform 1297f296bb3SBarry Smithcomputations while messages are in transit. Calls to `MatSetValues()` 1307f296bb3SBarry Smithwith the `INSERT_VALUES` and `ADD_VALUES` options *cannot* be mixed 1317f296bb3SBarry Smithwithout intervening calls to the assembly routines. For such 1327f296bb3SBarry Smithintermediate assembly calls the second routine argument typically should 1337f296bb3SBarry Smithbe `MAT_FLUSH_ASSEMBLY`, which omits some of the work of the full 1347f296bb3SBarry Smithassembly process. `MAT_FINAL_ASSEMBLY` is required only in the last 1357f296bb3SBarry Smithmatrix assembly before a matrix is used. 1367f296bb3SBarry Smith 1377f296bb3SBarry SmithEven though one may insert values into PETSc matrices without regard to 1387f296bb3SBarry Smithwhich process eventually stores them, for efficiency reasons we usually 1397f296bb3SBarry Smithrecommend generating most entries on the process where they are destined 1407f296bb3SBarry Smithto be stored. To help the application programmer with this task for 1417f296bb3SBarry Smithmatrices that are distributed across the processes by ranges, the 1427f296bb3SBarry Smithroutine 1437f296bb3SBarry Smith 1447f296bb3SBarry Smith``` 1457f296bb3SBarry SmithMatGetOwnershipRange(Mat A,PetscInt *first_row,PetscInt *last_row); 1467f296bb3SBarry Smith``` 1477f296bb3SBarry Smith 1487f296bb3SBarry Smithinforms the user that all rows from `first_row` to `last_row-1` 1497f296bb3SBarry Smith(since the value returned in `last_row` is one more than the global 1507f296bb3SBarry Smithindex of the last local row) will be stored on the local process. 1517f296bb3SBarry Smith 1527f296bb3SBarry SmithIf the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`. 1537f296bb3SBarry SmithIf the `Mat` was created directly, the range values are determined by the local sizes passed to `MatSetSizes()` or `MatCreateAIJ()` (and such low-level functions for other `MatType`). 1547f296bb3SBarry SmithIf `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`. 1557f296bb3SBarry SmithFor certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine 1567f296bb3SBarry Smiththe local values in the matrix. See {any}`sec_matlayout` for full details on row and column layouts. 1577f296bb3SBarry Smith 1587f296bb3SBarry SmithIn the sparse matrix implementations, once the assembly routines have 1597f296bb3SBarry Smithbeen called, the matrices are compressed and can be used for 1607f296bb3SBarry Smithmatrix-vector multiplication, etc. Any space for preallocated nonzeros 1617f296bb3SBarry Smiththat was not filled by a call to `MatSetValues()` or a related routine 1627f296bb3SBarry Smithis compressed out by assembling with `MAT_FINAL_ASSEMBLY`. If you 1637f296bb3SBarry Smithintend to use that extra space later, be sure to insert explicit zeros 1647f296bb3SBarry Smithbefore assembling with `MAT_FINAL_ASSEMBLY` so the space will not be 1657f296bb3SBarry Smithcompressed out. Once the matrix has been assembled, inserting new values 1667f296bb3SBarry Smithwill be expensive since it will require copies and possible memory 1677f296bb3SBarry Smithallocation. 1687f296bb3SBarry Smith 1697f296bb3SBarry SmithOne may repeatedly assemble matrices that retain the same 1707f296bb3SBarry Smithnonzero pattern (such as within a nonlinear or time-dependent problem). 1717f296bb3SBarry SmithWhere possible, data structures and communication 1727f296bb3SBarry Smithinformation will be reused (instead of regenerated) during successive 1737f296bb3SBarry Smithsteps, thereby increasing efficiency. See 1747f296bb3SBarry Smith<a href="PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/ksp/ksp/tutorials/ex5.c.html">KSP Tutorial ex5</a> 1757f296bb3SBarry Smithfor a simple example of solving two linear systems that use the same 1767f296bb3SBarry Smithmatrix data structure. 1777f296bb3SBarry Smith 1787f296bb3SBarry SmithFor matrices associated with `DMDA` there is a higher-level interface for providing 1797f296bb3SBarry Smiththe numerical values based on the concept of stencils. See the manual page of `MatSetValuesStencil()` for usage. 1807f296bb3SBarry Smith 1817f296bb3SBarry SmithFor GPUs the routines `MatSetPreallocationCOO()` and `MatSetValuesCOO()` should be used for efficient matrix assembly 1827f296bb3SBarry Smithinstead of `MatSetValues()`. 1837f296bb3SBarry Smith 1847f296bb3SBarry SmithWe now introduce the various families of PETSc matrices. `DMCreateMatrix()` manages 1857f296bb3SBarry Smiththe preallocation process (introduced below) automatically so many users do not need to 1867f296bb3SBarry Smithworry about the details of the preallocation process. 1877f296bb3SBarry Smith 1887f296bb3SBarry Smith(sec_matlayout)= 1897f296bb3SBarry Smith 1907f296bb3SBarry Smith### Matrix and Vector Layouts and Storage Locations 1917f296bb3SBarry Smith 1927f296bb3SBarry SmithThe layout of PETSc matrices across MPI ranks is defined by two things 1937f296bb3SBarry Smith 1947f296bb3SBarry Smith- the layout of the two compatible vectors in the computation of the matrix-vector product y = A * x and 1957f296bb3SBarry Smith- the memory where various parts of the matrix are stored across the MPI ranks. 1967f296bb3SBarry Smith 1977f296bb3SBarry SmithPETSc vectors always have a contiguous range of vector entries stored on each MPI rank. The first rank has entries from 0 to `rend1` - 1, the 1987f296bb3SBarry Smithnext rank has entries from `rend1` to `rend2` - 1, etc. Thus the ownership range on each rank is from `rstart` to `rend`, these values can be 1997f296bb3SBarry Smithobtained with `VecGetOwnershipRange`(`Vec` x, `PetscInt` * `rstart`, `PetscInt` * `rend`). Each PETSc `Vec` has a `PetscLayout` object that contains this information. 2007f296bb3SBarry Smith 2017f296bb3SBarry SmithAll PETSc matrices have two `PetscLayout`s, they define the vector layouts for y and x in the product, y = A * x. Their ownership range information 2027f296bb3SBarry Smithcan be obtained with `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRanges()`, and `MatGetOwnershipRangesColumn()`. 2037f296bb3SBarry SmithNote that `MatCreateVecs()` provides two vectors that have compatible layouts for the associated vector. 2047f296bb3SBarry Smith 2057f296bb3SBarry SmithFor most PETSc matrices, excluding `MATELEMENTAL` and `MATSCALAPACK`, the row ownership range obtained with `MatGetOwnershipRange()` also defines 2067f296bb3SBarry Smithwhere the matrix entries are stored; the matrix entries for rows `rstart` to `rend - 1` are stored on the corresponding MPI rank. For other matrices 2077f296bb3SBarry Smiththe rank where each matrix entry is stored is more complicated; information about the storage locations can be obtained with `MatGetOwnershipIS()`. 2087f296bb3SBarry SmithNote that for 2097f296bb3SBarry Smithmost PETSc matrices the values returned by `MatGetOwnershipIS()` are the same as those returned by `MatGetOwnershipRange()` and 2107f296bb3SBarry Smith`MatGetOwnershipRangeColumn()`. 2117f296bb3SBarry Smith 2127f296bb3SBarry SmithThe PETSc object `PetscLayout` contains the ownership information that is provided by `VecGetOwnershipRange()` and with `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`. Each vector has one layout, which can be obtained with `VecGetLayout()` and `MatGetLayouts()`. Layouts support the routines `PetscLayoutGetLocalSize()`, `PetscLayoutGetSize()`, `PetscLayoutGetBlockSize()`, `PetscLayoutGetRanges()`, `PetscLayoutCompare()` as well as a variety of creation routines. These are used by the `Vec` and `Mat` and so are rarely needed directly. Finally `PetscSplitOwnership()` is a utility routine that does the same splitting of ownership ranges as `PetscLayout`. 2137f296bb3SBarry Smith 2147f296bb3SBarry Smith(sec_matsparse)= 2157f296bb3SBarry Smith 2167f296bb3SBarry Smith### Sparse Matrices 2177f296bb3SBarry Smith 2187f296bb3SBarry SmithThe default matrix representation within PETSc is the general sparse AIJ 2197f296bb3SBarry Smithformat (also called the compressed sparse 2207f296bb3SBarry Smithrow format, CSR). This section discusses tips for *efficiently* using 2217f296bb3SBarry Smiththis matrix format for large-scale applications. Additional formats 2227f296bb3SBarry Smith(such as block compressed row and block symmetric storage, which are 2237f296bb3SBarry Smithgenerally much more efficient for problems with multiple degrees of 2247f296bb3SBarry Smithfreedom per node) are discussed below. Beginning users need not concern 2257f296bb3SBarry Smiththemselves initially with such details and may wish to proceed directly 2267f296bb3SBarry Smithto {any}`sec_matoptions`. However, when an application code 2277f296bb3SBarry Smithprogresses to the point of tuning for efficiency and/or generating 2287f296bb3SBarry Smithtiming results, it is *crucial* to read this information. 2297f296bb3SBarry Smith 2307f296bb3SBarry Smith#### Sequential AIJ Sparse Matrices 2317f296bb3SBarry Smith 2327f296bb3SBarry SmithIn the PETSc AIJ matrix formats, we store the nonzero elements by rows, 2337f296bb3SBarry Smithalong with an array of corresponding column numbers and an array of 2347f296bb3SBarry Smithpointers to the beginning of each row. Note that the diagonal matrix 2357f296bb3SBarry Smithentries are stored with the rest of the nonzeros (not separately). 2367f296bb3SBarry Smith 2377f296bb3SBarry SmithTo create a sequential AIJ sparse matrix, `A`, with `m` rows and 2387f296bb3SBarry Smith`n` columns, one uses the command 2397f296bb3SBarry Smith 2407f296bb3SBarry Smith``` 2417f296bb3SBarry SmithMatCreateSeqAIJ(PETSC_COMM_SELF,PetscInt m,PetscInt n,PetscInt nz,PetscInt *nnz,Mat *A); 2427f296bb3SBarry Smith``` 2437f296bb3SBarry Smith 2447f296bb3SBarry Smithwhere `nz` or `nnz` can be used to preallocate matrix memory, as 2457f296bb3SBarry Smithdiscussed below. The user can set `nz=0` and `nnz=NULL` for PETSc to 2467f296bb3SBarry Smithcontrol all matrix memory allocation. 2477f296bb3SBarry Smith 2487f296bb3SBarry SmithThe sequential and parallel AIJ matrix storage formats by default employ 2497f296bb3SBarry Smith*i-nodes* (identical nodes) when possible. We search for consecutive 2507f296bb3SBarry Smithrows with the same nonzero structure, thereby reusing matrix information 2517f296bb3SBarry Smithfor increased efficiency. Related options database keys are 2527f296bb3SBarry Smith`-mat_no_inode` (do not use i-nodes) and `-mat_inode_limit <limit>` 2537f296bb3SBarry Smith(set i-node limit (max limit=5)). Note that problems with a single degree 2547f296bb3SBarry Smithof freedom per grid node will automatically not use i-nodes. 2557f296bb3SBarry Smith 2567f296bb3SBarry SmithThe internal data representation for the AIJ formats employs zero-based 2577f296bb3SBarry Smithindexing. 2587f296bb3SBarry Smith 2597f296bb3SBarry Smith#### Preallocation of Memory for Sequential AIJ Sparse Matrices 2607f296bb3SBarry Smith 2617f296bb3SBarry SmithThe dynamic process of allocating new memory and copying from the old 2627f296bb3SBarry Smithstorage to the new is *intrinsically very expensive*. Thus, to obtain 2637f296bb3SBarry Smithgood performance when assembling an AIJ matrix, it is crucial to 2647f296bb3SBarry Smithpreallocate the memory needed for the sparse matrix. The user has two 2657f296bb3SBarry Smithchoices for preallocating matrix memory via `MatCreateSeqAIJ()`. 2667f296bb3SBarry Smith 2677f296bb3SBarry SmithOne can use the scalar `nz` to specify the expected number of nonzeros 2687f296bb3SBarry Smithfor each row. This is generally fine if the number of nonzeros per row 2697f296bb3SBarry Smithis roughly the same throughout the matrix (or as a quick and easy first 2707f296bb3SBarry Smithstep for preallocation). If one underestimates the actual number of 2717f296bb3SBarry Smithnonzeros in a given row, then during the assembly process PETSc will 2727f296bb3SBarry Smithautomatically allocate additional needed space. However, this extra 2737f296bb3SBarry Smithmemory allocation can slow the computation. 2747f296bb3SBarry Smith 2757f296bb3SBarry SmithIf different rows have very different numbers of nonzeros, one should 2767f296bb3SBarry Smithattempt to indicate (nearly) the exact number of elements intended for 2777f296bb3SBarry Smiththe various rows with the optional array, `nnz` of length `m`, where 2787f296bb3SBarry Smith`m` is the number of rows, for example 2797f296bb3SBarry Smith 2807f296bb3SBarry Smith``` 2817f296bb3SBarry SmithPetscInt nnz[m]; 2827f296bb3SBarry Smithnnz[0] = <nonzeros in row 0> 2837f296bb3SBarry Smithnnz[1] = <nonzeros in row 1> 2847f296bb3SBarry Smith.... 2857f296bb3SBarry Smithnnz[m-1] = <nonzeros in row m-1> 2867f296bb3SBarry Smith``` 2877f296bb3SBarry Smith 2887f296bb3SBarry SmithIn this case, the assembly process will require no additional memory 2897f296bb3SBarry Smithallocations if the `nnz` estimates are correct. If, however, the 2907f296bb3SBarry Smith`nnz` estimates are incorrect, PETSc will automatically obtain the 2917f296bb3SBarry Smithadditional needed space, at a slight loss of efficiency. 2927f296bb3SBarry Smith 2937f296bb3SBarry SmithUsing the array `nnz` to preallocate memory is especially important 2947f296bb3SBarry Smithfor efficient matrix assembly if the number of nonzeros varies 2957f296bb3SBarry Smithconsiderably among the rows. One can generally set `nnz` either by 2967f296bb3SBarry Smithknowing in advance the problem structure (e.g., the stencil for finite 2977f296bb3SBarry Smithdifference problems on a structured grid) or by precomputing the 2987f296bb3SBarry Smithinformation by using a segment of code similar to that for the regular 2997f296bb3SBarry Smithmatrix assembly. The overhead of determining the `nnz` array will be 3007f296bb3SBarry Smithquite small compared with the overhead of the inherently expensive 3017f296bb3SBarry Smith`malloc`s and moves of data that are needed for dynamic allocation 3027f296bb3SBarry Smithduring matrix assembly. Always guess high if an exact value is not known 3037f296bb3SBarry Smith(extra space is cheaper than too little). 3047f296bb3SBarry Smith 3057f296bb3SBarry SmithThus, when assembling a sparse matrix with very different numbers of 3067f296bb3SBarry Smithnonzeros in various rows, one could proceed as follows for finite 3077f296bb3SBarry Smithdifference methods: 3087f296bb3SBarry Smith 3097f296bb3SBarry Smith1. Allocate integer array `nnz`. 3107f296bb3SBarry Smith2. Loop over grid, counting the expected number of nonzeros for the 3117f296bb3SBarry Smith row(s) associated with the various grid points. 3127f296bb3SBarry Smith3. Create the sparse matrix via `MatCreateSeqAIJ()` or alternative. 3137f296bb3SBarry Smith4. Loop over the grid, generating matrix entries and inserting in matrix 3147f296bb3SBarry Smith via `MatSetValues()`. 3157f296bb3SBarry Smith 3167f296bb3SBarry SmithFor (vertex-based) finite element type calculations, an analogous 3177f296bb3SBarry Smithprocedure is as follows: 3187f296bb3SBarry Smith 3197f296bb3SBarry Smith1. Allocate integer array `nnz`. 3207f296bb3SBarry Smith2. Loop over vertices, computing the number of neighbor vertices, which 3217f296bb3SBarry Smith determines the number of nonzeros for the corresponding matrix 3227f296bb3SBarry Smith row(s). 3237f296bb3SBarry Smith3. Create the sparse matrix via `MatCreateSeqAIJ()` or alternative. 3247f296bb3SBarry Smith4. Loop over elements, generating matrix entries and inserting in matrix 3257f296bb3SBarry Smith via `MatSetValues()`. 3267f296bb3SBarry Smith 3277f296bb3SBarry SmithThe `-info` option causes the routines `MatAssemblyBegin()` and 3287f296bb3SBarry Smith`MatAssemblyEnd()` to print information about the success of the 3297f296bb3SBarry Smithpreallocation. Consider the following example for the `MATSEQAIJ` 3307f296bb3SBarry Smithmatrix format: 3317f296bb3SBarry Smith 3327f296bb3SBarry Smith``` 3337f296bb3SBarry SmithMatAssemblyEnd_SeqAIJ:Matrix size 10 X 10; storage space:20 unneeded, 100 used 3347f296bb3SBarry SmithMatAssemblyEnd_SeqAIJ:Number of mallocs during MatSetValues is 0 3357f296bb3SBarry Smith``` 3367f296bb3SBarry Smith 3377f296bb3SBarry SmithThe first line indicates that the user preallocated 120 spaces but only 3387f296bb3SBarry Smith100 were used. The second line indicates that the user preallocated 3397f296bb3SBarry Smithenough space so that PETSc did not have to internally allocate 3407f296bb3SBarry Smithadditional space (an expensive operation). In the next example the user 3417f296bb3SBarry Smithdid not preallocate sufficient space, as indicated by the fact that the 3427f296bb3SBarry Smithnumber of mallocs is very large (bad for efficiency): 3437f296bb3SBarry Smith 3447f296bb3SBarry Smith``` 3457f296bb3SBarry SmithMatAssemblyEnd_SeqAIJ:Matrix size 10 X 10; storage space:47 unneeded, 1000 used 3467f296bb3SBarry SmithMatAssemblyEnd_SeqAIJ:Number of mallocs during MatSetValues is 40000 3477f296bb3SBarry Smith``` 3487f296bb3SBarry Smith 3497f296bb3SBarry SmithAlthough at first glance such procedures for determining the matrix 3507f296bb3SBarry Smithstructure in advance may seem unusual, they are actually very efficient 3517f296bb3SBarry Smithbecause they alleviate the need for dynamic construction of the matrix 3527f296bb3SBarry Smithdata structure, which can be very expensive. 3537f296bb3SBarry Smith 3547f296bb3SBarry Smith#### Parallel AIJ Sparse Matrices 3557f296bb3SBarry Smith 3567f296bb3SBarry SmithParallel sparse matrices with the AIJ format can be created with the 3577f296bb3SBarry Smithcommand 3587f296bb3SBarry Smith 3597f296bb3SBarry Smith``` 3607f296bb3SBarry SmithMatCreateAIJ(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt M,PetscInt N,PetscInt d_nz,PetscInt *d_nnz, PetscInt o_nz,PetscInt *o_nnz,Mat *A); 3617f296bb3SBarry Smith``` 3627f296bb3SBarry Smith 3637f296bb3SBarry Smith`A` is the newly created matrix, while the arguments `m`, `M`, and 3647f296bb3SBarry Smith`N`, indicate the number of local rows and the number of global rows 3657f296bb3SBarry Smithand columns, respectively. In the PETSc partitioning scheme, all the 3667f296bb3SBarry Smithmatrix columns are local and `n` is the number of columns 3677f296bb3SBarry Smithcorresponding to the local part of a parallel vector. Either the local or 3687f296bb3SBarry Smithglobal parameters can be replaced with `PETSC_DECIDE`, so that PETSc 3697f296bb3SBarry Smithwill determine them. The matrix is stored with a fixed number of rows on 3707f296bb3SBarry Smitheach process, given by `m`, or determined by PETSc if `m` is 3717f296bb3SBarry Smith`PETSC_DECIDE`. 3727f296bb3SBarry Smith 3737f296bb3SBarry SmithIf `PETSC_DECIDE` is not used for the arguments `m` and `n`, then 3747f296bb3SBarry Smiththe user must ensure that they are chosen to be compatible with the 3757f296bb3SBarry Smithvectors. To do this, one first considers the matrix-vector product 3767f296bb3SBarry Smith$y = A x$. The `m` that is used in the matrix creation routine 3777f296bb3SBarry Smith`MatCreateAIJ()` must match the local size used in the vector creation 3787f296bb3SBarry Smithroutine `VecCreateMPI()` for `y`. Likewise, the `n` used must 3797f296bb3SBarry Smithmatch that used as the local size in `VecCreateMPI()` for `x`. 3807f296bb3SBarry Smith 3817f296bb3SBarry SmithThe user must set `d_nz=0`, `o_nz=0`, `d_nnz=`NULL, and 3827f296bb3SBarry Smith`o_nnz=NULL` for PETSc to control dynamic allocation of matrix memory 3837f296bb3SBarry Smithspace. Analogous to `nz` and `nnz` for the routine 3847f296bb3SBarry Smith`MatCreateSeqAIJ()`, these arguments optionally specify nonzero 3857f296bb3SBarry Smithinformation for the diagonal (`d_nz` and `d_nnz`) and off-diagonal 3867f296bb3SBarry Smith(`o_nz` and `o_nnz`) parts of the matrix. For a square global 3877f296bb3SBarry Smithmatrix, we define each process’s diagonal portion to be its local rows 3887f296bb3SBarry Smithand the corresponding columns (a square submatrix); each process’s 3897f296bb3SBarry Smithoff-diagonal portion encompasses the remainder of the local matrix (a 3907f296bb3SBarry Smithrectangular submatrix). The rank in the MPI communicator determines the 3917f296bb3SBarry Smithabsolute ordering of the blocks. That is, the process with rank 0 in the 3927f296bb3SBarry Smithcommunicator given to `MatCreateAIJ()` contains the top rows of the 3937f296bb3SBarry Smithmatrix; the i$^{th}$ process in that communicator contains the 3947f296bb3SBarry Smithi$^{th}$ block of the matrix. 3957f296bb3SBarry Smith 3967f296bb3SBarry Smith#### Preallocation of Memory for Parallel AIJ Sparse Matrices 3977f296bb3SBarry Smith 3987f296bb3SBarry SmithAs discussed above, preallocation of memory is critical for achieving 3997f296bb3SBarry Smithgood performance during matrix assembly, as this reduces the number of 4007f296bb3SBarry Smithallocations and copies required. We present an example for three 4017f296bb3SBarry Smithprocesses to indicate how this may be done for the `MATMPIAIJ` matrix 4027f296bb3SBarry Smithformat. Consider the 8 by 8 matrix, which is partitioned by default with 4037f296bb3SBarry Smiththree rows on the first process, three on the second and two on the 4047f296bb3SBarry Smiththird. 4057f296bb3SBarry Smith 4067f296bb3SBarry Smith$$ 4077f296bb3SBarry Smith\left( \begin{array}{cccccccccc} 4087f296bb3SBarry Smith1 & 2 & 0 & | & 0 & 3 & 0 & | & 0 & 4 \\ 4097f296bb3SBarry Smith0 & 5 & 6 & | & 7 & 0 & 0 & | & 8 & 0 \\ 4107f296bb3SBarry Smith9 & 0 & 10 & | & 11 & 0 & 0 & | & 12 & 0 \\ 4117f296bb3SBarry Smith\hline \\ 4127f296bb3SBarry Smith13 & 0 & 14 & | & 15 & 16 & 17 & | & 0 & 0 \\ 4137f296bb3SBarry Smith0 & 18 & 0 & | & 19 & 20 & 21 & | & 0 & 0 \\ 4147f296bb3SBarry Smith0 & 0 & 0 & | & 22 & 23 & 0 & | & 24 & 0 \\ 4157f296bb3SBarry Smith\hline \\ 4167f296bb3SBarry Smith25 & 26 & 27 & | & 0 & 0 & 28 & | & 29 & 0 \\ 4177f296bb3SBarry Smith30 & 0 & 0 & | & 31 & 32 & 33 & | & 0 &34 4187f296bb3SBarry Smith\end{array} \right) 4197f296bb3SBarry Smith$$ 4207f296bb3SBarry Smith 4217f296bb3SBarry SmithThe “diagonal” submatrix, `d`, on the first process is given by 4227f296bb3SBarry Smith 4237f296bb3SBarry Smith$$ 4247f296bb3SBarry Smith\left( \begin{array}{ccc} 4257f296bb3SBarry Smith1 & 2 & 0 \\ 4267f296bb3SBarry Smith0 & 5 & 6 \\ 4277f296bb3SBarry Smith9 & 0 & 10 4287f296bb3SBarry Smith\end{array} \right), 4297f296bb3SBarry Smith$$ 4307f296bb3SBarry Smith 4317f296bb3SBarry Smithwhile the “off-diagonal” submatrix, `o`, matrix is given by 4327f296bb3SBarry Smith 4337f296bb3SBarry Smith$$ 4347f296bb3SBarry Smith\left( \begin{array}{ccccc} 4357f296bb3SBarry Smith 0 & 3 & 0 & 0 & 4 \\ 4367f296bb3SBarry Smith 7 & 0 & 0 & 8 & 0 \\ 4377f296bb3SBarry Smith 11 & 0 & 0 & 12 & 0 \\ 4387f296bb3SBarry Smith\end{array} \right). 4397f296bb3SBarry Smith$$ 4407f296bb3SBarry Smith 4417f296bb3SBarry SmithFor the first process one could set `d_nz` to 2 (since each row has 2 4427f296bb3SBarry Smithnonzeros) or, alternatively, set `d_nnz` to $\{2,2,2\}.$ The 4437f296bb3SBarry Smith`o_nz` could be set to 2 since each row of the `o` matrix has 2 4447f296bb3SBarry Smithnonzeros, or `o_nnz` could be set to $\{2,2,2\}$. 4457f296bb3SBarry Smith 4467f296bb3SBarry SmithFor the second process the `d` submatrix is given by 4477f296bb3SBarry Smith 4487f296bb3SBarry Smith$$ 4497f296bb3SBarry Smith\left( \begin{array}{cccccccccc} 4507f296bb3SBarry Smith 15 & 16 & 17 \\ 4517f296bb3SBarry Smith 19 & 20 & 21 \\ 4527f296bb3SBarry Smith 22 & 23 & 0 4537f296bb3SBarry Smith\end{array} \right) . 4547f296bb3SBarry Smith$$ 4557f296bb3SBarry Smith 4567f296bb3SBarry SmithThus, one could set `d_nz` to 3, since the maximum number of nonzeros 4577f296bb3SBarry Smithin each row is 3, or alternatively one could set `d_nnz` to 4587f296bb3SBarry Smith$\{3,3,2\}$, thereby indicating that the first two rows will have 4597f296bb3SBarry Smith3 nonzeros while the third has 2. The corresponding `o` submatrix for 4607f296bb3SBarry Smiththe second process is 4617f296bb3SBarry Smith 4627f296bb3SBarry Smith$$ 4637f296bb3SBarry Smith\left( \begin{array}{cccccccccc} 4647f296bb3SBarry Smith13 & 0 & 14 & 0 & 0 \\ 4657f296bb3SBarry Smith0 & 18 & 0 & 0 & 0 \\ 4667f296bb3SBarry Smith0 & 0 & 0 & 24 & 0 \\ 4677f296bb3SBarry Smith\end{array} \right) 4687f296bb3SBarry Smith$$ 4697f296bb3SBarry Smith 4707f296bb3SBarry Smithso that one could set `o_nz` to 2 or `o_nnz` to {2,1,1}. 4717f296bb3SBarry Smith 4727f296bb3SBarry SmithNote that the user never directly works with the `d` and `o` 4737f296bb3SBarry Smithsubmatrices, except when preallocating storage space as indicated above. 4747f296bb3SBarry SmithAlso, the user need not preallocate exactly the correct amount of space; 4757f296bb3SBarry Smithas long as a sufficiently close estimate is given, the high efficiency 4767f296bb3SBarry Smithfor matrix assembly will remain. 4777f296bb3SBarry Smith 4787f296bb3SBarry SmithAs described above, the option `-info` will print information about 4797f296bb3SBarry Smiththe success of preallocation during matrix assembly. For the 4807f296bb3SBarry Smith`MATMPIAIJ` and `MATMPIBAIJ` formats, PETSc will also list the 4817f296bb3SBarry Smithnumber of elements owned by on each process that were generated on a 4827f296bb3SBarry Smithdifferent process. For example, the statements 4837f296bb3SBarry Smith 4847f296bb3SBarry Smith``` 4857f296bb3SBarry SmithMatAssemblyBegin_MPIAIJ:Stash has 10 entries, uses 0 mallocs 4867f296bb3SBarry SmithMatAssemblyBegin_MPIAIJ:Stash has 3 entries, uses 0 mallocs 4877f296bb3SBarry SmithMatAssemblyBegin_MPIAIJ:Stash has 5 entries, uses 0 mallocs 4887f296bb3SBarry Smith``` 4897f296bb3SBarry Smith 4907f296bb3SBarry Smithindicate that very few values have been generated on different 4917f296bb3SBarry Smithprocesses. On the other hand, the statements 4927f296bb3SBarry Smith 4937f296bb3SBarry Smith``` 4947f296bb3SBarry SmithMatAssemblyBegin_MPIAIJ:Stash has 100000 entries, uses 100 mallocs 4957f296bb3SBarry SmithMatAssemblyBegin_MPIAIJ:Stash has 77777 entries, uses 70 mallocs 4967f296bb3SBarry Smith``` 4977f296bb3SBarry Smith 4987f296bb3SBarry Smithindicate that many values have been generated on the “wrong” processes. 4997f296bb3SBarry SmithThis situation can be very inefficient, since the transfer of values to 5007f296bb3SBarry Smiththe “correct” process is generally expensive. By using the command 5017f296bb3SBarry Smith`MatGetOwnershipRange()` in application codes, the user should be able 5027f296bb3SBarry Smithto generate most entries on the owning process. 5037f296bb3SBarry Smith 5047f296bb3SBarry Smith*Note*: It is fine to generate some entries on the “wrong” process. 5057f296bb3SBarry SmithOften this can lead to cleaner, simpler, less buggy codes. One should 5067f296bb3SBarry Smithnever make code overly complicated in order to generate all values 5077f296bb3SBarry Smithlocally. Rather, one should organize the code in such a way that *most* 5087f296bb3SBarry Smithvalues are generated locally. 5097f296bb3SBarry Smith 5107f296bb3SBarry SmithThe routine `MatCreateAIJCUSPARSE()` allows one to create GPU based matrices for NVIDIA systems. 5117f296bb3SBarry Smith`MatCreateAIJKokkos()` can create matrices for use with CPU, OpenMP, NVIDIA, AMD, or Intel based GPU systems. 5127f296bb3SBarry Smith 5137f296bb3SBarry SmithIt is sometimes difficult to compute the required preallocation information efficiently, hence PETSc provides a 5147f296bb3SBarry Smithspecial `MatType`, `MATPREALLOCATOR` that helps make computing this information more straightforward. One first creates a matrix of this type and then, using the same 5157f296bb3SBarry Smithcode that one would use to actually compute the matrices numerical values, calls `MatSetValues()` for this matrix, without needing to provide any 5167f296bb3SBarry Smithpreallocation information (one need not provide the matrix numerical values). Once this is complete one uses `MatPreallocatorPreallocate()` to 5177f296bb3SBarry Smithprovide the accumulated preallocation information to 5187f296bb3SBarry Smiththe actual matrix one will use for the computations. We hope to simplify this process in the future, allowing the removal of `MATPREALLOCATOR`, 5197f296bb3SBarry Smithinstead simply allowing the use of its efficient insertion process automatically during the first assembly of any matrix type directly without 5207f296bb3SBarry Smithrequiring the detailed preallocation information. 5217f296bb3SBarry Smith 5227f296bb3SBarry SmithSee {any}`doc_matrix` for a table of the matrix types available in PETSc. 5237f296bb3SBarry Smith 5247f296bb3SBarry Smith(sec_matlmvm)= 5257f296bb3SBarry Smith 5267f296bb3SBarry Smith#### Limited-Memory Variable Metric (LMVM) Matrices 5277f296bb3SBarry Smith 5287f296bb3SBarry SmithVariable metric methods, also known as quasi-Newton methods, are 5297f296bb3SBarry Smithfrequently used for root finding problems and approximate Jacobian 5307f296bb3SBarry Smithmatrices or their inverses via sequential nonlinear updates based on the 5317f296bb3SBarry Smithsecant condition. The limited-memory variants do not store the full 5327f296bb3SBarry Smithexplicit Jacobian, and instead compute forward products and inverse 5337f296bb3SBarry Smithapplications based on a fixed number of stored update vectors. 5347f296bb3SBarry Smith 5357f296bb3SBarry Smith```{eval-rst} 5367f296bb3SBarry Smith.. list-table:: PETSc LMVM matrix implementations. 5377f296bb3SBarry Smith :name: tab_matlmvmimpl 5387f296bb3SBarry Smith :header-rows: 1 5397f296bb3SBarry Smith 5407f296bb3SBarry Smith * - Method 5417f296bb3SBarry Smith - PETSc Type 5427f296bb3SBarry Smith - Name 5437f296bb3SBarry Smith - Property 5447f296bb3SBarry Smith * - "Good" Broyden :cite:`keyprefix-griewank2012broyden` 5457f296bb3SBarry Smith - ``MATLMVMBrdn`` 5467f296bb3SBarry Smith - ``lmvmbrdn`` 5477f296bb3SBarry Smith - Square 5487f296bb3SBarry Smith * - "Bad" Broyden :cite:`keyprefix-griewank2012broyden` 5497f296bb3SBarry Smith - ``MATLMVMBadBrdn`` 5507f296bb3SBarry Smith - ``lmvmbadbrdn`` 5517f296bb3SBarry Smith - Square 5527f296bb3SBarry Smith * - Symmetric Rank-1 :cite:`keyprefix-nocedal2006numerical` 5537f296bb3SBarry Smith - ``MATLMVMSR1`` 5547f296bb3SBarry Smith - ``lmvmsr1`` 5557f296bb3SBarry Smith - Symmetric 5567f296bb3SBarry Smith * - Davidon-Fletcher-Powell (DFP) :cite:`keyprefix-nocedal2006numerical` 5577f296bb3SBarry Smith - ``MATLMVMDFP`` 5587f296bb3SBarry Smith - ``lmvmdfp`` 5597f296bb3SBarry Smith - SPD 5607f296bb3SBarry Smith * - Dense Davidon-Fletcher-Powell (DFP) :cite:`keyprefix-ErwayMarcia2017` 5617f296bb3SBarry Smith - ``MATLMVMDDFP`` 5627f296bb3SBarry Smith - ``lmvmddfp`` 5637f296bb3SBarry Smith - SPD 5647f296bb3SBarry Smith * - Broyden-Fletcher-Goldfarb-Shanno (BFGS) :cite:`keyprefix-nocedal2006numerical` 5657f296bb3SBarry Smith - ``MATLMVMBFGS`` 5667f296bb3SBarry Smith - ``lmvmbfgs`` 5677f296bb3SBarry Smith - SPD 5687f296bb3SBarry Smith * - Dense Broyden-Fletcher-Goldfarb-Shanno (BFGS) :cite:`keyprefix-ErwayMarcia2017` 5697f296bb3SBarry Smith - ``MATLMVMDBFGS`` 5707f296bb3SBarry Smith - ``lmvmdbfgs`` 5717f296bb3SBarry Smith - SPD 5727f296bb3SBarry Smith * - Dense Quasi-Newton 5737f296bb3SBarry Smith - ``MATLMVMDQN`` 5747f296bb3SBarry Smith - ``lmvmdqn`` 5757f296bb3SBarry Smith - SPD 5767f296bb3SBarry Smith * - Restricted Broyden Family :cite:`keyprefix-erway2017solving` 5777f296bb3SBarry Smith - ``MATLMVMSymBrdn`` 5787f296bb3SBarry Smith - ``lmvmsymbrdn`` 5797f296bb3SBarry Smith - SPD 5807f296bb3SBarry Smith * - Restricted Broyden Family (full-memory diagonal) 5817f296bb3SBarry Smith - ``MATLMVMDiagBrdn`` 5827f296bb3SBarry Smith - ``lmvmdiagbrdn`` 5837f296bb3SBarry Smith - SPD 5847f296bb3SBarry Smith``` 5857f296bb3SBarry Smith 5867f296bb3SBarry SmithPETSc implements seven different LMVM matrices listed in the 5877f296bb3SBarry Smithtable above. They can be created using the 5887f296bb3SBarry Smith`MatCreate()` and `MatSetType()` workflow, and share a number of 5897f296bb3SBarry Smithcommon interface functions. We will review the most important ones 5907f296bb3SBarry Smithbelow: 5917f296bb3SBarry Smith 5927f296bb3SBarry Smith- `MatLMVMAllocate(Mat B, Vec X, Vec F)` – Creates the internal data 5937f296bb3SBarry Smith structures necessary to store nonlinear updates and compute 5947f296bb3SBarry Smith forward/inverse applications. The `X` vector defines the solution 5957f296bb3SBarry Smith space while the `F` defines the function space for the history of 5967f296bb3SBarry Smith updates. 5977f296bb3SBarry Smith- `MatLMVMUpdate(Mat B, Vec X, Vec F)` – Applies a nonlinear update to 5987f296bb3SBarry Smith the approximate Jacobian such that $s_k = x_k - x_{k-1}$ and 5997f296bb3SBarry Smith $y_k = f(x_k) - f(x_{k-1})$, where $k$ is the index for 6007f296bb3SBarry Smith the update. 6017f296bb3SBarry Smith- `MatLMVMReset(Mat B, PetscBool destructive)` – Flushes the 6027f296bb3SBarry Smith accumulated nonlinear updates and resets the matrix to the initial 6037f296bb3SBarry Smith state. If `destructive = PETSC_TRUE`, the reset also destroys the 6047f296bb3SBarry Smith internal data structures and necessitates another allocation call 6057f296bb3SBarry Smith before the matrix can be updated and used for products and solves. 6067f296bb3SBarry Smith- `MatLMVMSetJ0(Mat B, Mat J0)` – Defines the initial Jacobian to 6077f296bb3SBarry Smith apply the updates to. If no initial Jacobian is provided, the updates 6087f296bb3SBarry Smith are applied to an identity matrix. 6097f296bb3SBarry Smith 6107f296bb3SBarry SmithLMVM matrices can be applied to vectors in forward mode via 6117f296bb3SBarry Smith`MatMult()` or `MatMultAdd()`, and in inverse mode via 6127f296bb3SBarry Smith`MatSolve()`. They also support `MatCreateVecs()`, `MatDuplicate()` 6137f296bb3SBarry Smithand `MatCopy()` operations. 6147f296bb3SBarry Smith 6157f296bb3SBarry SmithRestricted Broyden Family, DFP and BFGS methods, including their dense 6167f296bb3SBarry Smithversions, additionally implement special Jacobian initialization and 6177f296bb3SBarry Smithscaling options available via 6187f296bb3SBarry Smith`-mat_lmvm_scale_type <none,scalar,diagonal>`. We describe these 6197f296bb3SBarry Smithchoices below: 6207f296bb3SBarry Smith 6217f296bb3SBarry Smith- `none` – Sets the initial Jacobian to be equal to the identity 6227f296bb3SBarry Smith matrix. No extra computations are required when obtaining the search 6237f296bb3SBarry Smith direction or updating the approximation. However, the number of 6247f296bb3SBarry Smith function evaluations required to converge the Newton solution is 6257f296bb3SBarry Smith typically much larger than what is required when using other 6267f296bb3SBarry Smith initializations. 6277f296bb3SBarry Smith 6287f296bb3SBarry Smith- `scalar` – Defines the initial Jacobian as a scalar multiple of the 6297f296bb3SBarry Smith identity matrix. The scalar value $\sigma$ is chosen by solving 6307f296bb3SBarry Smith the one dimensional optimization problem 6317f296bb3SBarry Smith 6327f296bb3SBarry Smith $$ 6337f296bb3SBarry Smith \min_\sigma \|\sigma^\alpha Y - \sigma^{\alpha - 1} S\|_F^2, 6347f296bb3SBarry Smith $$ 6357f296bb3SBarry Smith 6367f296bb3SBarry Smith where $S$ and $Y$ are the matrices whose columns contain 6377f296bb3SBarry Smith a subset of update vectors $s_k$ and $y_k$, and 6387f296bb3SBarry Smith $\alpha \in [0, 1]$ is defined by the user via 6397f296bb3SBarry Smith `-mat_lmvm_alpha` and has a different default value for each LMVM 6407f296bb3SBarry Smith implementation (e.g.: default $\alpha = 1$ for BFGS produces 6417f296bb3SBarry Smith the well-known $y_k^T s_k / y_k^T y_k$ scalar initialization). 6427f296bb3SBarry Smith The number of updates to be used in the $S$ and $Y$ 6437f296bb3SBarry Smith matrices is 1 by default (i.e.: the latest update only) and can be 6447f296bb3SBarry Smith changed via `-mat_lmvm_sigma_hist`. This technique is inspired by 6457f296bb3SBarry Smith Gilbert and Lemarechal {cite}`keyprefix-gilbert-lemarechal`. 6467f296bb3SBarry Smith 6477f296bb3SBarry Smith- `diagonal` – Uses a full-memory restricted Broyden update formula 6487f296bb3SBarry Smith to construct a diagonal matrix for the Jacobian initialization. 6497f296bb3SBarry Smith Although the full-memory formula is utilized, the actual memory 6507f296bb3SBarry Smith footprint is restricted to only the vector representing the diagonal 6517f296bb3SBarry Smith and some additional work vectors used in its construction. The 6527f296bb3SBarry Smith diagonal terms are also re-scaled with every update as suggested in 6537f296bb3SBarry Smith {cite}`keyprefix-gilbert-lemarechal`. This initialization requires 6547f296bb3SBarry Smith the most computational effort of the available choices but typically 6557f296bb3SBarry Smith results in a significant reduction in the number of function 6567f296bb3SBarry Smith evaluations taken to compute a solution. 6577f296bb3SBarry Smith 6587f296bb3SBarry SmithThe dense implementations are numerically equivalent to DFP and BFGS, 6597f296bb3SBarry Smithbut they try to minimize memory transfer at the cost of storage 6607f296bb3SBarry Smith{cite}`keyprefix-ErwayMarcia2017`. Generally, dense formulations of DFP 6617f296bb3SBarry Smithand BFGS, `MATLMVMDDFP` and `MATLMVMDBFGS`, should be faster than 6627f296bb3SBarry Smithclassical recursive versions - on both CPU and GPU. It should be noted 6637f296bb3SBarry Smiththat `MatMult` of dense BFGS, and `MatSolve` of dense DFP requires 6647f296bb3SBarry SmithCholesky factorization, which may be numerically unstable, if a Jacobian 6657f296bb3SBarry Smithoption other than `none` is used. Therefore, the default 6667f296bb3SBarry Smithimplementation is to enable classical recursive algorithms to avoid 6677f296bb3SBarry Smiththe Cholesky factorization. This option can be toggled via 6687f296bb3SBarry Smith`-mat_lbfgs_recursive` and `-mat_ldfp_recursive`. 6697f296bb3SBarry Smith 6707f296bb3SBarry SmithDense Quasi-Newton, `MATLMVMDQN` is an implementation that uses 6717f296bb3SBarry Smith`MatSolve` of `MATLMVMDBFGS` for its `MatSolve`, and uses 6727f296bb3SBarry Smith`MatMult` of `MATLMVMDDFP` for its `MatMult`. It can be 6737f296bb3SBarry Smithseen as a hybrid implementation to avoid both recursive implementation 6747f296bb3SBarry Smithand Cholesky factorization, trading numerical accuracy for performances. 6757f296bb3SBarry Smith 6767f296bb3SBarry SmithNote that the user-provided initial Jacobian via `MatLMVMSetJ0()` 6777f296bb3SBarry Smithoverrides and disables all built-in initialization methods. 6787f296bb3SBarry Smith 6797f296bb3SBarry Smith(sec_matdense)= 6807f296bb3SBarry Smith 6817f296bb3SBarry Smith### Dense Matrices 6827f296bb3SBarry Smith 6837f296bb3SBarry SmithPETSc provides both sequential and parallel dense matrix formats, where 6847f296bb3SBarry Smitheach process stores its entries in a column-major array in the usual 6857f296bb3SBarry SmithFortran style. To create a sequential, dense PETSc matrix, `A` of 6867f296bb3SBarry Smithdimensions `m` by `n`, the user should call 6877f296bb3SBarry Smith 6887f296bb3SBarry Smith``` 6897f296bb3SBarry SmithMatCreateSeqDense(PETSC_COMM_SELF,PetscInt m,PetscInt n,PetscScalar *data,Mat *A); 6907f296bb3SBarry Smith``` 6917f296bb3SBarry Smith 6927f296bb3SBarry SmithThe variable `data` enables the user to optionally provide the 6937f296bb3SBarry Smithlocation of the data for matrix storage (intended for Fortran users who 6947f296bb3SBarry Smithwish to allocate their own storage space). Most users should merely set 6957f296bb3SBarry Smith`data` to `NULL` for PETSc to control matrix memory allocation. To 6967f296bb3SBarry Smithcreate a parallel, dense matrix, `A`, the user should call 6977f296bb3SBarry Smith 6987f296bb3SBarry Smith``` 6997f296bb3SBarry SmithMatCreateDense(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt M,PetscInt N,PetscScalar *data,Mat *A) 7007f296bb3SBarry Smith``` 7017f296bb3SBarry Smith 7027f296bb3SBarry SmithThe arguments `m`, `n`, `M`, and `N`, indicate the number of 7037f296bb3SBarry Smithlocal rows and columns and the number of global rows and columns, 7047f296bb3SBarry Smithrespectively. Either the local or global parameters can be replaced with 7057f296bb3SBarry Smith`PETSC_DECIDE`, so that PETSc will determine them. The matrix is 7067f296bb3SBarry Smithstored with a fixed number of rows on each process, given by `m`, or 7077f296bb3SBarry Smithdetermined by PETSc if `m` is `PETSC_DECIDE`. 7087f296bb3SBarry Smith 7097f296bb3SBarry SmithPETSc does not provide parallel dense direct solvers, instead 7107f296bb3SBarry Smithinterfacing to external packages that provide these solvers. Our focus 7117f296bb3SBarry Smithis on sparse iterative solvers. 7127f296bb3SBarry Smith 7137f296bb3SBarry Smith(sec_matnest)= 7147f296bb3SBarry Smith 7157f296bb3SBarry Smith### Block Matrices 7167f296bb3SBarry Smith 7177f296bb3SBarry SmithBlock matrices arise when coupling variables with different meaning, 7187f296bb3SBarry Smithespecially when solving problems with constraints (e.g. incompressible 7197f296bb3SBarry Smithflow) and “multi-physics” problems. Usually the number of blocks is 7207f296bb3SBarry Smithsmall and each block is partitioned in parallel. We illustrate for a 7217f296bb3SBarry Smith$3\times 3$ system with components labeled $a,b,c$. With 7227f296bb3SBarry Smithsome numbering of unknowns, the matrix could be written as 7237f296bb3SBarry Smith 7247f296bb3SBarry Smith$$ 7257f296bb3SBarry Smith\left( \begin{array}{ccc} 7267f296bb3SBarry Smith A_{aa} & A_{ab} & A_{ac} \\ 7277f296bb3SBarry Smith A_{ba} & A_{bb} & A_{bc} \\ 7287f296bb3SBarry Smith A_{ca} & A_{cb} & A_{cc} 7297f296bb3SBarry Smith \end{array} \right) . 7307f296bb3SBarry Smith$$ 7317f296bb3SBarry Smith 7327f296bb3SBarry SmithThere are two fundamentally different ways that this matrix could be 7337f296bb3SBarry Smithstored, as a single assembled sparse matrix where entries from all 7347f296bb3SBarry Smithblocks are merged together (“monolithic”), or as separate assembled 7357f296bb3SBarry Smithmatrices for each block (“nested”). These formats have different 7367f296bb3SBarry Smithperformance characteristics depending on the operation being performed. 7377f296bb3SBarry SmithIn particular, many preconditioners require a monolithic format, but 7387f296bb3SBarry Smithsome that are very effective for solving block systems (see 7397f296bb3SBarry Smith{any}`sec_block_matrices`) are more efficient when a nested 7407f296bb3SBarry Smithformat is used. In order to stay flexible, we would like to be able to 7417f296bb3SBarry Smithuse the same code to assemble block matrices in both monolithic and 7427f296bb3SBarry Smithnested formats. Additionally, for software maintainability and testing, 7437f296bb3SBarry Smithespecially in a multi-physics context where different groups might be 7447f296bb3SBarry Smithresponsible for assembling each of the blocks, it is desirable to be 7457f296bb3SBarry Smithable to use exactly the same code to assemble a single block 7467f296bb3SBarry Smithindependently as to assemble it as part of a larger system. To do this, 7477f296bb3SBarry Smithwe introduce the four spaces shown in {numref}`fig_localspaces`. 7487f296bb3SBarry Smith 7497f296bb3SBarry Smith- The monolithic global space is the space in which the Krylov and 7507f296bb3SBarry Smith Newton solvers operate, with collective semantics across the entire 7517f296bb3SBarry Smith block system. 7527f296bb3SBarry Smith- The split global space splits the blocks apart, but each split still 7537f296bb3SBarry Smith has collective semantics. 7547f296bb3SBarry Smith- The split local space adds ghost points and separates the blocks. 7557f296bb3SBarry Smith Operations in this space can be performed with no parallel 7567f296bb3SBarry Smith communication. This is often the most natural, and certainly the most 7577f296bb3SBarry Smith powerful, space for matrix assembly code. 7587f296bb3SBarry Smith- The monolithic local space can be thought of as adding ghost points 7597f296bb3SBarry Smith to the monolithic global space, but it is often more natural to use 7607f296bb3SBarry Smith it simply as a concatenation of split local spaces on each process. 7617f296bb3SBarry Smith It is not common to explicitly manipulate vectors or matrices in this 7627f296bb3SBarry Smith space (at least not during assembly), but it is a useful for 7637f296bb3SBarry Smith declaring which part of a matrix is being assembled. 7647f296bb3SBarry Smith 7657f296bb3SBarry Smith:::{figure} /images/manual/localspaces.svg 7667f296bb3SBarry Smith:alt: The relationship between spaces used for coupled assembly. 7677f296bb3SBarry Smith:name: fig_localspaces 7687f296bb3SBarry Smith 7697f296bb3SBarry SmithThe relationship between spaces used for coupled assembly. 7707f296bb3SBarry Smith::: 7717f296bb3SBarry Smith 7727f296bb3SBarry SmithThe key to format-independent assembly is the function 7737f296bb3SBarry Smith 7747f296bb3SBarry Smith``` 7757f296bb3SBarry SmithMatGetLocalSubMatrix(Mat A,IS isrow,IS iscol,Mat *submat); 7767f296bb3SBarry Smith``` 7777f296bb3SBarry Smith 7787f296bb3SBarry Smithwhich provides a “view” `submat` into a matrix `A` that operates in 7797f296bb3SBarry Smiththe monolithic global space. The `submat` transforms from the split 7807f296bb3SBarry Smithlocal space defined by `iscol` to the split local space defined by 7817f296bb3SBarry Smith`isrow`. The index sets specify the parts of the monolithic local 7827f296bb3SBarry Smithspace that `submat` should operate in. If a nested matrix format is 7837f296bb3SBarry Smithused, then `MatGetLocalSubMatrix()` finds the nested block and returns 7847f296bb3SBarry Smithit without making any copies. In this case, `submat` is fully 7857f296bb3SBarry Smithfunctional and has a parallel communicator. If a monolithic matrix 7867f296bb3SBarry Smithformat is used, then `MatGetLocalSubMatrix()` returns a proxy matrix 7877f296bb3SBarry Smithon `PETSC_COMM_SELF` that does not provide values or implement 7887f296bb3SBarry Smith`MatMult()`, but does implement `MatSetValuesLocal()` and, if 7897f296bb3SBarry Smith`isrow,iscol` have a constant block size, 7907f296bb3SBarry Smith`MatSetValuesBlockedLocal()`. Note that although `submat` may not be 7917f296bb3SBarry Smitha fully functional matrix and the caller does not even know a priori 7927f296bb3SBarry Smithwhich communicator it will reside on, it always implements the local 7937f296bb3SBarry Smithassembly functions (which are not collective). The index sets 7947f296bb3SBarry Smith`isrow,iscol` can be obtained using `DMCompositeGetLocalISs()` if 7957f296bb3SBarry Smith`DMCOMPOSITE` is being used. `DMCOMPOSITE` can also be used to create 7967f296bb3SBarry Smithmatrices, in which case the `MATNEST` format can be specified using 7977f296bb3SBarry Smith`-prefix_dm_mat_type nest` and `MATAIJ` can be specified using 7987f296bb3SBarry Smith`-prefix_dm_mat_type aij`. See 7997f296bb3SBarry Smith<a href="PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/snes/tutorials/ex28.c.html">SNES Tutorial ex28</a> 8007f296bb3SBarry Smithfor a simple example using this interface. 8017f296bb3SBarry Smith 8027f296bb3SBarry Smith(sec_matoptions)= 8037f296bb3SBarry Smith 8047f296bb3SBarry Smith## Basic Matrix Operations 8057f296bb3SBarry Smith 8067f296bb3SBarry SmithTable {any}`2.2 <fig_matrixops>` summarizes basic PETSc matrix operations. 8077f296bb3SBarry SmithWe briefly discuss a few of these routines in more detail below. 8087f296bb3SBarry Smith 8097f296bb3SBarry SmithThe parallel matrix can multiply a vector with `n` local entries, 8107f296bb3SBarry Smithreturning a vector with `m` local entries. That is, to form the 8117f296bb3SBarry Smithproduct 8127f296bb3SBarry Smith 8137f296bb3SBarry Smith``` 8147f296bb3SBarry SmithMatMult(Mat A,Vec x,Vec y); 8157f296bb3SBarry Smith``` 8167f296bb3SBarry Smith 8177f296bb3SBarry Smiththe vectors `x` and `y` should be generated with 8187f296bb3SBarry Smith 8197f296bb3SBarry Smith``` 8207f296bb3SBarry SmithVecCreateMPI(MPI_Comm comm,n,N,&x); 8217f296bb3SBarry SmithVecCreateMPI(MPI_Comm comm,m,M,&y); 8227f296bb3SBarry Smith``` 8237f296bb3SBarry Smith 8247f296bb3SBarry SmithBy default, if the user lets PETSc decide the number of components to be 8257f296bb3SBarry Smithstored locally (by passing in `PETSC_DECIDE` as the second argument to 8267f296bb3SBarry Smith`VecCreateMPI()` or using `VecCreate()`), vectors and matrices of 8277f296bb3SBarry Smiththe same dimension are automatically compatible for parallel 8287f296bb3SBarry Smithmatrix-vector operations. 8297f296bb3SBarry Smith 8307f296bb3SBarry SmithAlong with the matrix-vector multiplication routine, there is a version 8317f296bb3SBarry Smithfor the transpose of the matrix, 8327f296bb3SBarry Smith 8337f296bb3SBarry Smith``` 8347f296bb3SBarry SmithMatMultTranspose(Mat A,Vec x,Vec y); 8357f296bb3SBarry Smith``` 8367f296bb3SBarry Smith 8377f296bb3SBarry SmithThere are also versions that add the result to another vector: 8387f296bb3SBarry Smith 8397f296bb3SBarry Smith``` 8407f296bb3SBarry SmithMatMultAdd(Mat A,Vec x,Vec y,Vec w); 8417f296bb3SBarry SmithMatMultTransposeAdd(Mat A,Vec x,Vec y,Vec w); 8427f296bb3SBarry Smith``` 8437f296bb3SBarry Smith 8447f296bb3SBarry SmithThese routines, respectively, produce $w = A*x + y$ and 8457f296bb3SBarry Smith$w = A^{T}*x + y$ . In C it is legal for the vectors `y` and 8467f296bb3SBarry Smith`w` to be identical. In Fortran, this situation is forbidden by the 8477f296bb3SBarry Smithlanguage standard, but we allow it anyway. 8487f296bb3SBarry Smith 8497f296bb3SBarry SmithOne can print a matrix (sequential or parallel) to the screen with the 8507f296bb3SBarry Smithcommand 8517f296bb3SBarry Smith 8527f296bb3SBarry Smith``` 8537f296bb3SBarry SmithMatView(Mat mat,PETSC_VIEWER_STDOUT_WORLD); 8547f296bb3SBarry Smith``` 8557f296bb3SBarry Smith 8567f296bb3SBarry SmithOther viewers can be used as well. For instance, one can draw the 8577f296bb3SBarry Smithnonzero structure of the matrix into the default X-window with the 8587f296bb3SBarry Smithcommand 8597f296bb3SBarry Smith 8607f296bb3SBarry Smith``` 8617f296bb3SBarry SmithMatView(Mat mat,PETSC_VIEWER_DRAW_WORLD); 8627f296bb3SBarry Smith``` 8637f296bb3SBarry Smith 8647f296bb3SBarry SmithAlso one can use 8657f296bb3SBarry Smith 8667f296bb3SBarry Smith``` 8677f296bb3SBarry SmithMatView(Mat mat,PetscViewer viewer); 8687f296bb3SBarry Smith``` 8697f296bb3SBarry Smith 8707f296bb3SBarry Smithwhere `viewer` was obtained with `PetscViewerDrawOpen()`. Additional 8717f296bb3SBarry Smithviewers and options are given in the `MatView()` man page and 8727f296bb3SBarry Smith{any}`sec_viewers`. 8737f296bb3SBarry Smith 8747f296bb3SBarry Smith```{eval-rst} 8757f296bb3SBarry Smith.. list-table:: PETSc Matrix Operations 8767f296bb3SBarry Smith :name: fig_matrixops 8777f296bb3SBarry Smith :header-rows: 1 8787f296bb3SBarry Smith 8797f296bb3SBarry Smith * - Function Name 8807f296bb3SBarry Smith - Operation 8817f296bb3SBarry Smith * - ``MatAXPY(Mat Y, PetscScalar a, Mat X, MatStructure s);`` 8827f296bb3SBarry Smith - :math:`Y = Y + a*X` 8837f296bb3SBarry Smith * - ``MatAYPX(Mat Y, PetscScalar a, Mat X, MatStructure s);`` 8847f296bb3SBarry Smith - :math:`Y = a*Y + X` 8857f296bb3SBarry Smith * - ``MatMult(Mat A,Vec x, Vec y);`` 8867f296bb3SBarry Smith - :math:`y = A*x` 8877f296bb3SBarry Smith * - ``MatMultAdd(Mat A,Vec x, Vec y,Vec z);`` 8887f296bb3SBarry Smith - :math:`z = y + A*x` 8897f296bb3SBarry Smith * - ``MatMultTranspose(Mat A,Vec x, Vec y);`` 8907f296bb3SBarry Smith - :math:`y = A^{T}*x` 8917f296bb3SBarry Smith * - ``MatMultTransposeAdd(Mat A, Vec x, Vec y, Vec z);`` 8927f296bb3SBarry Smith - :math:`z = y + A^{T}*x` 8937f296bb3SBarry Smith * - ``MatNorm(Mat A,NormType type, PetscReal *r);`` 8947f296bb3SBarry Smith - :math:`r = A_{type}` 8957f296bb3SBarry Smith * - ``MatDiagonalScale(Mat A,Vec l,Vec r);`` 8967f296bb3SBarry Smith - :math:`A = \text{diag}(l)*A*\text{diag}(r)` 8977f296bb3SBarry Smith * - ``MatScale(Mat A,PetscScalar a);`` 8987f296bb3SBarry Smith - :math:`A = a*A` 8997f296bb3SBarry Smith * - ``MatConvert(Mat A, MatType type, Mat *B);`` 9007f296bb3SBarry Smith - :math:`B = A` 9017f296bb3SBarry Smith * - ``MatCopy(Mat A, Mat B, MatStructure s);`` 9027f296bb3SBarry Smith - :math:`B = A` 9037f296bb3SBarry Smith * - ``MatGetDiagonal(Mat A, Vec x);`` 9047f296bb3SBarry Smith - :math:`x = \text{diag}(A)` 9057f296bb3SBarry Smith * - ``MatTranspose(Mat A, MatReuse, Mat* B);`` 9067f296bb3SBarry Smith - :math:`B = A^{T}` 9077f296bb3SBarry Smith * - ``MatZeroEntries(Mat A);`` 9087f296bb3SBarry Smith - :math:`A = 0` 9097f296bb3SBarry Smith * - ``MatShift(Mat Y, PetscScalar a);`` 9107f296bb3SBarry Smith - :math:`Y = Y + a*I` 9117f296bb3SBarry Smith``` 9127f296bb3SBarry Smith 9137f296bb3SBarry Smith```{eval-rst} 9147f296bb3SBarry Smith.. list-table:: Values of MatStructure 9157f296bb3SBarry Smith :name: fig_matstructure 9167f296bb3SBarry Smith :header-rows: 1 9177f296bb3SBarry Smith 9187f296bb3SBarry Smith * - Name 9197f296bb3SBarry Smith - Meaning 9207f296bb3SBarry Smith * - ``SAME_NONZERO_PATTERN`` 9217f296bb3SBarry Smith - the matrices have an identical nonzero pattern 9227f296bb3SBarry Smith * - ``DIFFERENT_NONZERO_PATTERN`` 9237f296bb3SBarry Smith - the matrices may have a different nonzero pattern 9247f296bb3SBarry Smith * - ``SUBSET_NONZERO_PATTERN`` 9257f296bb3SBarry Smith - the second matrix has a subset of the nonzeros in the first matrix 9267f296bb3SBarry Smith * - ``UNKNOWN_NONZERO_PATTERN`` 9277f296bb3SBarry Smith - there is nothing known about the relation between the nonzero patterns of the two matrices 9287f296bb3SBarry Smith``` 9297f296bb3SBarry Smith 9307f296bb3SBarry SmithThe `NormType` argument to `MatNorm()` is one of `NORM_1`, 9317f296bb3SBarry Smith`NORM_INFINITY`, and `NORM_FROBENIUS`. 9327f296bb3SBarry Smith 9337f296bb3SBarry Smith(sec_matrixfree)= 9347f296bb3SBarry Smith 9357f296bb3SBarry Smith## Application Specific Custom Matrices 9367f296bb3SBarry Smith 9377f296bb3SBarry SmithSome people like to use matrix-free methods, which do 9387f296bb3SBarry Smithnot require explicit storage of the matrix, for the numerical solution 9397f296bb3SBarry Smithof partial differential equations. 9407f296bb3SBarry SmithSimilarly, users may already have a custom matrix data structure and routines 9417f296bb3SBarry Smithfor that data structure and would like to wrap their code up into a `Mat`; 9427f296bb3SBarry Smiththat is, provide their own custom matrix type. 9437f296bb3SBarry Smith 9447f296bb3SBarry SmithTo use the PETSc provided matrix-free matrix that uses finite differencing to approximate the matrix-vector product 9457f296bb3SBarry Smithuse `MatCreateMFFD()`, see {any}`sec_nlmatrixfree`. 9467f296bb3SBarry SmithTo provide your own matrix operations (such as `MatMult()`) 9477f296bb3SBarry Smithuse the following command to create a `Mat` structure 9487f296bb3SBarry Smithwithout ever actually generating the matrix: 9497f296bb3SBarry Smith 9507f296bb3SBarry Smith``` 951*2a8381b2SBarry SmithMatCreateShell(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt M, PetscInt N, PetscCtx ctx, Mat *mat); 9527f296bb3SBarry Smith``` 9537f296bb3SBarry Smith 9547f296bb3SBarry SmithHere `M` and `N` are the global matrix dimensions (rows and 9557f296bb3SBarry Smithcolumns), `m` and `n` are the local matrix dimensions, and `ctx` 9567f296bb3SBarry Smithis a pointer to data needed by any user-defined shell matrix operations; 9577f296bb3SBarry Smiththe manual page has additional details about these parameters. Most 9587f296bb3SBarry Smithmatrix-free algorithms require only the application of the linear 9597f296bb3SBarry Smithoperator to a vector. To provide this action, the user must write a 9607f296bb3SBarry Smithroutine with the calling sequence 9617f296bb3SBarry Smith 9627f296bb3SBarry Smith``` 9637f296bb3SBarry SmithUserMult(Mat mat,Vec x,Vec y); 9647f296bb3SBarry Smith``` 9657f296bb3SBarry Smith 9667f296bb3SBarry Smithand then associate it with the matrix, `mat`, by using the command 9677f296bb3SBarry Smith 9687f296bb3SBarry Smith``` 9697f296bb3SBarry SmithMatShellSetOperation(Mat mat,MatOperation MATOP_MULT, (void(*)(void)) PetscErrorCode (*UserMult)(Mat,Vec,Vec)); 9707f296bb3SBarry Smith``` 9717f296bb3SBarry Smith 9727f296bb3SBarry SmithHere `MATOP_MULT` is the name of the operation for matrix-vector 9737f296bb3SBarry Smithmultiplication. Within each user-defined routine (such as 9747f296bb3SBarry Smith`UserMult()`), the user should call `MatShellGetContext()` to obtain 9757f296bb3SBarry Smiththe user-defined context, `ctx`, that was set by `MatCreateShell()`. 9767f296bb3SBarry SmithThis shell matrix can be used with the iterative linear equation solvers 9777f296bb3SBarry Smithdiscussed in the following chapters. 9787f296bb3SBarry Smith 9797f296bb3SBarry SmithThe routine `MatShellSetOperation()` can be used to set any other 9807f296bb3SBarry Smithmatrix operations as well. The file 9817f296bb3SBarry Smith`$PETSC_DIR/include/petscmat.h` (<a href="PETSC_DOC_OUT_ROOT_PLACEHOLDER/include/petscmat.h.html">source</a>) 9827f296bb3SBarry Smithprovides a complete list of matrix operations, which have the form 9837f296bb3SBarry Smith`MATOP_<OPERATION>`, where `<OPERATION>` is the name (in all capital 9847f296bb3SBarry Smithletters) of the user interface routine (for example, `MatMult()` 9857f296bb3SBarry Smith$\to$ `MATOP_MULT`). All user-provided functions have the same 9867f296bb3SBarry Smithcalling sequence as the usual matrix interface routines, since the 9877f296bb3SBarry Smithuser-defined functions are intended to be accessed through the same 9887f296bb3SBarry Smithinterface, e.g., `MatMult(Mat,Vec,Vec)` $\to$ 9897f296bb3SBarry Smith`UserMult(Mat,Vec,Vec)`. The final argument for 9907f296bb3SBarry Smith`MatShellSetOperation()` needs to be cast to a `void *`, since the 9917f296bb3SBarry Smithfinal argument could (depending on the `MatOperation`) be a variety of 9927f296bb3SBarry Smithdifferent functions. 9937f296bb3SBarry Smith 9947f296bb3SBarry SmithNote that `MatShellSetOperation()` can also be used as a “backdoor” 9957f296bb3SBarry Smithmeans of introducing user-defined changes in matrix operations for other 9967f296bb3SBarry Smithstorage formats (for example, to override the default LU factorization 9977f296bb3SBarry Smithroutine supplied within PETSc for the `MATSEQAIJ` format). However, we 9987f296bb3SBarry Smithurge anyone who introduces such changes to use caution, since it would 9997f296bb3SBarry Smithbe very easy to accidentally create a bug in the new routine that could 10007f296bb3SBarry Smithaffect other routines as well. 10017f296bb3SBarry Smith 10027f296bb3SBarry SmithSee also {any}`sec_nlmatrixfree` for details on one set of 10037f296bb3SBarry Smithhelpful utilities for using the matrix-free approach for nonlinear 10047f296bb3SBarry Smithsolvers. 10057f296bb3SBarry Smith 10067f296bb3SBarry Smith(sec_mattranspose)= 10077f296bb3SBarry Smith 10087f296bb3SBarry Smith## Transposes of Matrices 10097f296bb3SBarry Smith 10107f296bb3SBarry SmithPETSc provides several ways to work with transposes of matrix. 10117f296bb3SBarry Smith 10127f296bb3SBarry Smith``` 10137f296bb3SBarry SmithMatTranspose(Mat A,MatReuse MAT_INITIAL_MATRIX or MAT_INPLACE_MATRIX or MAT_REUSE_MATRIX,Mat *B) 10147f296bb3SBarry Smith``` 10157f296bb3SBarry Smith 10167f296bb3SBarry Smithwill either do an in-place or out-of-place matrix explicit formation of the matrix transpose. After it has been called 10177f296bb3SBarry Smithwith `MAT_INPLACE_MATRIX` it may be called again with `MAT_REUSE_MATRIX` and it will recompute the transpose if the A 10187f296bb3SBarry Smithmatrix has changed. Internally it keeps track of whether the nonzero pattern of A has not changed so 10197f296bb3SBarry Smithwill reuse the symbolic transpose when possible for efficiency. 10207f296bb3SBarry Smith 10217f296bb3SBarry Smith``` 10227f296bb3SBarry SmithMatTransposeSymbolic(Mat A,Mat *B) 10237f296bb3SBarry Smith``` 10247f296bb3SBarry Smith 10257f296bb3SBarry Smithonly does the symbolic transpose on the matrix. After it is called `MatTranspose()` may be called with 10267f296bb3SBarry Smith`MAT_REUSE_MATRIX` to compute the numerical transpose. 10277f296bb3SBarry Smith 10287f296bb3SBarry SmithOccasionally one may already have a B matrix with the needed sparsity pattern to store the transpose and wants to reuse that 10297f296bb3SBarry Smithspace instead of creating a new matrix by calling `MatTranspose`(A,\`\`MAT_INITIAL_MATRIX\`\`,&B) but they cannot just call 10307f296bb3SBarry Smith`MatTranspose`(A,\`\`MAT_REUSE_MATRIX\`\`,&B) so instead they can call `MatTransposeSetPrecusor`(A,B) and then call 10317f296bb3SBarry Smith`MatTranspose`(A,\`\`MAT_REUSE_MATRIX\`\`,&B). This routine just provides to B the meta-data it needs to compute the numerical 10327f296bb3SBarry Smithfactorization efficiently. 10337f296bb3SBarry Smith 10347f296bb3SBarry SmithThe routine `MatCreateTranspose`(A,&B) provides a surrogate matrix B that behaviors like the transpose of A without forming 10357f296bb3SBarry Smiththe transpose explicitly. For example, `MatMult`(B,x,y) will compute the matrix-vector product of A transpose times x. 10367f296bb3SBarry Smith 10377f296bb3SBarry Smith(sec_othermat)= 10387f296bb3SBarry Smith 10397f296bb3SBarry Smith## Other Matrix Operations 10407f296bb3SBarry Smith 10417f296bb3SBarry SmithIn many iterative calculations (for instance, in a nonlinear equations 10427f296bb3SBarry Smithsolver), it is important for efficiency purposes to reuse the nonzero 10437f296bb3SBarry Smithstructure of a matrix, rather than determining it anew every time the 10447f296bb3SBarry Smithmatrix is generated. To retain a given matrix but reinitialize its 10457f296bb3SBarry Smithcontents, one can employ 10467f296bb3SBarry Smith 10477f296bb3SBarry Smith``` 10487f296bb3SBarry SmithMatZeroEntries(Mat A); 10497f296bb3SBarry Smith``` 10507f296bb3SBarry Smith 10517f296bb3SBarry SmithThis routine will zero the matrix entries in the data structure but keep 10527f296bb3SBarry Smithall the data that indicates where the nonzeros are located. In this way 10537f296bb3SBarry Smitha new matrix assembly will be much less expensive, since no memory 10547f296bb3SBarry Smithallocations or copies will be needed. Of course, one can also explicitly 10557f296bb3SBarry Smithset selected matrix elements to zero by calling `MatSetValues()`. 10567f296bb3SBarry Smith 10577f296bb3SBarry SmithBy default, if new entries are made in locations where no nonzeros 10587f296bb3SBarry Smithpreviously existed, space will be allocated for the new entries. To 10597f296bb3SBarry Smithprevent the allocation of additional memory and simply discard those new 10607f296bb3SBarry Smithentries, one can use the option 10617f296bb3SBarry Smith 10627f296bb3SBarry Smith``` 10637f296bb3SBarry SmithMatSetOption(Mat A,MAT_NEW_NONZERO_LOCATIONS,PETSC_FALSE); 10647f296bb3SBarry Smith``` 10657f296bb3SBarry Smith 10667f296bb3SBarry SmithOnce the matrix has been assembled, one can factor it numerically 10677f296bb3SBarry Smithwithout repeating the ordering or the symbolic factorization. This 10687f296bb3SBarry Smithoption can save some computational time, although it does require that 10697f296bb3SBarry Smiththe factorization is not done in-place. 10707f296bb3SBarry Smith 10717f296bb3SBarry SmithIn the numerical solution of elliptic partial differential equations, it 10727f296bb3SBarry Smithcan be cumbersome to deal with Dirichlet boundary conditions. In 10737f296bb3SBarry Smithparticular, one would like to assemble the matrix without regard to 10747f296bb3SBarry Smithboundary conditions and then at the end apply the Dirichlet boundary 10757f296bb3SBarry Smithconditions. In numerical analysis classes this process is usually 10767f296bb3SBarry Smithpresented as moving the known boundary conditions to the right-hand side 10777f296bb3SBarry Smithand then solving a smaller linear system for the interior unknowns. 10787f296bb3SBarry SmithUnfortunately, implementing this requires extracting a large submatrix 10797f296bb3SBarry Smithfrom the original matrix and creating its corresponding data structures. 10807f296bb3SBarry SmithThis process can be expensive in terms of both time and memory. 10817f296bb3SBarry Smith 10827f296bb3SBarry SmithOne simple way to deal with this difficulty is to replace those rows in 10837f296bb3SBarry Smiththe matrix associated with known boundary conditions, by rows of the 10847f296bb3SBarry Smithidentity matrix (or some scaling of it). This action can be done with 10857f296bb3SBarry Smiththe command 10867f296bb3SBarry Smith 10877f296bb3SBarry Smith``` 10887f296bb3SBarry SmithMatZeroRows(Mat A,PetscInt numRows,PetscInt rows[],PetscScalar diag_value,Vec x,Vec b), 10897f296bb3SBarry Smith``` 10907f296bb3SBarry Smith 10917f296bb3SBarry Smithor equivalently, 10927f296bb3SBarry Smith 10937f296bb3SBarry Smith``` 10947f296bb3SBarry SmithMatZeroRowsIS(Mat A,IS rows,PetscScalar diag_value,Vec x,Vec b); 10957f296bb3SBarry Smith``` 10967f296bb3SBarry Smith 10977f296bb3SBarry SmithFor sparse matrices this removes the data structures for certain rows of 10987f296bb3SBarry Smiththe matrix. If the pointer `diag_value` is `NULL`, it even removes 10997f296bb3SBarry Smiththe diagonal entry. If the pointer is not null, it uses that given value 11007f296bb3SBarry Smithat the pointer location in the diagonal entry of the eliminated rows. 11017f296bb3SBarry Smith 11027f296bb3SBarry SmithOne nice feature of this approach is that when solving a nonlinear 11037f296bb3SBarry Smithproblem such that at each iteration the Dirichlet boundary conditions 11047f296bb3SBarry Smithare in the same positions and the matrix retains the same nonzero 11057f296bb3SBarry Smithstructure, the user can call `MatZeroRows()` in the first iteration. 11067f296bb3SBarry SmithThen, before generating the matrix in the second iteration the user 11077f296bb3SBarry Smithshould call 11087f296bb3SBarry Smith 11097f296bb3SBarry Smith``` 11107f296bb3SBarry SmithMatSetOption(Mat A,MAT_NEW_NONZERO_LOCATIONS,PETSC_FALSE); 11117f296bb3SBarry Smith``` 11127f296bb3SBarry Smith 11137f296bb3SBarry SmithFrom that point, no new values will be inserted into those (boundary) 11147f296bb3SBarry Smithrows of the matrix. 11157f296bb3SBarry Smith 11167f296bb3SBarry SmithThe functions `MatZeroRowsLocal()` and `MatZeroRowsLocalIS()` can 11177f296bb3SBarry Smithalso be used if for each process one provides the Dirichlet locations in 11187f296bb3SBarry Smiththe local numbering of the matrix. A drawback of `MatZeroRows()` is 11197f296bb3SBarry Smiththat it destroys the symmetry of a matrix. Thus one can use 11207f296bb3SBarry Smith 11217f296bb3SBarry Smith``` 11227f296bb3SBarry SmithMatZeroRowsColumns(Mat A,PetscInt numRows,PetscInt rows[],PetscScalar diag_value,Vec x,Vec b), 11237f296bb3SBarry Smith``` 11247f296bb3SBarry Smith 11257f296bb3SBarry Smithor equivalently, 11267f296bb3SBarry Smith 11277f296bb3SBarry Smith``` 11287f296bb3SBarry SmithMatZeroRowsColumnsIS(Mat A,IS rows,PetscScalar diag_value,Vec x,Vec b); 11297f296bb3SBarry Smith``` 11307f296bb3SBarry Smith 11317f296bb3SBarry SmithNote that with all of these for a given assembled matrix it can be only 11327f296bb3SBarry Smithcalled once to update the x and b vector. It cannot be used if one 11337f296bb3SBarry Smithwishes to solve multiple right-hand side problems for the same matrix 11347f296bb3SBarry Smithsince the matrix entries needed for updating the b vector are removed in 11357f296bb3SBarry Smithits first use. 11367f296bb3SBarry Smith 11377f296bb3SBarry SmithOnce the zeroed rows are removed the new matrix has possibly many rows 11387f296bb3SBarry Smithwith only a diagonal entry affecting the parallel load balancing. The 11397f296bb3SBarry Smith`PCREDISTRIBUTE` preconditioner removes all the zeroed rows (and 11407f296bb3SBarry Smithassociated columns and adjusts the right-hand side based on the removed 11417f296bb3SBarry Smithcolumns) and then rebalances the resulting rows of smaller matrix across 11427f296bb3SBarry Smiththe processes. Thus one can use `MatZeroRows()` to set the Dirichlet 11437f296bb3SBarry Smithpoints and then solve with the preconditioner `PCREDISTRIBUTE`. Note 11447f296bb3SBarry Smithif the original matrix was symmetric the smaller solved matrix will also 11457f296bb3SBarry Smithbe symmetric. 11467f296bb3SBarry Smith 11477f296bb3SBarry SmithAnother matrix routine of interest is 11487f296bb3SBarry Smith 11497f296bb3SBarry Smith``` 11507f296bb3SBarry SmithMatConvert(Mat mat,MatType newtype,Mat *M) 11517f296bb3SBarry Smith``` 11527f296bb3SBarry Smith 11537f296bb3SBarry Smithwhich converts the matrix `mat` to new matrix, `M`, that has either 11547f296bb3SBarry Smiththe same or different format. Set `newtype` to `MATSAME` to copy the 11557f296bb3SBarry Smithmatrix, keeping the same matrix format. See 11567f296bb3SBarry Smith`$PETSC_DIR/include/petscmat.h` (<a href="PETSC_DOC_OUT_ROOT_PLACEHOLDER/include/petscmat.h.html">source</a>) 11577f296bb3SBarry Smithfor other available matrix types; standard ones are `MATSEQDENSE`, 11587f296bb3SBarry Smith`MATSEQAIJ`, `MATMPIAIJ`, `MATSEQBAIJ` and `MATMPIBAIJ`. 11597f296bb3SBarry Smith 11607f296bb3SBarry SmithIn certain applications it may be necessary for application codes to 11617f296bb3SBarry Smithdirectly access elements of a matrix. This may be done by using the the 11627f296bb3SBarry Smithcommand (for local rows only) 11637f296bb3SBarry Smith 11647f296bb3SBarry Smith``` 11657f296bb3SBarry SmithMatGetRow(Mat A,PetscInt row, PetscInt *ncols,const PetscInt (*cols)[],const PetscScalar (*vals)[]); 11667f296bb3SBarry Smith``` 11677f296bb3SBarry Smith 11687f296bb3SBarry SmithThe argument `ncols` returns the number of nonzeros in that row, while 11697f296bb3SBarry Smith`cols` and `vals` returns the column indices (with indices starting 11707f296bb3SBarry Smithat zero) and values in the row. If only the column indices are needed 11717f296bb3SBarry Smith(and not the corresponding matrix elements), one can use `NULL` for 11727f296bb3SBarry Smiththe `vals` argument. Similarly, one can use `NULL` for the `cols` 11737f296bb3SBarry Smithargument. The user can only examine the values extracted with 11747f296bb3SBarry Smith`MatGetRow()`; the values *cannot* be altered. To change the matrix 11757f296bb3SBarry Smithentries, one must use `MatSetValues()`. 11767f296bb3SBarry Smith 11777f296bb3SBarry SmithOnce the user has finished using a row, he or she *must* call 11787f296bb3SBarry Smith 11797f296bb3SBarry Smith``` 11807f296bb3SBarry SmithMatRestoreRow(Mat A,PetscInt row,PetscInt *ncols,PetscInt **cols,PetscScalar **vals); 11817f296bb3SBarry Smith``` 11827f296bb3SBarry Smith 11837f296bb3SBarry Smithto free any space that was allocated during the call to `MatGetRow()`. 11847f296bb3SBarry Smith 11857f296bb3SBarry Smith(sec_symbolic_numeric)= 11867f296bb3SBarry Smith 11877f296bb3SBarry Smith## Symbolic and Numeric Stages in Sparse Matrix Operations 11887f296bb3SBarry Smith 11897f296bb3SBarry SmithMany sparse matrix operations can be optimized by dividing the computation into two stages: a symbolic stage that 11907f296bb3SBarry Smithcreates any required data structures and does all the computations that do not require the matrices' numerical values followed by one or more uses of a 11917f296bb3SBarry Smithnumerical stage that use the symbolically computed information. Examples of such operations include `MatTranspose()`, `MatCreateSubMatrices()`, 11927f296bb3SBarry Smith`MatCholeskyFactorSymbolic()`, and `MatCholeskyFactorNumeric()`. 11937f296bb3SBarry SmithPETSc uses two different API's to take advantage of these optimizations. 11947f296bb3SBarry Smith 11957f296bb3SBarry SmithThe first approach explicitly divides the computation in the API. This approach is used, for example, with `MatCholeskyFactorSymbolic()`, `MatCholeskyFactorNumeric()`. 11967f296bb3SBarry SmithThe caller can take advantage of their knowledge of changes in the nonzero structure of the sparse matrices to call the appropriate routines as needed. In fact, they can 11977f296bb3SBarry Smithuse `MatGetNonzeroState()` to determine if a new symbolic computation is needed. The drawback of this approach is that the caller of these routines has to 11987f296bb3SBarry Smithmanage the creation of new matrices when the nonzero structure changes. 11997f296bb3SBarry Smith 12007f296bb3SBarry SmithThe second approach, as exemplified by `MatTranspose()`, does not expose the two stages explicit in the API, instead a flag, `MatReuse` is passed through the 12017f296bb3SBarry SmithAPI to indicate if a symbolic data structure is already available or needs to be computed. Thus `MatTranspose(A,MAT_INITIAL_MATRIX,&B)` is called first, then 12027f296bb3SBarry Smith`MatTranspose(A,MAT_REUSE_MATRIX,&B)` can be called repeatedly with new numerical values in the A matrix. In theory, if the nonzero structure of A changes, the 12037f296bb3SBarry Smithsymbolic computations for B could be redone automatically inside the same B matrix when there is a change in the nonzero state of the A matrix. In practice, in PETSc, the 12047f296bb3SBarry Smith`MAT_REUSE_MATRIX` for most PETSc routines only works if the nonzero structure does not change and the code may crash otherwise. The advantage of this approach 12057f296bb3SBarry Smith(when the nonzero structure changes are handled correctly) is that the calling code does not need to keep track of the nonzero state of the matrices; everything 12067f296bb3SBarry Smith"just works". However, the caller must still know when it is the first call to the routine so the flag `MAT_INITIAL_MATRIX` is being used. If the underlying implementation language supported detecting a yet to be initialized variable at run time, the `MatReuse` flag would not be need. 12077f296bb3SBarry Smith 12087f296bb3SBarry SmithPETSc uses two approaches because the same programming problem was solved with two different ways during PETSc's early development. 12097f296bb3SBarry SmithA better model would combine both approaches; an explicit 12107f296bb3SBarry Smithseparation of the stages and a unified operation that internally utilized the two stages appropriately and also handled changes to the nonzero structure. Code could be simplified in many places with this approach, in most places the use of the unified API would replace the use of the separate stages. 12117f296bb3SBarry Smith 12127f296bb3SBarry SmithSee {any}`sec_matsub` and {any}`sec_matmatproduct`. 12137f296bb3SBarry Smith 12147f296bb3SBarry Smith(sec_graph)= 12157f296bb3SBarry Smith 12167f296bb3SBarry Smith## Graph Operations 12177f296bb3SBarry Smith 12187f296bb3SBarry SmithPETSc has four families of graph operations that treat sparse `Mat` as representing graphs. 12197f296bb3SBarry Smith 12207f296bb3SBarry Smith```{eval-rst} 12217f296bb3SBarry Smith.. list-table:: 12227f296bb3SBarry Smith :widths: auto 12237f296bb3SBarry Smith :align: center 12247f296bb3SBarry Smith :header-rows: 1 12257f296bb3SBarry Smith 12267f296bb3SBarry Smith * - Operation 12277f296bb3SBarry Smith - Type 12287f296bb3SBarry Smith - Available methods 12297f296bb3SBarry Smith - User guide 12307f296bb3SBarry Smith * - Ordering to reduce fill 12317f296bb3SBarry Smith - N/A 12327f296bb3SBarry Smith - ``MatOrderingType`` 12337f296bb3SBarry Smith - :any:`sec_matfactor` 12347f296bb3SBarry Smith * - Partitioning for parallelism 12357f296bb3SBarry Smith - ``MatPartitioning`` 12367f296bb3SBarry Smith - ``MatPartitioningType`` 12377f296bb3SBarry Smith - :any:`sec_partitioning` 12387f296bb3SBarry Smith * - Coloring for parallelism or Jacobians 12397f296bb3SBarry Smith - ``MatColoring`` 12407f296bb3SBarry Smith - ``MatColoringType`` 12417f296bb3SBarry Smith - :any:`sec_fdmatrix` 12427f296bb3SBarry Smith * - Coarsening for multigrid 12437f296bb3SBarry Smith - ``MatCoarsen`` 12447f296bb3SBarry Smith - ``MatCoarsenType`` 12457f296bb3SBarry Smith - :any:`sec_amg` 12467f296bb3SBarry Smith``` 12477f296bb3SBarry Smith 12487f296bb3SBarry Smith(sec_partitioning)= 12497f296bb3SBarry Smith 12507f296bb3SBarry Smith## Partitioning 12517f296bb3SBarry Smith 12527f296bb3SBarry SmithFor almost all unstructured grid computation, the distribution of 12537f296bb3SBarry Smithportions of the grid across the process’s work load and memory can have 12547f296bb3SBarry Smitha very large impact on performance. In most PDE calculations the grid 12557f296bb3SBarry Smithpartitioning and distribution across the processes can (and should) be 12567f296bb3SBarry Smithdone in a “pre-processing” step before the numerical computations. 12577f296bb3SBarry SmithHowever, this does not mean it need be done in a separate, sequential 12587f296bb3SBarry Smithprogram; rather, it should be done before one sets up the parallel grid 12597f296bb3SBarry Smithdata structures in the actual program. PETSc provides an interface to 12607f296bb3SBarry Smiththe ParMETIS (developed by George Karypis; see 12617f296bb3SBarry Smith[the PETSc installation instructions](https://petsc.org/release/install/) 12627f296bb3SBarry Smithfor directions on installing PETSc to use ParMETIS) to allow the 12637f296bb3SBarry Smithpartitioning to be done in parallel. PETSc does not currently provide 12647f296bb3SBarry Smithdirectly support for dynamic repartitioning, load balancing by migrating 12657f296bb3SBarry Smithmatrix entries between processes, etc. For problems that require mesh 12667f296bb3SBarry Smithrefinement, PETSc uses the “rebuild the data structure” approach, as 12677f296bb3SBarry Smithopposed to the “maintain dynamic data structures that support the 12687f296bb3SBarry Smithinsertion/deletion of additional vector and matrix rows and columns 12697f296bb3SBarry Smithentries” approach. 12707f296bb3SBarry Smith 12717f296bb3SBarry SmithPartitioning in PETSc is organized around the `MatPartitioning` 12727f296bb3SBarry Smithobject. One first creates a parallel matrix that contains the 12737f296bb3SBarry Smithconnectivity information about the grid (or other graph-type object) 12747f296bb3SBarry Smiththat is to be partitioned. This is done with the command 12757f296bb3SBarry Smith 12767f296bb3SBarry Smith``` 12777f296bb3SBarry SmithMatCreateMPIAdj(MPI_Comm comm,int mlocal,PetscInt n,const PetscInt ia[],const PetscInt ja[],PetscInt *weights,Mat *Adj); 12787f296bb3SBarry Smith``` 12797f296bb3SBarry Smith 12807f296bb3SBarry SmithThe argument `mlocal` indicates the number of rows of the graph being 12817f296bb3SBarry Smithprovided by the given process, `n` is the total number of columns; 12827f296bb3SBarry Smithequal to the sum of all the `mlocal`. The arguments `ia` and `ja` 12837f296bb3SBarry Smithare the row pointers and column pointers for the given rows; these are 12847f296bb3SBarry Smiththe usual format for parallel compressed sparse row storage, using 12857f296bb3SBarry Smithindices starting at 0, *not* 1. 12867f296bb3SBarry Smith 12877f296bb3SBarry Smith:::{figure} /images/manual/usg.* 12887f296bb3SBarry Smith:alt: Numbering on Simple Unstructured Grid 12897f296bb3SBarry Smith:name: fig_usg 12907f296bb3SBarry Smith 12917f296bb3SBarry SmithNumbering on Simple Unstructured Grid 12927f296bb3SBarry Smith::: 12937f296bb3SBarry Smith 12947f296bb3SBarry SmithThis, of course, assumes that one has already distributed the grid 12957f296bb3SBarry Smith(graph) information among the processes. The details of this initial 12967f296bb3SBarry Smithdistribution is not important; it could be simply determined by 12977f296bb3SBarry Smithassigning to the first process the first $n_0$ nodes from a file, 12987f296bb3SBarry Smiththe second process the next $n_1$ nodes, etc. 12997f296bb3SBarry Smith 13007f296bb3SBarry SmithFor example, we demonstrate the form of the `ia` and `ja` for a 13017f296bb3SBarry Smithtriangular grid where we 13027f296bb3SBarry Smith 13037f296bb3SBarry Smith1. partition by element (triangle) 13047f296bb3SBarry Smith 13057f296bb3SBarry Smith- Process 0: `mlocal = 2`, `n = 4`, `ja =``{2,3, 3}`, 13067f296bb3SBarry Smith `ia =` `{0,2,3}` 13077f296bb3SBarry Smith- Process 1: `mlocal = 2`, `n = 4`, `ja =``{0, 0,1}`, 13087f296bb3SBarry Smith `ia =``{0,1,3}` 13097f296bb3SBarry Smith 13107f296bb3SBarry SmithNote that elements are not connected to themselves and we only indicate 13117f296bb3SBarry Smithedge connections (in some contexts single vertex connections between 13127f296bb3SBarry Smithelements may also be included). We use a space above to denote the 13137f296bb3SBarry Smithtransition between rows in the matrix; and 13147f296bb3SBarry Smith 13157f296bb3SBarry Smith2. partition by vertex. 13167f296bb3SBarry Smith 13177f296bb3SBarry Smith- Process 0: `mlocal = 3`, `n = 6`, 13187f296bb3SBarry Smith `ja =``{3,4, 4,5, 3,4,5}`, `ia =``{0, 2, 4, 7}` 13197f296bb3SBarry Smith- Process 1: `mlocal = 3`, `n = 6`, 13207f296bb3SBarry Smith `ja =``{0,2, 4, 0,1,2,3,5, 1,2,4}`, 13217f296bb3SBarry Smith `ia =``{0, 3, 8, 11}`. 13227f296bb3SBarry Smith 13237f296bb3SBarry SmithOnce the connectivity matrix has been created the following code will 13247f296bb3SBarry Smithgenerate the renumbering required for the new partition 13257f296bb3SBarry Smith 13267f296bb3SBarry Smith``` 13277f296bb3SBarry SmithMatPartitioningCreate(MPI_Comm comm,MatPartitioning *part); 13287f296bb3SBarry SmithMatPartitioningSetAdjacency(MatPartitioning part,Mat Adj); 13297f296bb3SBarry SmithMatPartitioningSetFromOptions(MatPartitioning part); 13307f296bb3SBarry SmithMatPartitioningApply(MatPartitioning part,IS *is); 13317f296bb3SBarry SmithMatPartitioningDestroy(MatPartitioning *part); 13327f296bb3SBarry SmithMatDestroy(Mat *Adj); 13337f296bb3SBarry SmithISPartitioningToNumbering(IS is,IS *isg); 13347f296bb3SBarry Smith``` 13357f296bb3SBarry Smith 13367f296bb3SBarry SmithThe resulting `isg` contains for each local node the new global number 13377f296bb3SBarry Smithof that node. The resulting `is` contains the new process number that 13387f296bb3SBarry Smitheach local node has been assigned to. 13397f296bb3SBarry Smith 13407f296bb3SBarry SmithNow that a new numbering of the nodes has been determined, one must 13417f296bb3SBarry Smithrenumber all the nodes and migrate the grid information to the correct 13427f296bb3SBarry Smithprocess. The command 13437f296bb3SBarry Smith 13447f296bb3SBarry Smith``` 13457f296bb3SBarry SmithAOCreateBasicIS(isg,NULL,&ao); 13467f296bb3SBarry Smith``` 13477f296bb3SBarry Smith 13487f296bb3SBarry Smithgenerates, see {any}`sec_ao`, an `AO` object that can be 13497f296bb3SBarry Smithused in conjunction with the `is` and `isg` to move the relevant 13507f296bb3SBarry Smithgrid information to the correct process and renumber the nodes etc. In 13517f296bb3SBarry Smiththis context, the new ordering is the “application” ordering so 13527f296bb3SBarry Smith`AOPetscToApplication()` converts old global indices to new global 13537f296bb3SBarry Smithindices and `AOApplicationToPetsc()` converts new global indices back 13547f296bb3SBarry Smithto old global indices. 13557f296bb3SBarry Smith 13567f296bb3SBarry SmithPETSc does not currently provide tools that completely manage the 13577f296bb3SBarry Smithmigration and node renumbering, since it will be dependent on the 13587f296bb3SBarry Smithparticular data structure you use to store the grid information and the 13597f296bb3SBarry Smithtype of grid information that you need for your application. We do plan 13607f296bb3SBarry Smithto include more support for this in the future, but designing the 13617f296bb3SBarry Smithappropriate general user interface and providing a scalable 13627f296bb3SBarry Smithimplementation that can be used for a wide variety of different grids 13637f296bb3SBarry Smithrequires a great deal of time. 13647f296bb3SBarry Smith 13657f296bb3SBarry SmithSee {any}`sec_fdmatrix` and {any}`sec_matfactor` for discussions on performing graph coloring and computing graph reorderings to 13667f296bb3SBarry Smithreduce fill in sparse matrix factorizations. 13677f296bb3SBarry Smith 13687f296bb3SBarry Smith```{eval-rst} 13697f296bb3SBarry Smith.. bibliography:: /petsc.bib 13707f296bb3SBarry Smith :filter: docname in docnames 13717f296bb3SBarry Smith :keyprefix: keyprefix- 13727f296bb3SBarry Smith :labelprefix: ref- 13737f296bb3SBarry Smith``` 1374