### Install PETSc and petsc4py Source: https://github.com/albertopadovan/resolvent4py/blob/main/README.md Install the specified PETSc build and petsc4py. ```bash conda install -c conda-forge petsc=3.23.3=build-string petsc4py ``` -------------------------------- ### Install SLEPc and slepc4py Source: https://github.com/albertopadovan/resolvent4py/blob/main/README.md Install the specified SLEPc build and slepc4py. ```bash conda install -c conda-forge slepc=3.23.2=build-string slepc4py ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/albertopadovan/resolvent4py/blob/main/README.md Install mpi4py, petsc4py, and slepc4py using pip. Ensure the versions match your installed PETSc and SLEPc versions. ```bash pip install mpi4py petsc4py==petsc-version slepc4py==slepc-version ``` -------------------------------- ### Verify Installation Source: https://github.com/albertopadovan/resolvent4py/blob/main/README.md Run these commands to confirm that the Python packages are correctly installed and accessible. ```bash python -c "from mpi4py import MPI" python -c "from petsc4py import PETSc" python -c "from slepc4py import SLEPc" ``` -------------------------------- ### Install resolvent4py Source: https://github.com/albertopadovan/resolvent4py/blob/main/README.md Install the resolvent4py package using pip. ```bash pip install resolvent4py ``` -------------------------------- ### Install mpi4py Source: https://github.com/albertopadovan/resolvent4py/blob/main/README.md Install the mpi4py package via conda. ```bash conda install -c conda-forge mpi4py ``` -------------------------------- ### Install resolvent4py Source: https://github.com/albertopadovan/resolvent4py/blob/main/README.md Final step to install the resolvent4py package via pip. ```bash pip install resolvent4py ``` -------------------------------- ### Export MPI Environment Variables Source: https://github.com/albertopadovan/resolvent4py/blob/main/README.md Update system paths to reference the local MPI installation if it was downloaded during the PETSc configuration stage. ```bash export PATH=$PETSC_DIR/$PETSC_ARCH/bin:$PATH \ export LD_LIBRARY_PATH=$PETSC_DIR/$PETSC_ARCH/lib:$LD_LIBRARY_PATH ``` -------------------------------- ### Run Demonstration Scripts Source: https://github.com/albertopadovan/resolvent4py/blob/main/docs/source/auto_examples/cgl/index.md Execute the demonstration scripts using MPI. These can be run with any number of processors. ```bash mpiexec -n 2 python -u demonstrate_*.py ``` -------------------------------- ### Create and activate conda environment Source: https://github.com/albertopadovan/resolvent4py/blob/main/README.md Initialize a new environment for the project. ```bash conda create -n resolvent4py_env python=3.11 conda activate resolvent4py_env ``` -------------------------------- ### Search for SLEPc builds Source: https://github.com/albertopadovan/resolvent4py/blob/main/README.md List available SLEPc builds compatible with the chosen PETSc configuration. ```bash conda search 'slepc=3.23.2=complex*' --channel conda-forge --info ``` -------------------------------- ### Harmonic Resolvent Analysis Workflow Source: https://github.com/albertopadovan/resolvent4py/blob/main/docs/source/auto_examples/toy_model/demonstrate_harmonic_resolvent.ipynb Full workflow for loading balanced matrix data, assembling the harmonic resolvent generator, applying projection operators, and computing singular values and eigenvalues. ```python import os import matplotlib.pyplot as plt import numpy as np import resolvent4py as res4py from petsc4py import PETSc from slepc4py import SLEPc plt.rcParams.update( { "font.family": "serif", "font.sans-serif": ["Computer Modern"], "font.size": 18, "text.usetex": True, } ) comm = PETSc.COMM_WORLD save_path = "data/" bflow_freqs = np.load(save_path + "bflow_freqs.npy") nfb = len(bflow_freqs) - 1 fnames_lst = [ ( save_path + "rows_%02d.dat" % j, save_path + "cols_%02d.dat" % j, save_path + "vals_%02d.dat" % j, ) for j in range(nfb + 1) ] nfp = nfb + 3 perts_freqs = np.arange(-nfp, nfp + 1) * bflow_freqs[1] nblocks = 2 * nfp + 1 # ------------------------------------------------------------------------------ # -------- Read data from file and assemble harmonic resolvent generator ------- # ------------------------------------------------------------------------------ N = 3 * len(perts_freqs) Nl = res4py.compute_local_size(N) n = 3 nl = res4py.compute_local_size(n) A = res4py.read_harmonic_balanced_matrix( fnames_lst, True, ((nl, n), (nl, n)), ((Nl, N), (Nl, N)), ) T = res4py.assemble_harmonic_resolvent_generator(A, perts_freqs) T.scale(-1.0) # Perturb the generator to avoid numerical singularities Id = res4py.create_AIJ_identity(comm, T.getSizes()) Id.scale(1e-7) T.axpy(1.0, Id) Id.destroy() ksp = res4py.create_mumps_solver(T) res4py.check_lu_factorization(T, ksp) Top = res4py.linear_operators.MatrixLinearOperator(T, ksp, nblocks) # ------------------------------------------------------------------------------ # -------- Read base-flow time-derivative and define projection operators ------ # -------- to remove the phase-shift direction --------------------------------- # ------------------------------------------------------------------------------ fnames_lst = [(save_path + "dQ_%02d.dat" % j) for j in range(len(bflow_freqs))] dQ = res4py.read_harmonic_balanced_vector(fnames_lst, True, (nl, n), (Nl, N)) dQ.scale(1 / dQ.norm()) w = Top.solve_hermitian_transpose(dQ) w.scale(1 / w.norm()) Phi = SLEPc.BV().create(comm) Phi.setSizes(dQ.getSizes(), 1) Phi.setType("mat") Psi = Phi.copy() Phi.insertVec(0, dQ) Psi.insertVec(0, w) Pd = res4py.linear_operators.ProjectionLinearOperator(Psi, Psi, True, nblocks) Pr = res4py.linear_operators.ProjectionLinearOperator(Phi, Phi, True, nblocks) lops = [Pr, Top, Pd] lops_actions = [Pr.apply, Top.solve, Pd.apply] Linop = res4py.linear_operators.ProductLinearOperator( lops, lops_actions, nblocks ) _, S, _ = res4py.linalg.randomized_svd(Linop, Linop.apply_mat, 30, 3, 10) S = np.diag(S) _, S2, _ = res4py.linalg.randomized_svd(Top, Top.solve_mat, 30, 3, 11) S2 = np.diag(S2) res_path = "results/" if comm.getRank() == 0: os.makedirs(res_path) if not os.path.exists(res_path) else None if comm.getRank() == 0: fig, ax = plt.subplots() ax.plot(np.arange(1, len(S) + 1), S.real, "ko", label=r"$P_r T^{-1} P_d$") ax.set_xlabel(r"Index $j$ for $P_r T^{-1} P_d$") ax.set_ylabel(r"$\sigma_j$") ax2 = ax.twiny() ax2.plot( np.arange(2, len(S2) + 1), S2[1:].real, "rx", label=r"$P T^{-1} P$" ) lines1, labels1 = ax.get_legend_handles_labels() lines2, labels2 = ax2.get_legend_handles_labels() ax.legend(lines1 + lines2, labels1 + labels2, loc="upper right") ax.set_xticks(np.arange(1, len(S) + 1)) ax2.set_xticks(np.arange(2, len(S2) + 1)) ax2.set_xlabel(r"Index $j$ for $P T^{-1} P$") plt.tight_layout() plt.savefig(res_path + "singular_values.png", dpi=100) P = res4py.linear_operators.ProjectionLinearOperator(Phi, Psi, True, nblocks) lops = [P, Top, P] lops_actions = [P.apply, Top.solve, P.apply] Linop = res4py.linear_operators.ProductLinearOperator( lops, lops_actions, nblocks ) D, _ = res4py.linalg.eig(Linop, Linop.apply, N - 3, 30, lambda x: -1 / x) D = np.diag(D) if comm.getRank() == 0: omega = bflow_freqs[1] idces = np.argwhere((D.imag > -omega / 2) & (D.imag <= omega / 2)).reshape( -1 ) plt.figure() plt.plot(D.real, D.imag, "ko") # plt.plot(D[idces].real, D[idces].imag, 'go') # plt.plot(0, 0, "rx") ax = plt.gca() ax.axhline(y=omega / 2, color="r", alpha=0.3) ax.axhline(y=-omega / 2, color="r", alpha=0.3) ax.set_xlabel(r"$\mathrm{Real}(\lambda)$") ax.set_ylabel(r"$\mathrm{Imag}(\lambda)$") plt.tight_layout() plt.savefig(res_path + "floquet_exponents.png", dpi=100) ``` -------------------------------- ### Run Harmonic Resolvent Analysis Source: https://github.com/albertopadovan/resolvent4py/blob/main/docs/source/auto_examples/toy_model/index.md Execute the analysis script using MPI; parallel execution is supported but may offer limited benefits for small systems. ```bash mpiexec -n 2 python -u demonstrate_harmonic_resolvent.py ``` -------------------------------- ### Configure PETSc for resolvent4py Source: https://github.com/albertopadovan/resolvent4py/blob/main/README.md Run this command within the PETSc directory to configure the library with the necessary dependencies and scalar settings. ```bash ./configure PETSC_ARCH=resolvent4py_arch --download-fblaslapack \ --download-mumps --download-scalapack --download-parmetis \ --download-metis --download-ptscotch --with-scalar-type=complex \ --download-mpich --download-cmake --download-bison \ --with-debugging=0 COPTFLAGS=-O3 CXXOPTFLAGS=-O3 FOPTFLAGS=-O3 ``` -------------------------------- ### Search for PETSc builds Source: https://github.com/albertopadovan/resolvent4py/blob/main/README.md List available PETSc builds with complex scalar and MUMPS support. ```bash conda search 'petsc=3.23.3=complex*' --channel conda-forge --info ``` -------------------------------- ### Perform Resolvent Analysis with Randomized SVD Source: https://github.com/albertopadovan/resolvent4py/blob/main/docs/source/auto_examples/cgl/demonstrate_rsvd.ipynb Loads a matrix, computes the LU decomposition of the resolvent operator, and performs randomized SVD to find singular values. Requires a pre-existing data directory with matrix files. ```python import os import matplotlib.pyplot as plt import numpy as np import resolvent4py as res4py import scipy as sp from petsc4py import PETSc import cgl plt.rcParams.update( { "font.family": "serif", "font.sans-serif": ["Computer Modern"], "font.size": 18, "text.usetex": True, } ) comm = PETSc.COMM_WORLD # Read the A matrix from file res4py.petscprint(comm, "Reading matrix from file...") load_path = "data/" N = 2000 Nl = res4py.compute_local_size(N) sizes = ((Nl, N), (Nl, N)) names = [ load_path + "rows.dat", load_path + "cols.dat", load_path + "vals.dat", ] A = res4py.read_coo_matrix(names, sizes) # Compute the SVD of the resolvent operator R = inv(1j*omega*I - A) using # the randomized SVD algorithm res4py.petscprint(comm, "Computing LU decomposition...") s = -1j * 0.648 Rinv = res4py.create_AIJ_identity(comm, sizes) Rinv.scale(s) Rinv.axpy(-1.0, A) ksp = res4py.create_mumps_solver(Rinv) res4py.check_lu_factorization(Rinv, ksp) L = res4py.linear_operators.MatrixLinearOperator(Rinv, ksp) # Compute the svd res4py.petscprint(comm, "Running randomized SVD...") n_rand = 10 n_loops = 1 n_svals = 2 U, S, V = res4py.linalg.randomized_svd( L, L.solve_mat, n_rand, n_loops, n_svals ) # Check convergence res4py.linalg.check_randomized_svd_convergence(L.solve, U, S, V) # Destroy objects L.destroy() V.destroy() U.destroy() res4py.petscprint(comm, "Making figures...") l = 30 * 2 x = np.linspace(-l / 2, l / 2, num=N, endpoint=True) nu = 1.0 * (2 + 0.4 * 1j) gamma = 1 - 1j mu0 = 0.38 mu2 = -0.01 sigma = 0.4 system = cgl.CGL(x, nu, gamma, mu0, mu2, sigma) if comm.getRank() == 0: save_path = "results/" os.makedirs(save_path) if not os.path.exists(save_path) else None Id = sp.sparse.identity(N) R = sp.linalg.inv((s * Id - system.A).todense()) _, s, _ = sp.linalg.svd(R) S = np.diag(S) plt.figure() plt.plot(S.real, "ko", label="res4py") plt.plot(s[: len(S)].real, "rx", label="exact") ax = plt.gca() ax.set_xlabel(r"Index $j$") ax.set_ylabel(r"Singular values $\sigma_j(\omega)$") ax.set_title(r"SVD of $R(\omega)$") ax.set_yscale("log") plt.legend() plt.tight_layout() plt.savefig(save_path + "singular_values.png") ``` -------------------------------- ### Resolvent Analysis Comparison Source: https://github.com/albertopadovan/resolvent4py/blob/main/docs/source/auto_examples/cgl/demonstrate_rsvd_dt.ipynb Performs resolvent analysis using both algebraic and time-stepping methods, then compares the singular values and modes. ```python import os import matplotlib.pyplot as plt import numpy as np import resolvent4py as res4py import scipy as sp from petsc4py import PETSc import cgl plt.rcParams.update( { "font.family": "serif", "font.sans-serif": ["Computer Modern"], "font.size": 18, "text.usetex": True, } ) comm = PETSc.COMM_WORLD # Read the A matrix from file res4py.petscprint(comm, "Reading matrix from file...") load_path = "data/" N = 2000 Nl = res4py.compute_local_size(N) sizes = ((Nl, N), (Nl, N)) names = [ load_path + "rows.dat", load_path + "cols.dat", load_path + "vals.dat", ] A = res4py.read_coo_matrix(names, sizes) # Compute the svd res4py.petscprint(comm, "Running randomized SVD (algebraic)...") omega = 0.648 n_rand = 2 n_loops = 1 n_svals = 2 Rinv = res4py.create_AIJ_identity(comm, sizes) Rinv.scale(-1j * omega) Rinv.axpy(-1.0, A) ksp = res4py.create_mumps_solver(Rinv) res4py.check_lu_factorization(Rinv, ksp) L = res4py.linear_operators.MatrixLinearOperator(Rinv, ksp) Ua, Sa, Va = res4py.linalg.randomized_svd( L, L.solve_mat, n_rand, n_loops, n_svals ) Sa = np.diag(Sa) res4py.petscprint(comm, "Running randomized SVD (time stepping)...") res4py.petscprint(comm, "This may take several minutes...") n_omegas = 1 n_periods = 100 dt = 1e-4 tol = 1e-3 verbose = 2 L = res4py.linear_operators.MatrixLinearOperator(A) U, S, V = ( res4py.linalg.resolvent_analysis_time_stepping.resolvent_analysis_rsvd_dt( L, dt, omega, n_omegas, n_periods, n_rand, n_loops, n_svals, tol, verbose, ) ) St = np.diag(S[-1]) Ut = U[-1] Vt = V[-1] idx = 0 bvs = [Ua, Ut, Va, Vt] arrays = [] for bv in bvs: vec = bv.getColumn(idx) vecseq = res4py.distributed_to_sequential_vector(vec) bv.restoreColumn(idx, vec) arrays.append(vecseq.getArray().copy()) vecseq.destroy() if comm.getRank() == 0: save_path = "results/" os.makedirs(save_path) if not os.path.exists(save_path) else None l = 30 * 2 x = np.linspace(-l / 2, l / 2, num=N, endpoint=True) nu = 1.0 * (2 + 0.4 * 1j) gamma = 1 - 1j mu0 = 0.38 mu2 = -0.01 sigma = 0.4 system = cgl.CGL(x, nu, gamma, mu0, mu2, sigma) plt.figure() plt.plot(Sa.real, "ko", label="rsvd") plt.plot(St.real, "rx", label="rsvd-dt") ax = plt.gca() ax.set_xlabel(r"Index $j$") ax.set_ylabel(r"Singular values $\sigma_j(\omega)$") ax.set_title(r"SVD of $R(\omega)$") ax.set_yscale("log") plt.legend() plt.tight_layout() plt.savefig(save_path + "singular_values_compare.png") plt.figure() plt.plot(x, np.abs(arrays[0]), label="rsvd") plt.plot(x, np.abs(arrays[1]), "--", label="rsvd-dt") ax = plt.gca() ax.set_xlabel(r"$x$") ax.set_ylabel(r"Abs. value of output mode") plt.legend() plt.tight_layout() plt.savefig(save_path + "output_mode_compare.png") plt.figure() plt.plot(x, np.abs(arrays[2]), label="rsvd") plt.plot(x, np.abs(arrays[3]), "--", label="rsvd-dt") ax = plt.gca() ax.set_xlabel(r"$x$") ax.set_ylabel(r"Abs. value of input mode") plt.legend() plt.tight_layout() plt.savefig(save_path + "input_mode_compare.png") ``` -------------------------------- ### Generate Data Matrices Source: https://github.com/albertopadovan/resolvent4py/blob/main/docs/source/auto_examples/cgl/index.md Execute this command to generate the necessary data matrices for the CGL analysis scripts. ```bash mpiexec -n 1 python -u generate_matrices.py ``` -------------------------------- ### Perform frequency-domain balanced truncation Source: https://github.com/albertopadovan/resolvent4py/blob/main/docs/source/auto_examples/cgl/demonstrate_balanced_truncation.ipynb Configures the linear operator generator, reads system matrices from files, and computes the balanced projection using resolvent4py. ```python from functools import partial import matplotlib.pyplot as plt import numpy as np import resolvent4py as res4py from petsc4py import PETSc plt.rcParams.update( { "font.family": "serif", "font.sans-serif": ["Computer Modern"], "font.size": 18, "text.usetex": True, } ) def L_generator(omega, A): comm = PETSc.COMM_WORLD Rinv = res4py.create_AIJ_identity(comm, A.getSizes()) Rinv.scale(1j * omega) Rinv.axpy(-1.0, A) ksp = res4py.create_mumps_solver(Rinv) L = res4py.linear_operators.MatrixLinearOperator(Rinv, ksp) return (L, L.solve_mat, (L.destroy,)) comm = PETSc.COMM_WORLD # Read the A matrix from file res4py.petscprint(comm, "Reading matrix from file...") load_path = "data/" N = 2000 Nl = res4py.compute_local_size(N) sizes = ((Nl, N), (Nl, N)) names = [ load_path + "rows.dat", load_path + "cols.dat", load_path + "vals.dat", ] A = res4py.read_coo_matrix(names, sizes) B = res4py.read_bv(load_path + "B.dat", (A.getSizes()[0], 2)) C = res4py.read_bv(load_path + "C.dat", (A.getSizes()[0], 3)) domega = 0.648 / 2 omegas = np.arange(-30, 30, domega) weights = domega / (2 * np.pi) * np.ones(len(omegas)) L_gen = partial(L_generator, A=A) L_generators = [L_gen for _ in range(len(omegas))] res4py.petscprint(comm, "Computing Gramian factors...") X, Y = res4py.model_reduction.compute_gramian_factors( L_generators, omegas, weights, B, C ) res4py.petscprint(comm, "Computing balanced projection...") Phi, Psi, S = res4py.model_reduction.compute_balanced_projection(X, Y, 10) ``` -------------------------------- ### Cite Resolvent4py with BibTeX Source: https://github.com/albertopadovan/resolvent4py/blob/main/README.md Use this BibTeX entry to cite the resolvent4py software in academic publications. ```bibtex @article{PADOVAN2025102286, title = {Resolvent4py: A parallel Python package for analysis, model reduction and control of large-scale linear systems}, journal = {SoftwareX}, volume = {31}, pages = {102286}, year = {2025}, issn = {2352-7110}, doi = {https://doi.org/10.1016/j.softx.2025.102286}, url = {https://www.sciencedirect.com/science/article/pii/S2352711025002523}, author = {Alberto Padovan and Vishal Anantharaman and Clarence W. Rowley and Blaine Vollmer and Tim Colonius and Daniel J. Bodony}, } ``` -------------------------------- ### Compute Eigendecomposition with Shift-and-Invert Source: https://github.com/albertopadovan/resolvent4py/blob/main/docs/source/auto_examples/cgl/demonstrate_eigendecomposition.ipynb Uses MUMPS solver for LU decomposition and Arnoldi iteration to compute eigenvalues closest to the origin. ```python import os import matplotlib.pyplot as plt import numpy as np import resolvent4py as res4py from petsc4py import PETSc import cgl plt.rcParams.update( { "font.family": "serif", "font.sans-serif": ["Computer Modern"], "font.size": 18, "text.usetex": True, } ) comm = PETSc.COMM_WORLD # Read the A matrix from file res4py.petscprint(comm, "Reading matrix from file...") load_path = "data/" N = 2000 Nl = res4py.compute_local_size(N) sizes = ((Nl, N), (Nl, N)) names = [ load_path + "rows.dat", load_path + "cols.dat", load_path + "vals.dat", ] A = res4py.read_coo_matrix(names, sizes) # Compute the eigendecomposition of L using shift and invert about s. # We need to define a matrix M = sI - A, compute its lu decomposition, # define a corresponding MatrixLinearOperator L and compute its eigendecomp. res4py.petscprint(comm, "Computing LU decomposition...") s = 0.0 M = res4py.create_AIJ_identity(comm, sizes) M.scale(s) M.axpy(-1.0, A) ksp = res4py.create_mumps_solver(M) res4py.check_lu_factorization(M, ksp) L = res4py.linear_operators.MatrixLinearOperator(M, ksp) # Compute the eigendecomp. res4py.petscprint(comm, "Running Arnoldi iteration...") krylov_dim = 50 n_evals = 10 D, V = res4py.linalg.eig( L, L.solve, krylov_dim, n_evals, lambda x: s - 1.0 / x ) # Check convergence L.destroy() L = res4py.linear_operators.MatrixLinearOperator(A) res4py.linalg.check_eig_convergence(L.apply, D, V) # Destroy objects L.destroy() V.destroy() # Make some plots if comm.getRank() == 0: l = 30 * 2 x = np.linspace(-l / 2, l / 2, num=N, endpoint=True) nu = 1.0 * (2 + 0.4 * 1j) gamma = 1 - 1j mu0 = 0.38 mu2 = -0.01 sigma = 0.4 system = cgl.CGL(x, nu, gamma, mu0, mu2, sigma) save_path = "results/" os.makedirs(save_path) if not os.path.exists(save_path) else None evals = system.compute_exact_eigenvalues(n_evals) D = np.diag(D) plt.figure() plt.plot(D.imag, D.real, "ko", label="res4py") plt.plot(evals.imag, evals.real, "rx", label="exact") ax = plt.gca() ax.set_xlabel(r"$\mathrm{Real}(\lambda_j)$") ax.set_ylabel(r"$\mathrm{Imag}(\lambda_j)$") ax.set_title(r"Eigenvalues $\lambda$") ax.axhline(y=0.0, linewidth=1.0, color="blue", alpha=0.3) plt.legend() plt.tight_layout() plt.savefig(save_path + "eigenvalues.png") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.