### Install petsc and petsc4py from PyPI Source: https://petsc.org/release/petsc4py/install Installs the petsc and petsc4py Python packages using pip. This is the simplest method for users who want to quickly get started with the library. ```bash $ python -m pip install petsc petsc4py ``` -------------------------------- ### Configure PETSc with MPICH and BLAS/LAPACK Downloads Source: https://petsc.org/release/install/install_tutorial This command configures PETSc and simultaneously downloads and installs MPICH and a BLAS/LAPACK reference implementation. This is a common starting point for setting up PETSc with essential dependencies. ```bash ./configure --download-mpich --download-fblaslapack ``` -------------------------------- ### PETSc Build Command Example Source: https://petsc.org/release/_sources/install/install_tutorial This is an example of a `make` command printed by the `configure` script for building PETSc. It includes instructions on setting PETSC_DIR and PETSC_ARCH environment variables, which are crucial for the build process. ```console make PETSC_DIR=/Users/jacobfaibussowitsch/NoSync/petsc PETSC_ARCH=arch-darwin-c-debug all ``` -------------------------------- ### Install petsc4py Documentation Dependencies Source: https://petsc.org/release/petsc4py/install Installs the necessary dependencies for building the petsc4py documentation using pip and a requirements file. ```bash $ python -m pip install -r src/binding/petsc4py/conf/requirements-docs.txt ``` -------------------------------- ### Building PETSc Example with Environment Variables (Bash) Source: https://petsc.org/release/_sources/install/multibuild Example of how to build a PETSc example by specifying PETSC_ARCH and PETSC_DIR on the command line in a Bash shell. This is useful for temporary configurations or specific builds. ```bash $ PETSC_ARCH=linux-gnu-c-debug make PETSC_DIR=/absolute/path/to/petsc ex1 ``` -------------------------------- ### Multiple PETSc Installs with --prefix Source: https://petsc.org/release/_sources/install/install This example demonstrates how to install multiple versions of PETSc with different configurations by specifying a unique `--prefix` for each installation. It also shows the use of `DESTDIR` during the `make install` step for packaging purposes. This method is useful for managing different PETSc builds with distinct MPI implementations or versions. ```console $ ./configure --prefix=/opt/petsc/petsc-3.24.0-mpich --with-mpi-dir=/opt/mpich $ make $ make install [DESTDIR=/tmp/petsc-pkg] $ ./configure --prefix=/opt/petsc/petsc-3.24.0-openmpi --with-mpi-dir=/opt/openmpi $ make $ make install [DESTDIR=/tmp/petsc-pkg] ``` -------------------------------- ### Run petsc4py Test Suite from Source Source: https://petsc.org/release/petsc4py/install Executes the complete petsc4py test suite when installing from source. Tests can be run directly using the runtests.py script or via the makefile. ```bash $ cd src/binding/petsc4py $ python test/runtests.py ``` ```bash $ make test -C src/binding/petsc4py ``` -------------------------------- ### Test Fortran Compiler Installation Source: https://petsc.org/release/install/install_tutorial This command checks if the Fortran compiler is installed and working correctly by compiling and running a simple Fortran program. If successful, it will print 'gfortran OK!' to the console. ```bash printf 'program t\nprint"(a)","gfortran OK!"\nend program' > t.f90 && gfortran t.f90 && ./a.out && rm -f t.f90 a.out ``` -------------------------------- ### PETSc Solver Setup and Profiling Source: https://petsc.org/release/src/ksp/ksp/tutorials/ex27 Explicitly calls KSPSetUp() and KSPSetUpOnBlocks() for precise profiling of the preconditioner setup phase. These calls are optional as they are also invoked within KSPSolve(). Dependencies include PETSc library. ```c /* Here we explicitly call KSPSetUp() and KSPSetUpOnBlocks() to enable more precise profiling of setting up the preconditioner. These calls are optional, since both will be called within KSPSolve() if they haven't been called already. */ PetscCall(KSPSetUp(ksp)); PetscCall(KSPSetUpOnBlocks(ksp)); ``` -------------------------------- ### Test C++ Compiler Installation Source: https://petsc.org/release/install/install_tutorial This command verifies the installation and functionality of the C++ compiler by compiling and executing a basic C++ program. A successful run will output 'c++ OK!'. ```bash printf '#include\nint main(){std::cout<<"c++ OK!"< t.cpp && c++ t.cpp && ./a.out && rm -f t.cpp a.out ``` -------------------------------- ### PETSc Implementation Function Naming Convention Example Source: https://petsc.org/release/developers/style Demonstrates the naming convention for implementation functions, which start with the function name, an underscore, and then the implementation name. ```c KSPSolve_GMRES(); ``` -------------------------------- ### Display PETSc Configure Help Source: https://petsc.org/release/install/install_tutorial This command displays all available configuration options and flags for PETSc. It is useful for understanding the full range of customization available during the installation process. ```bash ./configure --help ``` -------------------------------- ### Get Cell Stratum - PETSc Source: https://petsc.org/release/src/dm/field/tutorials/ex1 Retrieves the start and end indices for a specific stratum of cells in a mesh. This is often used to access boundary or interior cells. ```c PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd)); ``` -------------------------------- ### Configure and Build PETSc (Basic) Source: https://petsc.org/release/install/install_tutorial This snippet shows the basic commands to configure and build PETSc on a system where MPI and BLAS/LAPACK are already installed. It involves running the configure script followed by make commands. ```bash ./configure make all check ``` -------------------------------- ### PETSc Class Function Naming Convention Example Source: https://petsc.org/release/developers/style Illustrates the naming convention for application-usable functions, starting with the class object name, followed by any subclass name. ```c ISInvertPermutation(); MatMult(); KSPGMRESSetRestart(); ``` -------------------------------- ### Compile and Check PETSc Installation Source: https://petsc.org/release/install/install_tutorial This command initiates the build process for PETSc binaries from source code. It compiles all necessary components and runs a series of checks to ensure the installation is functional. This process can be resource-intensive and may take a significant amount of time, especially when run in parallel. ```bash $ make all check ``` -------------------------------- ### Set Initial Conditions for PETSc Vector Source: https://petsc.org/release/src/ts/tutorials/ex20td This example demonstrates how to set initial conditions for a PETSc vector. It involves getting the array pointer for the vector, assigning specific values to its elements, and then restoring the array. This is crucial for starting simulations accurately. ```C PetscCall(VecGetArray(user.U, &x_ptr)); x_ptr[0] = 2.0; x_ptr[1] = -2.0 / 3.0; PetscCall(VecRestoreArray(user.U, &x_ptr)); ``` -------------------------------- ### Set Up DMDa Mesh and Get Cell Stratum - PETSc Source: https://petsc.org/release/src/dm/field/tutorials/ex1 Sets up the DMDa mesh and retrieves the start and end indices for the cells of the mesh. This is a standard step after creating a DMDa object. ```c PetscCall(DMSetUp(dm)); PetscCall(DMDAGetHeightStratum(dm, 0, &cStart, &cEnd)); ``` -------------------------------- ### Copy PETSc Tutorial Example to Application Directory Source: https://petsc.org/release/_sources/manual/getting_started This command copies a PETSc tutorial C example (e.g., ex19.c) into the user's application directory. This serves as a starting point for developing custom applications. Ensure `PETSC_DIR` is set. ```bash cp $PETSC_DIR/src/snes/tutorials/ex19.c app.c ``` -------------------------------- ### PETSc: Get Mesh Information and Initialize Vectors Source: https://petsc.org/release/src/ts/tutorials/multirate/ex4 This snippet retrieves information about the distributed mesh (DA) and initializes a vector to zero. It's a common setup step in PETSc applications. ```c PetscCall(DMDAGetInfo(da, 0, &Mx, 0, 0, 0, 0, 0, &dof, 0, 0, 0, 0, 0)); /* Mx is the number of center points */ PetscCall(DMGlobalToLocalBegin(da, X, INSERT_VALUES, Xloc)); /* X is solution vector which does not contain ghost points */ PetscCall(DMGlobalToLocalEnd(da, X, INSERT_VALUES, Xloc)); PetscCall(VecZeroEntries(F)); /* F is the right-hand side function corresponds to center points */ ``` -------------------------------- ### Configure and Build PETSc (with specific compilers and downloads) Source: https://petsc.org/release/install/install_tutorial This snippet demonstrates how to configure PETSc while specifying C, C++, and Fortran compilers, and instructing PETSc to download and install MPICH and BLAS/LAPACK if they are not present. This is useful for setting up PETSc in environments where these dependencies are missing. ```bash ./configure --with-cc=gcc --with-cxx=g++ --with-fc=gfortran --download-mpich --download-fblaslapack make all check ``` -------------------------------- ### Verify PETSc Download and Update Source: https://petsc.org/release/install/install_tutorial This bash snippet demonstrates the output of a successful git clone operation for PETSc and includes a command to pull the latest changes. This is useful for confirming the download was successful and for keeping the local repository up-to-date. ```bash $ git clone -b release https://gitlab.com/petsc/petsc.git petsc Cloning into 'petsc'... remote: Enumerating objects: 862597, done. remote: Counting objects: 100% (862597/862597), done. remote: Compressing objects: 100% (197622/197622), done. remote: Total 862597 (delta 660708), reused 862285 (delta 660444) Receiving objects: 100% (862597/862597), 205.11 MiB | 3.17 MiB/s, done. Resolving deltas: 100% (660708/660708), done. Updating files: 100% (7748/7748), done. $ cd petsc $ git pull # Not strictly necessary, but nice to check Already up to date. ``` -------------------------------- ### Get PETSc Installation Directory (C) Source: https://petsc.org/release/manualpages/Sys/PetscGetPetscDir Retrieves the directory where PETSc is installed. This C function takes a character pointer array as output to store the directory path. It is a non-collective operation and does not support Fortran. ```c #include "petscsys.h" PetscErrorCode PetscGetPetscDir(const char *dir[]) ``` -------------------------------- ### Download PETSc Source Code using Git Source: https://petsc.org/release/install/install_tutorial This snippet shows the bash commands to create a directory, navigate into it, and clone the latest release branch of the PETSc repository using git. It's a straightforward way to obtain the source code for development. ```bash $ mkdir ~/projects $ cd ~/projects $ git clone -b release https://gitlab.com/petsc/petsc $ cd petsc ``` -------------------------------- ### PETSc Options Database Key Naming Convention Example Source: https://petsc.org/release/developers/style Describes the naming convention for PETSc options database keys: lowercase, underscores between words, matching the associated function name without 'set' or 'get'. ```shell -ksp_gmres_restart ``` -------------------------------- ### Example PETSc successful configuration output Source: https://petsc.org/release/_sources/install/install_tutorial This text block illustrates the expected output structure upon a successful PETSc `configure` process. It shows stages of configuration, testing, downloading, and compiling external packages like MPICH and FBLASLAPACK, followed by compiler and MPI information. This serves as a reference for users to verify their installation. ```text =============================================================================== Configuring PETSc to compile on your system =============================================================================== TESTING: configureSomething from PETSc.something(config/PETSc/configurescript.py:lineNUM) =============================================================================== Trying to download MPICH_DOWNLOAD_URL for MPICH =============================================================================== =============================================================================== Running configure on MPICH; this may take several minutes =============================================================================== =============================================================================== Running make on MPICH; this may take several minutes =============================================================================== =============================================================================== Running make install on MPICH; this may take several minutes =============================================================================== =============================================================================== Trying to download FBLASLAPACK_URL for FBLASLAPACK =============================================================================== =============================================================================== Compiling FBLASLAPACK; this may take several minutes =============================================================================== =============================================================================== Trying to download SOWING_DOWNLOAD_URL for SOWING =============================================================================== =============================================================================== Running configure on SOWING; this may take several minutes =============================================================================== =============================================================================== Running make on SOWING; this may take several minutes =============================================================================== =============================================================================== Running make install on SOWING; this may take several minutes =============================================================================== Compilers: C Compiler: Location information and flags C++ Compiler: Location information and flags . . . MPI: Includes: Include path ``` -------------------------------- ### Install PETSc with MacPorts Source: https://petsc.org/release/_sources/install/index Installs PETSc on macOS systems using the MacPorts package manager. This command requires root privileges to install system-wide. ```bash sudo port install petsc ``` -------------------------------- ### Main Function for Petsc Initialization and Simulation Setup in C Source: https://petsc.org/release/src/snes/tutorials/ex7 The main function initializes the PETSc environment, processes command-line options, creates mesh and discretization objects, and sets up global vectors. It then proceeds to compute the residual and Jacobian, view solution vectors, and perform free field tests before cleaning up resources. ```c int main(int argc, char **argv) { DM dm; Vec u, f; Mat J; AppCtx user; PetscCall(PetscInitialize(&argc, &argv, NULL, help)); PetscCall(ProcessOptions(PETSC_COMM_WORLD, &user)); PetscCall(CreateMesh(PETSC_COMM_WORLD, &user, &dm)); PetscCall(SetupDiscretization(dm, &user)); PetscCall(SetupAuxDiscretization(dm, &user)); PetscCall(DMCreateGlobalVector(dm, &u)); PetscCall(DMCreateGlobalVector(dm, &f)); if (user.printTr) PetscCall(PrintTraversal(dm)); PetscCall(ComputeResidual(dm, u, f)); PetscCall(VecViewFromOptions(f, NULL, "-res_view")); PetscCall(CreateJacobian(dm, &J)); PetscCall(ComputeJacobian(dm, u, J)); PetscCall(VecViewFromOptions(u, NULL, "-sol_view")); PetscCall(TestFreeField(dm)); PetscCall(VecDestroy(&f)); PetscCall(VecDestroy(&u)); PetscCall(DMDestroy(&dm)); PetscCall(PetscFinalize()); return 0; } ``` -------------------------------- ### Get Local Grid Boundaries with DMDAGetCorners Source: https://petsc.org/release/src/snes/tutorials/ex3 Retrieves the local grid boundaries (starting index and width) for a given distributed array (DMDA). This is essential for iterating over the locally owned portion of the grid, excluding ghost points, when performing computations. ```c PetscCall(DMDAGetCorners(da, &xs, NULL, NULL, &xm, NULL, NULL)); ``` -------------------------------- ### Display PETSc configure help options Source: https://petsc.org/release/_sources/install/install_tutorial This command displays all available configuration options and flags for the PETSc `configure` script. It's useful for understanding the full range of customization possible during the PETSc setup process. No specific inputs or outputs are defined, as it's a help command. ```console $ ./configure --help ``` -------------------------------- ### Install PETSc with Conda Source: https://petsc.org/release/_sources/install/index Installs PETSc using the Conda package manager. This command fetches the PETSc package and its dependencies from the conda-forge channel. ```bash conda install -c conda-forge petsc ``` -------------------------------- ### Initialize PETSc and Application Context Source: https://petsc.org/release/src/ts/tutorials/ex15 Initializes the PETSc environment and sets up the user application context, including grid dimensions, stencil points, and boundary conditions. It parses command-line options to configure these parameters. ```c int main(int argc, char **argv) { TS ts; /* nonlinear solver */ Vec u, r; /* solution, residual vectors */ Mat J, Jmf = NULL; /* Jacobian matrices */ DM da; PetscReal dt; AppCtx user; /* user-defined work context */ SNES snes; PetscInt Jtype; /* Jacobian type 0: user provide Jacobian; 1: slow finite difference; 2: fd with coloring; */ PetscFunctionBeginUser; PetscCall(PetscInitialize(&argc, &argv, NULL, help)); /* Initialize user application context */ user.da = NULL; user.nstencilpts = 5; user.c = -30.0; user.boundary = 0; /* 0: Drichlet BC; 1: Neumann BC */ user.viewJacobian = PETSC_FALSE; PetscCall(PetscOptionsGetInt(NULL, NULL, "-nstencilpts", &user.nstencilpts, NULL)); PetscCall(PetscOptionsGetInt(NULL, NULL, "-boundary", &user.boundary, NULL)); PetscCall(PetscOptionsHasName(NULL, NULL, "-viewJacobian", &user.viewJacobian)); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Create distributed array (DMDA) to manage parallel grid and vectors - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ if (user.nstencilpts == 5) { PetscCall(DMDACreate2d(PETSC_COMM_WORLD, DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, DMDA_STENCIL_STAR, 11, 11, PETSC_DECIDE, PETSC_DECIDE, 1, 1, NULL, NULL, &da)); } else if (user.nstencilpts == 9) { PetscCall(DMDACreate2d(PETSC_COMM_WORLD, DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, DMDA_STENCIL_BOX, 11, 11, PETSC_DECIDE, PETSC_DECIDE, 1, 1, NULL, NULL, &da)); } else SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_SUP, "nstencilpts %" PetscInt_FMT " is not supported", user.nstencilpts); PetscCall(DMSetFromOptions(da)); PetscCall(DMSetUp(da)); user.da = da; /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Extract global vectors from DMDA; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ PetscCall(DMCreateGlobalVector(da, &u)); PetscCall(VecDuplicate(u, &r)); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Create timestepping solver context - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ PetscCall(TSCreate(PETSC_COMM_WORLD, &ts)); PetscCall(TSSetProblemType(ts, TS_NONLINEAR)); PetscCall(TSSetType(ts, TSBEULER)); PetscCall(TSSetDM(ts, da)); PetscCall(TSSetIFunction(ts, r, FormIFunction, &user)); PetscCall(TSSetMaxTime(ts, 1.0)); PetscCall(TSSetExactFinalTime(ts, TS_EXACTFINALTIME_STEPOVER)); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Set initial conditions - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ PetscCall(FormInitialSolution(u, &user)); PetscCall(TSSetSolution(ts, u)); dt = .01; PetscCall(TSSetTimeStep(ts, dt)); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Set Jacobian evaluation routine - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ return 0; } ``` -------------------------------- ### C: PETSc DMDA Rotated Boundary Conditions Setup Source: https://petsc.org/release/src/dm/tutorials/ex6 Initializes PETSc, creates a 2D DMDA with ghosted boundaries, and sets up global and local vectors. This is the foundational step for handling complex boundary conditions. It requires the PETSc library to be installed and configured. ```c int main(int argc, char **argv) { PetscInt M = 6; DM da; Vec local, global, natural; PetscInt i, start, end, *ifrom, x, y, xm, ym; PetscScalar *xnatural; IS from, to; AO ao; VecScatter scatter1, scatter2; PetscViewer subviewer; PetscFunctionBeginUser; PetscCall(PetscInitialize(&argc, &argv, NULL, help)); /* Create distributed array and get vectors */ PetscCall(DMDACreate2d(PETSC_COMM_WORLD, DM_BOUNDARY_GHOSTED, DM_BOUNDARY_GHOSTED, DMDA_STENCIL_STAR, M, M, PETSC_DECIDE, PETSC_DECIDE, 1, 1, NULL, NULL, &da)); PetscCall(DMSetUp(da)); PetscCall(DMCreateGlobalVector(da, &global)); PetscCall(DMCreateLocalVector(da, &local)); /* ... rest of the code ... */ PetscFunctionReturn(0); } ``` -------------------------------- ### PETSc: Initialize and Configure Source: https://petsc.org/release/src/ksp/ksp/tutorials/ex16 Initializes PETSc, processes command-line arguments for mesh dimensions, and sets up the linear system solver context. It requires PETSc to be installed and configured. ```c int main(int argc, char **args) { Vec x, b, u; /* approx solution, RHS, exact solution */ Mat A; /* linear system matrix */ KSP ksp; /* linear solver context */ PetscReal norm; /* norm of solution error */ PetscInt ntimes, i, j, k, Ii, J, Istart, Iend; PetscInt m = 8, n = 7, its; PetscBool flg = PETSC_FALSE; PetscScalar v, one = 1.0, rhs; PetscFunctionBeginUser; PetscCall(PetscInitialize(&argc, &args, NULL, help)); PetscCall(PetscOptionsGetInt(NULL, NULL, "-m", &m, NULL)); PetscCall(PetscOptionsGetInt(NULL, NULL, "-n", &n, NULL)); /* ... matrix and vector creation ... */ PetscFunctionReturn(0); } ``` -------------------------------- ### C: Initialize PETSc and Set Options for ex3.c Source: https://petsc.org/release/src/ksp/ksp/tutorials/ex3 Initializes the PETSc environment, parses command-line options, and sets up basic problem parameters like mesh size. It defines the global system dimensions (N) and the number of elements (M), and calculates the mesh width (h). ```c static char help[] = "Bilinear elements on the unit square for Laplacian. To test the parallel\nmatrix assembly, the matrix is intentionally laid out across processors\ndifferently from the way it is assembled. Input arguments are:\n -m : problem size\n\n"; #include int main(int argc, char **args) { Vec u, b, ustar; Mat A; KSP ksp; PetscInt N, M; PetscMPIInt rank, size; PetscScalar Ke[16]; PetscScalar r[4]; PetscReal h, norm; PetscScalar x, y; PetscInt idx[4], count, *rows, i, m = 5, start, end, its; PetscFunctionBeginUser; PetscCall(PetscInitialize(&argc, &args, NULL, help)); PetscCall(PetscOptionsGetInt(NULL, NULL, "-m", &m, NULL)); N = (m + 1) * (m + 1); M = m * m; h = 1.0 / m; PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank)); PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size)); ``` -------------------------------- ### Install PETSc with Spack (Debug) Source: https://petsc.org/release/_sources/install/index Installs PETSc with debugging symbols enabled using the Spack package manager. This configuration is useful for development and troubleshooting. ```bash spack install petsc +debug ``` -------------------------------- ### Install PETSc with Homebrew Source: https://petsc.org/release/_sources/install/index Installs PETSc on macOS or Linux systems using the Homebrew package manager. This command downloads and compiles PETSc and its dependencies. ```bash brew install petsc ``` -------------------------------- ### Run PETSc Example Configuration Script Source: https://petsc.org/release/_sources/install/install Executes a pre-defined PETSc configuration script from the examples directory. This is useful for quickly setting up PETSc for specific environments like CI/OSX debug builds. ```console ./config/examples/arch-ci-osx-dbg.py ``` -------------------------------- ### Main Function Setup and PETSc Initialization in C Source: https://petsc.org/release/src/ts/utils/dmplexlandau/tutorials/ex1 This C snippet demonstrates the main function for a PETSc application. It initializes the PETSc environment, processes command-line arguments for simulation dimensions and options related to NRL data, and sets up initial data structures. ```c int main(int argc, char **argv) { DM pack; Vec X; PetscInt dim = 2, nDMs; TS ts, ts_nrl = NULL; Mat J; Vec *XsubArray = NULL; LandauCtx *ctx; PetscMPIInt rank; PetscBool use_nrl = PETSC_TRUE; PetscBool print_nrl = PETSC_FALSE; PetscReal dt0; PetscFunctionBeginUser; PetscCall(PetscInitialize(&argc, &argv, NULL, help)); PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank)); if (rank) { /* turn off output stuff for duplicate runs */ PetscCall(PetscOptionsClearValue(NULL, "-ex1_dm_view_e")); PetscCall(PetscOptionsClearValue(NULL, "-ex1_dm_view_i")); PetscCall(PetscOptionsClearValue(NULL, "-ex1_vec_view_e")); PetscCall(PetscOptionsClearValue(NULL, "-ex1_vec_view_i")); PetscCall(PetscOptionsClearValue(NULL, "-info")); PetscCall(PetscOptionsClearValue(NULL, "-snes_converged_reason")); PetscCall(PetscOptionsClearValue(NULL, "-pc_bjkokkos_ksp_converged_reason")); PetscCall(PetscOptionsClearValue(NULL, "-ksp_converged_reason")); PetscCall(PetscOptionsClearValue(NULL, "-ts_adapt_monitor")); PetscCall(PetscOptionsClearValue(NULL, "-ts_monitor")); PetscCall(PetscOptionsClearValue(NULL, "-snes_monitor")); } PetscCall(PetscOptionsGetInt(NULL, NULL, "-dim", &dim, NULL)); PetscCall(PetscOptionsGetBool(NULL, NULL, "-use_nrl", &use_nrl, NULL)); PetscCall(PetscOptionsGetBool(NULL, NULL, "-print_nrl", &print_nrl, NULL)); /* Create a mesh */ ``` -------------------------------- ### Install PETSc with APT (Debian/Ubuntu) Source: https://petsc.org/release/_sources/install/index Installs the PETSc development package on Debian-based systems using the APT package manager. This command requires root privileges. ```bash sudo apt install petsc-dev ``` -------------------------------- ### Compile and Check PETSc Installation Source: https://petsc.org/release/_sources/install/install_tutorial Builds the PETSc binaries from source and runs checks to verify the installation. This command should be executed after a successful configuration. ```console $ make all check ``` -------------------------------- ### Install petsc4py with Multiple PETSC_ARCH Source: https://petsc.org/release/petsc4py/install Installs petsc4py from the PETSc source tree supporting multiple PETSC_ARCH configurations. This is useful for complex build environments or cross-compilation scenarios. ```bash $ PETSC_ARCH='arch-0:...:arch-N' python -m pip install src/binding/petsc4py ``` -------------------------------- ### C: Main Program Initialization and Setup Source: https://petsc.org/release/src/ts/tutorials/multirate/ex2 The main function initializes the PETSc environment, sets up the ODE integrator (TS), creates and duplicates solution vectors, and handles runtime options for parameters like 'a', 'b', 'Tf', and 'dt'. ```c int main(int argc, char **argv) { TS ts; /* ODE integrator */ Vec U; /* solution will be stored here */ Vec Utrue; PetscMPIInt size; AppCtx ctx; PetscScalar *u; IS iss; /* IS for slow part */ IS isf; /* IS for fast part */ PetscInt *indicess; PetscInt *indicesf; PetscInt n = 2; PetscScalar error, tt; /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Initialize program - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ PetscFunctionBeginUser; PetscCall(PetscInitialize(&argc, &argv, NULL, help)); PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size)); PetscCheck(size == 1, PETSC_COMM_WORLD, PETSC_ERR_WRONG_MPI_SIZE, "Only for sequential runs"); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Create index for slow part and fast part - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ PetscCall(PetscMalloc1(1, &indicess)); indicess[0] = 0; PetscCall(PetscMalloc1(1, &indicesf)); indicesf[0] = 1; PetscCall(ISCreateGeneral(PETSC_COMM_SELF, 1, indicess, PETSC_COPY_VALUES, &iss)); PetscCall(ISCreateGeneral(PETSC_COMM_SELF, 1, indicesf, PETSC_COPY_VALUES, &isf)); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Create necessary vector - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ PetscCall(VecCreate(PETSC_COMM_WORLD, &U)); PetscCall(VecSetSizes(U, n, PETSC_DETERMINE)); PetscCall(VecSetFromOptions(U)); PetscCall(VecDuplicate(U, &Utrue)); PetscCall(VecCopy(U, Utrue)); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Set runtime options - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ PetscOptionsBegin(PETSC_COMM_WORLD, NULL, "ODE options", ""); { ctx.a = 1.0; ctx.b = 25.0; PetscCall(PetscOptionsScalar("-a", "", "", ctx.a, &ctx.a, NULL)); PetscCall(PetscOptionsScalar("-b", "", "", ctx.b, &ctx.b, NULL)); ctx.Tf = 5.0; ctx.dt = 0.01; PetscCall(PetscOptionsScalar("-Tf", "", "", ctx.Tf, &ctx.Tf, NULL)); PetscCall(PetscOptionsScalar("-dt", "", "", ctx.dt, &ctx.dt, NULL)); } PetscOptionsEnd(); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Initialize the solution ``` -------------------------------- ### Install PETSc and PETSc4Py with Pip Source: https://petsc.org/release/_sources/install/index Installs PETSc and its Python bindings (petsc4py) using pip. This command is suitable for Python environments and may require build tools. ```python python -m pip install petsc petsc4py ``` -------------------------------- ### Get Local Cell Interval - C Source: https://petsc.org/release/manualpages/DMForest/DMForestGetCellChart Retrieves the local range of cell indices (inclusive start, exclusive end) for a given DMForest. This function is not collective, meaning each process calls it independently to get its own local range. It requires the DM object and pointers to store the start and end indices. ```c #include "petscdmforest.h" #include "petscdm.h" #include "petscdmlabel.h" PetscErrorCode DMForestGetCellChart(DM dm, PetscInt *cStart, PetscInt *cEnd) ``` -------------------------------- ### Main Function for Petsc Simulation Source: https://petsc.org/release/src/tao/tutorials/ex1 The entry point for the PETSc application. It initializes PETSc, processes command-line options, creates and configures the Discretization (DM) and Solver (SNES) objects, sets up the initial guess and exact solutions, solves the problem, and computes errors. ```c int main(int argc, char **argv) { DM dm; SNES snes; Vec u, r; AppCtx user; PetscFunctionBeginUser; PetscCall(PetscInitialize(&argc, &argv, NULL, help)); PetscCall(ProcessOptions(PETSC_COMM_WORLD, &user)); PetscCall(SNESCreate(PETSC_COMM_WORLD, &snes)); PetscCall(CreateMesh(PETSC_COMM_WORLD, &user, &dm)); PetscCall(SNESSetDM(snes, dm)); PetscCall(SetupDiscretization(dm, &user)); PetscCall(DMCreateGlobalVector(dm, &u)); PetscCall(PetscObjectSetName((PetscObject)u, "solution")); PetscCall(VecDuplicate(u, &r)); PetscCall(DMPlexSetSNESLocalFEM(dm, PETSC_FALSE, &user)); PetscCall(SNESSetFromOptions(snes)); PetscCall(DMSNESCheckFromOptions(snes, u)); if (user.runType == RUN_FULL) { PetscDS ds; PetscErrorCode (*exactFuncs[3])(PetscInt dim, PetscReal t, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx); PetscErrorCode (*initialGuess[3])(PetscInt dim, PetscReal t, const PetscReal x[], PetscInt Nf, PetscScalar u[], void *ctx); PetscReal error; PetscCall(DMGetDS(dm, &ds)); PetscCall(PetscDSGetExactSolution(ds, 0, &exactFuncs[0], NULL)); PetscCall(PetscDSGetExactSolution(ds, 1, &exactFuncs[1], NULL)); PetscCall(PetscDSGetExactSolution(ds, 2, &exactFuncs[2], NULL)); initialGuess[0] = zero; initialGuess[1] = zero; initialGuess[2] = zero; PetscCall(DMProjectFunction(dm, 0.0, initialGuess, NULL, INSERT_VALUES, u)); PetscCall(VecViewFromOptions(u, NULL, "-initial_vec_view")); PetscCall(DMComputeL2Diff(dm, 0.0, exactFuncs, NULL, u, &error)); if (error < 1.0e-11) PetscCall(PetscPrintf(PETSC_COMM_WORLD, "Initial L_2 Error: < 1.0e-11\n")); else PetscCall(PetscPrintf(PETSC_COMM_WORLD, "Initial L_2 Error: %g\n", (double)error)); PetscCall(SNESSolve(snes, NULL, u)); PetscCall(DMComputeL2Diff(dm, 0.0, exactFuncs, NULL, u, &error)); if (error < 1.0e-11) PetscCall(PetscPrintf(PETSC_COMM_WORLD, "Final L_2 Error: < 1.0e-11\n")); else PetscCall(PetscPrintf(PETSC_COMM_WORLD, "Final L_2 Error: %g\n", (double)error)); } PetscCall(VecViewFromOptions(u, NULL, "-sol_vec_view")); PetscCall(VecDestroy(&u)); PetscCall(VecDestroy(&r)); PetscCall(SNESDestroy(&snes)); PetscCall(DMDestroy(&dm)); PetscCall(PetscFinalize()); return 0; } ``` -------------------------------- ### C: Create Viewer with PetscOptionsCreateViewer() Source: https://petsc.org/release/src/sys/classes/viewer/tutorials/ex2 This C code snippet demonstrates the creation of a PETSc viewer using PetscOptionsCreateViewer(). It initializes PETSc, creates a viewer based on command-line arguments, pushes a format, displays the viewer, and finally destroys the viewer and finalizes PETSc. Dependencies include the PETSc library. ```c static char help[] = "Demonstrates PetscOptionsCreateViewer().\n\n"; #include int main(int argc, char **args) { PetscViewer viewer; PetscViewerFormat format; PetscFunctionBeginUser; PetscCall(PetscInitialize(&argc, &args, NULL, help)); PetscCall(PetscOptionsCreateViewer(PETSC_COMM_WORLD, NULL, NULL, "-myviewer", &viewer, &format, NULL)); PetscCall(PetscViewerPushFormat(viewer, format)); PetscCall(PetscViewerView(viewer, PETSC_VIEWER_STDOUT_WORLD)); PetscCall(PetscViewerPopFormat(viewer)); PetscCall(PetscViewerDestroy(&viewer)); PetscCall(PetscFinalize()); return 0; } ``` -------------------------------- ### PETSc Initial Conditions Setup Source: https://petsc.org/release/src/ts/tutorials/ex20adj Sets the initial conditions for the simulation's state vector `user.U`. This involves obtaining a pointer to the vector's data, assigning specific values to its components, and then restoring the array. This step is crucial for starting the time integration accurately. ```c PetscCall(VecGetArray(user.U, &x_ptr)); x_ptr[0] = 2.0; x_ptr[1] = -2.0 / 3.0 + 10.0 / (81.0 * user.mu) - 292.0 / (2187.0 * user.mu * user.mu); PetscCall(VecRestoreArray(user.U, &x_ptr)); ``` -------------------------------- ### C: PETSc Matrix and Solver Setup Source: https://petsc.org/release/src/ksp/ksp/tutorials/ex60 This C code snippet outlines the initialization of a PETSc matrix, vector allocation, setting up a KSP solver with a composite preconditioner, and solving a linear system. It handles matrix creation, vector manipulation, and solver configuration, with error checking using PetscCall. Dependencies include PETSc libraries. ```c /* Create a diagonal matrix with a given distribution of diagonal elements */ PetscCall(MatCreate(PETSC_COMM_WORLD, &A)); PetscCall(MatSetSizes(A, PETSC_DECIDE, PETSC_DECIDE, n, n)); PetscCall(MatSetFromOptions(A)); PetscCall(MatSetUp(A)); PetscCall(AssembleDiagonalMatrix(A, diagfunc)); /* Allocate vectors and manufacture an exact solution and rhs */ PetscCall(MatCreateVecs(A, &x, NULL)); PetscCall(PetscObjectSetName((PetscObject)x, "Computed Solution")); PetscCall(MatCreateVecs(A, &b, NULL)); PetscCall(PetscObjectSetName((PetscObject)b, "RHS")); PetscCall(MatCreateVecs(A, &u, NULL)); PetscCall(PetscObjectSetName((PetscObject)u, "Reference Solution")); PetscCall(VecSet(u, 1.0)); PetscCall(MatMult(A, u, b)); /* Create a KSP object */ PetscCall(KSPCreate(PETSC_COMM_WORLD, &ksp)); PetscCall(KSPSetOperators(ksp, A, A)); /* Set up a composite preconditioner */ PetscCall(KSPGetPC(ksp, &pc)); PetscCall(PCSetType(pc, PCCOMPOSITE)); /* default composite with single Identity PC */ PetscCall(PCCompositeSetType(pc, PC_COMPOSITE_ADDITIVE)); PetscCall(PCCompositeAddPCType(pc, PCNONE)); if (eta > 0) { PetscCall(PCCompositeAddPCType(pc, PCSHELL)); PetscCall(PCCompositeGetPC(pc, 1, &pcnoise)); ctx.eta = eta; PetscCall(PCShellSetContext(pcnoise, &ctx)); PetscCall(PCShellSetApply(pcnoise, PCApply_Noise)); PetscCall(PCShellSetSetUp(pcnoise, PCSetup_Noise)); PetscCall(PCShellSetDestroy(pcnoise, PCDestroy_Noise)); PetscCall(PCShellSetName(pcnoise, "Noise PC")); } /* Set KSP from options (this can override the PC just defined) */ PetscCall(KSPSetFromOptions(ksp)); /* Solve */ PetscCall(KSPSolve(ksp, b, x)); /* Compute error */ PetscCall(VecAXPY(x, -1.0, u)); PetscCall(PetscObjectSetName((PetscObject)x, "Error")); PetscCall(VecNorm(x, NORM_2, &norm)); PetscCall(KSPGetIterationNumber(ksp, &its)); PetscCall(PetscPrintf(PETSC_COMM_WORLD, "Norm of error %g, Iterations %\" PetscInt_FMT \"\n", (double)norm, its)); /* Destroy objects and finalize */ PetscCall(KSPDestroy(&ksp)); PetscCall(MatDestroy(&A)); PetscCall(VecDestroy(&x)); PetscCall(VecDestroy(&b)); PetscCall(VecDestroy(&u)); PetscCall(PetscFinalize()); return 0; } ``` -------------------------------- ### Install petsc4py from PETSc Source Tree Source: https://petsc.org/release/petsc4py/install Installs petsc4py by building it from the PETSc source tree. This method requires PETSc to be pre-built and involves setting environment variables like PETSC_DIR and PETSC_ARCH. ```bash $ python -m pip install src/binding/petsc4py ```