### Copy PETSc Tutorial Example Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/manual/getting_started.md Copy a PETSc tutorial C source file to your application directory as a starting point. ```bash cp $PETSC_DIR/src/snes/tutorials/ex19.c app.c ``` -------------------------------- ### Run a PETSc example configure script Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/install/install.md Execute a pre-defined PETSc configuration script from the examples directory. Useful for testing or as a starting point for custom configurations. ```console $ ./config/examples/arch-ci-osx-dbg.py ``` -------------------------------- ### Run ex2 with Default Options Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/tutorials/handson.md Execute the ex2 example on a single processor with default solver options and monitor the time-stepping process. This is a basic run to verify the ODE integrator setup. ```console $ mpiexec -n 1 ./ex2 -ts_max_steps 10 -ts_monitor ``` -------------------------------- ### Initial PETSc Configure Command Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/install/multibuild.md This is an example of the initial configure command used to set up a PETSc installation with specific options like downloading MPICH and BLAS/LAPACK, and enabling debugging. ```bash $ ./configure --download-mpich --download-fblaslapack --with-debugging=1 ``` -------------------------------- ### Install PETSc in a User-Privileged Directory for Root Installation Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/install/install.md Demonstrates how to set up a directory with user privileges for PETSc installation in a common system location like /usr/local or /opt, which typically requires root access. The actual PETSc installation is performed as a regular user. ```console sudo mkdir /opt/petsc sudo chown user:group /opt/petsc cd /home/userid/petsc ./configure --prefix=/opt/petsc/my-root-petsc-install --some-other-options make make install ``` -------------------------------- ### Example of Managing Parallel Grid Partitioning Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/changes/2022.md A feeble example demonstrating how to manage partitioning a grid in parallel. Located in src/mat/examples/tutorials/ex2.c. ```c See src/mat/examples/tutorials/ex2.c ``` -------------------------------- ### Run Stokes Example with Specific Suffix in C Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/tutorials/physics/guide_to_stokes.md Execute a PETSc SNES tutorial example with a specific suffix for configuration. This example demonstrates convergence properties for a 2D P2-P1 discretization. ```c ierr = SNESRun(snes, "ex62", "2d_p2_p1_conv");CHKERRQ(ierr); ``` -------------------------------- ### Example PETSc Build Command Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/install/install_tutorial.md This is an example of a `make` command that might be printed by `configure` for building PETSc, including PETSC_DIR and PETSC_ARCH options. ```bash make PETSC_DIR=/Users/jacobfaibussowitsch/NoSync/petsc PETSC_ARCH=arch-darwin-c-debug all ``` -------------------------------- ### Testing `--prefix` Installations Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/manual/tests.md Execute tests for installations made with the `--prefix` option. This command is run from the installation directory. ```console $ make [-j ] -f share/petsc/examples/gmakefile.test test ``` -------------------------------- ### KSP Tutorial Example (C) Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/manual/getting_started.md A basic C example demonstrating the solution of a one-dimensional Laplacian problem using PETSc's KSP module. ```c #include int main(int argc, char **args) { PetscErrorCode ierr; KSP ksp; Mat A; Vec x, b; PetscInt N = 100; PetscReal வைத் = 1.0; ierr = PetscInitialize(&argc, &args, (char*)0, ""); if (ierr) return ierr; ierr = KSPCreate(PETSC_COMM_WORLD, &ksp); CHKERRQ(ierr); ierr = MatCreate(PETSC_COMM_WORLD, &A); CHKERRQ(ierr); ierr = MatSetSizes(A, PETSC_DECIDE, PETSC_DECIDE, N, N); CHKERRQ(ierr); ierr = MatSetFromOptions(A); CHKERRQ(ierr); ierr = MatSetUp(A); CHKERRQ(ierr); ierr = MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); ierr = MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); ierr = VecCreate(PETSC_COMM_WORLD, &x); CHKERRQ(ierr); ierr = VecSetSizes(x, PETSC_DECIDE, N); CHKERRQ(ierr); ierr = VecSetFromOptions(x); CHKERRQ(ierr); ierr = VecSetUp(x); CHKERRQ(ierr); ierr = VecDuplicate(x, &b); CHKERRQ(ierr); ierr = MatGetVecs(A, &x, &b); CHKERRQ(ierr); ierr = MatShift(A, -2.0); CHKERRQ(ierr); ierr = MatScale(A, -1.0); CHKERRQ(ierr); ierr = VecSet(x, 1.0); CHKERRQ(ierr); ierr = VecAssemblyBegin(x); CHKERRQ(ierr); ierr = VecAssemblyEnd(x); CHKERRQ(ierr); ierr = VecDuplicate(x, &b); CHKERRQ(ierr); ierr = MatMult(A, x, b); CHKERRQ(ierr); ierr = KSPSetOperators(ksp, A, A); CHKERRQ(ierr); ierr = KSPSetFromOptions(ksp); CHKERRQ(ierr); ierr = KSPSolve(ksp, b, x); CHKERRQ(ierr); ierr = KSPDestroy(&ksp); CHKERRQ(ierr); ierr = MatDestroy(&A); CHKERRQ(ierr); ierr = VecDestroy(&x); CHKERRQ(ierr); ierr = VecDestroy(&b); CHKERRQ(ierr); ierr = PetscFinalize(); return ierr; } ``` -------------------------------- ### Explicitly Set Up KSP Solver Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/manual/ksp.md Performs any necessary setup for the linear solver before calling KSPSolve. Useful for profiling setup phases. ```c KSPSetUp(KSP ksp); ``` -------------------------------- ### Configure PETSc with a custom installation prefix Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/install/install.md Configure PETSc to install in a user-specified directory, useful for managing multiple installations or installing in non-standard locations. Assumes C-only usage and downloads MPICH and f2cblaslapack. ```console $ ./configure --prefix=/home/user/soft/petsc-install --with-cc=gcc --with-cxx=0 --with-fc=0 --download-f2cblaslapack --download-mpich ``` -------------------------------- ### Install PETSc using DESTDIR for Package Managers Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/install/install.md Configures and installs PETSc with a specified prefix, then uses DESTDIR to stage the installation files in a temporary directory. This is useful for creating packages for package managers. ```console ./configure --prefix=/opt/petsc/my-root-petsc-install make make install DESTDIR=/tmp/petsc-pkg ``` -------------------------------- ### Example PETSc Configure Output Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/install/install_tutorial.md This is an example of the general output structure seen during a successful PETSc configuration process, including downloads and builds of external packages. ```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 ``` -------------------------------- ### Test C Compiler Installation Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/install/install_tutorial.md Verify that your C compiler is installed and functional by compiling and running a simple 'Hello, World!' program. ```bash $ printf '#include\nint main(){printf("cc OK!\n");}' > t.c && cc t.c && ./a.out && rm -f t.c a.out ``` -------------------------------- ### Basic PETSc Installation Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/install/install_tutorial.md Use this command to build PETSc when MPI and BLAS/LAPACK are already installed on your system. ```bash $ ./configure $ make all check ``` -------------------------------- ### SNES Tutorial ex1.c Example Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/manual/vec.md Example from SNES tutorial demonstrating vector operations within a function context. ```c #include PetscErrorCode FormFunction1(SNES snes,Vec x,Vec f,PetscCtx ctx) { PetscErrorCode ierr; PetscInt idx=0; PetscScalar *fvalue; PetscFunctionBegin; ierr = VecGetArray(f,&fvalue); if (ierr) return ierr; fvalue[idx] = -2.0*x[idx] + x[idx+1]; ierr = VecRestoreArray(f,&fvalue); if (ierr) return ierr; PetscFunctionReturn(PETSC_SUCCESS); } ``` -------------------------------- ### Output of Stokes Example Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/tutorials/physics/guide_to_stokes.md This is the standard output from the ex62 tutorial example when run with the '2d_p2_p1_conv' suffix, showing convergence results. ```text Starting SNES iterations SNES Function norm 1.000000e+00 SNES Function norm 1.000000e-01 SNES Function norm 1.000000e-02 SNES Function norm 1.000000e-03 SNES Function norm 1.000000e-04 SNES Function norm 1.000000e-05 SNES Function norm 1.000000e-06 SNES Function norm 1.000000e-07 SNES Function norm 1.000000e-08 SNES Function norm 1.000000e-09 SNES Function norm 1.000000e-10 SNES Function norm 1.000000e-11 SNES Function norm 1.000000e-12 SNES Function norm 1.000000e-13 SNES Function norm 1.000000e-14 SNES Function norm 1.000000e-15 SNES Function norm 1.000000e-16 SNES Converged reason: SNES_CONVERGED_FNORM_ABS Final norm 1.000000e-16 Final iterations 17 ``` -------------------------------- ### Example Feature Branch Creation Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/developers/contributing/developingmr.md An example of creating a feature branch for removing CPP in the `snes` package. ```console $ git checkout -b barry/snes-removecpp origin/main ``` -------------------------------- ### Install petsc4py from PETSc Source Source: https://gitlab.com/petsc/petsc/-/blob/main/src/binding/petsc4py/docs/source/install.md Install petsc4py by building it from the PETSc source tree after PETSc has been built. Ensure PETSC_DIR and PETSC_ARCH are set. ```bash $ python -m pip install src/binding/petsc4py ``` -------------------------------- ### Compile PETSc Example ex2 Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/tutorials/handson.md Compile the ex2 C example for nonlinear ODEs. Ensure you are in the correct directory. ```console $ cd petsc/src/ts/tutorials $ make ex2 ``` -------------------------------- ### SNES Tutorial ex47cu.cu Example Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/manual/vec.md Example from SNES CUDA tutorial demonstrating access to vector arrays on the GPU. ```cuda PetscCall(VecCUDAGetArrayRead(xlocal,&xarray)); ``` -------------------------------- ### Setting up TAU Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/manual/profiling.md Download, configure, and install TAU. Ensure the TAU binary directory is added to your PATH. ```bash wget http://tau.uoregon.edu/tau.tgz ./configure -cc=mpicc -c++=mpicxx -mpi -bfd=download -unwind=download && make install export PATH=/x86_64/bin:$PATH ``` -------------------------------- ### Get Vertex Range Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/manual/dmnetwork.md Obtain the starting and ending indices for vertices in the network. ```c DMNetworkGetVertexRange(DM dm, PetscInt *vStart, PetscInt *vEnd); ``` -------------------------------- ### Compile ex11.c Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/tutorials/handson.md Compile the ex11.c example file using make. ```console cd petsc/src/ts/tutorials make ex11 ``` -------------------------------- ### Get Edge Range Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/manual/dmnetwork.md Obtain the starting and ending indices for edges in the network. ```c DMNetworkGetEdgeRange(DM dm, PetscInt *eStart, PetscInt *eEnd); ``` -------------------------------- ### Getting Application Context in C Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/manual/fortran.md Example of retrieving the application context pointer in C using SNESGetApplicationContext. ```C AppCtx *ctx; SNESGetApplicationContext(snes, &ctx); ``` -------------------------------- ### View Log for Setup Costs Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/manual/ksp.md Run with -log_view to examine setup costs, specifically the time spent in Galerkin coarse grid construction (MatPtAP()) compared to the time spent in each solve (KSPSolve()). If MatPtAP() time is too large, consider increasing the coarsening rate. ```bash run_petsc_code -log_view ``` -------------------------------- ### Constructing PetscSF Graph Data Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/manual/vec.md Example of how to define the root and leaf connections for a PetscSF graph. This setup is crucial for defining the communication pattern. ```c PetscInt nroots, nleaves; PetscSFNode *roots; if (rank == 0) { // the number of entries in rootdata on this MPI process nroots = 2; // provide the matching location in rootdata for each entry in leafdata nleaves = 3; roots[0].rank = 0; roots[0].index = 0; roots[1].rank = 1; roots[1].index = 0; roots[2].rank = 0; roots[2].index = 1; } else { nroots = 1; nleaves = 3; roots[0].rank = 0; roots[0].index = 0; roots[1].rank = 0; roots[1].index = 1; roots[2].rank = 1; roots[1].index = 0; } ``` -------------------------------- ### Get Index Set Information Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/manual/vec.md Retrieves information about an index set, including its total size, and for stride-based sets, the starting point and stride. ```c ISGetSize(IS is, PetscInt *size); ``` ```c ISStrideGetInfo(IS is, PetscInt *first, PetscInt *stride); ``` -------------------------------- ### Build Example with Command-Line Variables Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/install/multibuild.md Build a PETSc example by specifying PETSC_ARCH and PETSC_DIR directly on the command line. This is useful for one-off builds or testing specific configurations. ```bash $ PETSC_ARCH=linux-gnu-c-debug make PETSC_DIR=/absolute/path/to/petsc ex1 ``` -------------------------------- ### Get Context from Shell Preconditioner Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/manual/ksp.md Retrieve the application-provided data structure that was previously set using PCShellSetContext. This is typically used within the apply or setup routines. ```c PCShellGetContext(PC pc, PetscCtxRt ctx); ``` -------------------------------- ### Load Options from YAML Document Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/manual/other.md This example demonstrates loading PETSc options from a file that starts with a YAML document structure, enabling automatic YAML parsing. ```yaml --- # This is a PETSc options file # Options are loaded from this file # # The following options are set: # # -da_refine 1 # -da_processors_x 2 # -da_processors_y 2 # -pc_type ilu # -ksp_type cg # -ksp_rtol 1.0e-4 # -ksp_max_it 100 # -log_summary # -start_in_debugger 0 # -stop_on_error 1 # -malloc_dump # -options_file /home/petsc/petsc/share/petsc/examples/tests/ex47-yaml_doc ``` -------------------------------- ### Define Package Configuration Options Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/developers/buildsystem.md The 'setupHelp()' method defines command-line arguments for the package configuration. It uses the 'nargs' module to specify argument types and default values. ```python def setupHelp(self, help): import nargs help.addArgument(self.Project, '-prefix=', nargs.Arg(None, '', 'Specify location to install '+self.Project+' (eg. /usr/local)')) help.addArgument(self.Project, '-load-path=', nargs.Arg(None, os.path.join(os.getcwd(), 'modules'), 'Specify location of auxiliary modules')) help.addArgument(self.Project, '-with-shared-libraries', nargs.ArgBool(None, 0, 'Make libraries shared')) help.addArgument(self.Project, '-with-dynamic-loading', nargs.ArgBool(None, 0, 'Make libraries dynamic')) return ``` -------------------------------- ### Run Example with Default Linear Solver Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/tutorials/handson.md Execute the ex19 code with 4 processors, 5 levels of grid refinement, and monitor nonlinear and linear solver convergence. This command also views the solver configuration. ```console $ mpiexec -n 4 ./ex19 -da_refine 5 -snes_monitor -ksp_monitor -snes_view ``` -------------------------------- ### Modify Test Configuration Template Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/developers/testing.md To change the lines written to the test file, modify the example template Python script. This script is located in the PETSc installation directory. ```bash $PETSC_DIR/config/example_template.py ``` -------------------------------- ### Compile ex13.c Example Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/tutorials/performance/guide_to_TAS.md Compile the ex13.c source file using make. Ensure you are in the PETSC_DIR/src/snes/tutorials/ directory. ```bash make ex13 ``` -------------------------------- ### Configure and Build Commands Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/developers/documentation.md Examples of common configuration and build commands using the 'console' directive, each preceded by '$'. ```console $ ./configure --some-args $ make libs $ make ./ex1 $ ./ex1 --some-args ``` -------------------------------- ### Initial PETSc Test Run Command Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/developers/testing.md This command initiates a PETSc test run, specifying the source file and an argument pattern. It's a basic example of how to start a test execution. ```console $ make test s='src/ksp/ksp/tests/ex9.c' i='*1' Using MAKEFLAGS: i=*1 s=src/ksp/ksp/tests/ex9.c TEST arch-osx-pkgs-opt-new/tests/counts/ksp_ksp_tests-ex9_1.counts ok ksp_ksp_tests-ex9_1+pc_fieldsplit_diag_use_amat-0_pc_fieldsplit_diag_use_amat-0_pc_fieldsplit_type-additive not ok diff-ksp_ksp_tests-ex9_1+pc_fieldsplit_diag_use_amat-0_pc_fieldsplit_diag_use_amat-0_pc_fieldsplit_type-additive ok ksp_ksp_tests-ex9_1+pc_fieldsplit_diag_use_amat-0_pc_fieldsplit_diag_use_amat-0_pc_fieldsplit_type-multiplicative ... ``` -------------------------------- ### Example C Code for PetscRegressor Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/manual/regressor.md This C code demonstrates a basic usage of PetscRegressor for solving an ordinary linear regression problem. It includes setup, fitting, and prediction steps. Ensure PETSc is configured and the necessary headers are included. ```c #include int main(int argc, char **argv) { PetscErrorCode ierr; PetscMPIInt rank; PetscInt n_samples = 100, n_features = 5; Mat X, X_new; Vec y, y_predicted; PetscRegressor reg; ierr = PetscInitialize(&argc, &argv, NULL, NULL); if (ierr) return ierr; ierr = MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (ierr) return ierr; /* Create a PetscRegressor */ ierr = PetscRegressorCreate(MPI_COMM_WORLD, ®); if (ierr) return ierr; /* Set regressor type (e.g., OLS) */ ierr = PetscRegressorSetType(reg, PETSCREGRESSORLINEAR_OLS); if (ierr) return ierr; /* Load options from command line */ ierr = PetscRegressorSetFromOptions(reg); if (ierr) return ierr; /* Create dummy data for training */ ierr = MatCreate(MPI_COMM_WORLD, &X); if (ierr) return ierr; ierr = MatSetSizes(X, PETSC_DECIDE, PETSC_DECIDE, n_samples, n_features); if (ierr) return ierr; ierr = MatSetUp(X); if (ierr) return ierr; ierr = MatSetRandom(X); if (ierr) return ierr; ierr = VecCreate(MPI_COMM_WORLD, &y); if (ierr) return ierr; ierr = VecSetSizes(y, PETSC_DECIDE, n_samples); if (ierr) return ierr; ierr = VecSetUp(y); if (ierr) return ierr; ierr = VecSetRandom(y); if (ierr) return ierr; /* Fit the regressor */ ierr = PetscRegressorFit(reg, X, y); if (ierr) return ierr; /* Create dummy data for prediction */ ierr = MatCreate(MPI_COMM_WORLD, &X_new); if (ierr) return ierr; ierr = MatSetSizes(X_new, PETSC_DECIDE, PETSC_DECIDE, n_samples / 2, n_features); if (ierr) return ierr; ierr = MatSetUp(X_new); if (ierr) return ierr; ierr = MatSetRandom(X_new); if (ierr) return ierr; ierr = VecCreate(MPI_COMM_WORLD, &y_predicted); if (ierr) return ierr; ierr = VecSetSizes(y_predicted, PETSC_DECIDE, n_samples / 2); if (ierr) return ierr; ierr = VecSetUp(y_predicted); if (ierr) return ierr; /* Predict target values */ ierr = PetscRegressorPredict(reg, X_new, y_predicted); if (ierr) return ierr; /* Clean up */ ierr = MatDestroy(&X); if (ierr) return ierr; ierr = VecDestroy(&y); if (ierr) return ierr; ierr = MatDestroy(&X_new); if (ierr) return ierr; ierr = VecDestroy(&y_predicted); if (ierr) return ierr; ierr = PetscRegressorDestroy(®); if (ierr) return ierr; return PetscFinalize(); } ``` -------------------------------- ### Enable CUDA Support in PETSc Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/install/install.md Pass the `--with-cuda` option to `configure` to enable PETSc's CUDA acceleration. Ensure you have a compatible NVIDIA GPU and the necessary drivers installed. CUDA examples typically use the `.cu` file extension. ```bash # Example configure command # ./configure --with-cuda [other options] ``` -------------------------------- ### Run ex2 on 4 Processors with Solver Monitoring Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/tutorials/handson.md Run the ex2 example on 4 processors, monitoring both the time-stepping and the convergence of the nonlinear and linear solvers. This helps in analyzing solver performance. ```console $ mpiexec -n 4 ./ex2 -ts_max_steps 10 -ts_monitor -snes_monitor -ksp_monitor ``` -------------------------------- ### Update MSYS2 and Install Packages Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/install/windows.md Update the MSYS2 installation and install essential packages required for PETSc dependencies. This command installs a comprehensive toolchain and libraries. ```bash $ pacman -Syu ``` ```bash $ pacman -S autoconf automake-wrapper bison bsdcpio make git \ mingw-w64-x86_64-toolchain patch python flex \ pkg-config pkgfile tar unzip mingw-w64-x86_64-cmake \ mingw-w64-x86_64-msmpi mingw-w64-x86_64-openblas mingw-w64-x86_64-jq ``` -------------------------------- ### Compile PETSc Example Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/tutorials/handson.md Compile the ex19.c tutorial code. Ensure you are in the correct directory within the PETSc source tree. ```console $ cd petsc/src/snes/tutorials/ $ make ex19 ``` -------------------------------- ### Get and Restore Ensemble Members Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/manual/da.md Use this pattern to get a read-only view of an ensemble member. Always pair get with restore. ```c PetscDAEnsembleGetMember(PetscDA da, PetscInt i, Vec *member); PetscDAEnsembleRestoreMember(PetscDA da, PetscInt i, Vec *member); ``` -------------------------------- ### PetscDA Setup and Options Application Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/manual/da.md Applies command-line overrides and allocates internal storage for the PetscDA object after options have been set. ```c PetscDASetFromOptions(PetscDA da); ``` ```c PetscDASetUp(PetscDA da); ``` -------------------------------- ### In-place Installation with PETSC_ARCH Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/install/install.md Configure PETSc for in-place installation by setting the `PETSC_ARCH` environment variable or passing it directly to `configure`. This installs libraries into a subdirectory named by `PETSC_ARCH`. ```bash $ export PETSC_ARCH=arch-debug $ ./configure $ make $ export PETSC_ARCH=arch-opt $ ./configure --some-optimization-options $ make ``` ```bash $ ./configure PETSC_ARCH=arch-debug $ make $ ./configure --some-optimization-options PETSC_ARCH=arch-opt $ make ``` ```bash $ ./configure $ make $ ./configure --with-debugging=0 $ make ``` -------------------------------- ### Quick Start: Check PETSc Libraries Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/manual/tests.md Use this command to verify that the PETSc libraries are functioning correctly. Ensure `$PETSC_DIR` and `$PETSC_ARCH` are set or provided. ```console $ make PETSC_DIR= PETSC_ARCH= check ``` -------------------------------- ### Install PETSc with MacPorts Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/install/index.md Use MacPorts to install PETSc on macOS. ```bash sudo port install petsc ``` -------------------------------- ### Install PETSc with Homebrew Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/install/index.md Use Homebrew to install PETSc on macOS. ```bash brew install petsc ``` -------------------------------- ### SNES Finite Difference Jacobian Approximation Setup Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/manual/snes.md Demonstrates the process of setting up finite difference Jacobian approximation using coloring. This involves initializing the Jacobian's nonzero structure, coloring the matrix, creating a `MatFDColoring` structure, and configuring SNES to use `SNESComputeJacobianDefaultColor`. ```c ISColoring iscoloring; MatFDColoring fdcoloring; MatColoring coloring; /* This initializes the nonzero structure of the Jacobian. This is artificial because clearly if we had a routine to compute the Jacobian we wouldn't need to use finite differences. */ FormJacobian(snes, x, &J, &J, &user); /* Color the matrix, i.e. determine groups of columns that share no common rows. These columns in the Jacobian can all be computed simultaneously. */ MatColoringCreate(J, &coloring); MatColoringSetType(coloring, MATCOLORINGSL); MatColoringSetFromOptions(coloring); MatColoringApply(coloring, &iscoloring); MatColoringDestroy(&coloring); /* Create the data structure that SNESComputeJacobianDefaultColor() uses to compute the actual Jacobians via finite differences. */ MatFDColoringCreate(J, iscoloring, &fdcoloring); ISColoringDestroy(&iscoloring); MatFDColoringSetFunction(fdcoloring, (MatFDColoringFn *)FormFunction, &user); MatFDColoringSetFromOptions(fdcoloring); /* Tell SNES to use the routine SNESComputeJacobianDefaultColor() to compute Jacobians. */ SNESSetJacobian(snes, J, J, SNESComputeJacobianDefaultColor, fdcoloring); ``` -------------------------------- ### Install PETSc with TAU Instrumentation Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/install/install.md Configure PETSc using `tau_cc.sh` as the C compiler when installing with the TAU instrumentation package. Ensure TAU and PDT are installed separately and `TAU_MAKEFILE` is set. ```bash $ export TAU_MAKEFILE=/home/balay/soft/linux64/tau-2.20.3/x86_64/lib/Makefile.tau-mpi-pdt $ ./configure CC=/home/balay/soft/linux64/tau-2.20.3/x86_64/bin/tau_cc.sh --with-fc=0 PETSC_ARCH=arch-tau ``` -------------------------------- ### PETSc Time Integrator Setup and Solve Source: https://context7.com/petsc/petsc/llms.txt Demonstrates the complete setup and execution of a PETSc TS solver for a simple ODE. Includes creating vectors, matrices, setting callbacks, time parameters, and solving. ```c PetscErrorCode TimeIntegratorDemo(void) { TS ts; Vec u; Mat J; UserCtx user = {.k = 1.0}; PetscReal ftime; PetscInt nsteps; PetscFunctionBeginUser; /* Initial condition vector */ PetscCall(VecCreateSeq(PETSC_COMM_SELF, 1, &u)); PetscCall(VecSet(u, 1.0)); /* u(0) = 1 */ /* Jacobian matrix */ PetscCall(MatCreateSeqDense(PETSC_COMM_SELF, 1, 1, NULL, &J)); /* Create and configure time integrator */ PetscCall(TSCreate(PETSC_COMM_WORLD, &ts)); PetscCall(TSSetType(ts, TSRK)); /* explicit Runge-Kutta */ PetscCall(TSSetProblemType(ts, TS_NONLINEAR)); PetscCall(TSSetRHSFunction(ts, NULL, RHSFunction, &user)); PetscCall(TSSetRHSJacobian(ts, J, J, RHSJacobian, &user)); PetscCall(TSSetSolution(ts, u)); /* Time interval and step size */ PetscCall(TSSetTime(ts, 0.0)); PetscCall(TSSetMaxTime(ts, 3.0)); PetscCall(TSSetTimeStep(ts, 0.1)); PetscCall(TSSetMaxSteps(ts, 1000)); PetscCall(TSSetExactFinalTime(ts, TS_EXACTFINALTIME_MATCHSTEP)); /* Register a monitor to print each step */ PetscCall(TSMonitorSet(ts, Monitor, NULL, NULL)); /* Allow all options to be set from command line */ PetscCall(TSSetFromOptions(ts)); /* Integrate */ PetscCall(TSSolve(ts, u)); PetscCall(TSGetSolveTime(ts, &ftime)); PetscCall(TSGetStepNumber(ts, &nsteps)); PetscCall(PetscPrintf(PETSC_COMM_WORLD, "Completed %" PetscInt_FMT " steps, final time = %g\n", nsteps, (double)ftime)); PetscCall(VecDestroy(&u)); PetscCall(MatDestroy(&J)); PetscCall(TSDestroy(&ts)); PetscFunctionReturn(PETSC_SUCCESS); } ``` -------------------------------- ### Read and Set PETSc Options in C Source: https://context7.com/petsc/petsc/llms.txt Demonstrates reading integer, real, boolean, and string options from the command line using `PetscOptionsGetInt`, `PetscOptionsGetReal`, `PetscOptionsGetBool`, and `PetscOptionsGetString`. Also shows how to programmatically inject options with `PetscOptionsInsertString` and how to use prefixes for multiple solver instances. Finally, it displays all currently set options using `PetscOptionsView`. ```c #include PetscErrorCode OptionsDemo(void) { PetscInt n; PetscReal tol; PetscBool monitor, found; char method[64]; PetscFunctionBeginUser; /* Read typed values from the options database */ n = 100; PetscCall(PetscOptionsGetInt(NULL, NULL, "-n", &n, &found)); if (found) PetscCall(PetscPrintf(PETSC_COMM_WORLD, "n = %" PetscInt_FMT "\n", n)); tol = 1.e-6; PetscCall(PetscOptionsGetReal(NULL, NULL, "-tol", &tol, NULL)); PetscCall(PetscOptionsGetBool(NULL, NULL, "-monitor", &monitor, NULL)); PetscCall(PetscOptionsGetString(NULL, NULL, "-method", method, sizeof(method), NULL)); /* Programmatically inject options (useful in testing, overriding defaults) */ PetscCall(PetscOptionsInsertString(NULL, "-ksp_type cg -pc_type icc -ksp_rtol 1.e-9")); /* Options with a prefix — useful when multiple KSPs/SNESes exist */ KSP ksp1, ksp2; /* ...create ksp1, ksp2... */ /* ksp1 reads -solver1_ksp_type, ksp2 reads -solver2_ksp_type */ /* PetscCall(KSPSetOptionsPrefix(ksp1, "solver1_")); */ /* PetscCall(KSPSetOptionsPrefix(ksp2, "solver2_")); */ /* View all currently set options */ PetscCall(PetscOptionsView(NULL, PETSC_VIEWER_STDOUT_WORLD)); PetscFunctionReturn(PETSC_SUCCESS); } /* Command line usage: ./myapp -n 500 -tol 1.e-9 -monitor -method bicg ./myapp -options_file myoptions.txt # load options from file ./myapp -help # list all available options ./myapp -options_view # show all active options at end */ ``` -------------------------------- ### Multiple Installs with --prefix Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/install/install.md Use `--prefix` to specify distinct installation locations for PETSc builds with different configurations. `DESTDIR` can be used during `make install` to stage files for packaging. ```bash $ ./configure --prefix=/opt/petsc/petsc-3.25.0-mpich --with-mpi-dir=/opt/mpich $ make $ make install [DESTDIR=/tmp/petsc-pkg] $ ./configure --prefix=/opt/petsc/petsc-3.25.0-openmpi --with-mpi-dir=/opt/openmpi $ make $ make install [DESTDIR=/tmp/petsc-pkg] ``` -------------------------------- ### Setting Initial Conditions and Solution Method Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/manual/ts.md Explains how to set the initial solution for an ODE and choose a solution method. ```APIDOC ## TSSetSolution ### Description Sets the initial conditions for the ODE. ### Method ```c TSSetSolution(TS ts, Vec initialsolution); ``` ### Parameters #### Path Parameters - **ts** (TS) - Required - The TS context - **initialsolution** (Vec) - Required - The vector containing the initial solution ## TSSetType ### Description Sets the solution method (integrator type) for the TS object. ### Method ```c TSSetType(TS ts, TSType type); ``` ### Parameters #### Path Parameters - **ts** (TS) - Required - The TS context - **type** (TSType) - Required - The type of solution method (e.g., `TSEULER`, `TSRK`, `TSCN`) ``` -------------------------------- ### Configure PETSc with Out-of-Place Installation Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/install/install.md Configures PETSc to install libraries and include files in a specified directory, separate from the source tree. Use the --prefix option to define the installation location. ```console ./configure --prefix=/home/userid/my-petsc-install --some-other-options ``` -------------------------------- ### Install PETSc with Pip Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/install/index.md Install PETSc and PETSc for Python (petsc4py) using pip. ```bash python -m pip install petsc petsc4py ``` -------------------------------- ### Example: Create Basic AO on Two Processes Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/manual/vec.md Demonstrates creating an AO object across two processes. Each process provides a subset of the ordering, ensuring no duplicate values are contributed globally. ```c AOCreateBasic(PETSC_COMM_WORLD, 2,{0, 3}, {3, 4}, &ao); ``` ```c AOCreateBasic(PETSC_COMM_WORLD, 3, {1, 2, 4}, {2, 1, 0}, &ao); ``` -------------------------------- ### Run Example with Trilinos ML Preconditioner Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/tutorials/handson.md Run the ex19 code with the ML preconditioner from Trilinos. This demonstrates using external libraries for advanced preconditioners. ```console $ mpiexec -n 4 ./ex19 -da_refine 5 -snes_monitor -ksp_monitor -snes_view -pc_type ml ``` -------------------------------- ### Install petsc4py from PyPI Source: https://gitlab.com/petsc/petsc/-/blob/main/src/binding/petsc4py/docs/source/install.md Use pip to install petsc and petsc4py directly from the Python Package Index. ```bash $ python -m pip install petsc petsc4py ``` -------------------------------- ### Minimal configure.py Script Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/developers/buildsystem.md A basic 'configure.py' script that sets up the build framework, processes command-line arguments, and initiates the configuration process. It loads specific configuration modules. ```python package = 'PETSc' def configure(configure_options): # Command line arguments take precedence (but don't destroy argv[0]) sys.argv = sys.argv[:1] + configure_options + sys.argv[1:] framework = config.framework.Framework(['--configModules='+package+'.Configure', '--optionsModule='+package+'.compilerOptions']+sys.argv[1:], loadArgDB = 0) framework.setup() framework.configure(out = sys.stdout) framework.storeSubstitutions(framework.argDB) framework.printSummary() framework.argDB.save(force = True) framework.logClear() framework.closeLog() if __name__ == '__main__': configure([]) ``` -------------------------------- ### Install Linting Requirements Source: https://gitlab.com/petsc/petsc/-/blob/main/src/binding/petsc4py/docs/source/contributing.md Install the necessary tools for linting Cython and Python code using pip. ```bash python -m pip install -r src/binding/petsc4py/conf/requirements-lint.txt ``` -------------------------------- ### Run ex50 with 3x3 Mesh and View Matrix Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/tutorials/handson.md Execute the ex50 example on a single processor with a 3x3 grid and display the assembled matrix. This helps in understanding matrix assembly for structured grids. ```console $ mpiexec -n 1 ./ex50 -da_grid_x 4 -da_grid_y 4 -mat_view ``` -------------------------------- ### Run SNES ex69 with Specific Options Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/tutorials/physics/guide_to_stokes.md Execute the SNES ex69 tutorial with refined mesh and specific solver/solution viewing options. Use this to investigate convergence with sharp viscosity variations. ```console $ make -f ./gmakefile test search="snes_tutorials-ex69_p2p1" EXTRA_OPTIONS="-dm_refine 5 -dm_view hdf5:$PETSC_DIR/sol.h5 -snes_view_solution hdf5:$PETSC_DIR/sol.h5::append -exact_vec_view hdf5:$PETSC_DIR/sol.h5::append -m 2 -n 2 -B 1" ``` ```console $ make -f ./gmakefile test search="snes_tutorials-ex69_p2p1" EXTRA_OPTIONS="-dm_refine 5 -dm_view hdf5:$PETSC_DIR/sol.h5 -snes_view_solution hdf5:$PETSC_DIR/sol.h5::append -exact_vec_view hdf5:$PETSC_DIR/sol.h5::append -m 2 -n 2 -B 3.75" ``` -------------------------------- ### Install PETSc with Spack Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/install/index.md Install PETSc using Spack, with options for debug, optimization, and external packages. ```bash spack install petsc +debug ``` ```bash spack install petsc cflags='-g -O3 -march=native -mtune=native' fflags='-g -O3 -march=native -mtune=native' cxxflags='-g -O3 -march=native -mtune=native' ``` ```bash spack install petsc +superlu-dist +metis +hypre +hdf5 ``` ```bash spack info petsc ``` -------------------------------- ### Initialize Object and Set Options Source: https://gitlab.com/petsc/petsc/-/blob/main/doc/faq/index.md Create a generic object and then set its options. This approach allows for default type setting and subsequent customization. ```c /* Create generic object */ XXXCreate(..,&obj); /* Must set all settings here, or default */ XXXSetFromOptions(obj); ```